exo-jcr SVN: r2766 - in jcr/trunk: exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl and 1 other directory.
by do-not-reply@jboss.org
Author: tolusha
Date: 2010-07-12 05:22:10 -0400 (Mon, 12 Jul 2010)
New Revision: 2766
Modified:
jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/BackupWorkspaceInitializer.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/PendingChangesLog.java
Log:
EXOJCR-837: fix ClassCastException
Modified: jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/BackupWorkspaceInitializer.java
===================================================================
--- jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/BackupWorkspaceInitializer.java 2010-07-09 15:13:07 UTC (rev 2765)
+++ jcr/trunk/exo.jcr.component.core/src/main/java/org/exoplatform/services/jcr/impl/core/BackupWorkspaceInitializer.java 2010-07-12 09:22:10 UTC (rev 2766)
@@ -31,11 +31,12 @@
import org.exoplatform.services.jcr.datamodel.IllegalNameException;
import org.exoplatform.services.jcr.datamodel.ItemData;
import org.exoplatform.services.jcr.datamodel.NodeData;
+import org.exoplatform.services.jcr.datamodel.ValueData;
import org.exoplatform.services.jcr.impl.Constants;
import org.exoplatform.services.jcr.impl.core.nodetype.NodeTypeManagerImpl;
import org.exoplatform.services.jcr.impl.core.value.ValueFactoryImpl;
-import org.exoplatform.services.jcr.impl.dataflow.TransientValueData;
import org.exoplatform.services.jcr.impl.dataflow.persistent.CacheableWorkspaceDataManager;
+import org.exoplatform.services.jcr.impl.dataflow.persistent.StreamPersistedValueData;
import org.exoplatform.services.jcr.impl.storage.JCRInvalidItemStateException;
import org.exoplatform.services.jcr.impl.storage.JCRItemExistsException;
import org.exoplatform.services.jcr.impl.util.io.FileCleaner;
@@ -440,20 +441,75 @@
public void restore() throws IOException
{
- List<ItemState> listItemState = itemDataChangesLog.getAllStates();
- for (int i = 0; i < this.listFixupStream.size(); i++)
+ int index = 0;
+ int restoredItemStateId = index < listFixupStream.size() ? listFixupStream.get(index).getItemSateId() : -1;
+ int restoredValueDataId = index < listFixupStream.size() ? listFixupStream.get(index).getValueDataId() : -1;
+
+ TransactionChangesLog restoredItemDataChangesLog = new TransactionChangesLog();
+
+ ChangesLogIterator logIterator = itemDataChangesLog.getLogIterator();
+ int curItemStateId = 0;
+ while (logIterator.hasNextLog())
{
- ItemState itemState = listItemState.get(listFixupStream.get(i).getItemSateId());
- ItemData itemData = itemState.getData();
+ List<ItemState> restoredItems = new ArrayList<ItemState>();
- PersistedPropertyData propertyData = (PersistedPropertyData)itemData;
- TransientValueData tvd =
- (TransientValueData)(propertyData.getValues().get(listFixupStream.get(i).getValueDataId()));
+ PlainChangesLog log = logIterator.nextLog();
+ for (ItemState item : log.getAllStates())
+ {
+ if (curItemStateId != restoredItemStateId)
+ {
+ restoredItems.add(item);
+ }
+ else
+ {
+ List<ValueData> restoredValues = new ArrayList<ValueData>();
- // re-init the value
- tvd.delegate(new TransientValueData(tvd.getOrderNumber(), null, null, new SpoolFile(PrivilegedFileHelper
- .getAbsolutePath(listFile.get(i))), fileCleaner, -1, null, true));
+ PersistedPropertyData propertyData = (PersistedPropertyData)item.getData();
+ for (int curValueDataId = 0; curValueDataId < propertyData.getValues().size(); curValueDataId++)
+ {
+ ValueData valueData = propertyData.getValues().get(curValueDataId);
+
+ if (curItemStateId == restoredItemStateId && curValueDataId == restoredValueDataId)
+ {
+ // reinit valuedata
+ ValueData restoredValueData =
+ new StreamPersistedValueData(valueData.getOrderNumber(), new SpoolFile(listFile.get(index)
+ .getAbsolutePath()));
+
+ restoredValues.add(restoredValueData);
+
+ index++;
+ restoredItemStateId =
+ index < listFixupStream.size() ? listFixupStream.get(index).getItemSateId() : -1;
+ restoredValueDataId =
+ index < listFixupStream.size() ? listFixupStream.get(index).getValueDataId() : -1;
+ }
+ else
+ {
+ restoredValues.add(valueData);
+ }
+ }
+
+ PersistedPropertyData restoredPropertyData =
+ new PersistedPropertyData(propertyData.getIdentifier(), propertyData.getQPath(), propertyData
+ .getParentIdentifier(), propertyData.getPersistedVersion(), propertyData.getType(),
+ propertyData.isMultiValued(), restoredValues);
+
+ ItemState restoredItem =
+ new ItemState(restoredPropertyData, item.getState(), item.isEventFire(), item.getAncestorToSave(),
+ item.isInternallyCreated(), item.isPersisted());
+
+ restoredItems.add(restoredItem);
+ }
+
+ curItemStateId++;
+ }
+
+ PlainChangesLog restoredLog =
+ new PlainChangesLogImpl(restoredItems, log.getSessionId(), log.getEventType(), log.getPairId());
+ restoredItemDataChangesLog.addLog(restoredLog);
}
+ itemDataChangesLog = restoredItemDataChangesLog;
for (int i = 0; i < listFile.size(); i++)
fileCleaner.addFile(listFile.get(i));
Modified: jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/PendingChangesLog.java
===================================================================
--- jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/PendingChangesLog.java 2010-07-09 15:13:07 UTC (rev 2765)
+++ jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/backup/impl/PendingChangesLog.java 2010-07-12 09:22:10 UTC (rev 2766)
@@ -18,12 +18,16 @@
*/
package org.exoplatform.services.jcr.ext.backup.impl;
+import org.exoplatform.services.jcr.dataflow.ChangesLogIterator;
import org.exoplatform.services.jcr.dataflow.ItemState;
+import org.exoplatform.services.jcr.dataflow.PlainChangesLog;
+import org.exoplatform.services.jcr.dataflow.PlainChangesLogImpl;
import org.exoplatform.services.jcr.dataflow.TransactionChangesLog;
import org.exoplatform.services.jcr.dataflow.persistent.PersistedPropertyData;
import org.exoplatform.services.jcr.datamodel.ItemData;
+import org.exoplatform.services.jcr.datamodel.ValueData;
import org.exoplatform.services.jcr.ext.replication.FixupStream;
-import org.exoplatform.services.jcr.impl.dataflow.TransientValueData;
+import org.exoplatform.services.jcr.impl.dataflow.persistent.StreamPersistedValueData;
import org.exoplatform.services.jcr.impl.util.io.FileCleaner;
import org.exoplatform.services.jcr.impl.util.io.SpoolFile;
import org.exoplatform.services.jcr.util.IdGenerator;
@@ -482,20 +486,75 @@
{
// TODO same code as in BackupWorkspaceInitializer?
- List<ItemState> listItemState = itemDataChangesLog.getAllStates();
- for (int i = 0; i < this.listFixupStream.size(); i++)
+ int index = 0;
+ int restoredItemStateId = index < listFixupStream.size() ? listFixupStream.get(index).getItemSateId() : -1;
+ int restoredValueDataId = index < listFixupStream.size() ? listFixupStream.get(index).getValueDataId() : -1;
+
+ TransactionChangesLog restoredItemDataChangesLog = new TransactionChangesLog();
+
+ ChangesLogIterator logIterator = itemDataChangesLog.getLogIterator();
+ int curItemStateId = 0;
+ while (logIterator.hasNextLog())
{
- ItemState itemState = listItemState.get(listFixupStream.get(i).getItemSateId());
- ItemData itemData = itemState.getData();
+ List<ItemState> restoredItems = new ArrayList<ItemState>();
- PersistedPropertyData propertyData = (PersistedPropertyData)itemData;
- TransientValueData tvd =
- (TransientValueData)(propertyData.getValues().get(listFixupStream.get(i).getValueDataId()));
+ PlainChangesLog log = logIterator.nextLog();
+ for (ItemState item : log.getAllStates())
+ {
+ if (curItemStateId != restoredItemStateId)
+ {
+ restoredItems.add(item);
+ }
+ else
+ {
+ List<ValueData> restoredValues = new ArrayList<ValueData>();
- // re-init the value
- tvd.delegate(new TransientValueData(tvd.getOrderNumber(), null, null, new SpoolFile(listFile.get(i)
- .getAbsolutePath()), fileCleaner, -1, null, true));
+ PersistedPropertyData propertyData = (PersistedPropertyData)item.getData();
+ for (int curValueDataId = 0; curValueDataId < propertyData.getValues().size(); curValueDataId++)
+ {
+ ValueData valueData = propertyData.getValues().get(curValueDataId);
+
+ if (curItemStateId == restoredItemStateId && curValueDataId == restoredValueDataId)
+ {
+ // reinit valuedata
+ ValueData restoredValueData =
+ new StreamPersistedValueData(valueData.getOrderNumber(), new SpoolFile(listFile.get(index)
+ .getAbsolutePath()));
+
+ restoredValues.add(restoredValueData);
+
+ index++;
+ restoredItemStateId =
+ index < listFixupStream.size() ? listFixupStream.get(index).getItemSateId() : -1;
+ restoredValueDataId =
+ index < listFixupStream.size() ? listFixupStream.get(index).getValueDataId() : -1;
+ }
+ else
+ {
+ restoredValues.add(valueData);
+ }
+ }
+
+ PersistedPropertyData restoredPropertyData =
+ new PersistedPropertyData(propertyData.getIdentifier(), propertyData.getQPath(), propertyData
+ .getParentIdentifier(), propertyData.getPersistedVersion(), propertyData.getType(), propertyData
+ .isMultiValued(), restoredValues);
+
+ ItemState restoredItem =
+ new ItemState(restoredPropertyData, item.getState(), item.isEventFire(), item.getAncestorToSave(),
+ item.isInternallyCreated(), item.isPersisted());
+
+ restoredItems.add(restoredItem);
+ }
+
+ curItemStateId++;
+ }
+
+ PlainChangesLog restoredLog =
+ new PlainChangesLogImpl(restoredItems, log.getSessionId(), log.getEventType(), log.getPairId());
+ restoredItemDataChangesLog.addLog(restoredLog);
}
+ itemDataChangesLog = restoredItemDataChangesLog;
if (listRandomAccessFile != null)
for (int i = 0; i < listRandomAccessFile.size(); i++)
@@ -503,7 +562,6 @@
for (int i = 0; i < listFile.size(); i++)
fileCleaner.addFile(listFile.get(i));
-
}
}
\ No newline at end of file
13 years, 10 months
exo-jcr SVN: r2765 - in jcr/trunk/exo.jcr.component.ext/src: test/java/org/exoplatform/services/jcr/ext/script/groovy and 1 other directory.
by do-not-reply@jboss.org
Author: aparfonov
Date: 2010-07-09 11:13:07 -0400 (Fri, 09 Jul 2010)
New Revision: 2765
Modified:
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java
jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestUpdateListener.java
jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java
Log:
EXOJCR-823:
Modified: jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java
===================================================================
--- jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java 2010-07-09 14:58:06 UTC (rev 2764)
+++ jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoader.java 2010-07-09 15:13:07 UTC (rev 2765)
@@ -38,6 +38,7 @@
import org.exoplatform.services.rest.ext.groovy.GroovyJaxrsPublisher;
import org.exoplatform.services.rest.ext.groovy.ResourceId;
import org.exoplatform.services.rest.impl.ResourceBinder;
+import org.exoplatform.services.rest.impl.ResourcePublicationException;
import org.exoplatform.services.rest.resource.ResourceContainer;
import org.exoplatform.services.script.groovy.GroovyScriptInstantiator;
import org.picocontainer.Startable;
@@ -61,6 +62,7 @@
import java.util.StringTokenizer;
import java.util.regex.Pattern;
+import javax.annotation.security.RolesAllowed;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
@@ -78,6 +80,7 @@
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -101,8 +104,6 @@
/** Service name. */
private static final String SERVICE_NAME = "GroovyScript2RestLoader";
- //
-
/** See {@link InitParams}. */
protected InitParams initParams;
@@ -123,6 +124,10 @@
protected GroovyJaxrsPublisher groovyPublisher;
+ protected List<GroovyScript2RestLoaderPlugin> loadPlugins;
+
+ protected List<GroovyScriptAddRepoPlugin> addRepoPlugins;
+
/** See {@link ResourceBinder}. */
private ResourceBinder binder;
@@ -184,6 +189,7 @@
* @param url the URL. The <code>url.toString()</code> must be corresponded
* to script class.
* @see GroovyScriptRestLoader#loadScript(URL).
+ * @deprecated
*/
public void unloadScript(URL url)
{
@@ -203,9 +209,14 @@
return unloadScript(new SimpleScriptKey(key));
}
+ /**
+ * @param key
+ * @return
+ * @deprecated
+ */
public boolean unloadScript(ScriptKey key)
{
- return groovyPublisher.unpublishResource(key);
+ return null != groovyPublisher.unpublishResource(key);
}
/**
@@ -221,6 +232,7 @@
/**
* @param url script's URL
* @return true if script loaded false otherwise
+ * @deprecated
*/
public boolean isLoaded(URL url)
{
@@ -230,6 +242,7 @@
/**
* @param key script's key. With this key script was created.
* @return true if script loaded false otherwise
+ * @deprecated
*/
public boolean isLoaded(ScriptKey key)
{
@@ -254,11 +267,20 @@
/**
* @param url the URL for loading script.
* @throws IOException it script can't be loaded.
+ * @deprecated
*/
public boolean loadScript(URL url) throws IOException
{
ResourceId key = new URLScriptKey(url);
- return groovyPublisher.publishPerRequest(new BufferedInputStream(url.openStream()), key);
+ try
+ {
+ groovyPublisher.publishPerRequest(new BufferedInputStream(url.openStream()), key, null);
+ return true;
+ }
+ catch (ResourcePublicationException e)
+ {
+ return true;
+ }
}
/**
@@ -299,32 +321,27 @@
* @param stream the stream which represents groovy script.
* @return if script loaded false otherwise
* @throws IOException if script can't be loaded or parsed
- * @deprecated use {@link #loadScript(ResourceId, InputStream)} instead.
- * Parameter <code>name</code> is not in used,
- * {@link ResourceId#getId()} will be used as script name
+ * @deprecated
*/
public boolean loadScript(ScriptKey key, String name, InputStream stream) throws IOException
{
- return loadScript(key, stream);
+ try
+ {
+ groovyPublisher.publishPerRequest(stream, key, null);
+ return true;
+ }
+ catch (ResourcePublicationException e)
+ {
+ return false;
+ }
}
/**
- * @param key the key which must be corresponded to object class name
- * @param stream the stream which represents groovy script.
- * @return if script loaded false otherwise
- * @throws IOException if script can't be loaded or parsed
- */
- public boolean loadScript(ResourceId resourceId, InputStream stream)
- {
- return groovyPublisher.publishPerRequest(stream, resourceId);
- }
-
- /**
* {@inheritDoc}
*/
public void start()
{
- if (registryService != null && !registryService.getForceXMLConfigurationValue(initParams))
+ if (registryService != null && initParams != null && !registryService.getForceXMLConfigurationValue(initParams))
{
SessionProvider sessionProvider = SessionProvider.createSystemProvider();
try
@@ -384,8 +401,8 @@
continue;
}
- loadScript(new NodeScriptKey(repositoryName, workspaceName, node), node.getProperty("jcr:data")
- .getStream());
+ this.groovyPublisher.publishPerRequest(node.getProperty("jcr:data").getStream(), new NodeScriptKey(
+ repositoryName, workspaceName, node), null);
}
session.getWorkspace().getObservationManager().addEventListener(
@@ -423,7 +440,7 @@
// done for this type of services. It can't be binded in common way cause
// to dependencies problem. And in other side not possible to use third
// part which can be injected by GroovyScript2RestLoader.
- binder.bind(this);
+ binder.addResource(this, null);
}
/**
@@ -435,13 +452,6 @@
}
/**
- * See {@link GroovyScript2RestLoaderPlugin}.
- */
- protected List<GroovyScript2RestLoaderPlugin> loadPlugins;
-
- protected List<GroovyScriptAddRepoPlugin> addRepoPlugins;
-
- /**
* @param cp See {@link ComponentPlugin}
*/
public void addPlugin(ComponentPlugin cp)
@@ -745,13 +755,14 @@
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -790,9 +801,8 @@
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.BAD_REQUEST).entity("Unexpected error. " + e.getMessage()).type(
- MediaType.TEXT_PLAIN).build();
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).type(MediaType.TEXT_PLAIN).build();
}
}
@@ -830,13 +840,14 @@
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -900,13 +911,14 @@
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -936,7 +948,7 @@
@POST
@Consumes({"multipart/*"})
@Path("update/{repository}/{workspace}/{path:.*}")
- public Response updateScripts(Iterator<FileItem> items, @Context UriInfo uriInfo,
+ public Response updateScript(Iterator<FileItem> items, @Context UriInfo uriInfo,
@PathParam("repository") String repository, @PathParam("workspace") String workspace,
@PathParam("path") String path)
{
@@ -960,13 +972,14 @@
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -1001,17 +1014,17 @@
Node scriptFile = (Node)ses.getItem("/" + path);
return Response.status(Response.Status.OK).entity(
scriptFile.getNode("jcr:content").getProperty("jcr:data").getStream()).type("script/groovy").build();
-
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -1044,22 +1057,24 @@
sessionProviderService.getSessionProvider(null).getSession(workspace,
repositoryService.getRepository(repository));
Node script = ((Node)ses.getItem("/" + path)).getNode("jcr:content");
+ ResourceId key = new NodeScriptKey(repository, workspace, script);
- ScriptMetadata meta =
- new ScriptMetadata(script.getProperty("exo:autoload").getBoolean(), isLoaded(new NodeScriptKey(repository,
- workspace, script)), script.getProperty("jcr:mimeType").getString(), script.getProperty(
- "jcr:lastModified").getDate().getTimeInMillis());
+ ScriptMetadata meta = new ScriptMetadata(script.getProperty("exo:autoload").getBoolean(), //
+ groovyPublisher.isPublished(key), //
+ script.getProperty("jcr:mimeType").getString(), //
+ script.getProperty("jcr:lastModified").getDate().getTimeInMillis());
return Response.status(Response.Status.OK).entity(meta).type(MediaType.APPLICATION_JSON).build();
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -1095,13 +1110,14 @@
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -1144,13 +1160,14 @@
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).entity(MediaType.TEXT_PLAIN).build();
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -1172,11 +1189,18 @@
* @param workspace workspace name
* @param path the path to JCR node that contains groovy script to be
* deployed
+ * @param state <code>true</code> if resource should be loaded and
+ * <code>false</code> otherwise. If this attribute is not present in
+ * HTTP request then it will be considered as <code>true</code>
+ * @param properties optional properties to be applied to loaded resource.
+ * Ignored if <code>state</code> parameter is false
*/
@POST
@Path("load/{repository}/{workspace}/{path:.*}")
+ @RolesAllowed({"administrators"})
public Response load(@PathParam("repository") String repository, @PathParam("workspace") String workspace,
- @PathParam("path") String path, @DefaultValue("true") @QueryParam("state") boolean state)
+ @PathParam("path") String path, @DefaultValue("true") @QueryParam("state") boolean state,
+ MultivaluedMap<String, String> properties)
{
Session ses = null;
try
@@ -1185,42 +1209,37 @@
sessionProviderService.getSessionProvider(null).getSession(workspace,
repositoryService.getRepository(repository));
Node script = ((Node)ses.getItem("/" + path)).getNode("jcr:content");
- ScriptKey key = new NodeScriptKey(repository, workspace, script);
+ ResourceId key = new NodeScriptKey(repository, workspace, script);
if (state)
{
- if (isLoaded(key))
- {
- unloadScript(key);
- }
- if (!loadScript(key, script.getProperty("jcr:data").getStream()))
- {
- String message =
- "Can't bind script " + path
- + ", it is not root resource or root resource with the same URI pattern already registered";
- return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
- }
+ groovyPublisher.unpublishResource(key);
+ groovyPublisher.publishPerRequest(script.getProperty("jcr:data").getStream(), key, properties);
}
else
{
- if (!unloadScript(key))
+ if (null == groovyPublisher.unpublishResource(key))
{
- String message =
- "Can't unbind script " + path + ", not bound or has wrong mapping to the resource class ";
- return Response.status(Response.Status.BAD_REQUEST).entity(message).build();
+ return Response.status(Response.Status.BAD_REQUEST).entity(
+ "Can't unbind script " + path + ", not bound or has wrong mapping to the resource class ").type(
+ MediaType.TEXT_PLAIN).build();
}
}
-
return Response.status(Response.Status.NO_CONTENT).build();
}
catch (PathNotFoundException e)
{
- LOG.error("Path " + path + " does not exists", e);
- return Response.status(Response.Status.NOT_FOUND).build();
+ String msg = "Path " + path + " does not exists";
+ LOG.error(msg);
+ return Response.status(Response.Status.NOT_FOUND).entity(msg).type(MediaType.TEXT_PLAIN).build();
}
+ catch (ResourcePublicationException e)
+ {
+ return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).type(MediaType.TEXT_PLAIN).build();
+ }
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -1232,6 +1251,109 @@
}
}
+ // @POST
+ // @Path("load/development/{repository}/{workspace}/{path:.*}")
+ // @RolesAllowed({"developers"})
+ // public Response loadDevelopment(@PathParam("repository") String repository,
+ // @PathParam("workspace") String workspace, @PathParam("path") String path,
+ // @DefaultValue("true") @QueryParam("state") boolean state, @Context SecurityContext security,
+ // MultivaluedMap<String, String> properties)
+ // {
+ // if (state)
+ // {
+ // return loadResource(repository, workspace, path, security, properties == null ? new MultivaluedMapImpl()
+ // : properties);
+ // }
+ // return unloadResource(repository, workspace, path, security);
+ // }
+
+ // /**
+ // * @param repository JCR repository
+ // * @param workspace JCR workspace
+ // * @param path path to script
+ // * @param security see {@link SecurityContext}
+ // * @param properties resource properties
+ // * @return response with corresponded status and info
+ // */
+ // private Response loadResource(String repository, String workspace, String path, SecurityContext security,
+ // MultivaluedMap<String, String> properties)
+ // {
+ // Session ses = null;
+ // try
+ // {
+ // ses =
+ // sessionProviderService.getSessionProvider(null).getSession(workspace,
+ // repositoryService.getRepository(repository));
+ // Node script = ((Node)ses.getItem("/" + path)).getNode("jcr:content");
+ // ResourceId key = new NodeScriptKey(repository, workspace, script);
+ // groovyPublisher.unpublishResource(key, security);
+ // groovyPublisher.publishPerRequest(script.getProperty("jcr:data").getStream(), key, properties, security);
+ // return Response.status(Response.Status.NO_CONTENT).build();
+ // }
+ // catch (PathNotFoundException e)
+ // {
+ // String msg = "Path " + path + " does not exists";
+ // LOG.error(msg);
+ // return Response.status(Response.Status.NOT_FOUND).entity(msg).type(MediaType.TEXT_PLAIN).build();
+ // }
+ // catch (ResourcePublicationException e)
+ // {
+ // return Response.status(Response.Status.BAD_REQUEST).entity(e.getMessage()).type(MediaType.TEXT_PLAIN).build();
+ // }
+ // catch (Exception e)
+ // {
+ // LOG.error(e.getMessage(), e);
+ // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
+ // .type(MediaType.TEXT_PLAIN).build();
+ // }
+ // finally
+ // {
+ // if (ses != null)
+ // {
+ // ses.logout();
+ // }
+ // }
+ // }
+ //
+ // private Response unloadResource(String repository, String workspace, String path, SecurityContext security)
+ // {
+ // Session ses = null;
+ // try
+ // {
+ // ses =
+ // sessionProviderService.getSessionProvider(null).getSession(workspace,
+ // repositoryService.getRepository(repository));
+ // Node script = ((Node)ses.getItem("/" + path)).getNode("jcr:content");
+ // ResourceId key = new NodeScriptKey(repository, workspace, script);
+ // if (null == groovyPublisher.unpublishResource(key, security))
+ // {
+ // return Response.status(Response.Status.BAD_REQUEST).entity(
+ // "Can't unbind script " + path + ", not bound or has wrong mapping to the resource class ").type(
+ // MediaType.TEXT_PLAIN).build();
+ // }
+ // return Response.status(Response.Status.NO_CONTENT).build();
+ // }
+ // catch (PathNotFoundException e)
+ // {
+ // String msg = "Path " + path + " does not exists";
+ // LOG.error(msg);
+ // return Response.status(Response.Status.NOT_FOUND).entity(msg).type(MediaType.TEXT_PLAIN).build();
+ // }
+ // catch (Exception e)
+ // {
+ // LOG.error(e.getMessage(), e);
+ // return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
+ // .type(MediaType.TEXT_PLAIN).build();
+ // }
+ // finally
+ // {
+ // if (ses != null)
+ // {
+ // ses.logout();
+ // }
+ // }
+ // }
+
/**
* Returns the list of all groovy-scripts found in workspace.
*
@@ -1252,7 +1374,6 @@
Session ses = null;
try
{
-
ses =
sessionProviderService.getSessionProvider(null).getSession(workspace,
repositoryService.getRepository(repository));
@@ -1313,8 +1434,8 @@
}
catch (Exception e)
{
- LOG.error("Unexpected error occurs ", e);
- return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. " + e.getMessage())
+ LOG.error(e.getMessage(), e);
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
.type(MediaType.TEXT_PLAIN).build();
}
finally
@@ -1353,7 +1474,7 @@
/**
* JCR groovy resource resolver.
*/
- class JcrGroovyResourceLoader extends DefaultGroovyResourceLoader
+ protected class JcrGroovyResourceLoader extends DefaultGroovyResourceLoader
{
public JcrGroovyResourceLoader(URL[] roots) throws MalformedURLException
@@ -1438,7 +1559,7 @@
}
/**
- * Script metadata, used for pass script metada as JSON.
+ * Script meta-data, used for pass script meta-data as JSON.
*/
public static class ScriptMetadata
{
Modified: jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestUpdateListener.java
===================================================================
--- jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestUpdateListener.java 2010-07-09 14:58:06 UTC (rev 2764)
+++ jcr/trunk/exo.jcr.component.ext/src/main/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestUpdateListener.java 2010-07-09 15:13:07 UTC (rev 2765)
@@ -20,6 +20,9 @@
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
+import org.exoplatform.services.rest.ObjectFactory;
+import org.exoplatform.services.rest.ext.groovy.ResourceId;
+import org.exoplatform.services.rest.resource.AbstractResourceDescriptor;
import javax.jcr.Node;
import javax.jcr.Session;
@@ -29,34 +32,25 @@
/**
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
- * @version $Id: GroovyScript2RestUpdateListener.java 34445 2009-07-24 07:51:18Z dkatayev $
+ * @version $Id: GroovyScript2RestUpdateListener.java 34445 2009-07-24 07:51:18Z
+ * dkatayev $
*/
public class GroovyScript2RestUpdateListener implements EventListener
{
- /**
- * Logger.
- */
+ /** Logger. */
private static final Log LOG = ExoLogger.getLogger("exo.jcr.component.ext.GroovyScript2RestUpdateListener");
- /**
- * Repository name.
- */
+ /** Repository name. */
private final String repository;
- /**
- * Workspace name.
- */
+ /** Workspace name. */
private final String workspace;
- /**
- * See {@link GroovyScript2RestLoader}.
- */
+ /** See {@link GroovyScript2RestLoader}. */
private final GroovyScript2RestLoader groovyScript2RestLoader;
- /**
- * See {@link Session}.
- */
+ /** See {@link Session}. */
private final Session session;
/**
@@ -118,10 +112,18 @@
*/
private void loadScript(Node node) throws Exception
{
- ScriptKey key = new NodeScriptKey(repository, workspace, node);
- if (groovyScript2RestLoader.isLoaded(key))
- groovyScript2RestLoader.unloadScript(key);
- groovyScript2RestLoader.loadScript(key, node.getProperty("jcr:data").getStream());
+ ResourceId key = new NodeScriptKey(repository, workspace, node);
+ ObjectFactory<AbstractResourceDescriptor> resource =
+ groovyScript2RestLoader.groovyPublisher.unpublishResource(key);
+ if (resource != null)
+ {
+ groovyScript2RestLoader.groovyPublisher.publishPerRequest(node.getProperty("jcr:data").getStream(), key,
+ resource.getObjectModel().getProperties());
+ }
+ else
+ {
+ groovyScript2RestLoader.groovyPublisher.publishPerRequest(node.getProperty("jcr:data").getStream(), key, null);
+ }
}
/**
@@ -132,9 +134,8 @@
*/
private void unloadScript(String path) throws Exception
{
- ScriptKey key = new NodeScriptKey(repository, workspace, path);
- if (groovyScript2RestLoader.isLoaded(key))
- groovyScript2RestLoader.unloadScript(key);
+ ResourceId key = new NodeScriptKey(repository, workspace, path);
+ groovyScript2RestLoader.groovyPublisher.unpublishResource(key);
}
}
Modified: jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java
===================================================================
--- jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java 2010-07-09 14:58:06 UTC (rev 2764)
+++ jcr/trunk/exo.jcr.component.ext/src/test/java/org/exoplatform/services/jcr/ext/script/groovy/GroovyScript2RestLoaderTest.java 2010-07-09 15:13:07 UTC (rev 2765)
@@ -24,8 +24,10 @@
import org.exoplatform.services.jcr.ext.registry.RESTRegistryTest.DummyContainerResponseWriter;
import org.exoplatform.services.jcr.ext.script.groovy.GroovyScript2RestLoader.ScriptMetadata;
import org.exoplatform.services.rest.RequestHandler;
+import org.exoplatform.services.rest.ext.method.filter.MethodAccessFilter;
import org.exoplatform.services.rest.impl.ContainerResponse;
import org.exoplatform.services.rest.impl.MultivaluedMapImpl;
+import org.exoplatform.services.rest.impl.ProviderBinder;
import org.exoplatform.services.rest.impl.ResourceBinder;
import org.exoplatform.services.rest.tools.ByteArrayContainerResponseWriter;
import org.exoplatform.services.rest.tools.ResourceLauncher;
@@ -96,6 +98,10 @@
launcher = new ResourceLauncher(handler);
+ ProviderBinder.setInstance(new ProviderBinder());
+ ProviderBinder providers = ProviderBinder.getInstance();
+ providers.addMethodInvokerFilter(new MethodAccessFilter());
+
session.save();
}
13 years, 10 months
exo-jcr SVN: r2764 - ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl.
by do-not-reply@jboss.org
Author: aparfonov
Date: 2010-07-09 10:58:06 -0400 (Fri, 09 Jul 2010)
New Revision: 2764
Modified:
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java
Log:
EXOJCR-824:
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java 2010-07-09 14:46:40 UTC (rev 2763)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java 2010-07-09 14:58:06 UTC (rev 2764)
@@ -159,7 +159,7 @@
if (expirationDate > 0 && expirationDate < System.currentTimeMillis())
{
iter.remove();
- for (ResourceListener listener: resourceListeners)
+ for (ResourceListener listener : resourceListeners)
{
listener.resourceRemoved(next.getObjectModel());
}
@@ -201,9 +201,15 @@
* @throws Exception if can't set instance of {@link RuntimeDelegate}
* @see MethodInvokerFactory
*/
- @SuppressWarnings("unchecked")
public ResourceBinder(ExoContainerContext containerContext, MethodInvokerFactory invokerFactory) throws Exception
{
+ this(containerContext, null, invokerFactory);
+ }
+
+ @SuppressWarnings("unchecked")
+ protected ResourceBinder(ExoContainerContext containerContext, ResourceCleaner cleaner,
+ MethodInvokerFactory invokerFactory) throws Exception
+ {
this.invokerFactory = invokerFactory;
// Initialize RuntimeDelegate instance
@@ -242,9 +248,9 @@
}
}
- Thread cleaner = new Thread(new ResourceCleaner(60));
- cleaner.setDaemon(true);
- cleaner.start();
+ Thread thread = new Thread(cleaner == null ? new ResourceCleaner(60) : cleaner);
+ thread.setDaemon(true);
+ thread.start();
}
/**
@@ -459,7 +465,7 @@
}
rootResources.add(resourceFactory);
Collections.sort(rootResources, RESOURCE_COMPARATOR);
- for (ResourceListener listener: resourceListeners)
+ for (ResourceListener listener : resourceListeners)
{
listener.resourceAdded(resourceFactory.getObjectModel());
}
@@ -635,7 +641,7 @@
}
if (resource != null)
{
- for (ResourceListener listener: resourceListeners)
+ for (ResourceListener listener : resourceListeners)
{
listener.resourceRemoved(resource.getObjectModel());
}
@@ -673,7 +679,7 @@
}
if (resource != null)
{
- for (ResourceListener listener: resourceListeners)
+ for (ResourceListener listener : resourceListeners)
{
listener.resourceRemoved(resource.getObjectModel());
}
13 years, 10 months
exo-jcr SVN: r2763 - ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl.
by do-not-reply@jboss.org
Author: aparfonov
Date: 2010-07-09 10:46:40 -0400 (Fri, 09 Jul 2010)
New Revision: 2763
Added:
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceListener.java
Modified:
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java
Log:
EXOJCR-824:
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java 2010-07-09 13:39:29 UTC (rev 2762)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java 2010-07-09 14:46:40 UTC (rev 2763)
@@ -329,6 +329,8 @@
*/
public void stop()
{
+ // TODO improve
+ ResourceBinder.cleanerStop = true;
}
//
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java 2010-07-09 13:39:29 UTC (rev 2762)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java 2010-07-09 14:46:40 UTC (rev 2763)
@@ -68,6 +68,12 @@
public class ResourceBinder
{
+ /**
+ * Name of property which may contains resource expiration date. Date
+ * expected as string representation of java.util.Date in long format.
+ */
+ public static final String RESOURCE_EXPIRED = "resource.expiration.date";
+
/** Logger. */
private static final Log LOG = ExoLogger.getLogger("exo.ws.rest.core.ResourceBinder");
@@ -93,12 +99,81 @@
}
};
+ static boolean cleanerStop = false;
+
+ protected class ResourceCleaner implements Runnable
+ {
+
+ private final int cleanerDelay;
+
+ /**
+ * @param cleanerDelay cleaner process delay in seconds
+ */
+ public ResourceCleaner(int cleanerDelay)
+ {
+ this.cleanerDelay = cleanerDelay;
+ }
+
+ public void run()
+ {
+ while (!cleanerStop)
+ {
+ try
+ {
+ Thread.sleep(cleanerDelay * 1000L);
+ }
+ catch (InterruptedException e)
+ {
+ ;
+ }
+ if (!cleanerStop)
+ {
+ processResources();
+ }
+ }
+ }
+
+ protected void processResources()
+ {
+ if (LOG.isDebugEnabled())
+ LOG.debug("Start resource cleaner");
+
+ synchronized (rootResources)
+ {
+ for (Iterator<ObjectFactory<AbstractResourceDescriptor>> iter = rootResources.iterator(); iter.hasNext();)
+ {
+ ObjectFactory<AbstractResourceDescriptor> next = iter.next();
+ List<String> str = next.getObjectModel().getProperty(RESOURCE_EXPIRED);
+ long expirationDate = -1;
+ if (str != null && str.size() > 0)
+ {
+ try
+ {
+ expirationDate = Long.parseLong(str.get(0));
+ }
+ catch (NumberFormatException e)
+ {
+ ;
+ }
+ }
+ if (expirationDate > 0 && expirationDate < System.currentTimeMillis())
+ {
+ iter.remove();
+ for (ResourceListener listener: resourceListeners)
+ {
+ listener.resourceRemoved(next.getObjectModel());
+ }
+ if (LOG.isDebugEnabled())
+ LOG.debug("Remove expired resource: " + next.getObjectModel());
+ }
+ }
+ }
+ }
+ }
+
/** Validator. */
protected final ResourceDescriptorVisitor rdv = ResourceDescriptorValidator.getInstance();
- /** Amount of available root resources. */
- protected int size = 0;
-
/** @see RuntimeDelegate */
protected final RuntimeDelegate rd;
@@ -112,6 +187,9 @@
protected final List<ObjectFactory<AbstractResourceDescriptor>> rootResources =
new ArrayList<ObjectFactory<AbstractResourceDescriptor>>();
+ /** Resource listeners. */
+ protected final List<ResourceListener> resourceListeners = new ArrayList<ResourceListener>();
+
public ResourceBinder(ExoContainerContext containerContext) throws Exception
{
this(containerContext, null);
@@ -163,6 +241,10 @@
LOG.error("Failed add JAX-RS resource " + resource.getClass().getName(), e);
}
}
+
+ Thread cleaner = new Thread(new ResourceCleaner(60));
+ cleaner.setDaemon(true);
+ cleaner.start();
}
/**
@@ -377,13 +459,29 @@
}
rootResources.add(resourceFactory);
Collections.sort(rootResources, RESOURCE_COMPARATOR);
- size++;
+ for (ResourceListener listener: resourceListeners)
+ {
+ listener.resourceAdded(resourceFactory.getObjectModel());
+ }
if (LOG.isDebugEnabled())
LOG.debug("Add resource: " + resourceFactory.getObjectModel());
}
}
/**
+ * Register new resource listener.
+ *
+ * @param listener listener
+ * @see ResourceListener
+ */
+ public void addResourceListener(ResourceListener listener)
+ {
+ resourceListeners.add(listener);
+ if (LOG.isDebugEnabled())
+ LOG.debug("Resource listener added: " + listener);
+ }
+
+ /**
* Register root resource.
*
* @param resourceClass class of candidate to be root resource
@@ -437,7 +535,6 @@
synchronized (rootResources)
{
rootResources.clear();
- size = 0;
}
}
@@ -493,7 +590,7 @@
@Deprecated
public List<AbstractResourceDescriptor> getRootResources()
{
- List<AbstractResourceDescriptor> l = new ArrayList<AbstractResourceDescriptor>(size);
+ List<AbstractResourceDescriptor> l = new ArrayList<AbstractResourceDescriptor>(rootResources.size());
synchronized (rootResources)
{
for (ObjectFactory<AbstractResourceDescriptor> f : rootResources)
@@ -509,7 +606,7 @@
*/
public int getSize()
{
- return size;
+ return rootResources.size();
}
/**
@@ -538,7 +635,10 @@
}
if (resource != null)
{
- size--;
+ for (ResourceListener listener: resourceListeners)
+ {
+ listener.resourceRemoved(resource.getObjectModel());
+ }
if (LOG.isDebugEnabled())
LOG.debug("Remove resource: " + resource.getObjectModel());
}
@@ -573,7 +673,10 @@
}
if (resource != null)
{
- size--;
+ for (ResourceListener listener: resourceListeners)
+ {
+ listener.resourceRemoved(resource.getObjectModel());
+ }
if (LOG.isDebugEnabled())
LOG.debug("Remove resource: " + resource.getObjectModel());
}
Added: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceListener.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceListener.java (rev 0)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceListener.java 2010-07-09 14:46:40 UTC (rev 2763)
@@ -0,0 +1,47 @@
+/**
+ * Copyright (C) 2010 eXo Platform SAS.
+ *
+ * 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.exoplatform.services.rest.impl;
+
+import org.exoplatform.services.rest.resource.AbstractResourceDescriptor;
+
+/**
+ * Listener for adding/removing JAX-RS resources.
+ *
+ * @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+public interface ResourceListener
+{
+
+ /**
+ * Method will be called if new resource add in {@link ResourceBinder} .
+ *
+ * @param resource added resource
+ */
+ void resourceAdded(AbstractResourceDescriptor resource);
+
+ /**
+ * Method will be called if resource removed from {@link ResourceBinder} .
+ *
+ * @param resource removed resource
+ */
+ void resourceRemoved(AbstractResourceDescriptor resource);
+
+}
Property changes on: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceListener.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
13 years, 10 months
exo-jcr SVN: r2762 - in ws/trunk/exo.ws.rest.ext/src: test/java/org/exoplatform/services/rest/ext/groovy and 1 other directory.
by do-not-reply@jboss.org
Author: aparfonov
Date: 2010-07-09 09:39:29 -0400 (Fri, 09 Jul 2010)
New Revision: 2762
Modified:
ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/DefaultGroovyResourceLoader.java
ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/GroovyJaxrsPublisher.java
ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyContextParamTest.java
ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyDependenciesTest.java
ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyExoComponentTest.java
ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySecureRestrictionTest.java
ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySimpleTest.java
Log:
EXOJCR-823:
Modified: ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/DefaultGroovyResourceLoader.java
===================================================================
--- ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/DefaultGroovyResourceLoader.java 2010-07-09 13:37:30 UTC (rev 2761)
+++ ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/DefaultGroovyResourceLoader.java 2010-07-09 13:39:29 UTC (rev 2762)
@@ -29,8 +29,9 @@
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Collections;
-import java.util.HashMap;
+import java.util.LinkedHashMap;
import java.util.Map;
+import java.util.Map.Entry;
/**
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
@@ -42,8 +43,11 @@
protected URL[] roots;
- protected Map<String, URL> resources = Collections.synchronizedMap(new HashMap<String, URL>());
+ // TODO need configurable ?
+ private int maxEntries = 512;
+ protected final Map<String, URL> resources;
+
public DefaultGroovyResourceLoader(URL[] roots) throws MalformedURLException
{
this.roots = new URL[roots.length];
@@ -59,6 +63,13 @@
this.roots[i] = roots[i];
}
}
+ resources = Collections.synchronizedMap(new LinkedHashMap<String, URL>()
+ {
+ protected boolean removeEldestEntry(Entry<String, URL> eldest)
+ {
+ return size() > maxEntries;
+ }
+ });
}
public DefaultGroovyResourceLoader(URL root) throws MalformedURLException
@@ -99,6 +110,7 @@
URL resource = null;
synchronized (filename)
{
+ System.out.println(">>>>>>>> "+resources.size());
resource = resources.get(filename);
boolean inCache = resource != null;
for (URL root : roots)
Modified: ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/GroovyJaxrsPublisher.java
===================================================================
--- ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/GroovyJaxrsPublisher.java 2010-07-09 13:37:30 UTC (rev 2761)
+++ ws/trunk/exo.ws.rest.ext/src/main/java/org/exoplatform/services/rest/ext/groovy/GroovyJaxrsPublisher.java 2010-07-09 13:39:29 UTC (rev 2762)
@@ -22,8 +22,12 @@
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;
+import org.exoplatform.services.rest.ObjectFactory;
import org.exoplatform.services.rest.PerRequestObjectFactory;
import org.exoplatform.services.rest.impl.ResourceBinder;
+import org.exoplatform.services.rest.impl.ResourcePublicationException;
+import org.exoplatform.services.rest.resource.AbstractResourceDescriptor;
+import org.exoplatform.services.rest.uri.UriPattern;
import org.exoplatform.services.script.groovy.GroovyScriptInstantiator;
import java.io.ByteArrayInputStream;
@@ -32,8 +36,12 @@
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import javax.ws.rs.Path;
+import javax.ws.rs.core.MultivaluedMap;
+
/**
* Manage via {@link ResourceBinder} Groovy based RESTful services.
*
@@ -55,8 +63,7 @@
protected GroovyClassLoader gcl;
- protected final Map<ResourceId, Class<?>> resources =
- Collections.synchronizedMap(new HashMap<ResourceId, Class<?>>());
+ protected final Map<ResourceId, String> resources = Collections.synchronizedMap(new HashMap<ResourceId, String>());
/**
* Create GroovyJaxrsPublisher which is able publish per-request and
@@ -84,6 +91,33 @@
}
/**
+ * Get resource corresponded to specified id <code>resourceId</code> .
+ *
+ * @param resourceId resource id
+ * @return resource or <code>null</code>
+ */
+ public ObjectFactory<AbstractResourceDescriptor> getResource(ResourceId resourceId)
+ {
+ String path = resources.get(resourceId);
+ if (path == null)
+ return null;
+
+ UriPattern pattern = new UriPattern(path);
+ List<ObjectFactory<AbstractResourceDescriptor>> rootResources = binder.getResources();
+ synchronized (rootResources)
+ {
+ for (ObjectFactory<AbstractResourceDescriptor> res : rootResources)
+ {
+ if (res.getObjectModel().getUriPattern().equals(pattern))
+ return res;
+ }
+ }
+ // If resource not exists any more but still in mapping.
+ resources.remove(resourceId);
+ return null;
+ }
+
+ /**
* Check is groovy resource with specified id is published or not
*
* @param resourceId id of resource to be checked
@@ -92,7 +126,7 @@
*/
public boolean isPublished(ResourceId resourceId)
{
- return resources.containsKey(resourceId);
+ return null != getResource(resourceId);
}
/**
@@ -100,19 +134,17 @@
*
* @param in stream which contains groovy source code of RESTful service
* @param resourceId id to be assigned to resource
- * @return <code>true</code> if resource was published and <code>false</code>
- * otherwise
+ * @param properties optional resource properties. This parameter may be
+ * <code>null</code>
* @throws NullPointerException if <code>resourceId == null</code>
+ * @throws ResourcePublicationException see
+ * {@link ResourceBinder#addResource(Class, MultivaluedMap)}
*/
- public boolean publishPerRequest(InputStream in, ResourceId resourceId)
+ public void publishPerRequest(InputStream in, ResourceId resourceId, MultivaluedMap<String, String> properties)
{
Class<?> rc = gcl.parseClass(createCodeSource(in, resourceId.getId()));
- boolean answ = binder.bind(rc);
- if (answ)
- {
- resources.put(resourceId, rc);
- }
- return answ;
+ binder.addResource(rc, properties);
+ resources.put(resourceId, rc.getAnnotation(Path.class).value());
}
/**
@@ -121,13 +153,15 @@
*
* @param source groovy source code of RESTful service
* @param resourceId id to be assigned to resource
- * @return <code>true</code> if resource was published and <code>false</code>
- * otherwise
+ * @param properties optional resource properties. This parameter may be
+ * <code>null</code>
* @throws NullPointerException if <code>resourceId == null</code>
+ * @throws ResourcePublicationException see
+ * {@link ResourceBinder#addResource(Class, MultivaluedMap)}
*/
- public final boolean publishPerRequest(String source, ResourceId resourceId)
+ public final void publishPerRequest(String source, ResourceId resourceId, MultivaluedMap<String, String> properties)
{
- return publishPerRequest(source, DEFAULT_CHARSET, resourceId);
+ publishPerRequest(source, DEFAULT_CHARSET, resourceId, properties);
}
/**
@@ -138,14 +172,17 @@
* @param charset source string charset. May be <code>null</code> than
* default charset will be in use
* @param resourceId id to be assigned to resource
- * @return <code>true</code> if resource was published and <code>false</code>
- * otherwise
+ * @param properties optional resource properties. This parameter may be
+ * <code>null</code>.
* @throws UnsupportedCharsetException if <code>charset</code> is unsupported
* @throws NullPointerException if <code>resourceId == null</code>
+ * @throws ResourcePublicationException see
+ * {@link ResourceBinder#addResource(Class, MultivaluedMap)}
*/
- public final boolean publishPerRequest(String source, String charset, ResourceId resourceId)
+ public final void publishPerRequest(String source, String charset, ResourceId resourceId,
+ MultivaluedMap<String, String> properties)
{
- return publishPerRequest(source, charset == null ? DEFAULT_CHARSET : Charset.forName(charset), resourceId);
+ publishPerRequest(source, charset == null ? DEFAULT_CHARSET : Charset.forName(charset), resourceId, properties);
}
/**
@@ -153,19 +190,17 @@
*
* @param in stream which contains groovy source code of RESTful service
* @param resourceId id to be assigned to resource
- * @return <code>true</code> if resource was published and <code>false</code>
- * otherwise
+ * @param properties optional resource properties. This parameter may be
+ * <code>null</code>
* @throws NullPointerException if <code>resourceId == null</code>
+ * @throws ResourcePublicationException see
+ * {@link ResourceBinder#addResource(Object, MultivaluedMap)}
*/
- public boolean publishSingleton(InputStream in, ResourceId resourceId)
+ public void publishSingleton(InputStream in, ResourceId resourceId, MultivaluedMap<String, String> properties)
{
Object r = instantiator.instantiateScript(createCodeSource(in, resourceId.getId()), gcl);
- boolean answ = binder.bind(r);
- if (answ)
- {
- resources.put(resourceId, r.getClass());
- }
- return answ;
+ binder.addResource(r, properties);
+ resources.put(resourceId, r.getClass().getAnnotation(Path.class).value());
}
/**
@@ -174,13 +209,15 @@
*
* @param source groovy source code of RESTful service
* @param resourceId name of resource
- * @return <code>true</code> if resource was published and <code>false</code>
- * otherwise
+ * @param properties optional resource properties. This parameter may be
+ * <code>null</code>.
* @throws NullPointerException if <code>resourceId == null</code>
+ * @throws ResourcePublicationException see
+ * {@link ResourceBinder#addResource(Object, MultivaluedMap)}
*/
- public final boolean publishSingleton(String source, ResourceId resourceId)
+ public final void publishSingleton(String source, ResourceId resourceId, MultivaluedMap<String, String> properties)
{
- return publishSingleton(source, DEFAULT_CHARSET, resourceId);
+ publishSingleton(source, DEFAULT_CHARSET, resourceId, properties);
}
/**
@@ -191,14 +228,17 @@
* @param charset source string charset. May be <code>null</code> than
* default charset will be in use
* @param resourceId name of resource
- * @return <code>true</code> if resource was published and <code>false</code>
- * otherwise
+ * @param properties optional resource properties. This parameter may be
+ * <code>null</code>.
* @throws UnsupportedCharsetException if <code>charset</code> is unsupported
* @throws NullPointerException if <code>resourceId == null</code>
+ * @throws ResourcePublicationException see
+ * {@link ResourceBinder#addResource(Object, MultivaluedMap)}
*/
- public final boolean publishSingleton(String source, String charset, ResourceId resourceId)
+ public final void publishSingleton(String source, String charset, ResourceId resourceId,
+ MultivaluedMap<String, String> properties)
{
- return publishSingleton(source, charset == null ? DEFAULT_CHARSET : Charset.forName(charset), resourceId);
+ publishSingleton(source, charset == null ? DEFAULT_CHARSET : Charset.forName(charset), resourceId, properties);
}
/**
@@ -222,31 +262,33 @@
* otherwise, e.g. because there is not resource corresponded to
* supplied <code>resourceId</code>
*/
- public boolean unpublishResource(ResourceId resourceId)
+ public ObjectFactory<AbstractResourceDescriptor> unpublishResource(ResourceId resourceId)
{
- Class<?> clazz = resources.get(resourceId);
- boolean answ = false;
- if (clazz != null)
+ String path = resources.get(resourceId);
+ if (path == null)
{
- answ = binder.unbind(clazz);
+ return null;
}
- if (answ)
+ ObjectFactory<AbstractResourceDescriptor> resource = binder.removeResource(path);
+ if (resource != null)
{
resources.remove(resourceId);
}
- return answ;
+ return resource;
}
- private boolean publishPerRequest(String source, Charset charset, ResourceId resourceId)
+ private void publishPerRequest(String source, Charset charset, ResourceId resourceId,
+ MultivaluedMap<String, String> properties)
{
byte[] bytes = source.getBytes(charset);
- return publishPerRequest(new ByteArrayInputStream(bytes), resourceId);
+ publishPerRequest(new ByteArrayInputStream(bytes), resourceId, properties);
}
- private boolean publishSingleton(String source, Charset charset, ResourceId resourceId)
+ private void publishSingleton(String source, Charset charset, ResourceId resourceId,
+ MultivaluedMap<String, String> properties)
{
byte[] bytes = source.getBytes(charset);
- return publishSingleton(new ByteArrayInputStream(bytes), resourceId);
+ publishSingleton(new ByteArrayInputStream(bytes), resourceId, properties);
}
/**
Modified: ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyContextParamTest.java
===================================================================
--- ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyContextParamTest.java 2010-07-09 13:37:30 UTC (rev 2761)
+++ ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyContextParamTest.java 2010-07-09 13:39:29 UTC (rev 2762)
@@ -58,7 +58,7 @@
assertEquals(0, binder.getSize());
assertEquals(0, groovyPublisher.resources.size());
- groovyPublisher.publishPerRequest(script, new BaseResourceId("g1"));
+ groovyPublisher.publishPerRequest(script, new BaseResourceId("g1"), null);
assertEquals(1, binder.getSize());
assertEquals(1, groovyPublisher.resources.size());
Modified: ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyDependenciesTest.java
===================================================================
--- ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyDependenciesTest.java 2010-07-09 13:37:30 UTC (rev 2761)
+++ ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyDependenciesTest.java 2010-07-09 13:39:29 UTC (rev 2762)
@@ -48,7 +48,7 @@
public void testDependency() throws Exception
{
- groovyPublisher.publishPerRequest(script, new BaseResourceId("GMain1"));
+ groovyPublisher.publishPerRequest(script, new BaseResourceId("GMain1"), null);
ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
ContainerResponse resp = launcher.service("GET", "/a", "", null, null, writer, null);
assertEquals(200, resp.getStatus());
Modified: ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyExoComponentTest.java
===================================================================
--- ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyExoComponentTest.java 2010-07-09 13:37:30 UTC (rev 2761)
+++ ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovyExoComponentTest.java 2010-07-09 13:39:29 UTC (rev 2762)
@@ -67,9 +67,9 @@
assertEquals(0, groovyPublisher.resources.size());
if (singleton)
- groovyPublisher.publishSingleton(script, resourceId);
+ groovyPublisher.publishSingleton(script, resourceId, null);
else
- groovyPublisher.publishPerRequest(script, resourceId);
+ groovyPublisher.publishPerRequest(script, resourceId, null);
assertEquals(1, binder.getSize());
assertEquals(1, groovyPublisher.resources.size());
Modified: ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySecureRestrictionTest.java
===================================================================
--- ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySecureRestrictionTest.java 2010-07-09 13:37:30 UTC (rev 2761)
+++ ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySecureRestrictionTest.java 2010-07-09 13:39:29 UTC (rev 2762)
@@ -45,7 +45,7 @@
public void testReadSystemPropertyFail() throws Exception
{
- groovyPublisher.publishPerRequest(script, new BaseResourceId("g1"));
+ groovyPublisher.publishPerRequest(script, new BaseResourceId("g1"), null);
ByteArrayContainerResponseWriter writer = new ByteArrayContainerResponseWriter();
ContainerResponse resp = launcher.service("GET", "/a/b", "", null, null, writer, null);
assertEquals(500, resp.getStatus());
Modified: ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySimpleTest.java
===================================================================
--- ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySimpleTest.java 2010-07-09 13:37:30 UTC (rev 2761)
+++ ws/trunk/exo.ws.rest.ext/src/test/java/org/exoplatform/services/rest/ext/groovy/GroovySimpleTest.java 2010-07-09 13:39:29 UTC (rev 2762)
@@ -60,12 +60,13 @@
assertEquals(0, groovyPublisher.resources.size());
if (singleton)
- groovyPublisher.publishSingleton(script, resourceId);
+ groovyPublisher.publishSingleton(script, resourceId, null);
else
- groovyPublisher.publishPerRequest(script, resourceId);
+ groovyPublisher.publishPerRequest(script, resourceId, null);
assertEquals(1, binder.getSize());
assertEquals(1, groovyPublisher.resources.size());
+ assertTrue(groovyPublisher.isPublished(resourceId));
String cs =
binder.getResources().get(0).getObjectModel().getObjectClass().getProtectionDomain().getCodeSource()
13 years, 10 months
exo-jcr SVN: r2761 - in ws/trunk: exo.ws.rest.core/src/main/java/org/exoplatform/services/rest and 10 other directories.
by do-not-reply@jboss.org
Author: aparfonov
Date: 2010-07-09 09:37:30 -0400 (Fri, 09 Jul 2010)
New Revision: 2761
Added:
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourcePublicationException.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/DummySecurityContext.java
Modified:
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/ObjectModel.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ConstructorDescriptorImpl.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/FilterDescriptorImpl.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestDispatcher.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/method/DefaultMethodInvoker.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/ProviderDescriptorImpl.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/AbstractResourceDescriptorImpl.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/PathValue.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/resource/AbstractResourceDescriptor.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/ResourceLauncher.java
ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/uri/UriPattern.java
ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/BaseTest.java
ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/ResourceBinderTest.java
ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/uri/UriPatternTest.java
ws/trunk/pom.xml
Log:
EXOJCR-823:
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/ObjectModel.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/ObjectModel.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/ObjectModel.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -20,9 +20,11 @@
import java.util.List;
+import javax.ws.rs.core.MultivaluedMap;
+
/**
* Abstract description of object.
- *
+ *
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
* @version $Id: $
*/
@@ -30,7 +32,7 @@
{
/**
- * @return collections constructor, MAY return empty collection or null if
+ * @return collections constructor, return empty collection not null if
* object is singleton. There is no setter for this to add new
* ConstructorInjector use
* <code>ObjectModel.getConstructorDescriptors().add(ConstructorInjector)</code>
@@ -38,8 +40,8 @@
List<ConstructorDescriptor> getConstructorDescriptors();
/**
- * @return collections of object fields, MAY return empty collection or null
- * if object is singleton. There is no setter for this to add new
+ * @return collections of object fields, return empty collection not null if
+ * object is singleton. There is no setter for this to add new
* ConstructorInjector use
* <code>ObjectModel.getFieldInjectors().add(FieldInjector)</code>
*/
@@ -50,4 +52,19 @@
*/
Class<?> getObjectClass();
+ /**
+ * @param key
+ * @return property by key
+ * @see #getProperties()
+ */
+ List<String> getProperty(String key);
+
+ /**
+ * Optional attributes.
+ *
+ * @return all properties. If there is no any optional attributes then empty
+ * map returned never <code>null</code>
+ */
+ MultivaluedMap<String, String> getProperties();
+
}
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ConstructorDescriptorImpl.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ConstructorDescriptorImpl.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ConstructorDescriptorImpl.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -233,11 +233,14 @@
}
catch (Exception e)
{
+ String msg = "Not able resolve constructor parameter " + cp;
Class<?> ac = a.annotationType();
if (ac == MatrixParam.class || ac == QueryParam.class || ac == PathParam.class)
- throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND).build());
+ throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND).entity(msg).type(
+ MediaType.TEXT_PLAIN).build());
- throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).build());
+ throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity(msg).type(
+ MediaType.TEXT_PLAIN).build());
}
}
else
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/FilterDescriptorImpl.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/FilterDescriptorImpl.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/FilterDescriptorImpl.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -32,6 +32,7 @@
import java.util.List;
import javax.ws.rs.Path;
+import javax.ws.rs.core.MultivaluedMap;
/**
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
@@ -57,7 +58,7 @@
/**
* Filter class constructors.
- *
+ *
* @see ConstructorDescriptor
*/
private final List<ConstructorDescriptor> constructors;
@@ -67,6 +68,9 @@
*/
private final List<FieldInjector> fields;
+ /** Optional data. */
+ private MultivaluedMap<String, String> properties;
+
/**
* @param filterClass {@link Class} of filter
*/
@@ -173,6 +177,30 @@
/**
* {@inheritDoc}
*/
+ public MultivaluedMap<String, String> getProperties()
+ {
+ if (properties == null)
+ {
+ properties = new MultivaluedMapImpl();
+ }
+ return properties;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public List<String> getProperty(String key)
+ {
+ if (properties != null)
+ {
+ return properties.get(key);
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public UriPattern getUriPattern()
{
return uriPattern;
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestDispatcher.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestDispatcher.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestDispatcher.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -62,14 +62,10 @@
public class RequestDispatcher
{
- /**
- * Logger.
- */
+ /** Logger. */
private static final Log LOG = ExoLogger.getLogger("exo.ws.rest.core.RequestDispatcher");
- /**
- * See {@link ResourceBinder}.
- */
+ /** See {@link ResourceBinder}. */
protected final ResourceBinder resourceBinder;
private final MethodInvokerFactory invokerFactory;
@@ -370,7 +366,6 @@
if (returnType == void.class || o == null)
{
response.setResponse(Response.noContent().build());
-
}
else if (Response.class.isAssignableFrom(returnType))
{
@@ -380,19 +375,14 @@
{
r.getMetadata().putSingle(HttpHeaders.CONTENT_TYPE, contentType);
}
-
response.setResponse(r);
-
}
else if (GenericEntity.class.isAssignableFrom(returnType))
{
-
response.setResponse(Response.ok(o, contentType).build());
-
}
else
{
-
response.setResponse(Response.ok(o, contentType).build());
}
@@ -565,60 +555,28 @@
}
/**
- * Get root resource
+ * Get root resource.
*
* @param parameterValues is taken from context
* @param requestPath is taken from context
* @return root resource
+ * @throws WebApplicationException if there is no matched root resources.
+ * Exception with prepared error response with 'Not Found' status
*/
protected ObjectFactory<AbstractResourceDescriptor> getRootResourse(List<String> parameterValues, String requestPath)
{
- ObjectFactory<AbstractResourceDescriptor> resourceFactory = null;
- List<ObjectFactory<AbstractResourceDescriptor>> resources = resourceBinder.getResources();
- // be sure no new entries added
- synchronized (resources)
- {
- for (ObjectFactory<AbstractResourceDescriptor> rc : resources)
- {
- if (rc.getObjectModel().getUriPattern().match(requestPath, parameterValues))
- {
- // all times will at least 1
- int len = parameterValues.size();
- // If capturing group contains last element and this element is
- // neither null nor '/' then ResourceClass must contains at least one
- // sub-resource method or sub-resource locator.
- if (parameterValues.get(len - 1) != null && !parameterValues.get(len - 1).equals("/"))
- {
- int subresnum =
- rc.getObjectModel().getSubResourceMethods().size()
- + rc.getObjectModel().getSubResourceLocators().size();
- if (subresnum == 0)
- {
- continue;
- }
- }
- resourceFactory = rc;
- break;
- }
- }
-
- }
-
+ ObjectFactory<AbstractResourceDescriptor> resourceFactory =
+ resourceBinder.getMatchedResource(requestPath, parameterValues);
if (resourceFactory == null)
{
-
if (LOG.isDebugEnabled())
{
LOG.debug("Root resource not found for " + requestPath);
}
-
// Stop here, there is no matched root resource
throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND).entity(
"There is no any resources matched to request path " + requestPath).type(MediaType.TEXT_PLAIN).build());
}
- else
- {
- return resourceFactory;
- }
+ return resourceFactory;
}
}
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/RequestHandlerImpl.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -18,21 +18,6 @@
*/
package org.exoplatform.services.rest.impl;
-import java.io.File;
-import java.io.OutputStream;
-import java.io.PrintWriter;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-
-import javax.ws.rs.WebApplicationException;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.StreamingOutput;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.ext.ExceptionMapper;
-
import org.exoplatform.container.component.ComponentPlugin;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.container.xml.ValueParam;
@@ -53,6 +38,21 @@
import org.exoplatform.services.rest.provider.EntityProvider;
import org.picocontainer.Startable;
+import java.io.File;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.StreamingOutput;
+import javax.ws.rs.core.Response.ResponseBuilder;
+import javax.ws.rs.ext.ExceptionMapper;
+
/**
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
* @version $Id: $
@@ -67,7 +67,7 @@
/**
* Application properties. Properties from this map will be copied to ApplicationContext
- * and may be accessible via method {@link ApplicationContextImpl#getProperties()}.
+ * and may be accessible via method {@link ApplicationContextImpl#getProperties()}.
*/
private static final Map<String, String> properties = new HashMap<String, String>();
@@ -90,7 +90,7 @@
/**
* Constructs new instance of {@link RequestHandler}.
- *
+ *
* @param dispatcher See {@link RequestDispatcher}
* @param params init parameters
*/
@@ -248,7 +248,7 @@
/**
* Create error response with specified status and body message.
- *
+ *
* @param status response status
* @param message response message
* @return response
@@ -267,7 +267,7 @@
/**
* Get JAXR header for response status.
- *
+ *
* @param status response status
* @return JAXRS header or null.
*/
@@ -372,7 +372,7 @@
/**
* Processing {@link ComponentPlugin} for injection external components.
- *
+ *
* @param plugin See {@link ComponentPlugin}
*/
@SuppressWarnings("unchecked")
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourceBinder.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -22,12 +22,15 @@
import org.exoplatform.container.ExoContainerContext;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
+import org.exoplatform.services.rest.ApplicationContext;
import org.exoplatform.services.rest.Filter;
import org.exoplatform.services.rest.ObjectFactory;
+import org.exoplatform.services.rest.ObjectModel;
import org.exoplatform.services.rest.PerRequestObjectFactory;
import org.exoplatform.services.rest.RequestFilter;
import org.exoplatform.services.rest.ResponseFilter;
import org.exoplatform.services.rest.SingletonObjectFactory;
+import org.exoplatform.services.rest.impl.method.DefaultMethodInvoker;
import org.exoplatform.services.rest.impl.method.MethodInvokerFactory;
import org.exoplatform.services.rest.impl.resource.AbstractResourceDescriptorImpl;
import org.exoplatform.services.rest.impl.resource.ResourceDescriptorValidator;
@@ -45,6 +48,7 @@
import javax.ws.rs.Path;
import javax.ws.rs.core.Application;
+import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.MessageBodyReader;
@@ -64,60 +68,60 @@
public class ResourceBinder
{
- /**
- * Logger.
- */
+ /** Logger. */
private static final Log LOG = ExoLogger.getLogger("exo.ws.rest.core.ResourceBinder");
+ /** Resource's comparator. */
protected static final Comparator<ObjectFactory<AbstractResourceDescriptor>> RESOURCE_COMPARATOR =
- new ResourceComparator();
-
- /**
- * Compare two {@link SingletonResourceFactory}.
- */
- private static final class ResourceComparator implements Comparator<ObjectFactory<AbstractResourceDescriptor>>
- {
- /**
- * Compare two ResourceClass for order.
- *
- * @param o1 first ResourceClass to be compared
- * @param o2 second ResourceClass to be compared
- * @return positive , zero or negative dependent of {@link UriPattern}
- * comparison
- * @see Comparator#compare(Object, Object)
- * @see UriPattern
- * @see UriPattern#URIPATTERN_COMPARATOR
- */
- public int compare(ObjectFactory<AbstractResourceDescriptor> o1, ObjectFactory<AbstractResourceDescriptor> o2)
+ new Comparator<ObjectFactory<AbstractResourceDescriptor>>()
{
- return UriPattern.URIPATTERN_COMPARATOR.compare(o1.getObjectModel().getUriPattern(), o2.getObjectModel()
- .getUriPattern());
- }
- };
+ /**
+ * Compare two ResourceClass for order.
+ *
+ * @param o1 first ResourceClass to be compared
+ * @param o2 second ResourceClass to be compared
+ * @return positive , zero or negative dependent of {@link UriPattern}
+ * comparison
+ * @see Comparator#compare(Object, Object)
+ * @see UriPattern
+ * @see UriPattern#URIPATTERN_COMPARATOR
+ */
+ public int compare(ObjectFactory<AbstractResourceDescriptor> o1, ObjectFactory<AbstractResourceDescriptor> o2)
+ {
+ return UriPattern.URIPATTERN_COMPARATOR.compare(o1.getObjectModel().getUriPattern(), o2.getObjectModel()
+ .getUriPattern());
+ }
+ };
- /**
- * Root resource descriptors.
- */
- protected final List<ObjectFactory<AbstractResourceDescriptor>> rootResources =
- new ArrayList<ObjectFactory<AbstractResourceDescriptor>>();
-
- /**
- * Validator.
- */
+ /** Validator. */
protected final ResourceDescriptorVisitor rdv = ResourceDescriptorValidator.getInstance();
+ /** Amount of available root resources. */
protected int size = 0;
+ /** @see RuntimeDelegate */
+ protected final RuntimeDelegate rd;
+
/**
- * @see RuntimeDelegate
+ * Producer of methods invokers. If not specified then
+ * {@link DefaultMethodInvoker} will be in use.
*/
- protected final RuntimeDelegate rd;
-
protected final MethodInvokerFactory invokerFactory;
+ /** List of all available root resources. */
+ protected final List<ObjectFactory<AbstractResourceDescriptor>> rootResources =
+ new ArrayList<ObjectFactory<AbstractResourceDescriptor>>();
+
+ public ResourceBinder(ExoContainerContext containerContext) throws Exception
+ {
+ this(containerContext, null);
+ }
+
/**
* @param containerContext eXo container context
+ * @param invokerFactory method invoker producer
* @throws Exception if can't set instance of {@link RuntimeDelegate}
+ * @see MethodInvokerFactory
*/
@SuppressWarnings("unchecked")
public ResourceBinder(ExoContainerContext containerContext, MethodInvokerFactory invokerFactory) throws Exception
@@ -127,8 +131,8 @@
// Initialize RuntimeDelegate instance
// This is first component in life cycle what needs.
// TODO better solution to initialize RuntimeDelegate
- rd = new RuntimeDelegateImpl();
- RuntimeDelegate.setInstance(rd);
+ RuntimeDelegate.setInstance(new RuntimeDelegateImpl());
+ rd = RuntimeDelegate.getInstance();
ExoContainer container = containerContext.getContainer();
@@ -150,16 +154,17 @@
// process them to be add as root resources.
for (Object resource : container.getComponentInstancesOfType(ResourceContainer.class))
{
- bind(resource);
+ try
+ {
+ addResource(resource, null);
+ }
+ catch (Exception e)
+ {
+ LOG.error("Failed add JAX-RS resource " + resource.getClass().getName(), e);
+ }
}
-
}
- public ResourceBinder(ExoContainerContext containerContext) throws Exception
- {
- this(containerContext, null);
- }
-
/**
* @param application Application
* @see Application
@@ -208,7 +213,7 @@
}
else
{
- bind(obj); // singleton resource
+ addResource(obj, null); // singleton resource
}
}
for (Class clazz : application.getClasses())
@@ -251,221 +256,252 @@
}
else
{
- bind(clazz); // per-request resource
+ addResource(clazz, null); // per-request resource
}
}
}
/**
- * Register supplied Object as root resource if it has valid JAX-RS
- * annotations and no one resource with the same UriPattern already
+ * Register supplied class as per-request root resource if it has valid
+ * JAX-RS annotations and no one resource with the same UriPattern already
* registered.
*
- * @param resource candidate to be root resource
- * @return true if resource was bound and false if resource was not bound
- * cause it is not root resource
+ * @param resourceClass class of candidate to be root resource
+ * @param properties optional resource properties. It may contains additional
+ * info about resource, e.g. description of resource, its
+ * responsibility, etc. This info can be retrieved
+ * {@link ObjectModel#getProperties()}. This parameter may be
+ * <code>null</code>
+ * @throws ResourcePublicationException if resource can't be published
+ * because to:
+ * <ul>
+ * <li>@javax.ws.rs.Path annotation is missing</li>
+ * <li>resource has not any method with JAX-RS annotations</li>
+ * <li>JAX-RS annotations are ambiguous or invalid</li>
+ * <li>resource with the sane {@link UriPattern} already registered</li>
+ * </ul>
+ * @see ObjectModel#getProperties()
+ * @see ObjectModel#getProperty(String)
*/
- public boolean bind(final Object resource)
+ public void addResource(final Class<?> resourceClass, MultivaluedMap<String, String> properties)
{
- final Path path = resource.getClass().getAnnotation(Path.class);
-
- AbstractResourceDescriptor descriptor = null;
- if (path != null)
+ Path path = resourceClass.getAnnotation(Path.class);
+ if (path == null)
{
- try
- {
- descriptor = new AbstractResourceDescriptorImpl(resource, invokerFactory);
- }
- catch (Exception e)
- {
- String msg = "Unexpected error occurs when process resource class " + resource.getClass().getName();
- LOG.error(msg, e);
- return false;
- }
+ throw new ResourcePublicationException("Resource class " + resourceClass.getName()
+ + " it is not root resource. " + "Path annotation javax.ws.rs.Path is not specified for this class.");
}
- else
+ try
{
- String msg =
- "Resource class " + resource.getClass().getName() + " it is not root resource. "
- + "Path annotation javax.ws.rs.Path is not specified for this class.";
- LOG.warn(msg);
- return false;
+ AbstractResourceDescriptor descriptor = new AbstractResourceDescriptorImpl(resourceClass, invokerFactory);
+ // validate AbstractResourceDescriptor
+ descriptor.accept(rdv);
+ if (properties != null)
+ descriptor.getProperties().putAll(properties);
+ addResource(new PerRequestObjectFactory<AbstractResourceDescriptor>(descriptor));
}
+ catch (Exception e)
+ {
+ throw new ResourcePublicationException(e.getMessage());
+ }
+ }
- // validate AbstractResourceDescriptor
+ /**
+ * Register supplied Object as singleton root resource if it has valid JAX-RS
+ * annotations and no one resource with the same UriPattern already
+ * registered.
+ *
+ * @param resource candidate to be root resource
+ * @param properties optional resource properties. It may contains additional
+ * info about resource, e.g. description of resource, its
+ * responsibility, etc. This info can be retrieved
+ * {@link ObjectModel#getProperties()}. This parameter may be
+ * <code>null</code>
+ * @throws ResourcePublicationException if resource can't be published
+ * because to:
+ * <ul>
+ * <li>@javax.ws.rs.Path annotation is missing</li>
+ * <li>resource has not any method with JAX-RS annotations</li>
+ * <li>JAX-RS annotations are ambiguous or invalid</li>
+ * <li>resource with the sane {@link UriPattern} already registered</li>
+ * </ul>
+ * @see ObjectModel#getProperties()
+ * @see ObjectModel#getProperty(String)
+ */
+ public void addResource(final Object resource, MultivaluedMap<String, String> properties)
+ {
+ Path path = resource.getClass().getAnnotation(Path.class);
+ if (path == null)
+ {
+ throw new ResourcePublicationException("Resource class " + resource.getClass().getName()
+ + " it is not root resource. " + "Path annotation javax.ws.rs.Path is not specified for this class.");
+ }
try
{
+ AbstractResourceDescriptor descriptor = new AbstractResourceDescriptorImpl(resource, invokerFactory);
+ // validate AbstractResourceDescriptor
descriptor.accept(rdv);
+ if (properties != null)
+ descriptor.getProperties().putAll(properties);
+ addResource(new SingletonObjectFactory<AbstractResourceDescriptor>(descriptor, resource));
}
catch (Exception e)
{
- LOG.error("Validation of root resource failed. ", e);
- return false;
+ throw new ResourcePublicationException(e.getMessage());
}
+ }
+ /**
+ * Register supplied root resource if no one resource with the same
+ * UriPattern already registered.
+ *
+ * @param resourceFactory root resource
+ * @throws ResourcePublicationException if resource can't be published
+ * because resource with the sane {@link UriPattern} already
+ * registered
+ */
+ public void addResource(final ObjectFactory<AbstractResourceDescriptor> resourceFactory)
+ {
+ UriPattern pattern = resourceFactory.getObjectModel().getUriPattern();
synchronized (rootResources)
{
- // check does exist other resource with the same URI pattern
- for (ObjectFactory<AbstractResourceDescriptor> exist : rootResources)
+ for (ObjectFactory<AbstractResourceDescriptor> resource : rootResources)
{
- if (exist.getObjectModel().getUriPattern().equals(descriptor.getUriPattern()))
+ if (resource.getObjectModel().getUriPattern().equals(resourceFactory.getObjectModel().getUriPattern()))
{
- String msg =
- "Resource class " + descriptor.getObjectClass().getName() + " can't be registered. Resource class "
- + exist.getClass().getName() + " with the same pattern "
- + exist.getObjectModel().getUriPattern().getTemplate() + " already registered.";
- LOG.warn(msg);
- return false;
+ throw new ResourcePublicationException("Resource class "
+ + resourceFactory.getObjectModel().getObjectClass().getName()
+ + " can't be registered. Resource class " + resource.getObjectModel().getObjectClass().getName()
+ + " with the same pattern " + pattern + " already registered.");
}
}
-
- // Singleton resource
- ObjectFactory<AbstractResourceDescriptor> res =
- new SingletonObjectFactory<AbstractResourceDescriptor>(descriptor, resource);
- rootResources.add(res);
+ rootResources.add(resourceFactory);
Collections.sort(rootResources, RESOURCE_COMPARATOR);
- LOG.info("Bind new resource " + res.getObjectModel().getUriPattern().getTemplate() + " : "
- + descriptor.getObjectClass());
+ size++;
+ if (LOG.isDebugEnabled())
+ LOG.debug("Add resource: " + resourceFactory.getObjectModel());
}
- size++;
- return true;
}
/**
+ * Register root resource.
+ *
* @param resourceClass class of candidate to be root resource
* @return true if resource was bound and false if resource was not bound
* cause it is not root resource
+ * @deprecated use {@link #addResource(Class, MultivaluedMap)} instead
*/
public boolean bind(final Class<?> resourceClass)
{
- final Path path = resourceClass.getAnnotation(Path.class);
-
- AbstractResourceDescriptor descriptor = null;
- if (path != null)
+ try
{
- try
- {
- descriptor = new AbstractResourceDescriptorImpl(resourceClass, invokerFactory);
- }
- catch (Exception e)
- {
- String msg = "Unexpected error occurs when process resource class " + resourceClass.getName();
- LOG.error(msg, e);
- return false;
- }
+ addResource(resourceClass, null);
+ return true;
}
- else
+ catch (ResourcePublicationException e)
{
- String msg =
- "Resource class " + resourceClass.getName() + " it is not root resource. "
- + "Path annotation javax.ws.rs.Path is not specified for this class.";
- LOG.warn(msg);
+ LOG.warn(e.getMessage());
return false;
}
+ }
- // validate AbstractResourceDescriptor
+ /**
+ * Register supplied Object as singleton root resource if it has valid JAX-RS
+ * annotations and no one resource with the same UriPattern already
+ * registered.
+ *
+ * @param resource candidate to be root resource
+ * @return true if resource was bound and false if resource was not bound
+ * cause it is not root resource
+ * @deprecated use {@link #addResource(Object, MultivaluedMap)} instead
+ */
+ public boolean bind(final Object resource)
+ {
try
{
- descriptor.accept(rdv);
+ addResource(resource, null);
+ return true;
}
- catch (Exception e)
+ catch (ResourcePublicationException e)
{
- LOG.error("Validation of root resource failed. ", e);
+ LOG.warn(e.getMessage());
return false;
}
-
- synchronized (rootResources)
- {
- // check does exist other resource with the same URI pattern
- for (ObjectFactory<AbstractResourceDescriptor> exist : rootResources)
- {
- AbstractResourceDescriptor existDescriptor = exist.getObjectModel();
- if (exist.getObjectModel().getUriPattern().equals(descriptor.getUriPattern()))
- {
-
- String msg =
- "Resource class " + descriptor.getObjectClass().getName() + " can't be registered. Resource class "
- + existDescriptor.getObjectClass().getName() + " with the same pattern "
- + exist.getObjectModel().getUriPattern().getTemplate() + " already registered.";
- LOG.warn(msg);
- return false;
- }
- }
- // per-request resource
- ObjectFactory<AbstractResourceDescriptor> res =
- new PerRequestObjectFactory<AbstractResourceDescriptor>(descriptor);
- rootResources.add(res);
- Collections.sort(rootResources, RESOURCE_COMPARATOR);
- LOG.info("Bind new resource " + res.getObjectModel().getUriPattern().getRegex() + " : " + resourceClass);
- }
- size++;
- return true;
}
/**
- * Remove root resource of supplied class from root resource collection.
- *
- * @param clazz root resource class
- * @return true if resource was unbound false otherwise
+ * Clear the list of ResourceContainer description.
*/
- @SuppressWarnings("unchecked")
- public boolean unbind(Class clazz)
+ public void clear()
{
synchronized (rootResources)
{
- Iterator<ObjectFactory<AbstractResourceDescriptor>> i = rootResources.iterator();
- while (i.hasNext())
- {
- ObjectFactory<AbstractResourceDescriptor> res = i.next();
- Class c = res.getObjectModel().getObjectClass();
- if (clazz.equals(c))
- {
- i.remove();
- LOG.info("Remove ResourceContainer " + res.getObjectModel().getUriPattern().getTemplate() + " : " + c);
- size--;
- return true;
- }
- }
- return false;
+ rootResources.clear();
+ size = 0;
}
}
- public boolean unbind(String uriTemplate)
+ /**
+ * Get root resource matched to <code>requestPath</code>.
+ *
+ * @param requestPath request path
+ * @param parameterValues see {@link ApplicationContext#getParameterValues()}
+ * @return root resource matched to <code>requestPath</code> or
+ * <code>null</code>
+ */
+ public ObjectFactory<AbstractResourceDescriptor> getMatchedResource(String requestPath, List<String> parameterValues)
{
+ ObjectFactory<AbstractResourceDescriptor> resourceFactory = null;
synchronized (rootResources)
{
- Iterator<ObjectFactory<AbstractResourceDescriptor>> i = rootResources.iterator();
- while (i.hasNext())
+ for (ObjectFactory<AbstractResourceDescriptor> resource : rootResources)
{
- ObjectFactory<AbstractResourceDescriptor> res = i.next();
- String t = res.getObjectModel().getUriPattern().getTemplate();
- if (t.equals(uriTemplate))
+ if (resource.getObjectModel().getUriPattern().match(requestPath, parameterValues))
{
- i.remove();
- LOG.info("Remove ResourceContainer " + res.getObjectModel().getUriPattern().getTemplate());
- size--;
- return true;
+ // all times will at least 1
+ int len = parameterValues.size();
+ // If capturing group contains last element and this element is
+ // neither null nor '/' then ResourceClass must contains at least one
+ // sub-resource method or sub-resource locator.
+ if (parameterValues.get(len - 1) != null && !parameterValues.get(len - 1).equals("/"))
+ {
+ int subresnum =
+ resource.getObjectModel().getSubResourceMethods().size()
+ + resource.getObjectModel().getSubResourceLocators().size();
+ if (subresnum == 0)
+ continue;
+ }
+ resourceFactory = resource;
+ break;
}
}
- return false;
}
+ return resourceFactory;
}
/**
- * Clear the list of ResourceContainer description.
+ * @return all registered root resources
*/
- public void clear()
+ public List<ObjectFactory<AbstractResourceDescriptor>> getResources()
{
- rootResources.clear();
- size = 0;
+ return rootResources;
}
/**
* @return all registered root resources
*/
- public List<ObjectFactory<AbstractResourceDescriptor>> getResources()
+ @Deprecated
+ public List<AbstractResourceDescriptor> getRootResources()
{
- return rootResources;
+ List<AbstractResourceDescriptor> l = new ArrayList<AbstractResourceDescriptor>(size);
+ synchronized (rootResources)
+ {
+ for (ObjectFactory<AbstractResourceDescriptor> f : rootResources)
+ {
+ l.add(f.getObjectModel());
+ }
+ }
+ return l;
}
/**
@@ -477,20 +513,98 @@
}
/**
- * @return all registered root resources
+ * Remove root resource of supplied class from root resource collection.
+ *
+ * @param clazz root resource class
+ * @return removed resource or <code>null</code> if resource of specified
+ * class not found
*/
- @Deprecated
- public List<AbstractResourceDescriptor> getRootResources()
+ @SuppressWarnings("unchecked")
+ public ObjectFactory<AbstractResourceDescriptor> removeResource(Class clazz)
{
- List<AbstractResourceDescriptor> l = new ArrayList<AbstractResourceDescriptor>(rootResources.size());
+ ObjectFactory<AbstractResourceDescriptor> resource = null;
synchronized (rootResources)
{
- for (ObjectFactory<AbstractResourceDescriptor> f : rootResources)
+ for (Iterator<ObjectFactory<AbstractResourceDescriptor>> iter = rootResources.iterator(); iter.hasNext()
+ && resource == null;)
{
- l.add(f.getObjectModel());
+ ObjectFactory<AbstractResourceDescriptor> next = iter.next();
+ Class<?> resourceClass = next.getObjectModel().getObjectClass();
+ if (clazz.equals(resourceClass))
+ {
+ iter.remove();
+ resource = next;
+ }
}
+ if (resource != null)
+ {
+ size--;
+ if (LOG.isDebugEnabled())
+ LOG.debug("Remove resource: " + resource.getObjectModel());
+ }
}
- return l;
+ return resource;
}
+ /**
+ * Remove root resource with specified UriTemplate from root resource
+ * collection.
+ *
+ * @param path root resource path
+ * @return removed resource or <code>null</code> if resource for specified
+ * template not found
+ */
+ public ObjectFactory<AbstractResourceDescriptor> removeResource(String path)
+ {
+ ObjectFactory<AbstractResourceDescriptor> resource = null;
+ UriPattern pattern = new UriPattern(path);
+ synchronized (rootResources)
+ {
+ for (Iterator<ObjectFactory<AbstractResourceDescriptor>> iter = rootResources.iterator(); iter.hasNext()
+ && resource == null;)
+ {
+ ObjectFactory<AbstractResourceDescriptor> next = iter.next();
+ UriPattern resourcePattern = next.getObjectModel().getUriPattern();
+ if (pattern.equals(resourcePattern))
+ {
+ iter.remove();
+ resource = next;
+ }
+ }
+ if (resource != null)
+ {
+ size--;
+ if (LOG.isDebugEnabled())
+ LOG.debug("Remove resource: " + resource.getObjectModel());
+ }
+ }
+ return resource;
+ }
+
+ /**
+ * Remove root resource of supplied class from root resource collection.
+ *
+ * @param clazz root resource class
+ * @return true if resource was unbound false otherwise
+ * @deprecated use {@link #removeResource(Class)}
+ */
+ @SuppressWarnings("unchecked")
+ public boolean unbind(Class clazz)
+ {
+ return null != removeResource(clazz);
+ }
+
+ /**
+ * Remove root resource with specified UriTemplate from root resource
+ * collection.
+ *
+ * @param path root resource path
+ * @return true if resource was unbound false otherwise
+ * @deprecated use {@link #removeResource(String)} instead
+ */
+ public boolean unbind(String path)
+ {
+ return null != removeResource(path);
+ }
+
}
Added: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourcePublicationException.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourcePublicationException.java (rev 0)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourcePublicationException.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -0,0 +1,39 @@
+/**
+ * Copyright (C) 2010 eXo Platform SAS.
+ *
+ * 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.exoplatform.services.rest.impl;
+
+/**
+ * Throws if root resource can't be published, e.g. resource can't be registered
+ * because to conflict of root path
+ *
+ * @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+public class ResourcePublicationException extends RuntimeException
+{
+
+ private static final long serialVersionUID = -7293299406099524107L;
+
+ public ResourcePublicationException(String message)
+ {
+ super(message);
+ }
+
+}
Property changes on: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/ResourcePublicationException.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/method/DefaultMethodInvoker.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/method/DefaultMethodInvoker.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/method/DefaultMethodInvoker.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -28,15 +28,16 @@
import org.exoplatform.services.rest.method.MethodInvokerFilter;
import org.exoplatform.services.rest.resource.GenericMethodResource;
-import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
+import java.util.List;
import javax.ws.rs.MatrixParam;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
@@ -84,13 +85,16 @@
catch (Exception e)
{
+ String msg = "Not able resolve method parameter " + mp;
Class<?> ac = a.annotationType();
if (ac == MatrixParam.class || ac == QueryParam.class || ac == PathParam.class)
{
- throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND).build());
+ throw new WebApplicationException(e, Response.status(Response.Status.NOT_FOUND).entity(msg).type(
+ MediaType.TEXT_PLAIN).build());
}
- throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).build());
+ throw new WebApplicationException(e, Response.status(Response.Status.BAD_REQUEST).entity(msg).type(
+ MediaType.TEXT_PLAIN).build());
}
@@ -106,37 +110,62 @@
else
{
MediaType contentType = context.getContainerRequest().getMediaType();
- MultivaluedMap<String, String> headers = context.getContainerRequest().getRequestHeaders();
MessageBodyReader entityReader =
context.getProviders().getMessageBodyReader(mp.getParameterClass(), mp.getGenericType(),
mp.getAnnotations(), contentType);
if (entityReader == null)
{
- if (LOG.isDebugEnabled())
+ List<String> contentLength =
+ context.getContainerRequest().getRequestHeader(HttpHeaders.CONTENT_LENGTH);
+ int length = 0;
+ if (contentLength != null && contentLength.size() > 0)
{
- LOG.warn("Unsupported media type. ");
+ length = Integer.parseInt(contentLength.get(0));
}
- throw new WebApplicationException(Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).build());
+ if (contentType == null && length == 0)
+ {
+ // If both Content-Length and Content-Type is not set
+ // consider there is no content. In this case we not able
+ // to determine reader required for content but
+ // 'Unsupported Media Type' (415) status looks strange if
+ // there is no content at all.
+ p[i++] = null;
+ }
+ else
+ {
+ String msg =
+ "Media type " + contentType + " is not supported. There is no corresponded entity reader.";
+ if (LOG.isDebugEnabled())
+ {
+ LOG.warn(msg);
+ }
+ throw new WebApplicationException(Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE).entity(
+ msg).type(MediaType.TEXT_PLAIN).build());
+ }
}
-
- try
+ else
{
- p[i++] =
- entityReader.readFrom(mp.getParameterClass(), mp.getGenericType(), mp.getAnnotations(),
- contentType, headers, entityStream);
- }
- catch (IOException e)
- {
-
- if (LOG.isDebugEnabled())
+ try
{
- e.printStackTrace();
+ MultivaluedMap<String, String> headers = context.getContainerRequest().getRequestHeaders();
+ p[i++] =
+ entityReader.readFrom(mp.getParameterClass(), mp.getGenericType(), mp.getAnnotations(),
+ contentType, headers, entityStream);
}
-
- throw new InternalException(e);
-
+ catch (Exception e)
+ {
+ if (LOG.isDebugEnabled())
+ {
+ e.printStackTrace();
+ }
+ if (e instanceof WebApplicationException)
+ {
+ throw (WebApplicationException)e;
+ }
+ throw new InternalException(e);
+ }
}
}
}
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/ProviderDescriptorImpl.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/ProviderDescriptorImpl.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/provider/ProviderDescriptorImpl.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -23,6 +23,7 @@
import org.exoplatform.services.rest.FieldInjector;
import org.exoplatform.services.rest.impl.ConstructorDescriptorImpl;
import org.exoplatform.services.rest.impl.FieldInjectorImpl;
+import org.exoplatform.services.rest.impl.MultivaluedMapImpl;
import org.exoplatform.services.rest.impl.header.MediaTypeHelper;
import org.exoplatform.services.rest.provider.ProviderDescriptor;
import org.exoplatform.services.rest.resource.ResourceDescriptorVisitor;
@@ -35,6 +36,7 @@
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
/**
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
@@ -50,7 +52,7 @@
/**
* Resource class constructors.
- *
+ *
* @see {@link ConstructorDescriptor}
*/
private final List<ConstructorDescriptor> constructors;
@@ -72,6 +74,9 @@
*/
private final List<MediaType> produces;
+ /** Optional data. */
+ private MultivaluedMap<String, String> properties;
+
/**
* @param providerClass provider class
*/
@@ -168,6 +173,30 @@
/**
* {@inheritDoc}
*/
+ public MultivaluedMap<String, String> getProperties()
+ {
+ if (properties == null)
+ {
+ properties = new MultivaluedMapImpl();
+ }
+ return properties;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public List<String> getProperty(String key)
+ {
+ if (properties != null)
+ {
+ return properties.get(key);
+ }
+ return null;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
public List<MediaType> produces()
{
return produces;
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/AbstractResourceDescriptorImpl.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/AbstractResourceDescriptorImpl.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/AbstractResourceDescriptorImpl.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -131,9 +131,7 @@
*/
private final List<FieldInjector> fields;
- /**
- * Optional data
- */
+ /** Optional data. */
private MultivaluedMap<String, String> properties;
private final MethodInvokerFactory invokerFactory;
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/PathValue.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/PathValue.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/impl/resource/PathValue.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -20,7 +20,7 @@
/**
* Describe the Path annotation, see {@link javax.ws.rs.Path}.
- *
+ *
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
* @version $Id: $
*/
@@ -53,7 +53,7 @@
*/
public String toString()
{
- return "( " + path + " )";
+ return "(" + path + ")";
}
}
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/resource/AbstractResourceDescriptor.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/resource/AbstractResourceDescriptor.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/resource/AbstractResourceDescriptor.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -22,14 +22,10 @@
import org.exoplatform.services.rest.impl.resource.PathValue;
import org.exoplatform.services.rest.uri.UriPattern;
-import java.util.List;
-
-import javax.ws.rs.core.MultivaluedMap;
-
/**
* Describe Resource Class or Root Resource Class. Resource Class is any Java
* class that uses JAX-RS annotations to implement corresponding Web resource.
- *
+ *
* @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
* @version $Id: $
*/
@@ -58,21 +54,6 @@
* @return sub-resource methods
*/
SubResourceMethodMap getSubResourceMethods();
-
- /**
- * Optional data
- *
- * @param key
- * @return property by key
- */
- List<String> getProperty(String key);
-
- /**
- * Optional data
- *
- * @return all properties
- */
- MultivaluedMap<String,String> getProperties();
/**
* @return See {@link UriPattern}
Added: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/DummySecurityContext.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/DummySecurityContext.java (rev 0)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/DummySecurityContext.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -0,0 +1,95 @@
+/**
+ * Copyright (C) 2010 eXo Platform SAS.
+ *
+ * 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.exoplatform.services.rest.tools;
+
+import org.exoplatform.services.rest.impl.ContainerRequest;
+
+import java.io.InputStream;
+import java.net.URI;
+import java.security.Principal;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.ws.rs.core.MultivaluedMap;
+
+/**
+ * @author <a href="mailto:andrew00x@gmail.com">Andrey Parfonov</a>
+ * @version $Id$
+ */
+class DummySecurityContext extends ContainerRequest
+{
+ private DummyPrincipal dummyPrincipal;
+
+ public DummySecurityContext(String method, URI requestUri, URI baseUri, InputStream entityStream,
+ MultivaluedMap<String, String> httpHeaders)
+ {
+ super(method, requestUri, baseUri, entityStream, httpHeaders);
+ dummyPrincipal = new DummyPrincipal();
+ }
+
+ @Override
+ public String getAuthenticationScheme()
+ {
+ // Consider as Basic Authentication
+ return BASIC_AUTH;
+ }
+
+ @Override
+ public Principal getUserPrincipal()
+ {
+ return dummyPrincipal;
+ }
+
+ @Override
+ public boolean isSecure()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean isUserInRole(String role)
+ {
+ return dummyPrincipal.isUserInRole(role);
+ }
+
+ class DummyPrincipal implements Principal
+ {
+
+ Set<String> roles = new HashSet<String>();
+
+ public DummyPrincipal()
+ {
+ roles.add("administrators");
+ roles.add("users");
+ }
+
+ public String getName()
+ {
+ return "root";
+ }
+
+ public boolean isUserInRole(String role)
+ {
+ return roles.contains(role);
+ }
+
+ }
+
+}
Property changes on: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/DummySecurityContext.java
___________________________________________________________________
Name: svn:mime-type
+ text/plain
Name: svn:keywords
+ Id
Name: svn:eol-style
+ native
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/ResourceLauncher.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/ResourceLauncher.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/tools/ResourceLauncher.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -77,8 +77,10 @@
if (writer == null)
writer = new DummyContainerResponseWriter();
+ // ContainerRequest request =
+ // new ContainerRequest(method, new URI(requestURI), new URI(baseURI), in, new InputHeadersMap(headers));
ContainerRequest request =
- new ContainerRequest(method, new URI(requestURI), new URI(baseURI), in, new InputHeadersMap(headers));
+ new DummySecurityContext(method, new URI(requestURI), new URI(baseURI), in, new InputHeadersMap(headers));
ContainerResponse response = new ContainerResponse(writer);
requestHandler.handleRequest(request, response);
return response;
Modified: ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/uri/UriPattern.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/uri/UriPattern.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/main/java/org/exoplatform/services/rest/uri/UriPattern.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -39,10 +39,10 @@
* Sort the templates according to the string comparison of the template
* regular expressions.
* <p>
- * JSR-311 specification: "Sort the set of matching resource classes using the
- * number of characters in the regular expression not resulting from template
- * variables as the primary key and the number of matching groups as a
- * secondary key"
+ * JSR-311 specification: "Sort the set of matching resource classes using
+ * the number of characters in the regular expression not resulting from
+ * template variables as the primary key and the number of matching groups as
+ * a secondary key"
* </p>
*/
public static final Comparator<UriPattern> URIPATTERN_COMPARATOR = new UriPatternComparator();
@@ -76,7 +76,7 @@
if (o1.getNumberOfLiteralCharacters() > o2.getNumberOfLiteralCharacters())
return -1;
- // pattern with two variables less the pattern with four variables
+ // pattern with two variables less the pattern with four variables
if (o1.getParameterNames().size() < o2.getParameterNames().size())
return 1;
if (o1.getParameterNames().size() > o2.getParameterNames().size())
@@ -129,7 +129,7 @@
/**
* Constructs UriPattern.
- *
+ *
* @param template the source template
* @see {@link javax.ws.rs.Path}
*/
@@ -180,12 +180,12 @@
*/
public int hashCode()
{
- return template.hashCode() + regex.hashCode();
+ return getRegex().hashCode();
}
/**
* Get the regex pattern.
- *
+ *
* @return the regex pattern
*/
public Pattern getPattern()
@@ -195,7 +195,7 @@
/**
* Get the URI template as a String.
- *
+ *
* @return the URI template
*/
public String getTemplate()
@@ -205,7 +205,7 @@
/**
* Get the regular expression.
- *
+ *
* @return the regular expression
*/
public String getRegex()
@@ -215,7 +215,7 @@
/**
* Get the number of literal characters in the template.
- *
+ *
* @return number of literal characters in the template
*/
public int getNumberOfLiteralCharacters()
@@ -237,7 +237,7 @@
* greater then number of keys. It can be used for check is resource is
* matching to requested. If resource is match the last element in list must
* be '/' or null.
- *
+ *
* @param uri the URI string
* @param parameters target list
* @return true if URI string is match to pattern, false otherwise
@@ -289,7 +289,7 @@
/**
* Create URI from URI part. Each URI part can contains templates.
- *
+ *
* @param schema the schema URI part
* @param userInfo the user info URI part
* @param host the host name URI part
@@ -299,7 +299,7 @@
* @param fragment the fragment URI part
* @param values the values which must be used instead templates parameters
* @param encode if true then encode value before add it in URI, otherwise
- * value must be validate to legal characters
+ * value must be validate to legal characters
* @return the URI string
*/
public static String createUriWithValues(String schema, String userInfo, String host, int port, String path,
@@ -334,7 +334,7 @@
if (path != null)
{
- if (sb.length() > 0 && path.charAt(0) != '/')
+ if (sb.length() > 0 && path.length() > 0 && path.charAt(0) != '/')
sb.append('/');
appendUriPart(sb, path, UriComponent.PATH, values, encode);
}
@@ -356,7 +356,7 @@
/**
* Create URI from URI part. Each URI part can contains templates.
- *
+ *
* @param schema the schema URI part
* @param userInfo the user info URI part
* @param host the host name URI part
@@ -366,7 +366,7 @@
* @param fragment the fragment URI part
* @param values the values which must be used instead templates parameters
* @param encode if true then encode value before add it in URI, otherwise
- * value must be validate to legal characters
+ * value must be validate to legal characters
* @return the URI string
*/
public static String createUriWithValues(String schema, String userInfo, String host, int port, String path,
@@ -404,7 +404,7 @@
if (path != null)
{
- if (sb.length() > 0 && path.charAt(0) != '/')
+ if (sb.length() > 0 && path.length() > 0 && path.charAt(0) != '/')
sb.append('/');
p = appendUriPart(sb, path, UriComponent.PATH, values, p, m, encode);
}
@@ -431,7 +431,7 @@
* @param component the URI component
* @param values values map
* @param encode if true then encode value before add it in URI, otherwise
- * value must be validate to legal characters
+ * value must be validate to legal characters
*/
private static void appendUriPart(StringBuffer sb, String uriPart, int component,
Map<String, ? extends Object> values, boolean encode)
@@ -471,17 +471,17 @@
* @param component the URI component
* @param sourceValues the source array of values
* @param offset the offset in array
- * @param values values map, keep parameter/value pair which have been already
- * found. From java docs:
- * <p>
- * All instances of the same template parameter will be replaced by
- * the same value that corresponds to the position of the first
- * instance of the template parameter. e.g. the template
- * "{a}/{b}/{a}" with values {"x", "y", "z"} will result in the the
- * URI "x/y/x", <i>not</i> "x/y/z".
- * </p>
+ * @param values values map, keep parameter/value pair which have been
+ * already found. From java docs:
+ * <p>
+ * All instances of the same template parameter will be replaced by
+ * the same value that corresponds to the position of the first
+ * instance of the template parameter. e.g. the template "{a}/{b}/{a}"
+ * with values {"x", "y", "z"} will result in the the URI "x/y/x",
+ * <i>not</i> "x/y/z".
+ * </p>
* @param encode if true then encode value before add it in URI, otherwise
- * value must be validate to legal characters
+ * value must be validate to legal characters
* @return offset
*/
private static int appendUriPart(StringBuffer sb, String uriPart, int component, Object[] sourceValues, int offset,
@@ -539,7 +539,7 @@
/**
* Check does given URI string has templates.
- *
+ *
* @param uri the URI which must be checked
* @return true if URI has templates false otherwise
*/
Modified: ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/BaseTest.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/BaseTest.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/BaseTest.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -63,28 +63,28 @@
{
}
- public boolean registry(Object resource) throws Exception
+ public void registry(Object resource) throws Exception
{
// container.registerComponentInstance(resource);
- return binder.bind(resource);
+ binder.addResource(resource, null);
}
- public boolean registry(Class<?> resourceClass) throws Exception
+ public void registry(Class<?> resourceClass) throws Exception
{
// container.registerComponentImplementation(resourceClass.getName(), resourceClass);
- return binder.bind(resourceClass);
+ binder.addResource(resourceClass, null);
}
- public boolean unregistry(Object resource)
+ public void unregistry(Object resource)
{
// container.unregisterComponentByInstance(resource);
- return binder.unbind(resource.getClass());
+ binder.removeResource(resource.getClass());
}
- public boolean unregistry(Class<?> resourceClass)
+ public void unregistry(Class<?> resourceClass)
{
// container.unregisterComponent(resourceClass.getName());
- return binder.unbind(resourceClass);
+ binder.removeResource(resourceClass);
}
}
Modified: ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/ResourceBinderTest.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/ResourceBinderTest.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/impl/ResourceBinderTest.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -45,14 +45,14 @@
public void testBind()
{
- binder.bind(Resource.class);
+ binder.addResource(Resource.class, null);
assertEquals(1, binder.getSize());
}
public void testUnbind()
{
- binder.bind(Resource.class);
- binder.unbind(Resource.class);
+ binder.addResource(Resource.class, null);
+ binder.removeResource(Resource.class);
assertEquals(0, binder.getSize());
}
@@ -95,24 +95,51 @@
public void testSameResourceURI()
{
- assertTrue(binder.bind(SameURIResource1.class));
+ binder.addResource(SameURIResource1.class, null);
assertEquals(1, binder.getSize());
- assertFalse(binder.bind(SameURIResource2.class));
+ try
+ {
+ binder.addResource(SameURIResource2.class, null);
+ }
+ catch (ResourcePublicationException e)
+ {
+ }
assertEquals(1, binder.getSize());
+
binder.clear();
- assertTrue(binder.bind(SameURIResource2.class));
+ binder.addResource(SameURIResource2.class, null);
assertEquals(1, binder.getSize());
- assertFalse(binder.bind(SameURIResource1.class));
+ try
+ {
+ binder.addResource(SameURIResource1.class, null);
+ }
+ catch (ResourcePublicationException e)
+ {
+ }
assertEquals(1, binder.getSize());
+
binder.clear();
- assertTrue(binder.bind(new SameURIResource1()));
+ binder.addResource(new SameURIResource1(), null);
assertEquals(1, binder.getSize());
- assertFalse(binder.bind(new SameURIResource2()));
+ try
+ {
+ binder.addResource(new SameURIResource2(), null);
+ }
+ catch (ResourcePublicationException e)
+ {
+ }
assertEquals(1, binder.getSize());
+
binder.clear();
- assertTrue(binder.bind(new SameURIResource2()));
+ binder.addResource(new SameURIResource2(), null);
assertEquals(1, binder.getSize());
- assertFalse(binder.bind(new SameURIResource1()));
+ try
+ {
+ binder.addResource(new SameURIResource1(), null);
+ }
+ catch (ResourcePublicationException e)
+ {
+ }
assertEquals(1, binder.getSize());
}
Modified: ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/uri/UriPatternTest.java
===================================================================
--- ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/uri/UriPatternTest.java 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/exo.ws.rest.core/src/test/java/org/exoplatform/services/rest/uri/UriPatternTest.java 2010-07-09 13:37:30 UTC (rev 2761)
@@ -129,15 +129,28 @@
}
- private static void testMatch(String pattern, String uri, String[] values)
+ private boolean log = false;
+
+ private void testMatch(String pattern, String uri, String[] values)
{
UriPattern p = new UriPattern(pattern);
- System.out.println("URI: " + uri);
- System.out.println("REGEX: " + p.getRegex());
+ if (log)
+ {
+ System.out.println("URI: " + uri);
+ System.out.println("REGEX: " + p.getRegex());
+ System.out.println("PATTERN: " + pattern);
+ System.out.println("TEMPLATE: " + p.getTemplate());
+ }
+
List<String> l = new ArrayList<String>();
assertTrue(p.match(uri, l));
- System.out.println("PARAMETERS: " + p.getParameterNames());
- System.out.println("VARIABLES: " + l);
+
+ if (log)
+ {
+ System.out.println("PARAMETERS: " + p.getParameterNames());
+ System.out.println("VARIABLES: " + l);
+ System.out.println();
+ }
assertEquals(values.length, l.size());
int i = 0;
for (String t : l)
Modified: ws/trunk/pom.xml
===================================================================
--- ws/trunk/pom.xml 2010-07-09 10:16:44 UTC (rev 2760)
+++ ws/trunk/pom.xml 2010-07-09 13:37:30 UTC (rev 2761)
@@ -1,11 +1,23 @@
+ <!--
- <!--
+ Copyright (C) 2009 eXo Platform SAS.
- Copyright (C) 2009 eXo Platform SAS. 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.
- -->
+ 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.
+
+ -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
13 years, 10 months
exo-jcr SVN: r2760 - core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate.
by do-not-reply@jboss.org
Author: tolusha
Date: 2010-07-09 06:16:44 -0400 (Fri, 09 Jul 2010)
New Revision: 2760
Modified:
core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java
core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java
core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java
Log:
EXOJCR-851: Searching users with special characters in name
Modified: core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java
===================================================================
--- core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java 2010-07-09 10:12:59 UTC (rev 2759)
+++ core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java 2010-07-09 10:16:44 UTC (rev 2760)
@@ -42,6 +42,9 @@
import org.exoplatform.services.organization.User;
import org.hibernate.Session;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* Created by The eXo Platform SAS.
*
@@ -67,6 +70,11 @@
protected String countQuery;
/**
+ * Binded fields.
+ */
+ protected Map<String, Object> binding;
+
+ /**
* HibernateUserListAccess constructor.
*
* @param service
@@ -81,9 +89,31 @@
this.service = service;
this.findQuery = findQuery;
this.countQuery = countQuery;
+ this.binding = new HashMap<String, Object>();
}
/**
+ * HibernateUserListAccess constructor.
+ *
+ * @param service
+ * The Hibernate Service.
+ * @param findQuery
+ * Find query string
+ * @param countQuery
+ * Count query string
+ * @param binding
+ * Binded fields
+ */
+ public HibernateUserListAccess(HibernateService service, String findQuery, String countQuery,
+ Map<String, Object> binding)
+ {
+ this.service = service;
+ this.findQuery = findQuery;
+ this.countQuery = countQuery;
+ this.binding = binding;
+ }
+
+ /**
* {@inheritDoc}
*/
public int getSize() throws Exception
Modified: core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java
===================================================================
--- core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java 2010-07-09 10:12:59 UTC (rev 2759)
+++ core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java 2010-07-09 10:16:44 UTC (rev 2760)
@@ -44,6 +44,8 @@
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
/**
* Created by The eXo Platform SAS.
@@ -70,11 +72,33 @@
}
/**
+ * SimpliHibernateUserListAccess constructor.
+ *
+ * @param service
+ * The Hibernate Service.
+ * @param findQuery
+ * Find query string
+ * @param countQuery
+ * Count query string
+ * @param binding
+ * Binded fields
+ */
+ public SimpleHibernateUserListAccess(HibernateService service, String findQuery, String countQuery,
+ Map<String, Object> binding)
+ {
+ super(service, findQuery, countQuery, binding);
+ }
+
+ /**
* {@inheritDoc}
*/
+ @Override
protected int getSize(Session session) throws Exception
{
- List l = session.createQuery(countQuery).list();
+ Query query = session.createQuery(countQuery);
+ bindFields(query);
+
+ List l = query.list();
Number count = (Number)l.get(0);
return count.intValue();
@@ -83,6 +107,7 @@
/**
* {@inheritDoc}
*/
+ @Override
protected User[] load(Session session, int index, int length) throws Exception
{
if (index < 0)
@@ -94,8 +119,9 @@
User[] users = new User[length];
Query query = session.createQuery(findQuery);
+ bindFields(query);
+
Iterator<Object> results = query.iterate();
-
for (int p = 0, counter = 0; counter < length; p++)
{
if (!results.hasNext())
@@ -113,4 +139,18 @@
return users;
}
+ /**
+ * BindFields.
+ *
+ * @param query
+ * Query
+ */
+ private void bindFields(Query query)
+ {
+ for (Entry<String, Object> entry : binding.entrySet())
+ {
+ query.setParameter(entry.getKey(), entry.getValue());
+ }
+ }
+
}
Modified: core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java
===================================================================
--- core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java 2010-07-09 10:12:59 UTC (rev 2759)
+++ core/branches/2.3.x/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java 2010-07-09 10:16:44 UTC (rev 2760)
@@ -195,7 +195,8 @@
oq.addGT("lastLoginTime", q.getFromLoginDate());
oq.addLT("lastLoginTime", q.getToLoginDate());
- return new SimpleHibernateUserListAccess(service_, oq.getHibernateQuery(), oq.getHibernateCountQuery());
+ return new SimpleHibernateUserListAccess(service_, oq.getHibernateQueryWithBinding(), oq
+ .getHibernateCountQueryWithBinding(), oq.getBindingFields());
}
public LazyPageList<User> findUsersByGroup(String groupId) throws Exception
13 years, 10 months
exo-jcr SVN: r2759 - core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate.
by do-not-reply@jboss.org
Author: tolusha
Date: 2010-07-09 06:12:59 -0400 (Fri, 09 Jul 2010)
New Revision: 2759
Modified:
core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java
core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java
core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java
Log:
EXOJCR-851: Searching users with special characters in name
Modified: core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java
===================================================================
--- core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java 2010-07-09 09:38:29 UTC (rev 2758)
+++ core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/HibernateUserListAccess.java 2010-07-09 10:12:59 UTC (rev 2759)
@@ -42,6 +42,9 @@
import org.exoplatform.services.organization.User;
import org.hibernate.Session;
+import java.util.HashMap;
+import java.util.Map;
+
/**
* Created by The eXo Platform SAS.
*
@@ -67,6 +70,11 @@
protected String countQuery;
/**
+ * Binded fields.
+ */
+ protected Map<String, Object> binding;
+
+ /**
* HibernateUserListAccess constructor.
*
* @param service
@@ -81,9 +89,31 @@
this.service = service;
this.findQuery = findQuery;
this.countQuery = countQuery;
+ this.binding = new HashMap<String, Object>();
}
/**
+ * HibernateUserListAccess constructor.
+ *
+ * @param service
+ * The Hibernate Service.
+ * @param findQuery
+ * Find query string
+ * @param countQuery
+ * Count query string
+ * @param binding
+ * Binded fields
+ */
+ public HibernateUserListAccess(HibernateService service, String findQuery, String countQuery,
+ Map<String, Object> binding)
+ {
+ this.service = service;
+ this.findQuery = findQuery;
+ this.countQuery = countQuery;
+ this.binding = binding;
+ }
+
+ /**
* {@inheritDoc}
*/
public int getSize() throws Exception
Modified: core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java
===================================================================
--- core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java 2010-07-09 09:38:29 UTC (rev 2758)
+++ core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/SimpleHibernateUserListAccess.java 2010-07-09 10:12:59 UTC (rev 2759)
@@ -44,6 +44,8 @@
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
/**
* Created by The eXo Platform SAS.
@@ -70,11 +72,33 @@
}
/**
+ * SimpliHibernateUserListAccess constructor.
+ *
+ * @param service
+ * The Hibernate Service.
+ * @param findQuery
+ * Find query string
+ * @param countQuery
+ * Count query string
+ * @param binding
+ * Binded fields
+ */
+ public SimpleHibernateUserListAccess(HibernateService service, String findQuery, String countQuery,
+ Map<String, Object> binding)
+ {
+ super(service, findQuery, countQuery, binding);
+ }
+
+ /**
* {@inheritDoc}
*/
+ @Override
protected int getSize(Session session) throws Exception
{
- List l = session.createQuery(countQuery).list();
+ Query query = session.createQuery(countQuery);
+ bindFields(query);
+
+ List l = query.list();
Number count = (Number)l.get(0);
return count.intValue();
@@ -83,6 +107,7 @@
/**
* {@inheritDoc}
*/
+ @Override
protected User[] load(Session session, int index, int length) throws Exception
{
if (index < 0)
@@ -94,8 +119,9 @@
User[] users = new User[length];
Query query = session.createQuery(findQuery);
+ bindFields(query);
+
Iterator<Object> results = query.iterate();
-
for (int p = 0, counter = 0; counter < length; p++)
{
if (!results.hasNext())
@@ -113,4 +139,18 @@
return users;
}
+ /**
+ * BindFields.
+ *
+ * @param query
+ * Query
+ */
+ private void bindFields(Query query)
+ {
+ for (Entry<String, Object> entry : binding.entrySet())
+ {
+ query.setParameter(entry.getKey(), entry.getValue());
+ }
+ }
+
}
Modified: core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java
===================================================================
--- core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java 2010-07-09 09:38:29 UTC (rev 2758)
+++ core/trunk/exo.core.component.organization.jdbc/src/main/java/org/exoplatform/services/organization/hibernate/UserDAOImpl.java 2010-07-09 10:12:59 UTC (rev 2759)
@@ -197,7 +197,8 @@
oq.addGT("lastLoginTime", q.getFromLoginDate());
oq.addLT("lastLoginTime", q.getToLoginDate());
- return new SimpleHibernateUserListAccess(service_, oq.getHibernateQuery(), oq.getHibernateCountQuery());
+ return new SimpleHibernateUserListAccess(service_, oq.getHibernateQueryWithBinding(), oq
+ .getHibernateCountQueryWithBinding(), oq.getBindingFields());
}
public LazyPageList<User> findUsersByGroup(String groupId) throws Exception
13 years, 10 months
exo-jcr SVN: r2758 - in core/branches/2.3.x: exo.core.component.organization.jdbc and 1 other directories.
by do-not-reply@jboss.org
Author: nzamosenchuk
Date: 2010-07-09 05:38:29 -0400 (Fri, 09 Jul 2010)
New Revision: 2758
Modified:
core/branches/2.3.x/exo.core.component.organization.jdbc/pom.xml
core/branches/2.3.x/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml
core/branches/2.3.x/pom.xml
Log:
EXOJCR-809: Adding Javassist dependency, and HibernateService component
Modified: core/branches/2.3.x/exo.core.component.organization.jdbc/pom.xml
===================================================================
--- core/branches/2.3.x/exo.core.component.organization.jdbc/pom.xml 2010-07-09 09:33:25 UTC (rev 2757)
+++ core/branches/2.3.x/exo.core.component.organization.jdbc/pom.xml 2010-07-09 09:38:29 UTC (rev 2758)
@@ -109,19 +109,12 @@
<artifactId>mysql-connector-java</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>javassist</groupId>
+ <artifactId>javassist</artifactId>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>**/TestOrganizationService.java</exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
-
- </build>
+
</project>
\ No newline at end of file
Modified: core/branches/2.3.x/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml
===================================================================
--- core/branches/2.3.x/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml 2010-07-09 09:33:25 UTC (rev 2757)
+++ core/branches/2.3.x/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml 2010-07-09 09:38:29 UTC (rev 2758)
@@ -91,8 +91,32 @@
</init-params>
</component>
+ <component>
+ <key>org.exoplatform.services.database.HibernateService</key>
+ <jmx-name>database:type=HibernateService</jmx-name>
+ <type>org.exoplatform.services.database.impl.HibernateServiceImpl</type>
+ <init-params>
+ <properties-param>
+ <name>hibernate.properties</name>
+ <description>Default Hibernate Service</description>
+ <property name="hibernate.show_sql" value="false"/>
+ <property name="hibernate.cglib.use_reflection_optimizer" value="true"/>
+ <property name="hibernate.connection.url" value="jdbc:hsqldb:file:target/temp/data/exodb"/>
+ <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
+ <property name="hibernate.connection.autocommit" value="true"/>
+ <property name="hibernate.connection.username" value="sa"/>
+ <property name="hibernate.connection.password" value=""/>
+ <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
+ <property name="hibernate.c3p0.min_size" value="5"/>
+ <property name="hibernate.c3p0.max_size" value="20"/>
+ <property name="hibernate.c3p0.timeout" value="1800"/>
+ <property name="hibernate.c3p0.max_statements" value="50"/>
+ </properties-param>
+ </init-params>
+ </component>
+
<import>classpath:/conf/portal/hibernate-organization-configuration.xml</import>
<!-- <import>classpath:/conf/portal/jdbc-organization-configuration.xml</import>-->
<import>classpath:/conf/portal/test-organization-configuration.xml</import>
<!-- <remove-configuration>org.exoplatform.services.database.HibernateService</remove-configuration>-->
-</configuration>
\ No newline at end of file
+</configuration>
Modified: core/branches/2.3.x/pom.xml
===================================================================
--- core/branches/2.3.x/pom.xml 2010-07-09 09:33:25 UTC (rev 2757)
+++ core/branches/2.3.x/pom.xml 2010-07-09 09:38:29 UTC (rev 2758)
@@ -351,6 +351,12 @@
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
+
+ <dependency>
+ <groupId>javassist</groupId>
+ <artifactId>javassist</artifactId>
+ <version>3.4.GA</version>
+ </dependency>
</dependencies>
</dependencyManagement>
13 years, 10 months
exo-jcr SVN: r2757 - in core/trunk: exo.core.component.organization.jdbc and 1 other directories.
by do-not-reply@jboss.org
Author: nzamosenchuk
Date: 2010-07-09 05:33:25 -0400 (Fri, 09 Jul 2010)
New Revision: 2757
Modified:
core/trunk/exo.core.component.organization.jdbc/pom.xml
core/trunk/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml
core/trunk/pom.xml
Log:
EXOJCR-809: Adding Javassist dependency, and HibernateService component
Modified: core/trunk/exo.core.component.organization.jdbc/pom.xml
===================================================================
--- core/trunk/exo.core.component.organization.jdbc/pom.xml 2010-07-08 10:48:01 UTC (rev 2756)
+++ core/trunk/exo.core.component.organization.jdbc/pom.xml 2010-07-09 09:33:25 UTC (rev 2757)
@@ -109,19 +109,12 @@
<artifactId>mysql-connector-java</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>javassist</groupId>
+ <artifactId>javassist</artifactId>
+ <scope>test</scope>
+ </dependency>
+
</dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <excludes>
- <exclude>**/TestOrganizationService.java</exclude>
- </excludes>
- </configuration>
- </plugin>
- </plugins>
-
- </build>
+
</project>
\ No newline at end of file
Modified: core/trunk/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml
===================================================================
--- core/trunk/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml 2010-07-08 10:48:01 UTC (rev 2756)
+++ core/trunk/exo.core.component.organization.jdbc/src/test/resources/conf/portal/test-configuration.xml 2010-07-09 09:33:25 UTC (rev 2757)
@@ -91,8 +91,32 @@
</init-params>
</component>
+ <component>
+ <key>org.exoplatform.services.database.HibernateService</key>
+ <jmx-name>database:type=HibernateService</jmx-name>
+ <type>org.exoplatform.services.database.impl.HibernateServiceImpl</type>
+ <init-params>
+ <properties-param>
+ <name>hibernate.properties</name>
+ <description>Default Hibernate Service</description>
+ <property name="hibernate.show_sql" value="false"/>
+ <property name="hibernate.cglib.use_reflection_optimizer" value="true"/>
+ <property name="hibernate.connection.url" value="jdbc:hsqldb:file:target/temp/data/exodb"/>
+ <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
+ <property name="hibernate.connection.autocommit" value="true"/>
+ <property name="hibernate.connection.username" value="sa"/>
+ <property name="hibernate.connection.password" value=""/>
+ <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
+ <property name="hibernate.c3p0.min_size" value="5"/>
+ <property name="hibernate.c3p0.max_size" value="20"/>
+ <property name="hibernate.c3p0.timeout" value="1800"/>
+ <property name="hibernate.c3p0.max_statements" value="50"/>
+ </properties-param>
+ </init-params>
+ </component>
+
<import>classpath:/conf/portal/hibernate-organization-configuration.xml</import>
<!-- <import>classpath:/conf/portal/jdbc-organization-configuration.xml</import>-->
<import>classpath:/conf/portal/test-organization-configuration.xml</import>
<!-- <remove-configuration>org.exoplatform.services.database.HibernateService</remove-configuration>-->
-</configuration>
\ No newline at end of file
+</configuration>
Modified: core/trunk/pom.xml
===================================================================
--- core/trunk/pom.xml 2010-07-08 10:48:01 UTC (rev 2756)
+++ core/trunk/pom.xml 2010-07-09 09:33:25 UTC (rev 2757)
@@ -357,6 +357,12 @@
<artifactId>commons-pool</artifactId>
<version>1.5.4</version>
</dependency>
+
+ <dependency>
+ <groupId>javassist</groupId>
+ <artifactId>javassist</artifactId>
+ <version>3.4.GA</version>
+ </dependency>
</dependencies>
</dependencyManagement>
13 years, 10 months