KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > install > SchemaUploader


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.install;
17
18 import java.io.File JavaDoc;
19 import java.io.FileInputStream JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.lang.reflect.Method JavaDoc;
22 import java.util.ArrayList JavaDoc;
23 import java.util.List JavaDoc;
24 import java.util.Locale JavaDoc;
25
26 import javax.xml.parsers.DocumentBuilder JavaDoc;
27 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
28
29 import org.apache.commons.cli.CommandLine;
30 import org.apache.commons.cli.CommandLineParser;
31 import org.apache.commons.cli.HelpFormatter;
32 import org.apache.commons.cli.Option;
33 import org.apache.commons.cli.Options;
34 import org.apache.commons.cli.ParseException;
35 import org.apache.commons.cli.PosixParser;
36 import org.outerj.daisy.repository.Credentials;
37 import org.outerj.daisy.repository.LocaleHelper;
38 import org.outerj.daisy.repository.Repository;
39 import org.outerj.daisy.repository.RepositoryManager;
40 import org.outerj.daisy.repository.ValueType;
41 import org.outerj.daisy.repository.clientimpl.RemoteRepositoryManager;
42 import org.outerj.daisy.repository.query.SortOrder;
43 import org.outerj.daisy.repository.schema.DocumentType;
44 import org.outerj.daisy.repository.schema.DocumentTypeNotFoundException;
45 import org.outerj.daisy.repository.schema.FieldType;
46 import org.outerj.daisy.repository.schema.FieldTypeNotFoundException;
47 import org.outerj.daisy.repository.schema.PartType;
48 import org.outerj.daisy.repository.schema.PartTypeNotFoundException;
49 import org.outerj.daisy.repository.schema.RepositorySchema;
50 import org.outerj.daisy.repository.schema.StaticListItem;
51 import org.outerj.daisy.repository.schema.StaticSelectionList;
52 import org.outerj.daisy.repository.user.Role;
53 import org.w3c.dom.Document JavaDoc;
54 import org.w3c.dom.Element JavaDoc;
55 import org.w3c.dom.NodeList JavaDoc;
56
57 public class SchemaUploader {
58     private Document JavaDoc document;
59     
60     public static void main (String JavaDoc[] args) throws Exception JavaDoc{
61         Options options = new Options();
62         Option schemaOption = new Option("s", "schema", true, "Schema file to be uploaded");
63         schemaOption.setRequired(true);
64         schemaOption.setArgName("schema-file");
65         Option urlOption = new Option("r", "url", true, "Repository URL");
66         urlOption.setRequired(true);
67         urlOption.setArgName("repository-url");
68         Option userOption = new Option("u", "user", true, "Repository user");
69         userOption.setRequired(true);
70         userOption.setArgName("username");
71         Option passwordOption = new Option("p", "password", true, "Repository user password");
72         passwordOption.setRequired(true);
73         passwordOption.setArgName("password");
74         options.addOption(schemaOption);
75         options.addOption(urlOption);
76         options.addOption(userOption);
77         options.addOption(passwordOption);
78         options.addOption("h", "help", false, "Show this message");
79         
80         CommandLineParser parser = new PosixParser();
81         try {
82             CommandLine cli = parser.parse(options, args);
83             
84             File JavaDoc file = new File JavaDoc(cli.getOptionValue("s"));
85             String JavaDoc url = cli.getOptionValue("r");
86             Credentials cred = new Credentials(cli.getOptionValue("u"), cli.getOptionValue("p"));
87             
88              
89             SchemaUploader uploader = new SchemaUploader(new FileInputStream JavaDoc(file));
90             RepositoryManager manager = new RemoteRepositoryManager(url, cred);
91             Repository repository = manager.getRepository(cred);
92             repository.switchRole(Role.ADMINISTRATOR);
93             uploader.load(repository.getRepositorySchema());
94         } catch (ParseException e) {
95             HelpFormatter help = new HelpFormatter();
96             help.printHelp("daisy-schema-uploader", options, true);
97         }
98     }
99
100     /**
101      * @param is the input stream from where to read the schema XML instructions.
102      * The caller is reponsible for closing this input stream.
103      */

104     public SchemaUploader(InputStream JavaDoc is) throws Exception JavaDoc {
105         DocumentBuilderFactory JavaDoc documentBuilderFactory = DocumentBuilderFactory.newInstance();
106         documentBuilderFactory.setNamespaceAware(true);
107         documentBuilderFactory.setValidating(false);
108         DocumentBuilder JavaDoc documentBuilder = documentBuilderFactory.newDocumentBuilder();
109         this.document = documentBuilder.parse(is);
110     }
111
112     public void load(RepositorySchema schema) throws Exception JavaDoc {
113         Element JavaDoc[] elements = getElementChildren(document.getDocumentElement());
114         for (int i = 0; i < elements.length; i++) {
115             if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("partType")) {
116                 handlePartType(elements[i], schema);
117             } else if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("documentType")) {
118                 handleDocumentType(elements[i], schema);
119             } else if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("fieldType")) {
120                 handleFieldType(elements[i], schema);
121             }
122         }
123     }
124
125     private void handleFieldType(Element JavaDoc element, RepositorySchema schema) throws Exception JavaDoc {
126         String JavaDoc name = getAttribute(element, "name", true);
127         String JavaDoc valueTypeName = getAttribute(element, "valueType", true);
128         ValueType valueType = ValueType.fromString(valueTypeName);
129         boolean aclAllowed = getAttribute(element, "aclAllowed", true).equalsIgnoreCase("true");
130         boolean multiValue = getAttribute(element, "multiValue", true).equalsIgnoreCase("true");
131         boolean allowFreeEntry = getAttribute(element, "allowFreeEntry", false).equalsIgnoreCase("true");
132         boolean deprecated = getAttribute(element, "deprecated", false).equalsIgnoreCase("true");
133
134         FieldType fieldType;
135         try {
136             fieldType = schema.getFieldTypeByName(name, true);
137             System.out.println("Field type " + name + " already exists, will update it if necessary.");
138             if (fieldType.getValueType() != valueType) {
139                 System.out.println("WARNING!!! Field type " + name + " already exists, and has a different value type: expected " + valueType + " but is " + fieldType.getValueType());
140             }
141             if (fieldType.isMultiValue() != multiValue) {
142                 System.out.println("WARNING!!! Field type " + name + " already exists, and has a different multi-value property: expected " + multiValue + " but is " + fieldType.isMultiValue());
143             }
144         } catch (FieldTypeNotFoundException e) {
145             fieldType = schema.createFieldType(name, valueType, multiValue);
146             System.out.println("Creating new field type " + name);
147         }
148
149         String JavaDoc size = element.getAttribute("size");
150         if (!size.equals("")) {
151             fieldType.setSize(Integer.parseInt(size));
152         }
153
154         fieldType.setAclAllowed(aclAllowed);
155         fieldType.setAllowFreeEntry(allowFreeEntry);
156         fieldType.setDeprecated(deprecated);
157
158         loadLocalizedData(element, fieldType);
159         
160         Element JavaDoc[] elements = getElementChildren(element);
161         for (int i = 0; i < elements.length; i++) {
162             if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("localizedData")) {
163
164              } else if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("staticSelectionList")) {
165                 StaticSelectionList list = fieldType.createStaticSelectionList();
166                 Element JavaDoc[] itemElements = getElementChildren(elements[i], "item");
167                 for (int j = 0; j < itemElements.length; j++) {
168                     String JavaDoc value = getAttribute(itemElements[j], "value", true);
169                     StaticListItem item = list.createStaticListItem(value);
170                     loadLocalizedData(itemElements[j], item);
171                 }
172              }else if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("querySelectionList")) {
173                  String JavaDoc query = getAttribute(elements[i], "query", true);
174                  boolean filterVariants = Boolean.valueOf(getAttribute(elements[i], "filterVariants", true)).booleanValue();
175                  SortOrder order = SortOrder.fromString(getAttribute(elements[i], "sortOrder", true));
176                  fieldType.createQuerySelectionList(query, filterVariants, order);
177              }else if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("linkQuerySelectionList")) {
178                  String JavaDoc whereClause = getAttribute(elements[i], "whereClause", true);
179                  boolean filterVariants = Boolean.valueOf(getAttribute(elements[i], "filterVariants", true)).booleanValue();
180                  fieldType.createLinkQuerySelectionList(whereClause, filterVariants);
181              } else if (elements[i].getNamespaceURI() == null) {
182                 throw new Exception JavaDoc("Unrecognized element: " + elements[i].getLocalName());
183              }
184         }
185
186         fieldType.save();
187     }
188
189     private void handlePartType(Element JavaDoc element, RepositorySchema schema) throws Exception JavaDoc {
190         String JavaDoc name = getAttribute(element, "name", true);
191         String JavaDoc mimeTypes = getAttribute(element, "mimeTypes", true);
192         String JavaDoc daisyHtmlString = getAttribute(element, "daisyHtml", true);
193         boolean daisyHtml = daisyHtmlString.equalsIgnoreCase("true");
194         boolean deprecated = getAttribute(element, "deprecated", false).equalsIgnoreCase("true");
195         String JavaDoc linkExtractor = element.getAttribute("linkExtractor");
196
197         PartType partType;
198         try {
199             partType = schema.getPartTypeByName(name, true);
200             System.out.println("Part Type " + name + " already exists, will update it if necessary.");
201         } catch (PartTypeNotFoundException e) {
202             partType = schema.createPartType(name, mimeTypes);
203             System.out.println("Creating new Part Type " + name);
204         }
205
206         partType.setMimeTypes(mimeTypes);
207         partType.setDaisyHtml(daisyHtml);
208         partType.setDeprecated(deprecated);
209         if (linkExtractor.length() > 0)
210             partType.setLinkExtractor(linkExtractor);
211
212         loadLocalizedData(element, partType);
213         Element JavaDoc[] elements = getElementChildren(element);
214         
215         for (int i = 0; i < elements.length; i++) {
216             if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("localizedData")) {
217               // do nothing
218
} else if (elements[i].getNamespaceURI() == null) {
219                 throw new Exception JavaDoc("Unrecognized element: " + elements[i].getLocalName());
220             }
221         }
222
223         partType.save();
224     }
225
226     private void handleDocumentType(Element JavaDoc element, RepositorySchema schema) throws Exception JavaDoc {
227         String JavaDoc name = getAttribute(element, "name", true);
228         boolean deprecated = getAttribute(element, "deprecated", false).equalsIgnoreCase("true");
229         DocumentType documentType;
230
231         try {
232             documentType = schema.getDocumentTypeByName(name, true);
233             System.out.println("Document Type " + name + " already exists, will update it if necessary.");
234         } catch (DocumentTypeNotFoundException e) {
235             documentType = schema.createDocumentType(name);
236             System.out.println("Creating new Document Type " + name);
237         }
238         documentType.clearPartTypeUses();
239         documentType.clearFieldTypeUses();
240         documentType.setDeprecated(deprecated);
241         loadLocalizedData(element, documentType);
242         Element JavaDoc[] elements = getElementChildren(element);
243         for (int i = 0; i < elements.length; i++) {
244             if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("localizedData")) {
245                // do nothing
246
} else if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("partTypeUse")) {
247                 String JavaDoc requiredString = getAttribute(elements[i], "required", true);
248                 boolean required = requiredString.equalsIgnoreCase("true");
249                 String JavaDoc partTypeName = getAttribute(elements[i], "partTypeName", true);
250                 PartType partType = schema.getPartTypeByName(partTypeName, false);
251                 documentType.addPartType(partType, required);
252             } else if (elements[i].getNamespaceURI() == null && elements[i].getLocalName().equals("fieldTypeUse")) {
253                 String JavaDoc requiredString = getAttribute(elements[i], "required", true);
254                 boolean required = requiredString.equalsIgnoreCase("true");
255                 String JavaDoc fieldTypeName = getAttribute(elements[i], "fieldTypeName", true);
256                 FieldType fieldType = schema.getFieldTypeByName(fieldTypeName, false);
257                 documentType.addFieldType(fieldType, required);
258             } else if (elements[i].getNamespaceURI() == null) {
259                 throw new Exception JavaDoc("Unrecognized element: " + elements[i].getLocalName());
260             }
261         }
262
263         documentType.save();
264     }
265
266     private Element JavaDoc[] getElementChildren(Element JavaDoc element) {
267         List JavaDoc elements = new ArrayList JavaDoc();
268         NodeList JavaDoc nodes = element.getChildNodes();
269         for (int i = 0; i < nodes.getLength(); i++) {
270             if (nodes.item(i) instanceof Element JavaDoc) {
271                 elements.add(nodes.item(i));
272             }
273         }
274         return (Element JavaDoc[])elements.toArray(new Element JavaDoc[0]);
275     }
276     
277     private Element JavaDoc[] getElementChildren(Element JavaDoc element, String JavaDoc tagName) {
278         Element JavaDoc[] elements = getElementChildren(element);
279         List JavaDoc taggedElements = new ArrayList JavaDoc();
280         for (int i = 0; i < elements.length; i++) {
281             if (elements[i].getTagName().equals(tagName)) {
282                 taggedElements.add(elements[i]);
283             }
284         }
285         return (Element JavaDoc[])taggedElements.toArray(new Element JavaDoc[0]);
286     }
287
288     private String JavaDoc getAttribute(Element JavaDoc element, String JavaDoc name, boolean required) throws Exception JavaDoc {
289         if (required && !element.hasAttribute(name))
290             throw new Exception JavaDoc("Missing attribute " + name + " on element " + element.getLocalName());
291
292         return element.getAttribute(name);
293     }
294     
295     private void loadLocalizedData (Element JavaDoc element, Object JavaDoc object) throws Exception JavaDoc{
296         Element JavaDoc[] elements = getElementChildren(element, "localizedData");
297         Class JavaDoc clazz = object.getClass();
298         Class JavaDoc[] params = {Locale JavaDoc.class, String JavaDoc.class};
299         Method JavaDoc setLabelMethod = null;
300         Method JavaDoc setDescriptionMethod = null;
301         
302         try {
303             setLabelMethod = clazz.getMethod("setLabel", params );
304         } catch (NoSuchMethodException JavaDoc e) {
305             // do nothing
306
}
307         try {
308             setDescriptionMethod = clazz.getMethod("setDescription", params );
309         } catch (NoSuchMethodException JavaDoc e) {
310             // do nothing
311
}
312         
313         for (int i = 0; i < elements.length; i++) {
314             String JavaDoc localeString = getAttribute(elements[i], "locale", true);
315             Locale JavaDoc locale = LocaleHelper.parseLocale(localeString);
316             String JavaDoc label = getAttribute(elements[i], "label", true);
317             String JavaDoc description = getAttribute(elements[i], "description", false);
318
319             if (!label.equals("") && setLabelMethod != null ) {
320                 Object JavaDoc[] values = {locale, label};
321                 setLabelMethod.invoke(object, values);
322             }
323             
324             if (!description.equals("") && setDescriptionMethod != null ) {
325                 Object JavaDoc [] values = {locale, description};
326                 setDescriptionMethod.invoke(object, values);
327             }
328         }
329                            
330     }
331     
332 }
333
Popular Tags