KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > emailnotifier > serverimpl > SubscriptionManagerHttpConnector


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.outerj.daisy.emailnotifier.serverimpl;
17
18 import org.apache.avalon.framework.logger.AbstractLogEnabled;
19 import org.apache.avalon.framework.service.Serviceable;
20 import org.apache.avalon.framework.service.ServiceManager;
21 import org.apache.avalon.framework.service.ServiceException;
22 import org.apache.avalon.framework.activity.Initializable;
23 import org.apache.avalon.framework.activity.Disposable;
24 import org.apache.cocoon.matching.helpers.WildcardHelper;
25 import org.apache.commons.collections.primitives.LongList;
26 import org.apache.commons.collections.primitives.ArrayLongList;
27 import org.apache.xmlbeans.XmlOptions;
28 import org.outerj.daisy.httpconnector.HttpConnector;
29 import org.outerj.daisy.httpconnector.DaisyUserPrincipal;
30 import org.outerj.daisy.httpconnector.HttpUtil;
31 import org.outerj.daisy.httpconnector.BadRequestException;
32 import org.outerj.daisy.emailnotifier.EmailSubscriptionManager;
33 import org.outerj.daisy.emailnotifier.Subscription;
34 import org.outerj.daisy.emailnotifier.Subscribers;
35 import org.outerj.daisy.repository.Repository;
36 import org.outerj.daisy.repository.VariantKey;
37 import org.outerj.daisy.xmlutil.LocalSAXParserFactory;
38 import org.mortbay.http.handler.AbstractHttpHandler;
39 import org.mortbay.http.HttpRequest;
40 import org.mortbay.http.HttpResponse;
41 import org.mortbay.http.HttpException;
42 import org.outerx.daisy.x10.SubscriptionDocument;
43 import org.outerx.daisy.x10.SubscribedDocument;
44
45 import java.io.IOException JavaDoc;
46 import java.util.HashMap JavaDoc;
47 import java.util.StringTokenizer JavaDoc;
48
49 /**
50  * @avalon.component version="1.0" name="subscription-manager-httpconnector" lifestyle="singleton"
51  */

