KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > dspace > content > crosswalk > XSLTIngestionCrosswalk


1 /*
2  * XSLTIngestionCrosswalk.java
3  *
4  * Version: $Revision: 1.2 $
5  *
6  * Date: $Date: 2006/09/25 08:19:25 $
7  *
8  * Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
9  * Institute of Technology. All rights reserved.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions are
13  * met:
14  *
15  * - Redistributions of source code must retain the above copyright
16  * notice, this list of conditions and the following disclaimer.
17  *
18  * - Redistributions in binary form must reproduce the above copyright
19  * notice, this list of conditions and the following disclaimer in the
20  * documentation and/or other materials provided with the distribution.
21  *
22  * - Neither the name of the Hewlett-Packard Company nor the name of the
23  * Massachusetts Institute of Technology nor the names of their
24  * contributors may be used to endorse or promote products derived from
25  * this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
32  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
33  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
34  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
35  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
36  * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
37  * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  */

40
41 package org.dspace.content.crosswalk;
42
43 import java.io.InputStream JavaDoc;
44 import java.io.IOException JavaDoc;
45 import java.sql.SQLException JavaDoc;
46 import java.util.Iterator JavaDoc;
47 import java.util.List JavaDoc;
48 import java.util.ArrayList JavaDoc;
49 import java.util.HashMap JavaDoc;
50 import java.util.Properties JavaDoc;
51 import java.util.Enumeration JavaDoc;
52 import java.io.OutputStream JavaDoc;
53 import java.io.StringReader JavaDoc;
54 import java.io.File JavaDoc;
55 import java.io.FileInputStream JavaDoc;
56
57 import java.sql.SQLException JavaDoc;
58 import org.apache.log4j.Logger;
59
60 import org.dspace.core.Context;
61 import org.dspace.core.Constants;
62 import org.dspace.content.Item;
63 import org.dspace.content.DCDate;
64 import org.dspace.content.DCValue;
65 import org.dspace.content.DSpaceObject;
66 import org.dspace.content.MetadataField;
67 import org.dspace.content.MetadataSchema;
68 import org.dspace.authorize.AuthorizeException;
69 import org.dspace.core.ConfigurationManager;
70 import org.dspace.core.SelfNamedPlugin;
71 import org.dspace.core.PluginManager;
72
73 import org.jdom.*;
74 import org.jdom.output.XMLOutputter;
75 import org.jdom.output.Format;
76 import org.jdom.input.SAXBuilder;
77 import org.jdom.input.JDOMParseException;
78 import org.jdom.xpath.XPath;
79 import org.jdom.transform.XSLTransformer;
80 import org.jdom.transform.XSLTransformException;
81
82 /**
83  * Configurable XSLT-driven ingestion Crosswalk
84  * <p>
85  * See the XSLTCrosswalk superclass for details on configuration.
86  *
87  * @author Larry Stone
88  * @version $Revision: 1.2 $
89  * @see XSLTCrosswalk
90  */

