[Registry-dev] svn commit r15770 -
trunk/registry/modules/core/src/main/java/org/wso2/registry/app
svn at wso2.org
svn at wso2.org
Thu Apr 17 21:17:17 PDT 2008
Author: glen
Date: Thu Apr 17 21:17:15 2008
New Revision: 15770
Log:
Missed a few adds in the refactor
Added:
trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryAdapter.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryProvider.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryResolver.java
trunk/registry/modules/core/src/main/java/org/wso2/registry/app/ResourceTarget.java
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryAdapter.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryAdapter.java Thu Apr 17 21:17:15 2008
@@ -0,0 +1,1191 @@
+package org.wso2.registry.app;
+
+import org.apache.abdera.Abdera;
+import org.apache.abdera.factory.Factory;
+import org.apache.abdera.i18n.iri.IRI;
+import org.apache.abdera.i18n.text.Sanitizer;
+import org.apache.abdera.model.*;
+import org.apache.abdera.protocol.server.RequestContext;
+import org.apache.abdera.protocol.server.ResponseContext;
+import org.apache.abdera.protocol.server.Target;
+import org.apache.abdera.protocol.server.TargetType;
+import org.apache.abdera.protocol.server.context.BaseResponseContext;
+import org.apache.abdera.protocol.server.context.EmptyResponseContext;
+import org.apache.abdera.protocol.server.context.ResponseContextException;
+import org.apache.abdera.protocol.server.impl.AbstractEntityCollectionAdapter;
+import org.apache.abdera.util.Constants;
+import org.apache.abdera.util.EntityTag;
+import org.apache.abdera.util.MimeTypeHelper;
+import org.apache.axiom.om.util.Base64;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.registry.Collection;
+import org.wso2.registry.Comment;
+import org.wso2.registry.*;
+import org.wso2.registry.exceptions.ResourceNotFoundException;
+import org.wso2.registry.jdbc.realm.RegistryRealm;
+import org.wso2.registry.secure.SecureRegistry;
+
+import javax.activation.MimeType;
+import javax.xml.namespace.QName;
+import java.io.*;
+import java.net.URLDecoder;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.util.*;
+
+ at SuppressWarnings("unchecked")
+public class RegistryAdapter
+ extends AbstractEntityCollectionAdapter<Resource> {
+ private Log log = LogFactory.getLog(RegistryAdapter.class);
+ final static String sanitizePattern = "[^A-Za-z0-9\\%!\\\\'()*+,=_]+";
+
+ RegistryResolver resolver;
+ Registry myRegistry;
+ RegistryRealm realm;
+
+ public RegistryAdapter(RegistryResolver resolver, Registry registry, RegistryRealm realm) {
+ this.resolver = resolver;
+ this.realm = realm;
+ myRegistry = registry;
+ }
+
+
+ /**
+ * Handle anything out of the ordinary Abdera-supported world.
+ *
+ * This method basically acts as a clearing house for all of the Registry-specific URLs
+ * that result in special processing, like ...;tags or ...;comments, etc. The resolver
+ * will have already parsed the URL and matched it with a particular custom TargetType, so
+ * in here we switch control based on the TargetType to a metadata-processing routine.
+ *
+ * @param request the RequestContext containing all the relevant info
+ * @return a ResponseContext indicating the disposition of the request
+ */
+ @SuppressWarnings({"ConstantConditions"})
+ public ResponseContext extensionRequest(RequestContext request) {
+ Target target = request.getTarget();
+ final TargetType type = target.getType();
+ if (!(target instanceof ResourceTarget)) {
+ // Deal with non-resource URLs, like "/tags..."
+ if (type.equals(RegistryResolver.TAGURL_TYPE)) {
+ return processTagURLRequest(request);
+ }
+ }
+ Resource resource = ((ResourceTarget)target).getResource();
+ String path = resource.getPath();
+ if (type.equals(RegistryResolver.TAGS_TYPE)) {
+ return processTagsRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.LOGS_TYPE)) {
+ return processLogsRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.RATINGS_TYPE)) {
+ return processRatingsRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.VERSIONS_TYPE)) {
+ return processVersionsRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.RENAME_TYPE)) {
+ return processRenameRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.DELETE_TYPE)) {
+ return processDeleteRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.COLLECTION_CUSTOM_TYPE)) {
+ if (request.getMethod().equals("HEAD")) {
+ // Doing a HEAD on a collection
+ try {
+ return buildHeadEntryResponse(request, getId(resource),
+ resource.getLastModified());
+ } catch (ResponseContextException e) {
+ log.error(e);
+ return e.getResponseContext();
+ }
+ }
+
+ // Must be a PUT.
+ return putCollection(request, path);
+ }
+ if (type.equals(RegistryResolver.ASSOCIATIONS_TYPE)) {
+ return processAssociationRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.COMMENTS_TYPE)) {
+ return processCommentsRequest(request, path);
+ }
+ if (type.equals(RegistryResolver.RESTORE_TYPE)) {
+ try {
+ getSecureRegistry(request).restoreVersion(path);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ return new EmptyResponseContext(200);
+ }
+ if (type.equals(RegistryResolver.ASPECT_TYPE)) {
+ return processAspectRequest(request, path);
+ }
+
+ return null;
+ }
+
+ /**
+ * Handle PUT of a collection (a feed).
+ *
+ * @param request active RequestContext
+ * @param path the resource path
+ * @return a ResponseContext which could contain success or an error
+ */
+ private ResponseContext putCollection(RequestContext request, String path) {
+ try {
+ final Registry secureRegistry = getSecureRegistry(request);
+ Collection resource = secureRegistry.newCollection();
+ Feed feed = (Feed)request.getDocument().getRoot();
+ // Just updating metadata
+ Properties properties = feed.getExtension(PropertyExtensionFactory.PROPERTIES);
+ RemoteRegistry.createPropertiesFromExtensionElement(properties, resource);
+ secureRegistry.put(path, resource);
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+
+ EmptyResponseContext response = new EmptyResponseContext(200);
+ response.setLocation(path);
+ return response; // TODO - fix return value
+ }
+
+ private ResponseContext processAspectRequest(RequestContext request, String path) {
+ String method = request.getMethod();
+ Registry registry;
+ try {
+ registry = getSecureRegistry(request);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+
+ String discriminator =
+ ((String[])request.getAttribute(RequestContext.Scope.REQUEST, "splitPath"))[1];
+ if (discriminator.equals("aspects")) {
+ if (method.equals("GET")) {
+ // get aspects
+ } else if (method.equals("POST")) {
+ // Associate
+ try {
+ String aspect = readToString(request.getInputStream());
+ registry.associateAspect(path, aspect);
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+ return new EmptyResponseContext(200);
+ }
+ return null;
+ }
+ // There should be an aspect name - parse it out
+ assert(discriminator.charAt(7) == '(');
+ int right = discriminator.indexOf(')');
+ assert(right > -1);
+ String aspectName = discriminator.substring(7, right);
+ String action;
+ if (discriminator.length() > right + 1) {
+ // Got an action too?
+ assert(method.equals("POST"));
+ action = discriminator.substring(right + 1);
+ try {
+ registry.invokeAspect(path, aspectName, action);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ // TODO - do we have to read the request fully?
+ return new EmptyResponseContext(200);
+ }
+ assert(method.equals("GET"));
+
+ // Return list of available actions.
+ Feed feed = getNewFeed("tag:aspectActions"); // TODO - fix ID
+ String [] actions;
+ try {
+ actions = registry.getAspectActions(path, aspectName);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ for (String a : actions) {
+ Entry e = factory.newEntry();
+ e.setId("tag:aspectAction[" + a + "]");
+ e.setContent(a);
+ feed.addEntry(e);
+ }
+ return buildResponseContextFromFeed(feed);
+ }
+
+ private ResponseContext processCommentsRequest(RequestContext request, String path) {
+ final String method = request.getMethod();
+ if (method.equals("GET")) {
+ int colonIdx = request.getUri().toString().indexOf(':');
+ if (colonIdx > -1) {
+ return getEntry(request);
+ } else {
+ // Return comments feed
+ return getFeed(request);
+ }
+ } else if (method.equals("POST")) {
+ // Accept either Atom or plain text for comments
+ Comment comment = new Comment();
+ final String contentType = request.getContentType().toString();
+ try {
+ if (request.isAtom()) {
+ Entry entry = (Entry)request.getDocument().getRoot();
+ comment.setText(entry.getContent());
+ comment.setUser(entry.getAuthor().getName());
+ comment.setTime(entry.getUpdated());
+ } else if (contentType.equals("text/plain")) {
+ InputStream is = request.getInputStream();
+ String text = readToString(is);
+ comment.setText(text);
+ }
+ String commentPath = getSecureRegistry(request).addComment(path, comment);
+ EmptyResponseContext responseContext = new EmptyResponseContext(200);
+ responseContext.setLocation(commentPath);
+ return responseContext;
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+ }
+ return new EmptyResponseContext(405); // unsupported method
+ }
+
+ private ResponseContext processAssociationRequest(RequestContext request, String path) {
+ if (request.getMethod().equals("GET")) {
+ String type = null;
+ String uri = request.getUri().toString();
+ int idx = uri.lastIndexOf(":");
+ if (idx > -1) {
+ type = uri.substring(idx + 1, uri.length() - 1);
+ }
+ // Return associations feed
+ Association [] associations;
+ try {
+ if (type != null) {
+ associations = getSecureRegistry(request).getAssociations(path, type);
+ } else {
+ associations = getSecureRegistry(request).getAllAssociations(path);
+ }
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+
+ // Build feed
+ Feed feed = getNewFeed("tag:associationFeed");
+ for (Association association : associations) {
+ Entry e = factory.newEntry();
+ e.setSummary(association.getAssociationType());
+ e.setContent(association.getDestinationPath());
+ feed.addEntry(e);
+ }
+ return buildResponseContextFromFeed(feed);
+ }
+ if (request.getMethod().equals("POST")) {
+ // Adding an association, expecting XML that looks like
+ // <reg:association type="type">http://associationPath</reg:association>
+ try {
+ Element assocEl = request.getDocument().getRoot();
+ if (!APPConstants.QNAME_ASSOC.equals(assocEl.getQName())) {
+ return new EmptyResponseContext(400, "Bad association element");
+ }
+ String type = assocEl.getAttributeValue(APPConstants.ASSOC_TYPE);
+ String assocPath = assocEl.getText();
+ getSecureRegistry(request).addAssociation(type, path, assocPath);
+ return new EmptyResponseContext(200);
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+ }
+
+ return null;
+ }
+
+ private Feed getNewFeed(String id) {
+ Feed feed = factory.newFeed();
+ feed.setId(id);
+ feed.setUpdated(new Date());
+ return feed;
+ }
+
+ private ResponseContext processTagURLRequest(RequestContext request) {
+ String uri = (String)request.getAttribute(RequestContext.Scope.REQUEST, "pathInfo");
+ if (uri.endsWith("/")) uri = uri.substring(0, uri.length() - 1);
+ if (uri.equals("/tags")) {
+ // TODO - implement this!
+ return new StringResponseContext("this is a list of tags with links", 200);
+ }
+ String tag = uri.substring(6);
+ Feed feed = getNewFeed("http://wso2.org/jdbcregistry/TagPaths");
+ feed.setTitle("Resource path for " + tag);
+ TaggedResourcePath [] paths;
+ try {
+ paths = getSecureRegistry(request).getResourcePathsWithTag(tag);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ for (TaggedResourcePath tagPath : paths) {
+ Entry entry = factory.newEntry();
+ String path = tagPath.getResourcePath();
+ entry.setTitle(path);
+ entry.addSimpleExtension(new QName(APPConstants.NAMESPACE, "taggings"),
+ "" + tagPath.getTagCount());
+ Map tagCounts = tagPath.getTagCounts();
+ Iterator iCounts = tagCounts.keySet().iterator();
+ java.util.Properties properties = new java.util.Properties();
+ while (iCounts.hasNext()) {
+ String key = (String)iCounts.next();
+ String count = (tagCounts.get(key)).toString();
+ properties.put(key, count);
+ }
+ RemoteRegistry.addPropertyExtensionElement(properties,
+ factory,
+ entry,
+ PropertyExtensionFactory.TAGS,
+ PropertyExtensionFactory.TAG);
+// entry.addSimpleExtension(new QName("tagCounts"), "" + tagPath.getTagCount())
+// entry.addLink(baseUri + "atom" + path, "path");
+// entry.addLink(baseUri + "atom" + path);
+ feed.addEntry(entry);
+ }
+
+ return buildResponseContextFromFeed(feed);
+ }
+
+ private ResponseContext processRenameRequest(RequestContext request, String path) {
+ if (!request.getMethod().equals("POST")) {
+ ResponseContext rc = new EmptyResponseContext(405, "Method not allowed");
+ rc.setAllow("POST");
+ return rc;
+ }
+
+ try {
+ InputStream is = request.getInputStream();
+ String newPath = readToString(is);
+ getSecureRegistry(request).rename(path, newPath);
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+
+ return new StringResponseContext("Rename successful.", 200);
+ }
+
+ private ResponseContext processDeleteRequest(RequestContext request, String path) {
+ assert(request.getMethod().equals("DELETE"));
+ try {
+ getSecureRegistry(request).delete(path);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ return new EmptyResponseContext(200);
+ }
+
+ /**
+ * Utility function to parse query string
+ * TODO: Isn't there a standard way to do this?
+ * @param query query string to parse
+ * @return a Map of name -> value for each parameter
+ */
+ public static Map<String, String> parseQueryString(String query) {
+ Map<String, String> map = new HashMap<String, String>();
+ if (query == null) return map;
+
+ StringTokenizer st = new StringTokenizer(query, "?&=", true);
+ String previous = "";
+ while (st.hasMoreTokens()) {
+ String current = st.nextToken();
+ if ("?".equals(current) || "&".equals(current)) {
+ // nothing to do here
+ } else if ("=".equals(current)) {
+ try {
+ map.put(URLDecoder.decode(previous, "UTF-8"),
+ URLDecoder.decode(st.nextToken(), "UTF-8"));
+ } catch (UnsupportedEncodingException e) {
+ break;
+ }
+ } else {
+ previous = current;
+ }
+ }
+ return map;
+ }
+
+ private ResponseContext processRatingsRequest(RequestContext request, String path) {
+ if (request.getMethod().equals("GET")) {
+ // Return ratings feed.
+ Feed feed = factory.newFeed();
+ feed.setUpdated(new Date()); // TODO - updated at last rating
+ feed.setId("http://wso2.org/jdbcregistry:averageRating"); // TODO - make real ID
+ feed.setTitle("Average Rating for the resource " + path);
+
+ String nodeLink = resolver.getBaseURI() + "/atom" + path +
+ RegistryConstants.URL_SEPARATOR +
+ APPConstants.PARAMETER_RATINGS;
+ feed.addLink(nodeLink);
+ try {
+ feed.addSimpleExtension(APPConstants.QNAME_AVGRATING,
+ "" + myRegistry.getAverageRating(path));
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ return buildResponseContextFromFeed(feed);
+ } else if (request.getMethod().equals("POST")) {
+ // We're trying to rate the resource.
+ try {
+ InputStream is = request.getInputStream();
+ String rateStr = readToString(is);
+ int rating = Integer.parseInt(rateStr);
+ getSecureRegistry(request).rateResource(path, rating);
+ return new StringResponseContext("Resource rated successfully", 200);
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+ }
+ return null;
+ }
+
+ private ResponseContext processQuery(RequestContext request, String path) {
+ Map params = new HashMap();
+
+ getSecureRegistry(request).executeQuery(path, params);
+ }
+
+ private ResponseContext processVersionsRequest(RequestContext request, String path) {
+ String [] versionPaths;
+ try {
+ Registry registry = getSecureRegistry(request);
+ versionPaths = registry.getVersions(path);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ Feed feed = getNewFeed("tag:" + path + ";versions");
+ for (String version : versionPaths) {
+ Entry e = factory.newEntry();
+ e.addLink(version, "versionLink");
+ feed.addEntry(e);
+ }
+ return buildResponseContextFromFeed(feed);
+ }
+
+ private ResponseContext processLogsRequest(RequestContext request, String path) {
+ Map<String, String> params = parseQueryString(request.getUri().getQuery());
+ String user = params.get("user");
+ Date fromDate = null;
+ Date toDate = null;
+ String recentParam = params.get("recentFirst");
+
+ DateFormat formatter = DateFormat.getDateInstance(DateFormat.SHORT);
+ String dateStr = params.get("from");
+ if (dateStr != null) {
+ try {
+ fromDate = formatter.parse(dateStr);
+ } catch (ParseException e) {
+ return new EmptyResponseContext(400, "Bad 'from' date format '" + dateStr + "'");
+ }
+ }
+ dateStr = params.get("to");
+ if (dateStr != null) {
+ try {
+ toDate = formatter.parse(dateStr);
+ } catch (ParseException e) {
+ return new EmptyResponseContext(400, "Bad 'to' date format '" + dateStr + "'");
+ }
+ }
+ boolean recentFirst = recentParam == null || recentParam.equals("true");
+ int action = 0;
+ LogEntry [] logs;
+ try {
+ final Registry reg = getSecureRegistry(request);
+ logs = reg.getLogs(path, action, user, fromDate, toDate, recentFirst);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ Feed feed = factory.newFeed();
+ feed.setId("http://wso2.org/jdbcregistry,2007:logs");
+ feed.setTitle("Logs for the resource" + path);
+ feed.addLink("", "self");
+ feed.setUpdated(new Date());
+ for (LogEntry logentry : logs) {
+ Entry entry = factory.newEntry();
+ entry.setEdited(logentry.getDate());
+ entry.setContent(logentry.getActionData());
+ entry.addAuthor(logentry.getUserName());
+ entry.addSimpleExtension(new QName(APPConstants.NAMESPACE, "action"),
+ "" + logentry.getAction());
+ entry.addSimpleExtension(new QName(APPConstants.NAMESPACE, "path"),
+ logentry.getResourcePath());
+ feed.addEntry(entry);
+ }
+ return buildResponseContextFromFeed(feed);
+ }
+
+ private ResponseContext buildResponseContextFromFeed(Feed feed) {
+ Document<Feed> docfeed = feed.getDocument();
+ ResponseContext rc = new BaseResponseContext<Document<Feed>>(docfeed);
+ rc.setEntityTag(calculateEntityTag(docfeed.getRoot()));
+ return rc;
+ }
+
+ private ResponseContext processTagsRequest(RequestContext request, String path) {
+ if (request.getMethod().equals("GET")) {
+ // Return the tags.
+ // TODO - resource.getTags()?
+ Tag[] tags;
+ try {
+ final Registry reg = getSecureRegistry(request);
+ tags = reg.getTags(path);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ Feed feed = factory.newFeed();
+ feed.setId("http://wso2.org/jdbcregistry:tags" + path);
+ feed.setTitle("Tags for " + path);
+// String nodeLink = baseUri + "atom" + path +
+// RegistryConstants.URL_SEPARATOR +
+// APPConstants.PARAMETER_TAGS;
+// feed.addLink(nodeLink);
+ feed.setUpdated(new Date());
+
+ for (Tag tag : tags) {
+ Entry entry = factory.newEntry();
+ entry.setTitle(tag.getTagName());
+ entry.setContent(tag.getTagName());
+ entry.addSimpleExtension(new QName(APPConstants.NAMESPACE, "taggings"),
+ "" + tag.getTagCount());
+ feed.addEntry(entry);
+ }
+
+ return buildResponseContextFromFeed(feed);
+ }
+ if (request.getMethod().equals("POST")) {
+ // POST adds a tag
+ if (request.isAtom()) {
+ try {
+ Entry e = (Entry)request.getDocument().getRoot();
+ String tag = e.getContent();
+ final Registry registry = getSecureRegistry(request);
+ registry.applyTag(path, tag);
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+ return new EmptyResponseContext(200, "Tag applied");
+ }
+ try {
+ InputStream is = request.getInputStream();
+ String tagText = readToString(is);
+ String [] tags = tagText.split(" ");
+ for (String tag : tags) {
+ try {
+ final Registry registry = getSecureRegistry(request);
+ registry.applyTag(path, tag);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ }
+ } catch (IOException e) {
+ return new StackTraceResponseContext(e);
+ }
+ }
+ return new StringResponseContext("hey there", 200);
+ }
+
+ private String readToString(InputStream is) throws IOException {
+ BufferedReader in = new BufferedReader(new InputStreamReader(is));
+ StringBuffer buffer = new StringBuffer();
+ String line;
+ while ((line = in.readLine()) != null) {
+ buffer.append(line);
+ }
+ return buffer.toString();
+ }
+
+ private EntityTag calculateEntityTag(Base base) {
+ String id = null;
+ String modified = null;
+ if (base instanceof Entry) {
+ id = ((Entry)base).getId().toString();
+ modified = ((Entry)base).getUpdatedElement().getText();
+ } else if (base instanceof Feed) {
+ id = ((Feed)base).getId().toString();
+ modified = ((Feed)base).getUpdatedElement().getText();
+ }
+ return EntityTag.generate(id, modified);
+ }
+
+ public ResponseContext postEntry(RequestContext request) {
+ Document<Element> document;
+ try {
+ document = request.getDocument(request.getAbdera().getParser());
+ } catch (IOException e) {
+ return new StackTraceResponseContext(e);
+ }
+ if (document.getRoot().getQName().equals(Constants.FEED)) {
+ // Posting a <feed>, so this is probably a collection creation...
+ return postFeed(request);
+ }
+ return super.postEntry(request);
+ }
+
+ public ResponseContext postFeed(RequestContext request) {
+ Document<Feed> doc;
+ try {
+ doc = request.getDocument();
+ } catch (IOException e) {
+ return new StackTraceResponseContext(e);
+ }
+ Feed feed = doc.getRoot();
+ String slug = request.getSlug();
+ if (slug == null) {
+ slug = Sanitizer.sanitize(feed.getTitle(), "-", sanitizePattern);
+ }
+ String parentPath = ((ResourceTarget)request.getTarget()).getResource().getPath();
+ if (!parentPath.endsWith(RegistryConstants.PATH_SEPARATOR)) {
+ parentPath += RegistryConstants.PATH_SEPARATOR;
+ }
+ String path = parentPath + slug;
+ String real;
+ try {
+ final Registry registry = getSecureRegistry(request);
+ Collection resource = registry.newCollection();
+ real = registry.put(path, resource);
+ } catch (RegistryException e) {
+ return new StackTraceResponseContext(e);
+ }
+ StringResponseContext responseContext =
+ new StringResponseContext("Feed created at " + real, 201);
+ responseContext.setLocation(real);
+ return responseContext;
+ }
+
+ public Resource postEntry(String title,
+ IRI id,
+ String summary,
+ Date updated,
+ List<Person> authors,
+ Content content,
+ RequestContext request) throws ResponseContextException {
+ Resource resource = ((ResourceTarget)request.getTarget()).getResource();
+ String path = resource.getPath();
+ final Registry registry;
+ try {
+ registry = getSecureRegistry(request);
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+
+ final String [] splitPath = (String [])request.getAttribute(RequestContext.Scope.REQUEST,
+ "splitPath");
+ if (splitPath != null) {
+ if ("comments".equals(splitPath[1])) {
+ // Comment post
+ Comment comment = new Comment(content.getText());
+ try {
+ String commentPath = registry.addComment(path, comment);
+ comment.setPath(commentPath);
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ return comment;
+ }
+ }
+
+ String name = request.getSlug();
+ if (name == null) {
+ if (title != null) {
+ name = Sanitizer.sanitize(title, "-", sanitizePattern);
+ } else {
+ name = generateResourceName();
+ }
+ } else {
+ name = Sanitizer.sanitize(name, "-", sanitizePattern);
+ }
+
+ if (!path.endsWith("/")) path += "/";
+
+ if (APPConstants.IMPORT_MEDIATYPE.equals(request.getContentType().toString())) {
+ // This is an import.
+ String importURL = request.getParameter("importURL");
+ String suggestedPath = request.getSlug();
+ Resource metadata = new ResourceImpl();
+ String location;
+ try {
+ final Registry secureRegistry = getSecureRegistry(request);
+ location = secureRegistry.importResource(suggestedPath,
+ importURL,
+ metadata);
+ return secureRegistry.get(location);
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ }
+
+ Entry entry;
+ try {
+ entry = (Entry)request.getDocument().getRoot();
+ } catch (IOException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+
+ Resource ret;
+ try {
+ ret = registry.newResource();
+ fillResourceFromEntry(entry, ret);
+ if (content.getContentType() == Content.Type.TEXT) {
+ ret.setContent(content.getText());
+ ret.setMediaType("text/plain");
+ } else if (content.getContentType() == Content.Type.MEDIA) {
+ ret.setContentStream(content.getDataHandler().getInputStream());
+ ret.setMediaType(content.getMimeType().toString());
+ }
+
+ registry.put(path + name, ret);
+ } catch (Exception e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+
+ return ret;
+ }
+
+ private void fillResourceFromEntry(Entry entry, Resource ret) {
+ Properties properties = entry.getExtension(PropertyExtensionFactory.PROPERTIES);
+ RemoteRegistry.createPropertiesFromExtensionElement(properties, ret);
+ String mediaType = entry.getSimpleExtension(new QName(APPConstants.NAMESPACE, "mediaType"));
+ if (mediaType != null) {
+ ret.setMediaType(mediaType);
+ } else {
+ ret.setMediaType("application/atom+xml");
+ }
+ if (entry.getSummary() != null) {
+ ret.setDescription(entry.getSummary());
+ }
+ }
+
+ public void deleteEntry(String resourceName, RequestContext request)
+ throws ResponseContextException {
+ }
+
+ private Factory factory = new Abdera().getFactory();
+
+ public boolean isMediaEntry(Resource entry) throws ResponseContextException {
+ if (entry instanceof Collection) return false;
+ // If this isn't atom, it's a media entry
+ return (!MimeTypeHelper.isAtom(entry.getMediaType()));
+ }
+
+ public Object getContent(Resource entry, RequestContext request)
+ throws ResponseContextException {
+ // No content for Collections
+ if (entry instanceof Collection) return null;
+
+ Object c;
+ try {
+ c = entry.getContent();
+ } catch (RegistryException e) {
+ return null;
+ }
+
+ if (c instanceof String) {
+ return c;
+ }
+
+ return "Hey there this is some text";
+ }
+
+ protected String addEntryDetails(RequestContext request,
+ Entry e,
+ IRI feedIri,
+ Resource entryObj) throws ResponseContextException {
+ final Registry registry;
+ try {
+ registry = getSecureRegistry(request);
+ } catch (RegistryException ex) {
+ throw new ResponseContextException(new StackTraceResponseContext(ex));
+ }
+
+ final String link = getLink(entryObj, feedIri, request);
+ if (entryObj instanceof Collection) {
+ // We need an alternate link for the collection here
+ e.addLink(link, "alternate");
+ }
+ if (entryObj instanceof Comment) {
+ e.addLink(link, "direct");
+ e.addLink(((Comment)entryObj).getResourcePath(), "resourcePath");
+ }
+ e.addLink(link, "path");
+
+ String path = entryObj.getPath();
+ try {
+ Tag [] tags = registry.getTags(path);
+ if (tags.length > 0) {
+ Element ext = factory.newElement(new QName(RegistryConstants.REGISTRY_NAMESPACE,
+ "tags"));
+ for (Tag tag : tags) {
+ Element tagEl =
+ factory.newElement(new QName(RegistryConstants.REGISTRY_NAMESPACE,
+ "tag"),
+ ext);
+ tagEl.setText(tag.getTagName());
+ }
+ e.addExtension(ext);
+ }
+ } catch (RegistryException e1) {
+ log.error(e1);
+ }
+
+ RemoteRegistry.addPropertyExtensionElement(entryObj.getProperties(),
+ factory,
+ e,
+ PropertyExtensionFactory.PROPERTIES,
+ PropertyExtensionFactory.PROPERTY);
+
+ return super.addEntryDetails(request, e, feedIri, entryObj);
+ }
+
+ protected void addFeedDetails(Feed feed, RequestContext request)
+ throws ResponseContextException {
+ super.addFeedDetails(feed, request);
+ final Resource resource = ((ResourceTarget)request.getTarget()).getResource();
+ RemoteRegistry.addPropertyExtensionElement(resource.getProperties(),
+ factory,
+ feed,
+ PropertyExtensionFactory.PROPERTIES,
+ PropertyExtensionFactory.PROPERTY);
+ if (request.getTarget().getType() == RegistryResolver.COMMENTS_TYPE) {
+ feed.addSimpleExtension(APPConstants.COMMENTS_QNAME, "true");
+ }
+ }
+
+ public Iterable<Resource> getEntries(final RequestContext request) throws ResponseContextException {
+ Resource resource = ((ResourceTarget)request.getTarget()).getResource();
+
+ final String [] splitPath = (String [])request.getAttribute(RequestContext.Scope.REQUEST,
+ "splitPath");
+ if (splitPath != null) {
+ if ("comments".equals(splitPath[1])) {
+ // Looking for comments, not the resource itself... so...
+ try {
+ resource = getSecureRegistry(request).get(resource.getPath() + ";comments");
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ }
+ }
+
+ if (resource instanceof Collection) {
+ final Resource r = resource;
+ return new Iterable<Resource> () {
+ public Iterator<Resource> iterator() {
+ try {
+ return new Resourcerator((Object [])r.getContent(),
+ getSecureRegistry(request));
+ } catch (RegistryException e) {
+ return null;
+ }
+ }
+ };
+ }
+
+ // Regular Resource, so the feed should be ... recent activity? For now nothing but
+ // metadata.
+ return null;
+ }
+
+ public class Resourcerator implements Iterator<Resource> {
+ Object [] paths;
+ int i = 0;
+ Registry registry;
+
+ public Resourcerator(Object [] paths, Registry registry) {
+ this.paths = paths;
+ this.registry = registry;
+ }
+
+ public boolean hasNext() {
+ return i < paths.length;
+ }
+
+ public Resource next() {
+ Object resourceOrString = paths[i++];
+
+ if (resourceOrString instanceof Resource) return (Resource)resourceOrString;
+
+ try {
+ return registry.get((String)resourceOrString);
+ } catch (RegistryException e) {
+ return null;
+ }
+ }
+
+ public void remove() {
+ }
+ }
+
+ public Resource getEntry(String resourceName, RequestContext request)
+ throws ResponseContextException {
+ return ((ResourceTarget)request.getTarget()).getResource();
+ }
+
+ public String getId(Resource entry) throws ResponseContextException {
+ return entry.getPath(); // TODO - use Abdera Builder mechanism for URL
+ }
+
+ public String getName(Resource entry) throws ResponseContextException {
+ return entry.getPath();
+ }
+
+ public String getTitle(Resource entry) throws ResponseContextException {
+ return entry.getDescription();
+ }
+
+ public Date getUpdated(Resource entry) throws ResponseContextException {
+ return entry.getLastModified();
+ }
+
+ public ResponseContext putEntry(RequestContext request) {
+ String path = ((ResourceTarget)request.getTarget()).getResource().getPath();
+ Resource ret;
+ try {
+ Entry entry = (Entry)request.getDocument().getRoot();
+ Content content = entry.getContentElement();
+ Registry registry = getSecureRegistry(request);
+ ret = registry.newResource();
+ fillResourceFromEntry(entry, ret);
+ if (content.getContentType() == Content.Type.TEXT) {
+ ret.setContent(content.getText());
+ ret.setMediaType("text/plain");
+ } else if (content.getContentType() == Content.Type.MEDIA) {
+ ret.setContentStream(content.getDataHandler().getInputStream());
+ ret.setMediaType(content.getMimeType().toString());
+ }
+
+ registry.put(path, ret);
+ } catch (Exception e) {
+ return new StackTraceResponseContext(e);
+ }
+
+ return new EmptyResponseContext(200);
+ }
+
+ public void putEntry(Resource entry,
+ String title,
+ Date updated,
+ List<Person> authors,
+ String summary,
+ Content content,
+ RequestContext request) throws ResponseContextException {
+ System.out.println("here");
+ }
+
+ public String getAuthor(RequestContext request) throws ResponseContextException {
+ return ((ResourceTarget)request.getTarget()).getResource().getAuthorUserName();
+ }
+
+ public List<Person> getAuthors(Resource entry, RequestContext request)
+ throws ResponseContextException {
+ Person author = request.getAbdera().getFactory().newAuthor();
+ author.setName(entry.getAuthorUserName());
+ return Arrays.asList(author);
+ }
+
+ public String getId(RequestContext request) {
+ try {
+ return getId(((ResourceTarget)request.getTarget()).getResource());
+ } catch (ResponseContextException e) {
+ return null;
+ }
+ }
+
+ public String getTitle(RequestContext request) {
+ return ((ResourceTarget)request.getTarget()).getResource().getDescription();
+ }
+
+ public Text getSummary(Resource entry, RequestContext request) throws ResponseContextException {
+ Text text = factory.newSummary();
+ text.setValue(entry.getDescription());
+ return text;
+ }
+
+ public Resource postMedia(MimeType mimeType,
+ String slug,
+ InputStream inputStream,
+ RequestContext request) throws ResponseContextException {
+ final Registry registry;
+ try {
+ registry = getSecureRegistry(request);
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+
+ String path = ((ResourceTarget)request.getTarget()).getResource().getPath();
+
+ final String [] splitPath = (String [])request.getAttribute(RequestContext.Scope.REQUEST,
+ "splitPath");
+ if (splitPath != null) {
+ if ("comments".equals(splitPath[1])) {
+ if (!mimeType.toString().equals("text/plain")) {
+ throw new ResponseContextException(
+ "Can only post Atom or text/plain to comments!", 400);
+ }
+ // Comment post
+ Comment comment;
+ try {
+ comment = new Comment(readToString(inputStream));
+ } catch (IOException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ try {
+ String commentPath = registry.addComment(path, comment);
+ comment.setPath(commentPath);
+ comment.setParentPath(path + ";comments");
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ return comment;
+ }
+ }
+
+ if (!path.endsWith("/")) {
+ path += "/";
+ }
+ slug = getGoodSlug(path, slug);
+ path = path + slug;
+ boolean isCollection = "app/collection".equals(mimeType.toString());
+ Resource ret;
+ try {
+ ret = isCollection ? registry.newCollection() : registry.newResource();
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ ret.setMediaType(mimeType.toString());
+ System.out.println("Mime type is " + mimeType.toString());
+ if (!isCollection) {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ byte [] buffer = new byte[1024];
+ try {
+ while (inputStream.available() > 0) {
+ int amount = inputStream.read(buffer, 0, 1024);
+ bos.write(buffer, 0, amount);
+ }
+ } catch (IOException e) {
+ // nothing here
+ }
+ String content = new String(bos.toByteArray());
+ ret.setContent(content);
+ }
+ try {
+ registry.put(path, ret);
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ return ret;
+ }
+
+ private String getGoodSlug(String suggested, String slug) {
+ if (slug == null) slug = "";
+ slug = Sanitizer.sanitize(slug, "", sanitizePattern);
+ try {
+ Resource resource = myRegistry.get(suggested + slug);
+ while (resource != null) {
+ int i = 1;
+ final int len = slug.length();
+ char c = slug.charAt(len - i);
+ while (i < len && c >= '0' && c <= '9') {
+ i++;
+ c = slug.charAt(len - i);
+ }
+ int newi;
+ if (i == 1) {
+ newi = 1;
+ } else {
+ String prefix = slug.substring(0, len - i + 1);
+ newi = Integer.parseInt(slug.substring(len - i + 1)) + 1;
+ slug = prefix;
+ }
+ slug = slug + newi;
+ resource = myRegistry.get(suggested + slug);
+ }
+ } catch (ResourceNotFoundException e) {
+ // great!
+ } catch (RegistryException e) {
+ log.error(e);
+ return null;
+ }
+ return slug;
+ }
+
+ public String getContentType(Resource entry) {
+ return entry.getMediaType();
+ }
+
+ public String getMediaName(Resource entry) throws ResponseContextException {
+ String path = entry.getPath(); //TODO : fix
+ return path.substring(1);
+ }
+
+ protected String addMediaContent(IRI feedIri,
+ Entry entry,
+ Resource entryObj,
+ RequestContext request) throws ResponseContextException {
+ IRI mediaIri = new IRI(resolver.getBaseURI() + RegistryResolver.RESOURCE +
+ getMediaName(entryObj));
+ String mediaLink = mediaIri.toString();
+ entry.setContent(mediaIri, getContentType(entryObj));
+ entry.addLink(mediaLink, "edit-media");
+
+ return mediaLink;
+ }
+
+ public InputStream getMediaStream(Resource entry) throws ResponseContextException {
+ byte [] bytes;
+ try {
+ final Object cobj = entry.getContent();
+ bytes = (byte[])cobj;
+ } catch (RegistryException e) {
+ throw new ResponseContextException(new StackTraceResponseContext(e));
+ }
+ return new ByteArrayInputStream(bytes);
+ }
+
+ protected String getFeedIriForEntry(Resource entryObj, RequestContext request) {
+ return resolver.getBaseURI()+ "/atom" + entryObj.getParentPath();
+ }
+
+ /**
+ * This method will create a SecureRegistry for APP. If the user has send the user name and the
+ * password then the jdbcregistry will be created using the value he has given, else the
+ * jdbcregistry instance will be created as annon user.
+ *
+ * @param request : RequestContext to get the authorization header
+ * @return : Created jdbcregistry
+ * @throws RegistryException : If something went wrong
+ */
+ private Registry getSecureRegistry(RequestContext request) throws RegistryException {
+ String authorizationString = request.getAuthorization();
+ if (authorizationString != null) {
+ // spliting the Authorization string "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
+ String values[] = authorizationString.split("\\ ");
+ if ("Basic".equals(values[0])) {
+ //decoding the username and passord
+ authorizationString = new String(Base64.decode(values[1]));
+ //spliting the decode sting to get the userName and the password;
+ values = authorizationString.split("\\:");
+ String userName = values[0];
+ String password = values[1];
+ // user name and password have found
+ return new SecureRegistry(userName, password, myRegistry, realm);
+ } else {
+ throw new RegistryException("Invalid Authorization string");
+ }
+ } else {
+ // seems like need to create a secure jdbcregistry with annon user
+ return new SecureRegistry(RegistryConstants.ANONYMOUS_USER, "guest", myRegistry, realm);
+ }
+ }
+
+ int curResource = 1;
+
+ private synchronized String generateResourceName() {
+ return "resource" + curResource++;
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryProvider.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryProvider.java Thu Apr 17 21:17:15 2008
@@ -0,0 +1,95 @@
+/*
+ * Copyright (c) 2007, 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.app;
+
+import org.apache.abdera.protocol.server.*;
+import org.apache.abdera.protocol.server.context.RequestContextWrapper;
+import org.apache.abdera.protocol.server.impl.AbstractWorkspaceProvider;
+import org.apache.abdera.protocol.server.impl.SimpleWorkspaceInfo;
+import org.apache.abdera.protocol.server.impl.TemplateTargetBuilder;
+import org.wso2.registry.Registry;
+import org.wso2.registry.config.RegistryContext;
+import org.wso2.registry.config.RegistryConfigurationProcessor;
+import org.wso2.registry.jdbc.InMemoryJDBCRegistry;
+import org.wso2.registry.jdbc.JDBCRegistry;
+import org.wso2.registry.jdbc.realm.InMemoryRegistryRealm;
+import org.wso2.registry.jdbc.realm.RegistryRealm;
+
+import java.io.InputStream;
+
+public class RegistryProvider extends AbstractWorkspaceProvider {
+ RegistryAdapter adapter;
+ RegistryResolver resolver;
+ Registry registry;
+ public static final String baseURI = "/wso2registry";
+
+ public class SimpleFilter implements Filter {
+ public ResponseContext filter(RequestContext request, FilterChain chain) {
+ RequestContextWrapper rcw = new RequestContextWrapper(request);
+ rcw.setAttribute("offset", 10);
+ rcw.setAttribute("count", 10);
+ return chain.next(rcw);
+ }
+ }
+
+ public CollectionAdapter getCollectionAdapter(RequestContext request) {
+ return adapter;
+ }
+
+// private void populate() throws RegistryException {
+// Resource r = registry.newResource();
+// r.setContent("here's some text!");
+// r.setMediaType("text/plain");
+// registry.put("/r1", r);
+//
+// Collection c = registry.newCollection();
+// registry.put("/dept", c);
+//
+// registry.put("/dept/finance", c);
+//
+// registry.put("/dept/finance/myserv", r);
+//
+// registry.applyTag("/dept/finance/myserv", "cool");
+// }
+
+ public RegistryProvider() throws Exception {
+ RegistryRealm realm = new InMemoryRegistryRealm();
+ registry = new InMemoryJDBCRegistry(realm);
+ RegistryContext ctx = new RegistryContext();
+ RegistryConfigurationProcessor.populateRegistryConfig((InputStream)null, ctx);
+ ((JDBCRegistry)registry).setRegistryContext(ctx);
+
+ resolver = new RegistryResolver(registry, baseURI);
+ adapter = new RegistryAdapter(resolver, registry, realm);
+
+ this.setTargetResolver(resolver);
+
+ this.setTargetBuilder(
+ new TemplateTargetBuilder().setTemplate(TargetType.TYPE_COLLECTION,
+ "{target_base}/atom/{collection}").
+ setTemplate(RegistryResolver.TAGS_TYPE, "{target_base}/atom/{collection};tags"));
+ SimpleWorkspaceInfo workspace = new SimpleWorkspaceInfo();
+ workspace.setTitle("A Simple Workspace");
+ workspace.addCollection(adapter);
+ addWorkspace(workspace);
+ addFilter(new SimpleFilter());
+ }
+
+ protected ResponseContext processCollection(RequestContext context,
+ CollectionAdapter adapter) {
+ return null;
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryResolver.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/app/RegistryResolver.java Thu Apr 17 21:17:15 2008
@@ -0,0 +1,193 @@
+/*
+ * Copyright (c) 2007, 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.app;
+
+import org.apache.abdera.protocol.server.Target;
+import org.apache.abdera.protocol.server.RequestContext;
+import org.apache.abdera.protocol.server.TargetType;
+import org.apache.abdera.protocol.server.impl.SimpleTarget;
+import org.apache.abdera.protocol.Resolver;
+import org.apache.abdera.protocol.Request;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.wso2.registry.*;
+import org.wso2.registry.exceptions.ResourceNotFoundException;
+
+import java.util.Map;
+import java.util.HashMap;
+import java.net.URLDecoder;
+import java.io.UnsupportedEncodingException;
+
+public class RegistryResolver implements Resolver<Target> {
+ private Log log = LogFactory.getLog(RegistryResolver.class);
+
+ public static final String RESOURCE = "/resource/";
+ public static final String ATOM = "/atom/";
+
+ public static final TargetType TAGS_TYPE = TargetType.get("tags", true);
+ public static final TargetType LOGS_TYPE = TargetType.get("logs", true);
+ public static final TargetType RATINGS_TYPE = TargetType.get("ratings", true);
+ public static final TargetType RENAME_TYPE = TargetType.get("rename", true);
+ public static final TargetType COMMENTS_TYPE = TargetType.get("comments", true);
+ public static final TargetType TAGURL_TYPE = TargetType.get("tagURL", true);
+ public static final TargetType ASSOCIATIONS_TYPE = TargetType.get("associations", true);
+ public static final TargetType RESTORE_TYPE = TargetType.get("restore", true);
+ public static final TargetType ASPECT_TYPE = TargetType.get("aspect", true);
+ public static final TargetType VERSIONS_TYPE = TargetType.get("versions", true);
+
+ // These custom types we need to handle methods that Abdera doesn't deal with adequately
+ public static final TargetType DELETE_TYPE = TargetType.get("delete", true);
+ public static final TargetType COLLECTION_CUSTOM_TYPE = TargetType.get("col-custom", true);
+
+ private Registry registry;
+ private String baseURI;
+
+ public RegistryResolver(Registry registry, String baseURI) {
+ this.registry = registry;
+ this.baseURI = baseURI;
+ }
+
+ static Map<String, TargetType> types;
+ static {
+ types = new HashMap<String, TargetType>();
+ types.put("tags", TAGS_TYPE);
+ types.put("logs", LOGS_TYPE);
+ types.put("ratings", RATINGS_TYPE);
+ types.put("comments", COMMENTS_TYPE);
+ types.put("rename", RENAME_TYPE);
+ types.put("tagURL", TAGURL_TYPE);
+ types.put("associations", ASSOCIATIONS_TYPE);
+ types.put("restore", RESTORE_TYPE);
+ types.put("versions", VERSIONS_TYPE);
+ }
+
+ public Target resolve(Request request) {
+ RequestContext context = (RequestContext)request;
+ String uri = context.getUri().toString();
+ try {
+ uri = URLDecoder.decode(uri, "utf-8");
+ } catch (UnsupportedEncodingException e) {
+ log.error(e);
+ return null;
+ }
+ // URI will start with the baseURI, which we need to strip off.
+ uri = uri.substring(baseURI.length());
+ context.setAttribute("pathInfo", uri);
+ String [] parts = splitPath(uri);
+ boolean hasColon = false;
+ TargetType type = null;
+ if (parts.length > 1) {
+ // Store the split URL for later
+ context.setAttribute("splitPath", parts);
+ String discriminator = parts[1];
+ int idx = discriminator.indexOf("?");
+ if (idx > -1) {
+ discriminator = discriminator.substring(0, idx);
+ }
+ idx = discriminator.indexOf(":");
+ if (idx > -1) {
+ discriminator = discriminator.substring(0, idx);
+ hasColon = true;
+ }
+
+ if (discriminator.startsWith("aspect")) {
+ type = ASPECT_TYPE;
+ } else {
+ type = types.get(discriminator);
+ }
+
+ // If we have a discriminator that we don't understand, return a 404
+ if (type == null) return null;
+
+ // For the rest of this code, we'll want the "raw" resource URI
+ if (!hasColon || !type.equals(COMMENTS_TYPE))
+ uri = parts[0];
+ }
+
+ System.out.println(uri);
+ boolean isMedia = false;
+ if (uri.startsWith(RESOURCE)) {
+ uri = uri.substring(RESOURCE.length() - 1);
+ isMedia = true;
+ } else if (uri.startsWith(ATOM)) {
+ uri = uri.substring(ATOM.length() - 1);
+ } else if (uri.startsWith("/tags") && (uri.length() == 5 || uri.charAt(5) == '/')) {
+ return new SimpleTarget(TAGURL_TYPE, context);
+ } else {
+ return null;
+ }
+
+ Resource resource = null;
+ final String method = context.getMethod();
+ try {
+ // TODO - should this be secureRegistry?
+ resource = registry.get(uri);
+ } catch (ResourceNotFoundException e) {
+ // If this is a straight-ahead POST to a non-existent directory, create it?
+ if (method.equals("POST") && parts.length == 1) {
+ // Need to create it...
+ try {
+ Collection c = registry.newCollection();
+ registry.put(uri, c);
+ resource = registry.get(uri);
+ } catch (RegistryException e1) {
+ log.error(e1);
+ return null;
+ }
+ }
+ } catch (RegistryException e) {
+ return null; // return 404
+ }
+
+ context.setAttribute("MyResolver", this);
+ if (type == null) {
+ if (method.equals("DELETE")) {
+ // Unfortunately, deletions aren't quite handled the way we want them
+ // in AbstractEntityCollectionProvider, so for now we're using an
+ // extensionRequest to get it done.
+ type = DELETE_TYPE;
+ } else {
+ if (resource instanceof Collection) {
+ if (method.equals("HEAD") || method.equals("PUT")) {
+ // Abdera doesn't handle HEAD or PUT on collections yet... this should
+ // go away once that's fixed!
+ type = COLLECTION_CUSTOM_TYPE;
+ } else {
+ type = TargetType.TYPE_COLLECTION;
+ }
+ } else {
+ type = isMedia ? TargetType.TYPE_MEDIA : TargetType.TYPE_ENTRY;
+ }
+ }
+ }
+ return new ResourceTarget(type, context, resource);
+ }
+
+ /**
+ * This method will split the path into parts around the path separator, returning an array of
+ * the parts.
+ *
+ * @param path : URL path
+ * @return String array of the splited string
+ */
+ private String[] splitPath(String path) {
+ return path.split("\\" + RegistryConstants.URL_SEPARATOR);
+ }
+
+ public String getBaseURI() {
+ return baseURI;
+ }
+}
Added: trunk/registry/modules/core/src/main/java/org/wso2/registry/app/ResourceTarget.java
==============================================================================
--- (empty file)
+++ trunk/registry/modules/core/src/main/java/org/wso2/registry/app/ResourceTarget.java Thu Apr 17 21:17:15 2008
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2007, 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.app;
+
+import org.apache.abdera.protocol.server.TargetType;
+import org.apache.abdera.protocol.server.RequestContext;
+import org.apache.abdera.protocol.server.impl.SimpleTarget;
+import org.wso2.registry.Resource;
+
+public class ResourceTarget extends SimpleTarget {
+ Resource resource;
+
+ public ResourceTarget(TargetType type, RequestContext context, Resource resource) {
+ super(type, context);
+ this.resource = resource;
+ }
+
+ public Resource getResource() {
+ return resource;
+ }
+}
More information about the Registry-dev
mailing list