[Registry-dev] svn commit r14499 - in
trunk/registry/modules/core/src/main/java/org/wso2/registry:
. config jdbc jdbc/handlers jdbc/handlers/builtin
jdbc/handlers/builtin/utils jdbc/handlers/filters servlet utils
svn at wso2.org
svn at wso2.org
Tue Mar 4 07:31:42 PST 2008
Author: chathura
Date: Tue Mar 4 07:31:13 2008
New Revision: 14499
Log:
Implemented the new handler model as discussed in the mailing list.
Now handlers for processing a request is selected based on the associated filter implementation.
Both URL handlers and media type handlers can be implemented as handlers.
MediaTypeMatcher selects handlers based on media types and the URLMatcher selects handlers based on URLs.
It is possible to introduce more handler types to match different criteria.
All previous media type handlers and URL handlers are reimplemented according the new handler model.
Registry configuration file (registry.xml) and its processing implementation is changed to work with the new handler model.
Now it is possible to configure handlers and their associated filters in the configuration file.
Added:
trunk/registry/modules/core/src/main/java/org/wso2/registry/config/HandlerConfiguration.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/Repository.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/Handler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/HandlerManager.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/RequestContext.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/Axis2RepositoryHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/CommentCollectionURLHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/CommentURLHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/RatingCollectionURLHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/RatingURLHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/SQLQueryHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/SynapseRepositoryHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/TagURLHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/WSDLMediaTypeHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/XSDMediaTypeHandler.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/utils/
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/utils/SchemaFileProcessor.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/utils/WSDLFileProcessor.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/filters/
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/filters/Filter.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/filters/MediaTypeMatcher.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/filters/URLMatcher.java
Modified:
trunk/registry/modules/core/src/main/java/org/wso2/registry/RegistryConstants.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/Resource.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryConfigurationProcessor.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryContext.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/JDBCRegistry.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/servlet/RegistryServlet.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/servlet/registry.xml
trunk/registry/modules/core/src/main/java/org/wso2/registry/utils/RegistryUtils.java
Modified: trunk/registry/modules/core/src/main/java/org/wso2/registry/RegistryConstants.java
==============================================================================
--- trunk/registry/modules/core/src/main/java/org/wso2/registry/RegistryConstants.java (original)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/RegistryConstants.java Tue Mar 4 07:31:13 2008
@@ -79,7 +79,7 @@
// internal media types
public static final String DEFAULT_MEDIA_TYPE = "default";
- public static final String SQL_QUERY_MEDIA_TYPE = "sql-query";
+ public static final String SQL_QUERY_MEDIA_TYPE = "application/vnd.sql.query";
public static final String COMMENT_MEDIA_TYPE = "comment";
public static final String RATING_MEDIA_TYPE = "rating";
public static final String TAG_MEDIA_TYPE = "tag";
Modified: trunk/registry/modules/core/src/main/java/org/wso2/registry/Resource.java
==============================================================================
--- trunk/registry/modules/core/src/main/java/org/wso2/registry/Resource.java (original)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/Resource.java Tue Mar 4 07:31:13 2008
@@ -34,6 +34,8 @@
String getMediaType();
+ int getState();
+
void setMediaType(String mediaType);
String getParentPath();
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/config/HandlerConfiguration.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/config/HandlerConfiguration.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.config;
+
+import org.wso2.registry.jdbc.handlers.filters.Filter;
+import org.wso2.registry.jdbc.handlers.Handler;
+
+public class HandlerConfiguration {
+
+ private Filter filter;
+ private Handler handler;
+
+ public Filter getFilter() {
+ return filter;
+ }
+
+ public void setFilter(Filter filter) {
+ this.filter = filter;
+ }
+
+ public Handler getHandler() {
+ return handler;
+ }
+
+ public void setHandler(Handler handler) {
+ this.handler = handler;
+ }
+}
Modified: trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryConfigurationProcessor.java
==============================================================================
--- trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryConfigurationProcessor.java (original)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryConfigurationProcessor.java Tue Mar 4 07:31:13 2008
@@ -22,7 +22,11 @@
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
import org.wso2.registry.RegistryException;
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.filters.Filter;
import org.wso2.registry.i18n.Messages;
import javax.xml.namespace.QName;
@@ -31,8 +35,12 @@
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;
+import java.lang.reflect.Method;
public class RegistryConfigurationProcessor {
+
+ private static final Log log = LogFactory.getLog(RegistryConfigurationProcessor.class);
+
public static void populateRegistryConfig(String filename, RegistryContext context)
throws RegistryException {
try {
@@ -57,7 +65,7 @@
}
if (in == null) {
throw new RegistryException(Messages.getMessage("inputstream.null",
- "org/wso2/servlet/registry.xml"));
+ "org/wso2/servlet/registry.xml"));
}
try {
StAXOMBuilder buillder = new StAXOMBuilder(in);
@@ -115,6 +123,8 @@
DataBaseConfiguration currentConfiguration =
registryContext.getDBConfig(currentConfigName);
registryContext.setDefaultDataBaseConfiguration(currentConfiguration);
+
+ initializeHandlers(configElement, registryContext);
// process media type handler config
Iterator mediaTypeHandlers = configElement.
@@ -213,4 +223,90 @@
}
return root;
}
+
+ private static void initializeHandlers(OMElement configElement, RegistryContext registryContext)
+ throws RegistryException {
+
+ // process handler configurations
+
+ try {
+ Iterator<OMElement> handlerConfigs =
+ configElement.getChildrenWithName(new QName("handler"));
+ while (handlerConfigs.hasNext()) {
+
+
+
+ OMElement handlerConfigElement = handlerConfigs.next();
+
+ String handlerClassName = handlerConfigElement.getAttributeValue(new QName("class"));
+
+ Class handlerClass = Class.forName(handlerClassName);
+ Handler handler = (Handler) handlerClass.newInstance();
+
+ // set configured properties of the handler object
+ Iterator<OMElement> handlerProps =
+ handlerConfigElement.getChildrenWithName(new QName("property"));
+ while (handlerProps.hasNext()) {
+ OMElement propElement = handlerProps.next();
+
+ String propName = propElement.getAttributeValue(new QName("name"));
+ String propValue = propElement.getText();
+
+ String setterName = getSetterName(propName);
+ Method setter = handlerClass.getMethod(setterName, String.class);
+ setter.invoke(handler, propValue);
+ }
+
+ // initialize and configure the filter for this handler
+ OMElement filterElement =
+ handlerConfigElement.getFirstChildWithName(new QName("filter"));
+ String filterClassName = filterElement.getAttributeValue(new QName("class"));
+
+ Class filterClass = Class.forName(filterClassName);
+ Filter filter = (Filter) filterClass.newInstance();
+
+ // set configured properties of the filter object
+ Iterator<OMElement> filterProps =
+ filterElement.getChildrenWithName(new QName("property"));
+ while (filterProps.hasNext()) {
+ OMElement propElement = filterProps.next();
+
+ String propName = propElement.getAttributeValue(new QName("name"));
+ String propValue = propElement.getText();
+
+ String setterName = getSetterName(propName);
+ Method setter = filterClass.getMethod(setterName, String.class);
+ setter.invoke(filter, propValue);
+ }
+
+
+ HandlerConfiguration handlerConfiguration = new HandlerConfiguration();
+ handlerConfiguration.setHandler(handler);
+ handlerConfiguration.setFilter(filter);
+
+ registryContext.addHandlerConfiguration(handlerConfiguration);
+ }
+
+ } catch (Exception e) {
+
+ String msg = "Could not initialize custom handlers. Caused by: " + e.getMessage();
+ log.fatal(msg, e);
+
+ throw new RegistryException(msg, e);
+ }
+ }
+
+ private static String getSetterName(String varName) {
+
+ String setterName;
+
+ if (varName.length() == 1) {
+ setterName = "set" + varName.substring(0, 1).toUpperCase();
+ } else {
+ setterName = "set" +
+ varName.substring(0, 1).toUpperCase() + varName.substring(1, varName.length());
+ }
+
+ return setterName;
+ }
}
Modified: trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryContext.java
==============================================================================
--- trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryContext.java (original)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/config/RegistryContext.java Tue Mar 4 07:31:13 2008
@@ -38,6 +38,7 @@
private RegURLSupplier urlSupplier;
private DataBaseConfiguration defaultDataBaseConfiguration = null;
private Map dbConfigs = new HashMap<String, DataBaseConfiguration>();
+ private List<HandlerConfiguration> handlerConfigurations = new ArrayList();
private List mediaTypeHandlers = new ArrayList();
private List urlHandlers = new ArrayList();
private List queryProcessors = new ArrayList();
@@ -102,6 +103,18 @@
dbConfigs.put(name, config);
}
+ public List<HandlerConfiguration> getHandlerConfigurations() {
+ return handlerConfigurations;
+ }
+
+ public void setHandlerConfigurations(List<HandlerConfiguration> handlerConfigurations) {
+ this.handlerConfigurations = handlerConfigurations;
+ }
+
+ public void addHandlerConfiguration(HandlerConfiguration handlerConfiguration) {
+ handlerConfigurations.add(handlerConfiguration);
+ }
+
public List getMediaTypeHandlers() {
return mediaTypeHandlers;
}
Modified: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/JDBCRegistry.java
==============================================================================
--- trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/JDBCRegistry.java (original)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/JDBCRegistry.java Tue Mar 4 07:31:13 2008
@@ -30,6 +30,13 @@
import org.wso2.registry.jdbc.queries.QueryProcessorManager;
import org.wso2.registry.jdbc.realm.RegistryRealm;
import org.wso2.registry.jdbc.urlhandlers.URLHandlerManager;
+import org.wso2.registry.jdbc.handlers.HandlerManager;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.filters.MediaTypeMatcher;
+import org.wso2.registry.jdbc.handlers.filters.URLMatcher;
+import org.wso2.registry.jdbc.handlers.filters.Filter;
+import org.wso2.registry.jdbc.handlers.builtin.*;
import org.wso2.registry.users.UserRealm;
import org.wso2.registry.utils.AuthorizationUtil;
import org.wso2.registry.utils.VersionedPath;
@@ -52,8 +59,8 @@
private static final Log log = LogFactory.getLog(JDBCRegistry.class);
private DataSource dataSource = null;
- private URLHandlerManager urlHandlerManager;
- private MediaTypeManager mediaTypeManager;
+ //private URLHandlerManager urlHandlerManager;
+ //private MediaTypeManager mediaTypeManager;
private QueryProcessorManager queryProcessorManager;
private VersionedResourceDAO resourceDAO = null;
private TagsDAO tagsDAO = null;
@@ -61,6 +68,9 @@
private RatingsDAO ratingsDAO = null;
private LogsDAO logsDAO = null;
+ private HandlerManager handlerManager;
+ private Repository repository;
+
private UserRealm defaultRealm = null;
/**
@@ -117,8 +127,11 @@
defaultRealm = realm;
- urlHandlerManager = new URLHandlerManager(dataSource, realm, this);
- mediaTypeManager = new MediaTypeManager(dataSource, realm, this);
+ repository = new Repository(dataSource, realm);
+ handlerManager = new HandlerManager(dataSource, realm, this, repository);
+
+ //urlHandlerManager = new URLHandlerManager(dataSource, realm, this);
+ //mediaTypeManager = new MediaTypeManager(dataSource, realm, this);
queryProcessorManager = new QueryProcessorManager(dataSource, realm);
resourceDAO = new VersionedResourceDAO();
@@ -172,6 +185,8 @@
e.printStackTrace();
}
}
+
+ registerBuiltInHandlers();
}
public Resource newResource() throws RegistryException {
@@ -198,17 +213,26 @@
* @throws RegistryException ResourceNotFound exception is thrown if the resource is not in the
* registry
*/
- public ResourceImpl get(String path) throws RegistryException {
+ public Resource get(String path) throws RegistryException {
path = preparePath(path);
- ResourceImpl resource;
// check if this path refers to a resource referred by a URL query (e.g. comment)
- resource = urlHandlerManager.get(path);
+
+ RequestContext requestContext = new RequestContext();
+ requestContext.setResourcePath(path);
+
+ Resource resource = handlerManager.get(requestContext);
+
+ //resource = urlHandlerManager.get(path);
// check if the resource in the path has a mediatype handler
+ //if (resource == null) {
+ // resource = mediaTypeManager.get(path);
+ //}
+
if (resource == null) {
- resource = mediaTypeManager.get(path);
+ resource = repository.get(path);
}
if (resource == null) {
@@ -263,14 +287,27 @@
throws RegistryException {
suggestedPath = preparePath(suggestedPath);
- String actualPath;
+ RequestContext requestContext = new RequestContext();
+ requestContext.setResourcePath(suggestedPath);
+ requestContext.setResource(resource);
- actualPath = urlHandlerManager.put(suggestedPath, resource);
+ handlerManager.putChild(requestContext);
- if (actualPath == null) {
- mediaTypeManager.put(suggestedPath, (ResourceImpl)resource);
+ handlerManager.put(requestContext);
+
+ String actualPath = requestContext.getActualPath();
+
+ if (!requestContext.isProcessingComplete()) {
+ actualPath = suggestedPath;
+ repository.put(suggestedPath, resource);
}
+ //actualPath = urlHandlerManager.put(suggestedPath, resource);
+ //
+ //if (actualPath == null) {
+ // mediaTypeManager.put(suggestedPath, (ResourceImpl)resource);
+ //}
+
Connection conn = getConnection();
try {
@@ -312,7 +349,24 @@
suggestedPath = preparePath(suggestedPath);
- String savedPath = mediaTypeManager.importResource(suggestedPath, sourceURL, metadata);
+ RequestContext importChildContext = new RequestContext();
+ importChildContext.setResourcePath(RegistryUtils.getParentPath(suggestedPath));
+ handlerManager.importChild(importChildContext);
+
+ RequestContext requestContext = new RequestContext();
+ requestContext.setResourcePath(suggestedPath);
+ requestContext.setSourceURL(sourceURL);
+ requestContext.setResource(metadata);
+
+ handlerManager.importResource(requestContext);
+ String savedPath = requestContext.getActualPath();
+
+ if (!requestContext.isProcessingComplete()) {
+ savedPath = suggestedPath;
+ repository.importResource(suggestedPath, sourceURL, metadata);
+ }
+
+ //String savedPath = mediaTypeManager.importResource(suggestedPath, sourceURL, metadata);
Connection conn = getConnection();
@@ -377,11 +431,11 @@
long resourceID = resourceDAO.getResourceID(currentPath, conn);
resourceDAO.renameResource(currentPath,
- newPath,
- getConnection(),
- User.getCurrentUser(),
- defaultRealm,
- this);
+ newPath,
+ getConnection(),
+ User.getCurrentUser(),
+ defaultRealm,
+ this);
logsDAO.addLog(resourceID, userID, LogEntry.RENAME, currentPath, conn);
@@ -420,8 +474,17 @@
path = preparePath(path);
- if (!urlHandlerManager.delete(path)) {
- mediaTypeManager.delete(path);
+ RequestContext requestContext = new RequestContext();
+ requestContext.setResourcePath(path);
+
+ handlerManager.delete(requestContext);
+
+ //if (!urlHandlerManager.delete(path)) {
+ // mediaTypeManager.delete(path);
+ //}
+
+ if (!requestContext.isProcessingComplete()) {
+ repository.delete(path);
}
Connection conn = getConnection();
@@ -1248,5 +1311,47 @@
return logEntries;
}
+
+ public void addHandler(Filter filter, Handler handler) {
+ handlerManager.addHanlder(filter, handler);
+ }
+
+ private void registerBuiltInHandlers() {
+
+ Axis2RepositoryHandler axis2RepositoryHandler = new Axis2RepositoryHandler();
+ MediaTypeMatcher axis2MediaTypeMatcher = new MediaTypeMatcher("application/vnd.apache.axis2");
+ handlerManager.addHanlder(axis2MediaTypeMatcher, axis2RepositoryHandler);
+
+ SQLQueryHandler sqlQueryHandler = new SQLQueryHandler();
+ MediaTypeMatcher sqlMediaTypeMatcher =
+ new MediaTypeMatcher(RegistryConstants.SQL_QUERY_MEDIA_TYPE);
+ handlerManager.addHanlder(sqlMediaTypeMatcher, sqlQueryHandler);
+
+ CommentURLHandler commentURLHandler = new CommentURLHandler();
+ URLMatcher commentURLMatcher = new URLMatcher();
+ commentURLMatcher.setGetPattern(".+;comments:[0-9]+");
+ commentURLMatcher.setDeletePattern(".+;comments:[0-9]+");
+ handlerManager.addHanlder(commentURLMatcher, commentURLHandler);
+
+ CommentCollectionURLHandler commentCollectionURLHandler = new CommentCollectionURLHandler();
+ URLMatcher commentCollectionURLMatcher = new URLMatcher();
+ commentCollectionURLMatcher.setGetPattern(".+;comments");
+ handlerManager.addHanlder(commentCollectionURLMatcher, commentCollectionURLHandler);
+
+ RatingURLHandler ratingURLHandler = new RatingURLHandler();
+ URLMatcher ratingURLMatcher = new URLMatcher();
+ ratingURLMatcher.setGetPattern(".+;ratings:.+");
+ handlerManager.addHanlder(ratingURLMatcher, ratingURLHandler);
+
+ RatingCollectionURLHandler ratingCollectionURLHandler = new RatingCollectionURLHandler();
+ URLMatcher ratingCollectionURLMatcher = new URLMatcher();
+ ratingCollectionURLMatcher.setGetPattern(".+;ratings");
+ handlerManager.addHanlder(ratingCollectionURLMatcher, ratingCollectionURLHandler);
+
+ TagURLHandler tagURLHandler = new TagURLHandler();
+ URLMatcher tagURLMatcher = new URLMatcher();
+ tagURLMatcher.setGetPattern(".+;.+:.+:.+");
+ handlerManager.addHanlder(tagURLMatcher, tagURLHandler);
+ }
}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/Repository.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/Repository.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,460 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc;
+
+import org.wso2.registry.*;
+import org.wso2.registry.users.UserRealm;
+import org.wso2.registry.jdbc.dao.VersionedResourceDAO;
+import org.wso2.registry.utils.AuthorizationUtil;
+import org.wso2.registry.i18n.Messages;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.MalformedURLException;
+import java.net.URLConnection;
+import java.util.List;
+import java.util.Iterator;
+
+public class Repository {
+
+ private static final Log log = LogFactory.getLog(Repository.class);
+
+ /**
+ * Data source for obtaining database connections. Media type handlers need to access the
+ * database for performing almost all the tasks.
+ */
+ protected DataSource dataSource;
+
+ /**
+ * User manager realm, which can be used to set permissions on resources. Media type handlers
+ * may want to add other resources (e.g. imports) than the originally given resource. So it is
+ * necessary to allow media type handler to set permissions for the resources it is dealing
+ * with.
+ */
+ protected UserRealm realm;
+
+ /** ResourceDAO for directly accessing resources. */
+ private VersionedResourceDAO resourceDAO = new VersionedResourceDAO();
+
+ public Repository(DataSource dataSource, UserRealm userRealm) {
+ this.dataSource = dataSource;
+ this.realm = userRealm;
+ }
+
+ public Resource get(String path) throws RegistryException {
+
+ Resource resource;
+
+ String plainPath = path;
+ long versionNumber = -1;
+ if (path.indexOf("?v=") != -1) {
+ String[] parts = path.split("\\?v=");
+ plainPath = parts[0];
+ versionNumber = Long.parseLong(parts[1]);
+ }
+
+ plainPath = getPreparedPath(plainPath);
+
+ Connection conn;
+ try {
+ conn = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+ //if we uncomment following three lines then , no onc access a deleted resource
+// if (!resourceDAO.isResourceActive(plainPath,conn)) {
+// throw new RegistryException("Trying to access a deleted resource");
+// }
+ try {
+ //resource = resourceDAO.get(path, conn);
+ if (versionNumber == -1) {
+ resource = resourceDAO.getLatestVersion(plainPath, conn);
+
+ } else {
+ resource = resourceDAO.get(plainPath, versionNumber, conn);
+ }
+
+ } catch (Exception e) {
+
+ String msg = Messages.getMessage("resource.get.fail", path);
+ log.error(msg, e);
+ throw new RegistryException(msg);
+
+ } finally {
+ try {
+ conn.close();
+ } catch (SQLException e) {
+ e.printStackTrace();
+ }
+ }
+
+ // we are just getting the content from the database. not a content modification.
+ if (resource != null && resource instanceof ResourceImpl) {
+ ((ResourceImpl) resource).setContentModified(false);
+ }
+
+ return resource;
+ }
+
+ public boolean put(String path, Resource resource) throws RegistryException {
+
+ String userID = User.getCurrentUser();
+
+ if (!(resource instanceof ResourceImpl)) {
+ String msg = "Only the ResourceImpl instances " +
+ "are supported in the org.wso2.registry.jdbc.Repository.";
+ throw new RegistryException(msg);
+ }
+
+ ResourceImpl resourceImpl = (ResourceImpl) resource;
+
+ Connection conn;
+ try {
+ conn = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+
+ try {
+ conn.setAutoCommit(false);
+
+ ResourceImpl a = resourceDAO.getLatestVersion(path, conn);
+ if (a != null) {
+
+ // if the parent collections of this resource are in deleted state, make them
+ // activated
+ activateParentCollections(path, conn);
+
+ // given resource already exist. update it.
+ resourceImpl.setId(a.getId());
+
+ // if client has not explicitly set the author, keep the original author name.
+ if (resource.getAuthorUserName() == null) {
+ resourceImpl.setAuthorUserName(a.getAuthorUserName());
+ }
+ resourceImpl.setPath(path);
+ resourceImpl.setState(RegistryConstants.ACTIVE_STATE);
+ resourceImpl.setLastUpdaterUserName(userID);
+ resourceDAO.update(path, resourceImpl, conn);
+ if (resourceImpl.isDirectory()) {
+ if (!a.isDirectory()) {
+ throw new RegistryException("Trying to add a collection while a " +
+ "resource with the same name exist in the system");
+ }
+ } else {
+ if (a.isDirectory()) {
+ throw new RegistryException("Trying to add a resource while a " +
+ "collection with the same name exist in the system");
+ }
+ }
+
+ if (resourceImpl.isContentModified() ||
+ a.getState() == RegistryConstants.DELETED_STATE) {
+ resourceDAO.addResourceVersion(resourceImpl, conn);
+ }
+
+ long resourceID = resourceDAO.getResourceID(path, conn);
+ long currentVersion = resourceDAO.getCurrentVersionNumber(path, conn);
+ resourceDAO.addDependencies(
+ resourceID, currentVersion, resource.getDependencies(), conn);
+
+ } else {
+
+ // given resource does not exist. add it as a new resource.
+
+ // first create all ascendant collections
+ createParentCollections(path, conn, userID);
+
+ // now add the required resource
+ resourceImpl.setPath(path);
+ if (resource.getAuthorUserName() == null) {
+ resourceImpl.setAuthorUserName(userID);
+ }
+ resourceImpl.setLastUpdaterUserName(userID);
+
+ resourceDAO.add(resourceImpl, conn);
+ AuthorizationUtil.setDefaultAuthorizations(realm, path, userID);
+
+ resourceImpl.setId(resourceDAO.getResourceID(path, conn));
+ resourceDAO.addResourceVersion(resourceImpl, conn);
+
+ long resourceID = resourceDAO.getResourceID(path, conn);
+ long currentVersion = resourceDAO.getCurrentVersionNumber(path, conn);
+ resourceDAO.addDependencies(
+ resourceID, currentVersion, resource.getDependencies(), conn);
+ }
+
+ conn.commit();
+
+ } catch (Exception e) {
+
+ try {
+ conn.rollback();
+ } catch (SQLException e1) {
+ e1.printStackTrace();
+ }
+
+ String msg = Messages.getMessage("resource.put.fail", path, e.getMessage());
+ log.error(msg, e);
+ throw new RegistryException(msg);
+ } finally {
+ try {
+ conn.close();
+ } catch (SQLException e) {
+ log.error("Exception occur in side the finaly block of " + this + " put");
+ }
+ }
+ return true;
+ }
+
+ /**
+ * This method will first split the given path and then try to create directory for each part
+ * for example if the path is "/abc/xyx/r1" , then first it will see whether the resource "/abc"
+ * is there if it is not there then it will create that else go to "/abc/xyz" , and see whether
+ * the resource is there , if so continue the same procedure
+ *
+ * @param path : Location where we need to add the resource
+ * @param conn : DB connection
+ * @param userID : user
+ * @throws SQLException : Something went wrong
+ * @throws RegistryException : Something went wrong
+ */
+ private void createParentCollections(String path,
+ Connection conn,
+ String userID)
+ throws SQLException, IOException, RegistryException {
+
+ String[] parts = path.split(RegistryConstants.PATH_SEPARATOR);
+
+ String currentPath = RegistryConstants.ROOT_PATH + parts[1];
+ for (int i = 2; i < parts.length; i++) {
+
+ ResourceImpl currentCollection = resourceDAO.getLatestVersion(currentPath, conn);
+ if (currentCollection == null) {
+ currentCollection = new CollectionImpl();
+ currentCollection.setPath(currentPath);
+ currentCollection.setAuthorUserName(userID);
+ currentCollection.setLastUpdaterUserName(userID);
+
+ resourceDAO.add(currentCollection, conn);
+ AuthorizationUtil.setDefaultAuthorizations(realm, currentPath, userID);
+// currentCollection = resourceDAO.getLatestVersion(currentPath, conn);
+
+ } else {
+
+ if (currentCollection.getState() == RegistryConstants.DELETED_STATE) {
+
+ //currentCollection = new Resource();
+ //currentCollection.setPath(currentPath);
+ //currentCollection.setDirectory(true);
+ //currentCollection.setAuthorUserName(userID);
+ //currentCollection.setLastUpdaterUserName(userID);
+ resourceDAO.markActivated(currentCollection.getId(), conn);
+ //put(currentPath, currentCollection);
+
+ } else if (!currentCollection.isDirectory()) {
+
+ String message =
+ Messages.getMessage("resource.adding.error", currentPath, path);
+ throw new RegistryException(message);
+ }
+ }
+
+ currentPath = currentPath + RegistryConstants.PATH_SEPARATOR + parts[i];
+ }
+ }
+
+ private void activateParentCollections(String path,
+ Connection conn)
+ throws SQLException, IOException, RegistryException {
+
+ if (path.equals(RegistryConstants.ROOT_PATH)) {
+ // if we are at root, there are no parent collections.
+ return;
+ }
+
+ String[] parts = path.split(RegistryConstants.PATH_SEPARATOR);
+
+ String currentPath = RegistryConstants.ROOT_PATH + parts[1];
+ for (int i = 2; i < parts.length; i++) {
+
+ ResourceImpl currentCollection = resourceDAO.getLatestVersion(currentPath, conn);
+ if (currentCollection == null) {
+
+ String msg = "Parent collection: " + currentPath + " of the exsiting resource:" +
+ path + " cannot be null";
+ log.error(msg);
+ throw new RegistryException(msg);
+
+ } else {
+
+ if (currentCollection.getState() == RegistryConstants.DELETED_STATE) {
+
+ resourceDAO.markActivated(currentCollection.getId(), conn);
+
+ } else if (!currentCollection.isDirectory()) {
+
+ String msg = "Parent : " + currentPath + " of the exsiting resource:" + path +
+ " should be a collection resource.";
+ log.error(msg);
+ throw new RegistryException(msg);
+ }
+ }
+
+ currentPath = currentPath + RegistryConstants.PATH_SEPARATOR + parts[i];
+ }
+ }
+
+ public String importResource(String path, String sourceURL, Resource metadata)
+ throws RegistryException {
+
+ URL url;
+ try {
+ url = new URL(sourceURL);
+ } catch (MalformedURLException e) {
+ String msg = "Given source URL is not valid.";
+ throw new RegistryException(msg, e);
+ }
+
+ try {
+ URLConnection uc = url.openConnection();
+ InputStream in = uc.getInputStream();
+
+ //ByteArrayOutputStream out = new ByteArrayOutputStream();
+ //byte[] buffer = new byte[1024];
+ //int c;
+ //while ((c = in.read(buffer)) != -1) {
+ // out.write(buffer, 0, c);
+ //}
+ //out.flush();
+
+ ResourceImpl resource = new ResourceImpl();
+ resource.setPath(path);
+ String mediaType = metadata.getMediaType();
+ if (mediaType == null)
+ mediaType = uc.getContentType();
+ resource.setMediaType(mediaType);
+ resource.setDescription(metadata.getDescription());
+ resource.setContentStream(in);
+
+ put(path, resource);
+
+ } catch (IOException e) {
+ String msg = "Could not read from the given URL: " + sourceURL;
+ throw new RegistryException(msg, e);
+ }
+ return path;
+ }
+
+ public boolean delete(String path) throws RegistryException {
+
+ Connection conn;
+ try {
+ conn = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+
+ try {
+ conn.setAutoCommit(false);
+ ResourceImpl resource = resourceDAO.getLatestVersion(path, conn);
+ if (resource != null) {
+ if (resource.isDirectory()) {
+ deleteDirectory(resource, conn);
+ } else {
+ resourceDAO.markDeleted(path, conn);
+ resourceDAO.deleteResource(resource, conn);
+ //prepareToDelete(resource.getId(), conn);
+ //resourceDAO.delete(resource.getResourcePath(), conn);
+ }
+ } else {
+ String msg = Messages.getMessage("delete.null.resource", path);
+ log.error(msg);
+ throw new RegistryException(msg);
+ }
+ conn.commit();
+ } catch (Exception e) {
+ try {
+ conn.rollback();
+ } catch (SQLException e1) {
+ log.error("Exception occur in side the catch block of " + this + " delete");
+ }
+ String msg = Messages.getMessage("resource.delete.fail", path);
+ log.error(msg, e);
+ throw new RegistryException(msg);
+ } finally {
+ try {
+ conn.close();
+ } catch (SQLException e) {
+ log.error("Exception occur in side the finaly block of " + this + " delete");
+ }
+ }
+ return true;
+ }
+
+ private void deleteDirectory(ResourceImpl collection, Connection conn)
+ throws SQLException, IOException, RegistryException {
+ List childList = resourceDAO.getChildren(collection.getId(), -1, conn);
+ Iterator i = childList.iterator();
+ while (i.hasNext()) {
+ ResourceImpl child = (ResourceImpl)i.next();
+// if (child.isDirectory()) {
+// deleteDirectory(child, conn);
+// } else {
+ resourceDAO.markDeleted(child.getPath(), conn);
+ resourceDAO.deleteResource(child, conn);
+// }
+ }
+ resourceDAO.markDeleted(collection.getPath(), conn);
+ resourceDAO.deleteResource(collection, conn);
+ }
+
+ public boolean putChild(String childPath, Resource resource) throws RegistryException {
+ // General resource should not have any constraint on adding children.
+ return true;
+ }
+
+ public boolean importChild(String childPath, String sourceURL) throws RegistryException {
+ return true;
+ }
+
+ private String getPreparedPath(String resourcePath) {
+
+ String preparedPath = resourcePath;
+ if (preparedPath.equals(RegistryConstants.ROOT_PATH)) {
+ return preparedPath;
+
+ } else {
+
+ if (!preparedPath.startsWith(RegistryConstants.ROOT_PATH)) {
+ preparedPath = RegistryConstants.ROOT_PATH + preparedPath;
+ }
+
+ if (preparedPath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
+ preparedPath = preparedPath.substring(0, preparedPath.length() - 1);
+ }
+ }
+
+ return preparedPath;
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/Handler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/Handler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers;
+
+import org.wso2.registry.users.UserRealm;
+import org.wso2.registry.jdbc.dao.VersionedResourceDAO;
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.Registry;
+import org.wso2.registry.ResourceImpl;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.Resource;
+import org.wso2.registry.utils.AuthorizationUtil;
+
+import javax.sql.DataSource;
+
+/**
+ * Base class of all handler implementations. Provides the methods that handlers should implement.
+ * This class also provides the datasource, user realm, registry and repository instances to be
+ * used by handler impls.
+ */
+public abstract class Handler {
+
+ /**
+ * Data source for obtaining database connections. Media type handlers need to access the
+ * database for performing almost all the tasks.
+ */
+ protected DataSource dataSource;
+
+ /**
+ * User manager realm, which can be used to set permissions on resources. Media type handlers
+ * may want to add other resources (e.g. imports) than the originally given resource. So it is
+ * necessary to allow media type handler to set permissions for the resources it is dealing
+ * with.
+ */
+ protected UserRealm realm;
+
+ /**
+ * Handlers can use this repository to perform resource operations directly with the database,
+ * without being intercepted by other media type handlers. It takes care of all version
+ * handling operations. It is recommended to use the methods of the repository to put or get
+ * resources once the handler specific processing is completed, rather directly using
+ * database connections obtained from the datasource.
+ */
+ protected Repository repository;
+
+ /**
+ * Instance of the Registry implementation (possibly the JDBCRegistry). Media type
+ * handler authors can use this registry to perform any action within the media type handler.
+ * e.g. tagging, commenting, rating
+ *
+ * However it is not recommended to use this for put, get, delete and import operations. If
+ * this is used for those operations, it will invoke the media type handlers again, which
+ * could possibly result in an infinite loop. Use the DefaultMediaTypeHandler instance, which
+ * can be obtained from the given MediaTypeManager instance for those four operations.
+ */
+ protected Registry registry;
+
+ /** ResourceDAO for directly accessing resources. */
+ protected VersionedResourceDAO resourceDAO = new VersionedResourceDAO();
+
+ /** Some common authorization tasks are implemented in this util. */
+ protected AuthorizationUtil authorizationUtil = new AuthorizationUtil();
+
+ public Handler() {}
+
+ public Handler(DataSource dataSource,
+ UserRealm realm,
+ Repository repository,
+ Registry registry) {
+
+ this.dataSource = dataSource;
+ this.realm = realm;
+ this.repository = repository;
+ this.registry = registry;
+ }
+
+ /**
+ * Processes the GET action for resource path of the requestContext.
+ *
+ * @param requestContext Information about the current request.
+ *
+ *requestContext.resourcePath: Path of the resource
+ *
+ *requestContext.resource: Resource at the given path. This can be null if no other handler has
+ * retrieved that resource so far. If it contains a value, matching handlers are free to do any
+ * change to the resource, even thay can replace the resource with completely new instance.
+ *
+ * @return Resource instance if the handler processed the GET action successfully.
+ *
+ * @throws org.wso2.registry.RegistryException If the media type handler is supposed to handle
+ * the get on the media type and if the get fails due a handler specific error
+ */
+ public abstract Resource get(RequestContext requestContext) throws RegistryException;
+
+ /**
+ * Processes the PUT action. Actual path to which the resource is put may differ from the path
+ * given in the requestContext.resourcePath. Therefore, after putting the resource, the actual
+ * path to which the resource is put is set in the requestContext.actualPath.
+ *
+ * @param requestContext Information about the current request.
+ *
+ * requestContext.resourcePath: Path to put the resource.
+ * requestContext.resource: Resource to put
+ *
+ * @throws RegistryException If the media type handler is supposed to handle the put on the
+ * media type and if the put fails due a handler specific error
+ */
+ public abstract void put(RequestContext requestContext) throws RegistryException;
+
+ /**
+ * Creates a resource in the given path by fetching the resource content from the given URL.
+ *
+ * @param requestContext Information about the current request.
+ *
+ * requestContext.resourcePath: Path to add the new resource.
+ *
+ * requestContext.sourceURL: URL to fetch the resource content
+ *
+ * requestContext.resource: Resource instance containing the metadata for the resource to be
+ * imported. Once import is done, new resource is created combining the metadata of this
+ * metadata object and the imported content.
+ *
+ * @throws RegistryException If the media type handler is supposed to handle the import on the
+ * media type and if the import fails due a handler specific error
+ */
+ public abstract void importResource(RequestContext requestContext) throws RegistryException;
+
+ /**
+ * Processes the DELETE action of the media type.
+ *
+ * @param requestContext Information about the current request.
+ *
+ * requestContext.resourcePath: path path of the resource to be deleted.
+ *
+ * @throws RegistryException If the media type handler is supposed to handle the delete on the
+ * media type and if the delete fails due a handler specific error
+ */
+ public abstract void delete(RequestContext requestContext) throws RegistryException;
+
+ /**
+ * Invokes when a child resource is added. Only the media type handlers of collection resources
+ * may have a meaningfull implementation of this method.
+ *
+ * @param requestContext
+ * requestContext.resourcePath: path of the parent collection
+ * requestContext.resource: New child resource to be added
+ *
+ * @return True if the child resource is allowed to be added. False if the child resource is
+ * rejected.
+ *
+ * @throws RegistryException If the media type handler is supposed to handle the putChild on the
+ * media type and if the putChild fails due a handler specific error
+ */
+ public abstract void putChild(RequestContext requestContext) throws RegistryException;
+
+ /**
+ * Invokes when a child resource is imported. Only the media type handlers of collection
+ * resources may have a meaningfull implementation of this method.
+ *
+ * @param requestContext
+ * requestContext.resourcePath
+ *
+ * @throws RegistryException If the media type handler is supposed to handle the importChild
+ * on the media type and if the importChild fails due a handler specific error
+ */
+ public abstract void importChild(RequestContext requestContext) throws RegistryException;
+
+
+ // Provide setters for datasource, user realm, registry and repository. so that these parameters
+ // can be set by the handler manager, instead of having the users to set them before registering
+ // with the registry
+
+
+ public void setDataSource(DataSource dataSource) {
+ this.dataSource = dataSource;
+ }
+
+ public void setRealm(UserRealm realm) {
+ this.realm = realm;
+ }
+
+ public void setRepository(Repository repository) {
+ this.repository = repository;
+ }
+
+ public void setRegistry(Registry registry) {
+ this.registry = registry;
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/HandlerManager.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/HandlerManager.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers;
+
+import org.wso2.registry.jdbc.handlers.filters.Filter;
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.Registry;
+import org.wso2.registry.users.UserRealm;
+
+import javax.sql.DataSource;
+import java.util.Map;
+import java.util.HashMap;
+import java.util.Iterator;
+
+public class HandlerManager {
+
+ private Map<Filter, Handler> handlerMap = new HashMap();
+
+ private DataSource dataSource;
+ private UserRealm userRealm;
+ private Registry registry;
+ private Repository repository;
+
+ public HandlerManager(
+ DataSource dataSource, UserRealm userRealm, Registry registry, Repository repository) {
+ this.dataSource = dataSource;
+ this.userRealm = userRealm;
+ this.registry = registry;
+ this.repository = repository;
+ }
+
+ public void addHanlder(Filter filter, Handler handler) {
+
+ filter.setRepository(repository);
+
+ handler.setDataSource(dataSource);
+ handler.setRealm(userRealm);
+ handler.setRegistry(registry);
+ handler.setRepository(repository);
+
+ handlerMap.put(filter, handler);
+ }
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+
+ Resource resource = null;
+
+ Iterator<Filter> filters = handlerMap.keySet().iterator();
+ while (filters.hasNext()) {
+ Filter filter = filters.next();
+ if (filter.handleGet(requestContext)) {
+ resource = handlerMap.get(filter).get(requestContext);
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ break;
+ }
+ }
+
+ return resource;
+ }
+
+ public String put(RequestContext requestContext) throws RegistryException {
+
+ Iterator<Filter> filters = handlerMap.keySet().iterator();
+ while (filters.hasNext()) {
+ Filter filter = filters.next();
+ if (filter.handlePut(requestContext)) {
+ handlerMap.get(filter).put(requestContext);
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ break;
+ }
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ return requestContext.getActualPath();
+ } else {
+ return null;
+ }
+ }
+
+ public String importResource(RequestContext requestContext) throws RegistryException {
+
+ Iterator<Filter> filters = handlerMap.keySet().iterator();
+ while (filters.hasNext()) {
+ Filter filter = filters.next();
+ if (filter.handleImportResource(requestContext)) {
+ handlerMap.get(filter).importResource(requestContext);
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ break;
+ }
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ return requestContext.getActualPath();
+ } else {
+ return null;
+ }
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+
+ Iterator<Filter> filters = handlerMap.keySet().iterator();
+ while (filters.hasNext()) {
+ Filter filter = filters.next();
+ if (filter.handleDelete(requestContext)) {
+ handlerMap.get(filter).delete(requestContext);
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ break;
+ }
+ }
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+
+ Iterator<Filter> filters = handlerMap.keySet().iterator();
+ while (filters.hasNext()) {
+ Filter filter = filters.next();
+ if (filter.handlePutChild(requestContext)) {
+ handlerMap.get(filter).putChild(requestContext);
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ break;
+ }
+ }
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+
+ Iterator<Filter> filters = handlerMap.keySet().iterator();
+ while (filters.hasNext()) {
+ Filter filter = filters.next();
+ if (filter.handleImportChild(requestContext)) {
+ handlerMap.get(filter).importChild(requestContext);
+ }
+
+ if (requestContext.isProcessingComplete()) {
+ break;
+ }
+ }
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/RequestContext.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/RequestContext.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers;
+
+import org.wso2.registry.Resource;
+import org.wso2.registry.Collection;
+
+/**
+ * Objects of this class contains the information about the current request to the registry.
+ * All attributes of such objects should be either null or should contain a *valid" value. That is,
+ * if an attribute contains a non-null value it is safe to assume that attribute contains a valid
+ * value as mentioned by the javadoc of that attribute.
+ */
+public class RequestContext {
+
+ /**
+ * Specifies whether the processing of the current request is completed or not. If this is true,
+ * any further processing of the request is not done.
+ */
+ private boolean processingComplete;
+
+ /**
+ * Path of the currently processing resource as given by the client of the Registry API
+ */
+ private String resourcePath;
+
+ /**
+ * Path of the currently processing resource, which may have been modified by Registry impls to
+ * represent the actual path in which resource resides.
+ */
+ private String actualPath;
+
+ /**
+ * Currently processing resource. This is the resource referred by the actual path.
+ */
+ private Resource resource;
+
+ /**
+ * URL where the current resource content is located.
+ */
+ private String sourceURL;
+
+ /**
+ * Path of the parent collection of the current resource.
+ */
+ private String parentPath;
+
+ /**
+ * Parent collection of the current resource.
+ */
+ private Collection parentCollection;
+
+ public boolean isProcessingComplete() {
+ return processingComplete;
+ }
+
+ public void setProcessingComplete(boolean processingComplete) {
+ this.processingComplete = processingComplete;
+ }
+
+ public String getResourcePath() {
+ return resourcePath;
+ }
+
+ public void setResourcePath(String resourcePath) {
+ this.resourcePath = resourcePath;
+ }
+
+ public String getSourceURL() {
+ return sourceURL;
+ }
+
+ public void setSourceURL(String sourceURL) {
+ this.sourceURL = sourceURL;
+ }
+
+ public String getActualPath() {
+ return actualPath;
+ }
+
+ public void setActualPath(String actualPath) {
+ this.actualPath = actualPath;
+ }
+
+ public Resource getResource() {
+ return resource;
+ }
+
+ public void setResource(Resource resource) {
+ this.resource = resource;
+ }
+
+ public String getParentPath() {
+ return parentPath;
+ }
+
+ public void setParentPath(String parentPath) {
+ this.parentPath = parentPath;
+ }
+
+ public Collection getParentCollection() {
+ return parentCollection;
+ }
+
+ public void setParentCollection(Collection parentCollection) {
+ this.parentCollection = parentCollection;
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/Axis2RepositoryHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/Axis2RepositoryHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.*;
+import org.wso2.registry.users.UserRealm;
+
+import javax.sql.DataSource;
+
+public class Axis2RepositoryHandler extends Handler {
+
+ public Axis2RepositoryHandler() {}
+
+ public Axis2RepositoryHandler(
+ DataSource dataSource, UserRealm userRealm, Repository repository, Registry registry) {
+ super(dataSource, userRealm, repository, registry);
+ }
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+ return null;
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+
+ String path = requestContext.getResourcePath();
+ repository.put(path, requestContext.getResource());
+
+ String confPath = path +
+ RegistryConstants.PATH_SEPARATOR + RegistryConstants
+ .AXIS2_CONF_COLLECTION_NAME;
+ CollectionImpl confCollection = new CollectionImpl();
+ confCollection.setPath(confPath);
+ confCollection.setMediaType(RegistryConstants.AXIS2_CONF_COLLECTION_MEDIA_TYPE);
+ repository.put(confPath, confCollection);
+
+ String servicesPath = path +
+ RegistryConstants.PATH_SEPARATOR + RegistryConstants
+ .AXIS2_SERVICES_COLLECTION_NAME;
+ CollectionImpl servicesCollection = new CollectionImpl();
+ servicesCollection.setPath(servicesPath);
+ servicesCollection.setMediaType(RegistryConstants.AXIS2_SERVICES_COLLECTION_MEDIA_TYPE);
+ repository.put(servicesPath, servicesCollection);
+
+ String modulesPath = path +
+ RegistryConstants.PATH_SEPARATOR + RegistryConstants
+ .AXIS2_MODULES_COLLECTION_NAME;
+ CollectionImpl modulesCollection = new CollectionImpl();
+ modulesCollection.setPath(modulesPath);
+ modulesCollection.setMediaType(RegistryConstants.AXIS2_MODULES_COLLECTION_MEDIA_TYPE);
+ repository.put(modulesPath, modulesCollection);
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ requestContext.setProcessingComplete(false);
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+
+ Resource childResource = requestContext.getResource();
+ if (childResource == null) {
+ childResource = repository.get(requestContext.getResourcePath());
+ requestContext.setResource(childResource);
+ }
+ String childMediaType = requestContext.getResource().getMediaType();
+
+ if(!(RegistryConstants.AXIS2_CONF_COLLECTION_MEDIA_TYPE.equals(childMediaType) ||
+ RegistryConstants.AXIS2_SERVICES_COLLECTION_MEDIA_TYPE.equals(childMediaType) ||
+ RegistryConstants.AXIS2_MODULES_COLLECTION_MEDIA_TYPE.equals(childMediaType))) {
+
+ requestContext.setProcessingComplete(true);
+
+ } else {
+ String msg = "Resources of type: " + childMediaType +
+ " are not allowed to add as child resources of " +
+ "the typed collection Axis2 Repository.";
+ throw new RegistryException(msg);
+ }
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/CommentCollectionURLHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/CommentCollectionURLHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.Comment;
+import org.wso2.registry.CollectionImpl;
+
+public class CommentCollectionURLHandler extends Handler {
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+
+ String url = requestContext.getResourcePath();
+
+ String[] parts = url.split(";");
+
+ if (parts.length != 2) {
+ return null;
+ }
+
+ if (parts[0].length() == 0) {
+ return null;
+ }
+
+ if (!parts[1].equals("comments")) {
+ return null;
+ }
+
+ Comment[] comments = registry.getComments(parts[0]);
+ CollectionImpl resource = new CollectionImpl();
+ resource.setContent(comments);
+
+ requestContext.setProcessingComplete(true);
+ return resource;
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/CommentURLHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/CommentURLHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.jdbc.dao.CommentsDAO;
+import org.wso2.registry.*;
+import org.wso2.registry.secure.AuthorizationFailedException;
+import org.wso2.registry.utils.AuthorizationUtil;
+import org.wso2.registry.users.UserRealm;
+import org.wso2.registry.users.UserStoreException;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import javax.sql.DataSource;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+public class CommentURLHandler extends Handler {
+
+ private static final Log log = LogFactory.getLog(CommentURLHandler.class);
+
+ private CommentsDAO commentsDAO = new CommentsDAO();
+
+ public CommentURLHandler() {}
+
+ public CommentURLHandler(
+ DataSource dataSource, UserRealm userRealm, Repository repository, Registry registry) {
+ super(dataSource, userRealm, repository, registry);
+ }
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+
+ String url = requestContext.getResourcePath();
+ String[] parts = url.split(";");
+
+ if (parts.length != 2) {
+ return null;
+ }
+
+ if (parts[0].length() == 0) {
+ return null;
+ }
+
+ if (!parts[1].startsWith("comments:")) {
+ return null;
+ }
+
+ String commentID = parts[1].substring("comments:".length());
+ if (!(commentID.length() > 0)) {
+ return null;
+ }
+
+ long cID;
+ try {
+ cID = Long.parseLong(commentID);
+
+ } catch (NumberFormatException e) {
+ // note that this might not be an exceptional scenario. there could be a different URL
+ // form, which contains strings after "comment".
+ // it is just that it is not the URL we expect here
+ return null;
+ }
+
+ Connection conn;
+ try {
+ conn = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+
+ Comment comment = null;
+ String resourcePath = "";
+ try {
+ comment = commentsDAO.getComment(cID, conn);
+ resourcePath = commentsDAO.getResourcePathOfComment(cID, conn);
+
+ } catch (SQLException e) {
+ String msg = "Could not get the comment with ID: " + cID +
+ ". Caused by: " + e.getMessage();
+ log.error(msg, e);
+ throw new RegistryException(msg);
+
+ } finally {
+ if (conn != null) {
+ try {
+ conn.close();
+ } catch (SQLException ignore) {
+ log.info("exception.closing.db");
+ }
+ }
+ }
+
+ if (comment == null) {
+ String msg = "Requested comment with ID: " + cID + " is not available.";
+ log.info(msg);
+ throw new RegistryException(msg);
+ }
+
+ ResourceImpl resource = new ResourceImpl();
+ resource.setPath(url);
+ resource.setMediaType(RegistryConstants.COMMENT_MEDIA_TYPE);
+ resource.setContent(comment.getText());
+ resource.setAuthorUserName(comment.getUser());
+ resource.setCreatedTime(comment.getTime());
+ resource.setProperty("resourcePath", resourcePath);
+
+ requestContext.setProcessingComplete(true);
+ return resource;
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+
+ requestContext.setProcessingComplete(false);
+ String path = requestContext.getResourcePath();
+ String[] parts = path.split(";");
+
+ if (parts.length != 2) {
+ return;
+ }
+
+ if (parts[0].length() == 0) {
+ return;
+ }
+
+ if (!parts[1].startsWith("comments:")) {
+ return;
+ }
+
+ String commentID = parts[1].substring("comments:".length());
+ if (!(commentID.length() > 0)) {
+ return;
+ }
+
+ long cID;
+ try {
+ cID = Long.parseLong(commentID);
+
+ } catch (NumberFormatException e) {
+ // note that this might not be an exceptional scenario. there could be a different URL
+ // form, which contains strings after "comment".
+ // it is just that it is not the URL we expect here
+ return;
+ }
+
+ String userID = User.getCurrentUser();
+ String authPath = AuthorizationUtil.getAuthorizationPath(path);
+ String commentAuthor;
+
+ Connection conn1 = null;
+ try {
+ conn1 = dataSource.getConnection();
+
+ Comment comment = commentsDAO.getComment(cID, conn1);
+ commentAuthor = comment.getUser();
+
+ } catch (SQLException e) {
+
+ String msg = "Failed to get the author of the comment.";
+ log.error(msg, e);
+ throw new RegistryException(msg, e);
+
+ } finally {
+ if (conn1 != null) {
+ try {
+ conn1.close();
+ } catch (SQLException e) {
+ log.info("exception.closing.db");
+ }
+ }
+ }
+
+ // check if the current user has permission to delete this comment.
+ // users who have PUT permission on the commented resource can delete any comment on
+ // that resource. Any user can delete his own comment.
+
+ try {
+ if (!userID.equals(commentAuthor) &&
+ !realm.getAuthorizer().isUserAuthorized(userID, authPath, ActionConstants.PUT)) {
+
+ String msg = "User: " + userID +
+ " is not authorized to delete the comment on the resource: " +
+ authPath;
+ log.info(msg);
+ throw new AuthorizationFailedException(msg);
+ }
+
+ } catch (UserStoreException e) {
+ //
+ }
+
+
+ Connection conn2;
+ try {
+ conn2 = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+
+ try {
+
+ commentsDAO.deleteComment(cID, conn2);
+
+ } catch (SQLException e) {
+ String msg = "Could not delete the comment with the path: " + path;
+ throw new RegistryException(msg, e);
+ } finally {
+ if (conn2 != null) {
+ try {
+ conn2.close();
+ } catch (SQLException ignore) {
+ log.info("exception.closing.db");
+ }
+ }
+ }
+
+ requestContext.setProcessingComplete(true);
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+ //To change body of implemented methods use File | Settings | File Templates.
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/RatingCollectionURLHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/RatingCollectionURLHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.dao.RatingsDAO;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.CollectionImpl;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.List;
+import java.util.ArrayList;
+
+public class RatingCollectionURLHandler extends Handler {
+
+ private static final Log log = LogFactory.getLog(RatingCollectionURLHandler.class);
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+
+ String url = requestContext.getResourcePath();
+
+ String[] parts = url.split(";");
+
+ if (parts.length != 2) {
+ return null;
+ }
+
+ if (parts[0].length() == 0) {
+ return null;
+ }
+
+ if (!parts[1].equals("ratings")) {
+ return null;
+ }
+
+ if (parts[1].length() != "ratings".length()) {
+ return null;
+ }
+
+ String resourcePath = parts[0];
+
+ Connection conn;
+ try {
+ conn = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+
+ RatingsDAO ratingsDAO = new RatingsDAO();
+
+ try {
+ CollectionImpl resource = new CollectionImpl();
+ resource.setPath(url);
+
+ String[] ratedUserNames = ratingsDAO.getRatedUserNames(resourcePath, conn);
+ List ratingPaths = new ArrayList();
+ for (String ratedUserName : ratedUserNames) {
+ String ratingPath = resourcePath + ";ratings:" + ratedUserName;
+ ratingPaths.add(ratingPath);
+ }
+
+ String[] ratingsContent = (String[])ratingPaths.toArray(new String[ratingPaths.size()]);
+ resource.setContent(ratingsContent);
+
+ return resource;
+
+ } catch (SQLException e) {
+ String msg = "Failed to get ratings for resource: " +
+ resourcePath + ". Caused by: " + e.getMessage();
+ log.error(msg, e);
+ throw new RegistryException(msg);
+
+ } finally {
+ try {
+ conn.close();
+ } catch (SQLException ignore) {
+ log.info("exception.closing.db");
+ }
+ }
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/RatingURLHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/RatingURLHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,113 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.dao.RatingsDAO;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.ResourceImpl;
+import org.wso2.registry.RegistryConstants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import java.util.Date;
+
+public class RatingURLHandler extends Handler {
+
+ private static final Log log = LogFactory.getLog(RatingURLHandler.class);
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+
+ String url = requestContext.getResourcePath();
+
+ String[] parts = url.split(";");
+
+ if (parts.length != 2) {
+ return null;
+ }
+
+ if (parts[0].length() == 0) {
+ return null;
+ }
+
+ String[] details = parts[1].split(":");
+ if (details.length != 2 || !details[0].equals("ratings") || details[1].length() == 0) {
+ return null;
+ }
+
+ String resourcePath = parts[0];
+ String ratedUserName = details[1];
+
+ Connection conn;
+
+ try {
+ conn = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+
+ try {
+ RatingsDAO ratingsDAO = new RatingsDAO();
+ int rating = ratingsDAO.getRating(resourcePath, ratedUserName, conn);
+ Date ratedTime = ratingsDAO.getRatedTime(resourcePath, ratedUserName, conn);
+
+ ResourceImpl resource = new ResourceImpl();
+ resource.setMediaType(RegistryConstants.RATING_MEDIA_TYPE);
+ resource.setContent(rating);
+ resource.setAuthorUserName(ratedUserName);
+ resource.setPath(url);
+ resource.setCreatedTime(ratedTime);
+ resource.setProperty("resourcePath", resourcePath);
+
+ return resource;
+
+ } catch (SQLException e) {
+ String msg = "Could not get the rating for resource at " + resourcePath +
+ ". Caused by: " + e.getMessage();
+ log.error(msg, e);
+ throw new RegistryException(msg);
+
+ } finally {
+ if (conn != null) {
+ try {
+ conn.close();
+ } catch (SQLException ignore) {
+ log.info("Error while closing the DB connection");
+ }
+ }
+ }
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/SQLQueryHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/SQLQueryHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.mediatypes.MediaTypeHandler;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+
+public class SQLQueryHandler extends Handler {
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+
+ Resource resource = requestContext.getResource();
+ if (resource == null) {
+ resource = repository.get(requestContext.getResourcePath());
+ requestContext.setResource(resource);
+ }
+
+ Object content = resource.getContent();
+ if (content instanceof byte[]) {
+ resource.setContent(new String((byte[])content));
+ }
+
+ requestContext.setProcessingComplete(true);
+ return resource;
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+
+ Resource resource = requestContext.getResource();
+
+ Object content = resource.getContent();
+ if (content instanceof String) {
+ String textContent = (String)content;
+ resource.setContent(textContent.getBytes());
+ }
+
+ repository.put(requestContext.getResourcePath(), resource);
+ requestContext.setProcessingComplete(true);
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/SynapseRepositoryHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/SynapseRepositoryHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.mediatypes.MediaTypeHandler;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.RegistryConstants;
+import org.wso2.registry.CollectionImpl;
+
+public class SynapseRepositoryHandler extends Handler {
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+ return null;
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+
+ String path = requestContext.getResourcePath();
+ Resource resource = requestContext.getResource();
+
+ repository.put(path, resource);
+
+ String confPath = path +
+ RegistryConstants.PATH_SEPARATOR + RegistryConstants
+ .SYNAPSE_CONF_COLLECTION_NAME;
+ CollectionImpl confCollection = new CollectionImpl();
+ confCollection.setPath(confPath);
+ confCollection.setMediaType(RegistryConstants.SYNAPSE_CONF_COLLECTION_MEDIA_TYPE);
+ repository.put(confPath, confCollection);
+
+ String seqPath = path + RegistryConstants.PATH_SEPARATOR +
+ RegistryConstants.SYNAPSE_SEQUENCES_COLLECTION_NAME;
+ CollectionImpl seqCollection = new CollectionImpl();
+ seqCollection.setPath(seqPath);
+ seqCollection.setMediaType(RegistryConstants.SYNAPSE_SEQUENCE_COLLECTION_MEDIA_TYPE);
+ repository.put(seqPath, seqCollection);
+
+ String epPath = path + RegistryConstants.PATH_SEPARATOR +
+ RegistryConstants.SYNAPSE_ENDPOINT_COLLECTION_NAME;
+ CollectionImpl epCollection = new CollectionImpl();
+ epCollection.setPath(epPath);
+ epCollection.setMediaType(RegistryConstants.SYNAPSE_ENDPOINT_COLLECTION_MEDIA_TYPE);
+ repository.put(epPath, epCollection);
+
+ String proxyServicesPath = path + RegistryConstants.PATH_SEPARATOR +
+ RegistryConstants.SYNAPSE_PROXY_SERVICES_COLLECTION_NAME;
+ CollectionImpl proxyCollection = new CollectionImpl();
+ proxyCollection.setPath(proxyServicesPath);
+ proxyCollection
+ .setMediaType(RegistryConstants.SYNAPSE_PROXY_SERVICES_COLLECTION_MEDIA_TYPE);
+ repository.put(proxyServicesPath, proxyCollection);
+
+ String tasksPath = path + RegistryConstants.PATH_SEPARATOR +
+ RegistryConstants.SYNAPSE_TASKS_COLLECTION_NAME;
+ CollectionImpl tasksCollection = new CollectionImpl();
+ tasksCollection.setPath(tasksPath);
+ tasksCollection.setMediaType(RegistryConstants.SYNAPSE_TASKS_COLLECTION_MEDIA_TYPE);
+ repository.put(tasksPath, tasksCollection);
+
+ String entriesPath = path + RegistryConstants.PATH_SEPARATOR +
+ RegistryConstants.SYNAPSE_ENTRIES_COLLECTION_NAME;
+ CollectionImpl entryCollection = new CollectionImpl();
+ entryCollection.setPath(entriesPath);
+ entryCollection.setMediaType(RegistryConstants.SYNAPSE_ENTRIES_COLLECTION_MEDIA_TYPE);
+ repository.put(entriesPath, entryCollection);
+
+ requestContext.setProcessingComplete(true);
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+
+ String childMediaType = requestContext.getResource().getMediaType();
+
+ if(!(RegistryConstants.SYNAPSE_CONF_COLLECTION_MEDIA_TYPE.equals(childMediaType) ||
+ RegistryConstants.SYNAPSE_SEQUENCE_COLLECTION_MEDIA_TYPE.equals(childMediaType) ||
+ RegistryConstants.SYNAPSE_ENDPOINT_COLLECTION_MEDIA_TYPE.equals(childMediaType) ||
+ RegistryConstants.SYNAPSE_PROXY_SERVICES_COLLECTION_MEDIA_TYPE.equals(childMediaType)
+ || RegistryConstants.SYNAPSE_TASKS_COLLECTION_MEDIA_TYPE.equals(childMediaType) ||
+ RegistryConstants.SYNAPSE_ENTRIES_COLLECTION_MEDIA_TYPE.equals(childMediaType))) {
+
+ String msg = "Resources of type: " + childMediaType +
+ " are not allowed to add as child resources of " +
+ "the typed collection Synapse Repository.";
+
+ throw new RegistryException(msg);
+
+ }
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/TagURLHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/TagURLHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.dao.TagsDAO;
+import org.wso2.registry.jdbc.dataobjects.TaggingDO;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.ResourceImpl;
+import org.wso2.registry.RegistryConstants;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+public class TagURLHandler extends Handler {
+
+ private static final Log log = LogFactory.getLog(TagURLHandler.class);
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+
+ String url = requestContext.getResourcePath();
+
+ String[] parts = url.split(";");
+
+ if (parts.length != 2) {
+ return null;
+ }
+
+ if (parts[0].length() == 0) {
+ return null;
+ }
+
+ String[] queries = parts[1].split(":");
+
+ if (queries.length != 3) {
+ return null;
+ }
+
+ String resourcePath = parts[0];
+ String tagName = queries[1];
+ String userName = queries[2];
+
+ Connection conn;
+ try {
+ conn = dataSource.getConnection();
+ } catch (SQLException e) {
+ throw new RegistryException(e.getMessage());
+ }
+
+ try {
+ TagsDAO tagsDAO = new TagsDAO();
+ TaggingDO taggingDO = tagsDAO.getTagging(resourcePath, tagName, userName, conn);
+
+ ResourceImpl resource = new ResourceImpl();
+ resource.setMediaType(RegistryConstants.TAG_MEDIA_TYPE);
+ resource.setContent(taggingDO.getTagName());
+ resource.setAuthorUserName(taggingDO.getTaggedUserName());
+ resource.setCreatedTime(taggingDO.getTaggedTime());
+ resource.setProperty("resourcePath", taggingDO.getResourcePath());
+
+ return resource;
+
+ } catch (SQLException e) {
+ String msg = "Could not get tagging. Caused by: " + e.getMessage();
+ throw new RegistryException(msg, e);
+
+ } finally {
+ try {
+ conn.close();
+ } catch (SQLException ignore) {
+ log.info("exception.closing.db");
+ }
+ }
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/WSDLMediaTypeHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/WSDLMediaTypeHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.handlers.builtin.utils.WSDLFileProcessor;
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.RegistryConstants;
+import org.wso2.registry.utils.AuthorizationUtil;
+import org.wso2.registry.utils.RegistryUtils;
+
+public class WSDLMediaTypeHandler extends Handler {
+
+ private WSDLFileProcessor wsdlFileProcessor;
+
+ public void setRepository(Repository repository) {
+ super.setRepository(repository);
+
+ wsdlFileProcessor = new WSDLFileProcessor(repository);
+ }
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+ return null;
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+
+ Resource metadata = requestContext.getResource();
+ String parentPath = RegistryUtils.getParentPath(requestContext.getResourcePath());
+ String sourceURL = requestContext.getSourceURL();
+
+ String savedName = wsdlFileProcessor
+ .saveWSDLFileToRegistry(sourceURL, parentPath, true, metadata);
+
+ if (parentPath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
+ requestContext.setActualPath(parentPath + savedName);
+ } else {
+ requestContext.setActualPath(parentPath + RegistryConstants.PATH_SEPARATOR + savedName);
+ }
+
+ requestContext.setProcessingComplete(true);
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/XSDMediaTypeHandler.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/XSDMediaTypeHandler.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin;
+
+import org.wso2.registry.jdbc.handlers.Handler;
+import org.wso2.registry.jdbc.handlers.RequestContext;
+import org.wso2.registry.jdbc.handlers.builtin.utils.SchemaFileProcessor;
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.RegistryConstants;
+import org.wso2.registry.utils.AuthorizationUtil;
+import org.wso2.registry.utils.RegistryUtils;
+
+public class XSDMediaTypeHandler extends Handler {
+
+ SchemaFileProcessor schemaFileProcessor;
+
+ public void setRepository(Repository repository) {
+ super.setRepository(repository);
+
+ schemaFileProcessor = new SchemaFileProcessor(repository);
+ }
+
+ public Resource get(RequestContext requestContext) throws RegistryException {
+ return null;
+ }
+
+ public void put(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importResource(RequestContext requestContext) throws RegistryException {
+
+ Resource metadata = requestContext.getResource();
+ String parentPath = RegistryUtils.getParentPath(requestContext.getResourcePath());
+ String sourceURL = requestContext.getSourceURL();
+
+ String savedName = schemaFileProcessor
+ .saveSchemaFileToRegistry(sourceURL, parentPath, true, metadata);
+
+ if (parentPath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
+ requestContext.setActualPath(parentPath + savedName);
+ } else {
+ requestContext.setActualPath(parentPath + RegistryConstants.PATH_SEPARATOR + savedName);
+ }
+
+ requestContext.setProcessingComplete(true);
+ }
+
+ public void delete(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void putChild(RequestContext requestContext) throws RegistryException {
+ }
+
+ public void importChild(RequestContext requestContext) throws RegistryException {
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/utils/SchemaFileProcessor.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/utils/SchemaFileProcessor.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin.utils;
+
+import org.wso2.registry.jdbc.mediatypes.builtin.DefaultMediaTypeHandler;
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.ResourceImpl;
+import org.wso2.registry.RegistryConstants;
+import org.apache.ws.commons.schema.XmlSchemaCollection;
+import org.apache.ws.commons.schema.XmlSchema;
+import org.apache.ws.commons.schema.XmlSchemaObjectCollection;
+import org.apache.ws.commons.schema.XmlSchemaExternal;
+import org.xml.sax.InputSource;
+
+import java.util.*;
+import java.io.ByteArrayOutputStream;
+
+public class SchemaFileProcessor {
+
+ private Repository repository;
+
+ // remove this when it is not needed
+ private int i;
+
+ public SchemaFileProcessor(Repository repository) {
+ this.repository = repository;
+ }
+
+ /**
+ * Import a schema file to the registry after saving all its includes and imports to the
+ * registry and updating the schema locations accordingly.
+ *
+ * @param location the original schema location
+ * @param registryBasePath base path of the registry
+ * @param processIncludes true if we should recurse through includes
+ * @param metadata template Resource from which to obtain media-type, description, etc.
+ * @return the resulting path of the new resource
+ * @throws org.wso2.registry.RegistryException
+ */
+ public String saveSchemaFileToRegistry(String location,
+ String registryBasePath,
+ boolean processIncludes,
+ Resource metadata)
+ throws RegistryException {
+ return saveSchemaFileToRegistry(location, new HashMap(), registryBasePath, processIncludes,
+ metadata);
+ }
+
+ /**
+ * Import a schema file to the registry after saving all its includes and imports to the
+ * registry and updating the schema locations accordingly.
+ *
+ * @param location the original schema location
+ * @param processedSchemaMap a Map from original URI (String) to new schema location (String)
+ * @param registryBasePath base path of the registry
+ * @param processIncludes true if we should recurse through includes
+ * @param metadata template Resource from which to obtain media-type, description,
+ * etc.
+ * @return the resulting path of the new resource
+ * @throws RegistryException
+ */
+ public String saveSchemaFileToRegistry(String location,
+ Map processedSchemaMap,
+ String registryBasePath,
+ boolean processIncludes,
+ Resource metadata)
+ throws RegistryException {
+
+ XmlSchemaCollection xmlSchemaCollection = new XmlSchemaCollection();
+ InputSource inputSource = new InputSource(location);
+
+ // Here we assue schema is correct. Schema validation is beyond our scope, so we don't
+ // bother with a ValidationEventHandler.
+ XmlSchema xmlSchema = xmlSchemaCollection.read(inputSource, null);
+
+ String baseUri = xmlSchema.getSourceURI();
+ String xsdFileName = baseUri.substring(baseUri.lastIndexOf("/") + 1);
+ String savedName = xsdFileName.substring(0, xsdFileName.indexOf(".")) + ".xsd";
+
+ // this is not an inline wsdl schema. so pass null to change map.
+ calculateNewSchemaNames(xmlSchema, processedSchemaMap, new HashSet(), false,
+ processIncludes);
+ saveSchemaFileToRegistry(xmlSchema, processedSchemaMap, null, new HashSet(), false,
+ registryBasePath, processIncludes, metadata);
+
+ return savedName;
+ }
+
+ /**
+ * calculate the new schema file names to save the schema. Here we can not save the schema file
+ * as it is since there may be recursive imports. So what we have to do is to first determine
+ * the schema names to be saved and then change the schema locations accordingly. In this method
+ * first we iterate through the imports and includes and find the names. have used the
+ * visitedSchemas variable to keep track of the visited schemas to avoid the recursion.
+ *
+ * @param xmlSchema the schema to we'd like to save into the registry
+ * @param processedSchemaMap a Map from original URI (String) to new schema location (String)
+ * @param visitedSchemas a Set of previously visited schema source uris
+ * @param isWSDLInlineSchema true if the given schema is an inline schema of a wsdl - if so, we
+ * do not need to calculate a name for it
+ * @param processIncludes true if we should process includes
+ */
+ public void calculateNewSchemaNames(XmlSchema xmlSchema,
+ Map processedSchemaMap,
+ Set visitedSchemas,
+ boolean isWSDLInlineSchema,
+ boolean processIncludes) {
+
+ if (processIncludes) {
+ // first process the imports and includes
+ XmlSchemaObjectCollection includes = xmlSchema.getIncludes();
+ // set this as an visited schema to stop recursion
+ visitedSchemas.add(xmlSchema.getSourceURI());
+ if (includes != null) {
+ Object externalComponent;
+ XmlSchemaExternal xmlSchemaExternal;
+ XmlSchema innerSchema;
+ for (Iterator iter = includes.getIterator(); iter.hasNext();) {
+ externalComponent = iter.next();
+ if (externalComponent instanceof XmlSchemaExternal) {
+ xmlSchemaExternal = (XmlSchemaExternal)externalComponent;
+ innerSchema = xmlSchemaExternal.getSchema();
+ String sourceURI = innerSchema.getSourceURI();
+ // Process if we haven't already encountered this one
+ if (!processedSchemaMap.containsKey(sourceURI) &&
+ !visitedSchemas.contains(sourceURI)) {
+ calculateNewSchemaNames(innerSchema, processedSchemaMap, visitedSchemas,
+ false, processIncludes);
+ }
+ }
+ }
+ }
+ }
+
+ // after processing includes and imports save the xml schema
+ if (!isWSDLInlineSchema) {
+ String baseUri = xmlSchema.getSourceURI();
+ String xsdFileName = baseUri.substring(baseUri.lastIndexOf("/") + 1);
+ String fileNameToSave = xsdFileName.substring(0, xsdFileName.indexOf(".")) + ".xsd";
+ while (processedSchemaMap.containsValue(fileNameToSave)) {
+ fileNameToSave = xsdFileName.substring(0, xsdFileName.indexOf(".")) + ++i + ".xsd";
+ }
+ // add this entry to the processed wsdl map
+ processedSchemaMap.put(baseUri, fileNameToSave);
+ }
+ }
+
+ /**
+ * Save the schemas to the registry. used the calculated names in the processedSchemaMap to
+ * change the schema locations.
+ *
+ * @param xmlSchema the schema to save
+ * @param processedSchemaMap a Map from original URI (String) to new schema location (String)
+ * @param changeSchemaNames a Map from original URIs to changed URIs. Used to update the WSDL
+ * inline schema imports/includes when saving WSDLs.
+ * @param visitedSchemas a Set of schema URIs (Strings) that we've already visited
+ * @param isWSDLInlineSchema true if this is an inline schema from a WSDL
+ * @param registryBasePath the base path of the registry
+ * @param processIncludes true if we should recurse into includes of this schema
+ * @param metadata template Resource for metadata (media-type, description)
+ * @throws RegistryException
+ */
+ public void saveSchemaFileToRegistry(XmlSchema xmlSchema,
+ Map processedSchemaMap,
+ Map changeSchemaNames,
+ Set visitedSchemas,
+ boolean isWSDLInlineSchema,
+ String registryBasePath,
+ boolean processIncludes,
+ Resource metadata) throws RegistryException {
+
+ if (processIncludes) {
+ // first process the imports and includes
+ XmlSchemaObjectCollection includes = xmlSchema.getIncludes();
+ // set this as an visited schema to stop recursion
+ visitedSchemas.add(xmlSchema.getSourceURI());
+ if (includes != null) {
+ for (Iterator iter = includes.getIterator(); iter.hasNext();) {
+ Object externalComponent = iter.next();
+ if (externalComponent instanceof XmlSchemaExternal) {
+ XmlSchemaExternal xmlSchemaExternal = (XmlSchemaExternal)externalComponent;
+ String sourceURI = xmlSchemaExternal.getSchema().getSourceURI();
+ if (!visitedSchemas.contains(sourceURI)) {
+ saveSchemaFileToRegistry(xmlSchemaExternal.getSchema(),
+ processedSchemaMap, null, visitedSchemas,
+ false, registryBasePath, processIncludes,
+ null);
+ }
+
+ // add the new name to changeschema map
+ // have to do before change the schema location
+ String newLocation = (String)processedSchemaMap.get(sourceURI);
+ if (isWSDLInlineSchema) {
+ changeSchemaNames.put(xmlSchemaExternal.getSchemaLocation(),
+ newLocation);
+ }
+ // set the new location
+ xmlSchemaExternal.setSchemaLocation(newLocation);
+ }
+ }
+ }
+ }
+
+ // after processing includes and imports save the xml schema
+ if (!isWSDLInlineSchema) {
+ String fileNameToSave = (String)processedSchemaMap.get(xmlSchema.getSourceURI());
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ xmlSchema.write(byteArrayOutputStream);
+ byte[] xsdContent = byteArrayOutputStream.toByteArray();
+
+ ResourceImpl xsdResource = new ResourceImpl();
+ if (metadata != null) {
+ xsdResource.setMediaType(metadata.getMediaType());
+ xsdResource.setDescription(metadata.getDescription());
+ }
+ xsdResource.setContent(xsdContent);
+
+ String xsdPath;
+ if (RegistryConstants.ROOT_PATH.equals(registryBasePath)) {
+ xsdPath = RegistryConstants.ROOT_PATH + fileNameToSave;
+ } else {
+ xsdPath = registryBasePath + RegistryConstants.PATH_SEPARATOR + fileNameToSave;
+ }
+
+ repository.put(xsdPath, xsdResource);
+
+ //xmlSchema.write(new FileOutputStream("repository/" + fileNameToSave),
+ // getDefaultOptionMap());
+ // add this entry to the proccessed wsdl map
+ }
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/utils/WSDLFileProcessor.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/jdbc/handlers/builtin/utils/WSDLFileProcessor.java Tue Mar 4 07:31:13 2008
@@ -0,0 +1,282 @@
+/*
+ * Copyright (c) 2006, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.wso2.registry.jdbc.handlers.builtin.utils;
+
+import org.wso2.registry.jdbc.Repository;
+import org.wso2.registry.Resource;
+import org.wso2.registry.RegistryException;
+import org.wso2.registry.RegistryConstants;
+import org.wso2.registry.ResourceImpl;
+import org.apache.ws.commons.schema.XmlSchema;
+import org.apache.ws.commons.schema.XmlSchemaCollection;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Node;
+import org.w3c.dom.NamedNodeMap;
+
+import javax.wsdl.xml.WSDLReader;
+import javax.wsdl.xml.WSDLWriter;
+import javax.wsdl.factory.WSDLFactory;
+import javax.wsdl.WSDLException;
+import javax.wsdl.Definition;
+import javax.wsdl.Import;
+import javax.wsdl.Types;
+import javax.wsdl.extensions.schema.Schema;
+import java.util.*;
+import java.io.ByteArrayOutputStream;
+
+public class WSDLFileProcessor {
+
+ // remove this when it is not needed
+ private int i;
+
+ public static final String IMPORT_TAG = "import";
+ public static final String INCLUDE_TAG = "include";
+
+ Repository repository;
+
+ public WSDLFileProcessor(Repository repository) {
+ this.repository = repository;
+ }
+
+ /**
+ * saves a wsdl file including its imports and imported schemas.
+ *
+ * @param location
+ * @throws javax.wsdl.WSDLException
+ */
+ public String saveWSDLFileToRegistry(String location,
+ String registryBasePath,
+ boolean processImports,
+ Resource metadata)
+ throws RegistryException {
+ WSDLReader wsdlReader;
+ String fileNameToSave;
+
+ try {
+ wsdlReader = WSDLFactory.newInstance().newWSDLReader();
+ } catch (WSDLException e) {
+ String msg = "Could not initiate the wsdl reader. Caused by: " + e.getMessage();
+ throw new RegistryException(msg);
+ }
+
+ wsdlReader.setFeature("javax.wsdl.importDocuments", true);
+ Definition wsdlDefinition;
+
+ try {
+ wsdlDefinition = wsdlReader.readWSDL(location);
+ String baseUri = wsdlDefinition.getDocumentBaseURI();
+ String wsdlFileName = baseUri.substring(baseUri.lastIndexOf("/") + 1);
+ fileNameToSave = wsdlFileName.substring(0, wsdlFileName.indexOf(".")) + ".wsdl";
+ } catch (WSDLException e) {
+ String msg = "Could not read the wsdl at location " + location + ". Caused by: " +
+ e.getMessage();
+ throw new RegistryException(msg);
+ }
+
+ Map processedWSDLMap = new HashMap();
+ calculateWSDLNamesAndChangeTypes(wsdlDefinition, processedWSDLMap, new HashMap(),
+ new HashSet(), registryBasePath, processImports);
+ saveWSDLFileToRegistry(wsdlDefinition, processedWSDLMap, new HashSet(), registryBasePath,
+ processImports, metadata);
+
+ return fileNameToSave;
+ }
+
+ /**
+ * saves the given wsdl definition file with its imported wsdls and imported and included
+ * schemas.
+ *
+ * @param wsdlDefinition - wsdl file to save
+ * @param processedWSDLMap - map with original source URI vs new uris for wsdls
+ * @param processedScheamMap - map with orignal source URI vs new uris for schemas
+ */
+
+ public void calculateWSDLNamesAndChangeTypes(Definition wsdlDefinition,
+ Map processedWSDLMap,
+ Map processedScheamMap,
+ Set visitedWSDLs,
+ String registryBasePath,
+ boolean processImports) throws RegistryException {
+ // first we have to process the imports and change the
+ // schema locations suite for the registry
+
+ if (processImports) {
+ Iterator iter = wsdlDefinition.getImports().values().iterator();
+ Vector values;
+ Import wsdlImport;
+ // add this to visited list to stop recursion
+ visitedWSDLs.add(wsdlDefinition.getDocumentBaseURI());
+ for (; iter.hasNext();) {
+ values = (Vector)iter.next();
+ for (Iterator valuesIter = values.iterator(); valuesIter.hasNext();) {
+ wsdlImport = (Import)valuesIter.next();
+ // process the types recuresiveilt
+ Definition innerDefinition = wsdlImport.getDefinition();
+ if (!visitedWSDLs.contains(innerDefinition.getDocumentBaseURI())) {
+ // we have not process this wsdl file earlier
+ calculateWSDLNamesAndChangeTypes(
+ innerDefinition, processedWSDLMap, processedScheamMap, visitedWSDLs,
+ registryBasePath, processImports);
+ }
+ }
+ }
+ }
+
+ // change the schema names
+ Types types = wsdlDefinition.getTypes();
+ if (types != null) {
+ List extensibleElements = types.getExtensibilityElements();
+ Schema schemaExtension;
+ Object extensionObject;
+ XmlSchema xmlSchema;
+ XmlSchemaCollection xmlSchemaCollection;
+ SchemaFileProcessor schemaFileProcessor;
+ Map changedLocationMap;
+ String basuri = wsdlDefinition.getDocumentBaseURI();
+ basuri = basuri.substring(0, basuri.lastIndexOf("/") + 1);
+ for (Iterator extensibleElementsIter = extensibleElements.iterator();
+ extensibleElementsIter.hasNext();) {
+ extensionObject = extensibleElementsIter.next();
+ if (extensionObject instanceof Schema) {
+ // first get the schema object
+ schemaExtension = (Schema)extensionObject;
+ // create an xml schema object to be processed by SchemaFile procesor.
+ xmlSchemaCollection = new XmlSchemaCollection();
+ xmlSchemaCollection.setBaseUri(basuri);
+ xmlSchema = xmlSchemaCollection.read(schemaExtension.getElement());
+ schemaFileProcessor = new SchemaFileProcessor(repository);
+ changedLocationMap = new HashMap();
+ schemaFileProcessor.calculateNewSchemaNames(
+ xmlSchema, processedScheamMap, new HashSet(), true, processImports);
+ schemaFileProcessor.saveSchemaFileToRegistry(
+ xmlSchema, processedScheamMap, changedLocationMap, new HashSet(), true,
+ registryBasePath, processImports, null);
+ // update the current schema locations with the generated ones.
+ changeLocations(schemaExtension.getElement(), changedLocationMap);
+ }
+ }
+ }
+
+ // after processing the defintions save this to the registry
+ // TODO: save this to the registry for the moment save this to the
+ // folder and omit any exception occurs.
+ String baseUri = wsdlDefinition.getDocumentBaseURI();
+ String wsdlFileName = baseUri.substring(baseUri.lastIndexOf("/") + 1);
+ String fileNameToSave = wsdlFileName.substring(0, wsdlFileName.indexOf(".")) + ".wsdl";
+ while (processedWSDLMap.containsValue(fileNameToSave)) {
+ fileNameToSave = wsdlFileName.substring(0, wsdlFileName.indexOf(".")) + ++i + ".wsdl";
+ }
+ // add this entry to the proccessed wsdl map
+ processedWSDLMap.put(baseUri, fileNameToSave);
+
+ }
+
+ public void saveWSDLFileToRegistry(Definition wsdlDefinition,
+ Map p