91 public class XSLTIngestionCrosswalk
92     extends XSLTCrosswalk
93     implements IngestionCrosswalk
94 {
95     /** log4j category */
96     private static Logger log = Logger.getLogger(XSLTIngestionCrosswalk.class);
97
98     private final static String JavaDoc DIRECTION = "submission";
99
100     private static String JavaDoc aliases[] = makeAliases(DIRECTION);
101
102     public static String JavaDoc[] getPluginNames()
103     {
104         return aliases;
105     }
106
107     // apply metadata values returned in DIM to the target item.
108
private void applyDim(List JavaDoc dimList, Item item)
109         throws MetadataValidationException
110     {
111         Iterator JavaDoc di = dimList.iterator();
112         while (di.hasNext())
113         {
114             Element elt = (Element)di.next();
115             if (elt.getName().equals("field") && elt.getNamespace().equals(DIM_NS))
116                 applyDimField(elt, item);
117
118             // if it's a <dim> container, apply its guts
119
else if (elt.getName().equals("dim") && elt.getNamespace().equals(DIM_NS))
120                 applyDim(elt.getChildren(), item);
121
122             else
123             {
124                 log.error("Got unexpected element in DIM list: "+elt.toString());
125                 throw new MetadataValidationException("Got unexpected element in DIM list: "+elt.toString());
126             }
127         }
128     }
129
130     // adds the metadata element from one <field>
131
private void applyDimField(Element field, Item item)
132     {
133         String JavaDoc schema = field.getAttributeValue("mdschema");
134         String JavaDoc element = field.getAttributeValue("element");
135         String JavaDoc qualifier = field.getAttributeValue("qualifier");
136         String JavaDoc lang = field.getAttributeValue("lang");
137
138         item.addMetadata(schema, element, qualifier, lang, field.getText());
139     }
140
141     /**
142      * Translate metadata with XSL stylesheet and ingest it.
143      * Translation produces a list of DIM "field" elements;
144      * these correspond directly to Item.addMetadata() calls so
145      * they are simply executed.
146      */

147     public void ingest(Context context, DSpaceObject dso, List JavaDoc metadata)
148         throws CrosswalkException,
149                IOException JavaDoc, SQLException JavaDoc, AuthorizeException
150     {
151         if (dso.getType() != Constants.ITEM)
152             throw new CrosswalkObjectNotSupported("XsltSubmissionionCrosswalk can only crosswalk to an Item.");
153         Item item = (Item)dso;
154
155         XSLTransformer xform = getTransformer(DIRECTION);
156         if (xform == null)
157             throw new CrosswalkInternalException("Failed to initialize transformer, probably error loading stylesheet.");
158         try
159         {
160             List JavaDoc dimList = xform.transform(metadata);
161             applyDim(dimList, item);
162         }
163         catch (XSLTransformException e)
164         {
165             log.error("Got error: "+e.toString());
166             throw new CrosswalkInternalException("XSL Transformation failed: "+e.toString());
167         }
168     }
169
170     /**
171      * Ingest a whole document. Build Document object around root element,
172      * and feed that to the transformation, since it may get handled
173      * differently than a List of metadata elements.
174      */

175     public void ingest(Context context, DSpaceObject dso, Element root)
176         throws CrosswalkException, IOException JavaDoc, SQLException JavaDoc, AuthorizeException
177     {
178         if (dso.getType() != Constants.ITEM)
179             throw new CrosswalkObjectNotSupported("XsltSubmissionionCrosswalk can only crosswalk to an Item.");
180         Item item = (Item)dso;
181
182         XSLTransformer xform = getTransformer(DIRECTION);
183         if (xform == null)
184             throw new CrosswalkInternalException("Failed to initialize transformer, probably error loading stylesheet.");
185         try
186         {
187             Document dimDoc = xform.transform(new Document((Element)root.clone()));
188             applyDim(dimDoc.getRootElement().getChildren(), item);
189         }
190         catch (XSLTransformException e)
191         {
192             log.error("Got error: "+e.toString());
193             throw new CrosswalkInternalException("XSL Transformation failed: "+e.toString());
194         }
195
196     }
197
198     /**
199      * Simple command-line rig for testing the DIM output of a stylesheet.
200      * Usage: java XSLTIngestionCrosswalk <crosswalk-name> <input-file>
201      */

202     public static void main(String JavaDoc[] argv) throws Exception JavaDoc
203     {
204         if (argv.length < 2)
205         {
206             System.err.println("Usage: java XSLTIngestionCrosswalk [-l] <crosswalk-name> <input-file>");
207             System.exit(1);
208         }
209
210         int i = 0;
211         boolean list = false;
212         // skip first arg if it's the list option
213
if (argv.length > 2 && argv[0].equals("-l"))
214         {
215             ++i;
216             list = true;
217         }
218         IngestionCrosswalk xwalk = (IngestionCrosswalk)PluginManager.getNamedPlugin(
219                 IngestionCrosswalk.class, argv[i]);
220         if (xwalk == null)
221         {
222             System.err.println("Error, cannot find an IngestionCrosswalk plugin for: \""+argv[i]+"\"");
223             System.exit(1);
224         }
225
226         XSLTransformer xform = ((XSLTIngestionCrosswalk)xwalk).getTransformer(DIRECTION);
227         if (xform == null)
228             throw new CrosswalkInternalException("Failed to initialize transformer, probably error loading stylesheet.");
229
230         SAXBuilder builder = new SAXBuilder();
231         Document inDoc = builder.build(new FileInputStream JavaDoc(argv[i+1]));
232         XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
233         Document dimDoc = null;
234         List JavaDoc dimList = null;
235         if (list)
236         {
237             dimList = xform.transform(inDoc.getRootElement().getChildren());
238             outputter.output(dimList, System.out);
239         }
240         else
241         {
242             dimDoc = xform.transform(inDoc);
243             outputter.output(dimDoc, System.out);
244             dimList = dimDoc.getRootElement().getChildren();
245         }
246
247         // Sanity-check the generated DIM, make sure it would load.
248
Context context = new Context();
249         Iterator JavaDoc di = dimList.iterator();
250         while (di.hasNext())
251         {
252             // skip over comment, text and other trash some XSLs generate..
253
Object JavaDoc o = di.next();
254             if (!(o instanceof Element))
255                 continue;
256
257             Element elt = (Element)o;
258             if (elt.getName().equals("field") && elt.getNamespace().equals(DIM_NS))
259             {
260                 String JavaDoc schema = elt.getAttributeValue("mdschema");
261                 String JavaDoc element = elt.getAttributeValue("element");
262                 String JavaDoc qualifier = elt.getAttributeValue("qualifier");
263                 MetadataSchema ms = MetadataSchema.find(context, schema);
264                 if (ms == null )
265                 {
266                     System.err.println("DIM Error, Cannot find metadata schema for: schema=\""+schema+
267                         "\" (... element=\""+element+"\", qualifier=\""+qualifier+"\")");
268     }
269                 else
270                 {
271                     if (qualifier != null && qualifier.equals(""))
272                     {
273                         System.err.println("DIM Warning, qualifier is empty string: "+
274                               " schema=\""+schema+"\", element=\""+element+"\", qualifier=\""+qualifier+"\"");
275                         qualifier = null;
276                     }
277                     MetadataField mf = MetadataField.findByElement(context,
278                                   ms.getSchemaID(), element, qualifier);
279                     if (mf == null)
280                         System.err.println("DIM Error, Cannot find metadata field for: schema=\""+schema+
281                             "\", element=\""+element+"\", qualifier=\""+qualifier+"\"");
282                 }
283             }
284             else
285             {
286                 // ("Got unexpected element in DIM list: "+elt.toString());
287
throw new MetadataValidationException("Got unexpected element in DIM list: "+elt.toString());
288             }
289         }
290     }
291
292 }
293
Popular Tags