KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > dav > server > webservice > PublishService


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  *
19  * Created: 29-Nov-2004 by jejking
20  * Version: $Revision: 1.5 $
21  * Last Updated: $Date: 2004/12/24 12:10:45 $
22  */

23 package org.openharmonise.dav.server.webservice;
24
25
26 import java.io.File JavaDoc;
27 import java.io.FileInputStream JavaDoc;
28 import java.io.FileOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.rmi.RemoteException JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.zip.Deflater JavaDoc;
33 import java.util.zip.ZipEntry JavaDoc;
34 import java.util.zip.ZipOutputStream JavaDoc;
35
36 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
37 import javax.xml.parsers.ParserConfigurationException JavaDoc;
38
39 import org.openharmonise.commons.dsi.*;
40 import org.openharmonise.commons.net.Email;
41 import org.openharmonise.commons.xml.*;
42 import org.openharmonise.commons.xml.namespace.NamespaceType;
43 import org.openharmonise.dav.server.utils.*;
44 import org.openharmonise.rm.DataAccessException;
45 import org.openharmonise.rm.config.ConfigException;
46 import org.openharmonise.rm.config.ConfigSettings;
47 import org.openharmonise.rm.dsi.DataStoreInterfaceFactory;
48 import org.openharmonise.rm.factory.HarmoniseFactoryException;
49 import org.openharmonise.rm.factory.HarmoniseObjectFactory;
50 import org.openharmonise.rm.publishing.*;
51 import org.openharmonise.rm.resources.AbstractChildObject;
52 import org.openharmonise.rm.resources.AbstractParentObject;
53 import org.openharmonise.rm.resources.content.Section;
54 import org.openharmonise.rm.resources.lifecycle.Status;
55 import org.openharmonise.rm.resources.metadata.properties.PropertyGroup;
56 import org.openharmonise.rm.resources.publishing.WebPage;
57 import org.w3c.dom.*;
58 import org.xml.sax.SAXException JavaDoc;
59 /**
60  *
61  * Webservice to publish a Harmonise Page using a State element (containing the page id),
62  * a Harmonise Page template or a combination of both. Note that the presense of a
63  * Harmonise Page template would overide the presense of a Page id in the State.
64  * @author matt treanor
65  * @version $Revision: 1.5 $
66  *
67  */