52 public class SubscriptionManagerHttpConnector extends AbstractLogEnabled implements Serviceable, Initializable, Disposable {
53     private HttpConnector httpConnector;
54     private SubscriptionManagerHttpHandler httpHandler = new SubscriptionManagerHttpHandler();
55     private static final int[] subscriptionPattern = WildcardHelper.compilePattern("/emailnotifier/subscription/*");
56     private static final int[] eventSubscribersPattern = WildcardHelper.compilePattern("/emailnotifier/*EventsSubscribers");
57     private static final int[] documentSubscriptionsPattern = WildcardHelper.compilePattern("/emailnotifier/documentSubscription/*");
58     private static final int[] documentSubscriptionForUserPattern = WildcardHelper.compilePattern("/emailnotifier/documentSubscription/*/*");
59     private static final int[] collectionSubscriptionsPattern = WildcardHelper.compilePattern("/emailnotifier/collectionSubscription/*");
60
61     /**
62      * @avalon.dependency key="httpconnector" type="org.outerj.daisy.httpconnector.HttpConnector"
63      */

64     public void service(ServiceManager serviceManager) throws ServiceException {
65         httpConnector = (HttpConnector)serviceManager.lookup("httpconnector");
66     }
67
68     public void initialize() throws Exception JavaDoc {
69         httpConnector.addHandler(httpHandler);
70     }
71
72     public void dispose() {
73         httpConnector.removeHandler(httpHandler);
74     }
75
76     private class SubscriptionManagerHttpHandler extends AbstractHttpHandler {
77         public void handle(String JavaDoc pathInContext, String JavaDoc pathParams, HttpRequest request, HttpResponse response)
78                 throws HttpException, IOException JavaDoc {
79             String JavaDoc path = request.getPath();
80             if (!path.startsWith("/emailnotifier"))
81                 return;
82
83             try {
84                 Repository repository = ((DaisyUserPrincipal)request.getUserPrincipal()).getRepository();
85                 EmailSubscriptionManager subscriptionManager = (EmailSubscriptionManager)repository.getExtension("EmailSubscriptionManager");
86
87                 HashMap JavaDoc matchMap = new HashMap JavaDoc();
88                 if (WildcardHelper.match(matchMap, path, subscriptionPattern)) {
89                     long userId = HttpUtil.parseId("user", (String JavaDoc)matchMap.get("1"));
90
91                     Subscription subscription = subscriptionManager.getSubscription(userId);
92
93                     if (request.getMethod().equals(HttpRequest.__GET)) {
94                         response.setContentType("text/xml");
95                         subscription.getXml().save(response.getOutputStream());
96                         response.commit();
97                         return;
98                     } else if (request.getMethod().equals(HttpRequest.__POST)) {
99                         XmlOptions xmlOptions = new XmlOptions().setLoadUseXMLReader(LocalSAXParserFactory.newXmlReader());
100                         SubscriptionDocument subscriptionDocument = SubscriptionDocument.Factory.parse(request.getInputStream(), xmlOptions);
101                         SubscriptionDocument.Subscription subscriptionXml = subscriptionDocument.getSubscription();
102                         subscription.setFromXml(subscriptionXml);
103                         subscription.save();
104
105                         response.commit();
106                         return;
107                     } else if (request.getMethod().equals(HttpRequest.__DELETE)) {
108                         subscriptionManager.deleteSubscription(userId);
109                         response.commit();
110                         return;
111                     } else {
112                         response.sendError(HttpResponse.__405_Method_Not_Allowed);
113                         return;
114                     }
115                 } else if (path.equals("/emailnotifier/subscription")) {
116                     if (request.getMethod().equals(HttpRequest.__GET)) {
117                         response.setContentType("text/xml");
118                         subscriptionManager.getSubscriptions().getXml().save(response.getOutputStream());
119                         response.commit();
120                         return;
121                     } else {
122                         response.sendError(HttpResponse.__405_Method_Not_Allowed);
123                         return;
124                     }
125                 } else if (WildcardHelper.match(matchMap, path, eventSubscribersPattern)) {
126                     if (request.getMethod().equals(HttpRequest.__GET)) {
127                         String JavaDoc type = (String JavaDoc)matchMap.get("1");
128                         Subscribers subscribers = null;
129
130                         if (type.equals("document") || type.equals("comment")) {
131                             long documentId = HttpUtil.getLongParam(request, "documentId");
132                             long branchId = HttpUtil.getLongParam(request, "branch");
133                             long languageId = HttpUtil.getLongParam(request, "language");
134                             String JavaDoc collectionIdsParam = request.getParameter("collectionIds");
135                             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(collectionIdsParam, ",");
136                             LongList collectionIdList = new ArrayLongList();
137                             while (tokenizer.hasMoreTokens()) {
138                                 collectionIdList.add(HttpUtil.parseId("collection", tokenizer.nextToken()));
139                             }
140                             if (type.equals("document"))
141                                 subscribers = subscriptionManager.getAllDocumentEventSubscribers(documentId, branchId, languageId, collectionIdList.toArray());
142                             else
143                                 subscribers = subscriptionManager.getAllCommentEventSubscribers(documentId, branchId, languageId, collectionIdList.toArray());
144                         } else if (type.equals("schema")) {
145                             subscribers = subscriptionManager.getAllSchemaEventSubscribers();
146                         } else if (type.equals("user")) {
147                             subscribers = subscriptionManager.getAllUserEventSubscribers();
148                         } else if (type.equals("collection")) {
149                             subscribers = subscriptionManager.getAllCollectionEventSubscribers();
150                         } else if (type.equals("acl")) {
151                             subscribers = subscriptionManager.getAllAclEventSubscribers();
152                         } else {
153                             HttpUtil.sendCustomError("Invalid event group type: " + type, HttpResponse.__400_Bad_Request, response);
154                             return;
155                         }
156
157                         subscribers.getXml().save(response.getOutputStream());
158                         response.commit();
159                         return;
160                     } else {
161                         response.sendError(HttpResponse.__405_Method_Not_Allowed);
162                         return;
163                     }
164                 } else if (WildcardHelper.match(matchMap, path, documentSubscriptionsPattern)) {
165                     long documentId = HttpUtil.parseId("document", (String JavaDoc)matchMap.get("1"));
166                     if (request.getMethod().equals("POST")) {
167                         String JavaDoc action = request.getParameter("action");
168                         if (action == null) {
169                             throw new Exception JavaDoc("Missing action parameter");
170                         } else if (action.equals("add")) {
171                             long userId = HttpUtil.getLongParam(request, "userId");
172                             long branchId = HttpUtil.getLongParam(request, "branch");
173                             long languageId = HttpUtil.getLongParam(request, "language");
174                             subscriptionManager.addDocumentSubscription(userId, new VariantKey(documentId, branchId, languageId));
175                             response.commit();
176                         } else if (action.equals("remove")) {
177                             long userId = HttpUtil.getLongParam(request, "userId");
178                             long branchId = HttpUtil.getLongParam(request, "branch");
179                             long languageId = HttpUtil.getLongParam(request, "language");
180                             subscriptionManager.deleteDocumentSubscription(userId, new VariantKey(documentId, branchId, languageId));
181                             response.commit();
182                         } else {
183                             throw new Exception JavaDoc("Invalid value for action parameter: " + action);
184                         }
185                     } else if (request.getMethod().equals("DELETE")) {
186                         if (request.getParameter("branch") != null) {
187                             long branchId = HttpUtil.getLongParam(request, "branch");
188                             long languageId = HttpUtil.getLongParam(request, "language");
189                             subscriptionManager.deleteAllSubscriptionsForDocumentVariant(new VariantKey(documentId, branchId, languageId));
190                         } else {
191                             subscriptionManager.deleteAllSubscriptionsForDocument(documentId);
192                         }
193                         response.commit();
194                     } else {
195                         response.sendError(HttpResponse.__405_Method_Not_Allowed);
196                     }
197                 } else if (WildcardHelper.match(matchMap, path, documentSubscriptionForUserPattern)) {
198                     if (request.getMethod().equals("GET")) {
199                         long documentId = HttpUtil.parseId("document", (String JavaDoc)matchMap.get("1"));
200                         long branchId = HttpUtil.getLongParam(request, "branch");
201                         long languageId = HttpUtil.getLongParam(request, "language");
202                         long userId = HttpUtil.parseId("user", (String JavaDoc)matchMap.get("2"));
203                         boolean isSubscribed = subscriptionManager.isSubsribed(userId, new VariantKey(documentId, branchId, languageId));
204                         SubscribedDocument subscribedDocument = SubscribedDocument.Factory.newInstance();
205                         subscribedDocument.setSubscribed(isSubscribed);
206                         subscribedDocument.save(response.getOutputStream());
207                         response.commit();
208                     } else {
209                         response.sendError(HttpResponse.__405_Method_Not_Allowed);
210                     }
211                 } else if (WildcardHelper.match(matchMap, path, collectionSubscriptionsPattern)) {
212                     long collectionId = HttpUtil.parseId("collection", (String JavaDoc)matchMap.get("1"));
213                     if (request.getMethod().equals("DELETE")) {
214                         subscriptionManager.deleteAllSubscriptionsForCollection(collectionId);
215                         response.commit();
216                     } else {
217                         response.sendError(HttpResponse.__405_Method_Not_Allowed);
218                     }
219                 }
220             } catch (BadRequestException e) {
221                 // doesn't need to be logged
222
HttpUtil.sendCustomError(e.getMessage(), HttpResponse.__400_Bad_Request, response);
223             } catch (Throwable JavaDoc e) {
224                 getLogger().error("Error processing request " + path, e);
225                 HttpUtil.sendCustomError(e, HttpResponse.__202_Accepted, response);
226             }
227         }
228     }
229 }
230
Popular Tags