68 public class PublishService {
69     private static final String JavaDoc ATTRIB_HREF = "href";
70     protected AbstractDataStoreInterface m_dsi = null;
71     static final String JavaDoc TAG_HARMONISE_PUBLISH_SERVICE = "HarmonisePublishService";
72     static final String JavaDoc PNAME_UPLOADED_TEMPFILE_DIR = "UPLOADED_TEMPFILE_DIR";
73     static final String JavaDoc PNAME_EMAIL_HOST = "EMAIL_HOST";
74     static final String JavaDoc DOCUMENT_ROOT_PATH = "/root/documents";
75     static final String JavaDoc PROP_GROUP_ROOT_PATH = "/root/props";
76
77     /**
78      *
79      * @param sXml
80      * @return
81      * @throws RemoteException
82      */

83     public String JavaDoc publish(String JavaDoc sXml) throws RemoteException JavaDoc {
84         String JavaDoc sResult = null;
85         try {
86             Document doc = XMLDocument.getXMLDocumentFromString(sXml);
87             Element inputRoot = doc.getDocumentElement();
88             String JavaDoc sTagName = inputRoot.getTagName();
89             if (sTagName.equals(TAG_HARMONISE_PUBLISH_SERVICE) == false) {
90                 throw new RemoteException JavaDoc(
91                     "Root element must be " + TAG_HARMONISE_PUBLISH_SERVICE);
92             }
93             convertWebdavPaths(doc);
94             NodeList nodes = inputRoot.getElementsByTagName(State.TAG_STATE);
95             Element stateEl = (Element) nodes.item(0);
96             State state = null;
97             if (stateEl != null) {
98                 Document stateXml = new XMLDocument();
99                 stateXml.appendChild(XMLUtils.copyNode(stateEl, stateXml));
100                 state = new State(stateXml, getDataStoreInterface());
101             } else {
102                 state = new State(getDataStoreInterface());
103                 Element el = state.createElement(State.TAG_STATE);
104                 state.appendChild(el);
105             }
106             nodes = inputRoot.getElementsByTagName(WebPage.TAG_HARMONISE);
107             Element ohEl = (Element) nodes.item(0);
108             WebPageEngine engine =
109                 new WebPageEngine(this.getDataStoreInterface());
110             HarmoniseOutput out = null;
111             WebPage page = null;
112             if (ohEl != null) {
113                 out = engine.createXML(ohEl, state);
114             } else {
115                 nodes = stateEl.getElementsByTagName(WebPage.TAG_PAGE);
116                 Element pageEl = (Element) nodes.item(0);
117                 if (pageEl != null) {
118                     String JavaDoc sId = pageEl.getAttribute(WebPage.ATTRIB_ID);
119                     if (sId != null) {
120                         int nId = Integer.parseInt(sId);
121                         page = new WebPage(getDataStoreInterface(), nId);
122                         System.out.println("Found page " + page.getName());
123                     }
124                 }
125                 out = engine.createXML(page, state);
126             }
127             XMLPrettyPrint printer = new XMLPrettyPrint();
128             printer.setNamespaceAware(true);
129             Element outEL = out.getDocumentElement();
130             sResult = printer.printNode(outEL);
131         } catch (Exception JavaDoc e) {
132             throw new RemoteException JavaDoc(e.getLocalizedMessage());
133         }
134         return sResult;
135     }
136
137     public void publishContent(String JavaDoc sEmail, boolean bShowContent, boolean bShowMetadata) throws RemoteException JavaDoc {
138         String JavaDoc sResult = null;
139         try {
140             String JavaDoc sTempDir = ConfigSettings.getProperty(PNAME_UPLOADED_TEMPFILE_DIR);
141             String JavaDoc sZipPath = sTempDir + "/HarmoniseContent.zip";
142             FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(sZipPath);
143             ZipOutputStream JavaDoc zos = new ZipOutputStream JavaDoc(fos);
144             zos.setLevel(Deflater.DEFAULT_COMPRESSION);
145             
146             if(bShowContent) {
147                 String JavaDoc sHarmonisePath = sTempDir + "/HarmoniseContent";
148             
149                 File JavaDoc harmoniseDir = new File JavaDoc(sHarmonisePath);
150                 harmoniseDir.mkdir();
151                 
152                 AbstractParentObject docRoot = (AbstractParentObject) HarmoniseObjectFactory.instantiateHarmoniseObject(getDataStoreInterface(),Section.class.getName(), DOCUMENT_ROOT_PATH);
153                 writeCollection(docRoot, harmoniseDir);
154                 
155                 recurseDir(zos, sHarmonisePath);
156                 
157                 harmoniseDir.delete();
158             }
159             
160             if(bShowMetadata) {
161                 HarmoniseOutput out = new HarmoniseOutput(getDataStoreInterface());
162             
163                 Element propGroupEl = out.createElement("Metadata");
164                 out.appendChild(propGroupEl);
165                 
166                 PropertyGroup propGroupRoot = (PropertyGroup) HarmoniseObjectFactory.instantiateHarmoniseObject(getDataStoreInterface(),PropertyGroup.class.getName(), PROP_GROUP_ROOT_PATH);
167                 writePropertyGroup(propGroupRoot, out.getDocumentElement(), out);
168                 
169                 String JavaDoc sMetadataPath = sTempDir + "/Metadata.xml";
170                 File JavaDoc metadataFile = new File JavaDoc(sMetadataPath);
171                 
172                 XMLPrettyPrint pp = new XMLPrettyPrint();
173                 pp.printNodeToFile(out.getDocumentElement(), metadataFile);
174                 addToZip(zos, metadataFile.getPath());
175                 
176                 metadataFile.delete();
177             }
178             zos.close();
179             fos.close();
180             if(bShowContent || bShowMetadata){
181                 File JavaDoc zipFile = new File JavaDoc(sZipPath);
182                 mailFile(sEmail, zipFile);
183             }
184             
185         } catch (Exception JavaDoc e) {
186             throw new RemoteException JavaDoc(e.getLocalizedMessage());
187         }
188     }
189     private void recurseDir(ZipOutputStream JavaDoc zos, String JavaDoc filePath) throws ConfigException, IOException JavaDoc{
190         File JavaDoc file = new File JavaDoc(filePath);
191         File JavaDoc[] fileList = file.listFiles();
192         for (int i = 0; i < fileList.length; i++) {
193             if (fileList[i].isDirectory()) {
194                 recurseDir (zos, fileList[i].getPath());
195             } else if (fileList[i].isFile()) {
196                 // Call the zipFunc function
197
addToZip(zos, fileList[i].getPath());
198             }
199         }
200     }
201     private void addToZip(ZipOutputStream JavaDoc zos, String JavaDoc filePath) throws IOException JavaDoc, ConfigException{
202         FileInputStream JavaDoc in = new FileInputStream JavaDoc(filePath);
203         String JavaDoc sTempDir = ConfigSettings.getProperty(PNAME_UPLOADED_TEMPFILE_DIR);
204         
205         String JavaDoc zipPath = filePath.substring(sTempDir.length()-1);
206         zos.putNextEntry(new ZipEntry JavaDoc(zipPath));
207         byte[] buffer = new byte[18024];
208         int len;
209         while((len = in.read(buffer)) > 0){
210             zos.write(buffer, 0, len);
211         }
212     }
213     private void writeCollection(AbstractParentObject parent, File JavaDoc parentDir) throws ConfigException, DataAccessException, PublishException, StateException, RemoteException JavaDoc, SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc, FactoryConfigurationError JavaDoc{
214         File JavaDoc dir = new File JavaDoc(parentDir.getAbsolutePath() + "/" + parent.getName());
215         dir.mkdir();
216         Iterator JavaDoc iter = parent.getChildren().iterator();
217         while(iter.hasNext()){
218             AbstractChildObject child = (AbstractChildObject) iter.next();
219                         
220             if(child instanceof AbstractParentObject) {
221                 AbstractParentObject sub = (AbstractParentObject) child;
222                 writeCollection(sub, dir);
223             } else if(child.getStatus() == Status.APPROVED) {
224                 writeDocument(child, getResourceTemplate().getDocumentElement(), dir);
225             }
226         }
227         
228     }
229     private void writeDocument(AbstractChildObject resource,Element templateRoot, File JavaDoc parentDir) throws DataAccessException, PublishException, SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc, FactoryConfigurationError JavaDoc, StateException, RemoteException JavaDoc{
230         File JavaDoc file = new File JavaDoc(parentDir.getAbsolutePath() + "/" + resource.getName() + ".xml");
231
232         HarmoniseOutput out = new HarmoniseOutput(getDataStoreInterface());
233         Element elResource = resource.publish(templateRoot,out,getState());
234         
235         XMLPrettyPrint pp = new XMLPrettyPrint();
236         pp.printNodeToFile(elResource, file);
237     }
238     private void writePropertyGroup(PropertyGroup propGroup, Element topEl, HarmoniseOutput out) throws HarmoniseFactoryException, ConfigException, DataAccessException, PublishException, StateException, RemoteException JavaDoc, SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc, FactoryConfigurationError JavaDoc{
239         Element docEl = propGroup.publish(getPropertyGroupTemplate().getDocumentElement(), out, getState());
240         
241         Iterator JavaDoc iter = propGroup.getChildren().iterator();
242         while(iter.hasNext()){
243             AbstractChildObject child = (AbstractChildObject) iter.next();
244                         
245             if(child instanceof PropertyGroup) {
246                 PropertyGroup sub = (PropertyGroup) child;
247                 writePropertyGroup(sub, topEl, out);
248             } else if(child.getStatus() == Status.APPROVED) {
249                 writeProperty(child, getPropertyTemplate().getDocumentElement(), docEl, out);
250             }
251         }
252         topEl.appendChild(docEl);
253     }
254     private void writeProperty(AbstractChildObject prop, Element templateRoot, Element topEl, HarmoniseOutput out) throws PublishException, StateException, RemoteException JavaDoc, SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc, FactoryConfigurationError JavaDoc{
255         Element docEl = prop.publish(getPropertyTemplate().getDocumentElement(), out, getState());
256         topEl.appendChild(docEl);
257     }
258     private AbstractDataStoreInterface getDataStoreInterface()
259         throws RemoteException JavaDoc {
260         if (m_dsi == null) {
261             try {
262                 m_dsi = DataStoreInterfaceFactory.getDataStoreInterface();
263             } catch (DataStoreException e) {
264                 throw new RemoteException JavaDoc(e.getLocalizedMessage(), e);
265             }
266         }
267         return m_dsi;
268     }
269     private void convertWebdavPaths(Document doc)
270         throws DOMException, NameResolverException {
271         //translate webdav paths to real ones
272
NodeList pathNodes =
273             doc.getElementsByTagName(AbstractChildObject.TAG_PATH);
274         Element curElm = null;
275         String JavaDoc sPath = null;
276         //Element parentEl = null;
277
for (int i = 0; i < pathNodes.getLength(); i++) {
278             curElm = (Element) pathNodes.item(i); // get the current path
279
Text pathText = (Text) curElm.getFirstChild();
280             // get the first child
281
if (pathText != null) {
282                 sPath = pathText.getData();
283                 if(sPath.startsWith(HarmoniseNameResolver.URL_SEPARATOR)) {
284                 String JavaDoc sRealPath =
285                     HarmoniseNameResolver.getRealPath(sPath);
286
287                 if (sRealPath != null) {
288                     pathText.setData(sRealPath);
289                 }
290                 }
291             }
292         }
293         //translate webdav paths in xincludes
294
NodeList xincludes =
295             doc.getElementsByTagNameNS(
296                 NamespaceType.XINCLUDE.getURI(),
297                 "include");
298         String JavaDoc sHref = null;
299         for (int i = 0; i < xincludes.getLength(); i++) {
300             curElm = (Element) xincludes.item(i);
301             // get the current path
302
Attr hrefAttr =
303                 (Attr) curElm.getAttributeNode(
304                     ATTRIB_HREF);
305             // get the first child
306
sHref = hrefAttr.getValue();
307             if(sHref.startsWith(HarmoniseNameResolver.URL_SEPARATOR + HarmoniseNameResolver.WEBDAV_ROOT_MARKER)){
308                 hrefAttr.setValue(HarmoniseNameResolver.getRealPath(sHref));
309             }
310         }
311     }
312     private void mailFile(String JavaDoc recipient_address, File JavaDoc file) throws ConfigException, Exception JavaDoc{
313         String JavaDoc sender_address = "HarmoniseServer";
314         String JavaDoc message = "Contents of the Harmonise Server";
315         String JavaDoc subject = "Harmonise Content";
316         Email email = new Email(ConfigSettings.getProperty(PNAME_EMAIL_HOST),recipient_address, sender_address,
317                 subject, message, file);
318         if(email.send() == false ){
319             throw new RemoteException JavaDoc("There was a problem emailing the file " + file.getPath());
320         } else {
321             file.delete();
322         }
323     }
324     public static void main(String JavaDoc args[]){
325         String JavaDoc sReturn = "";
326         try {
327             PublishService service = new PublishService();
328             String JavaDoc sXml = null;
329
330             sXml = "<HarmonisePublishService><State>" +
331                 "<Page id=\"1000\"/>" +
332                 "</State></HarmonisePublishService>";
333             sReturn = service.publish(sXml);
334         } catch (RemoteException JavaDoc e) {
335             // TODO Auto-generated catch block
336
System.out.println(e.getLocalizedMessage());
337         }
338         System.out.println(sReturn);
339         System.exit(0);
340     }
341     private Document getResourceTemplate() throws SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc, FactoryConfigurationError JavaDoc{
342         String JavaDoc sXml = "<HarmoniseObject><Name/><DisplayName/><Summary/><Content/><Profile default='true'><AllPropertyInstances/></Profile><Status/></HarmoniseObject>";
343         return XMLDocument.getXMLDocumentFromString(sXml);
344     }
345     private Document getPropertyGroupTemplate() throws SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc, FactoryConfigurationError JavaDoc{
346         String JavaDoc sXml = "<PropertyGroup><Name/><Summary/></PropertyGroup>";
347         return XMLDocument.getXMLDocumentFromString(sXml);
348     }
349     private Document getPropertyTemplate() throws SAXException JavaDoc, IOException JavaDoc, ParserConfigurationException JavaDoc, FactoryConfigurationError JavaDoc{
350         String JavaDoc sXml = "<Property><DomainList/><Range><RangeDetails/><RangeObject/></Range></Property>";
351         return XMLDocument.getXMLDocumentFromString(sXml);
352     }
353     private State getState() throws StateException, RemoteException JavaDoc{
354         State state = new State(getDataStoreInterface());
355         return state;
356     }
357 }
358
Popular Tags