KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > eclipse > jdt > internal > ui > jarpackager > JarPackageReader


1 /*******************************************************************************
2  * Copyright (c) 2000, 2006 IBM Corporation and others.
3  * All rights reserved. This program and the accompanying materials
4  * are made available under the terms of the Eclipse Public License v1.0
5  * which accompanies this distribution, and is available at
6  * http://www.eclipse.org/legal/epl-v10.html
7  *
8  * Contributors:
9  * IBM Corporation - initial API and implementation
10  *******************************************************************************/

11 package org.eclipse.jdt.internal.ui.jarpackager;
12
13 import java.io.BufferedInputStream JavaDoc;
14 import java.io.ByteArrayInputStream JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.InputStream JavaDoc;
17 import java.util.ArrayList JavaDoc;
18 import java.util.HashSet JavaDoc;
19 import java.util.List JavaDoc;
20 import java.util.Set JavaDoc;
21
22 import javax.xml.parsers.DocumentBuilder JavaDoc;
23 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
24 import javax.xml.parsers.ParserConfigurationException JavaDoc;
25
26 import org.eclipse.core.resources.IFile;
27 import org.eclipse.core.resources.IFolder;
28 import org.eclipse.core.resources.IProject;
29 import org.eclipse.core.resources.ResourcesPlugin;
30
31 import org.eclipse.core.runtime.Assert;
32 import org.eclipse.core.runtime.CoreException;
33 import org.eclipse.core.runtime.IPath;
34 import org.eclipse.core.runtime.IStatus;
35 import org.eclipse.core.runtime.MultiStatus;
36 import org.eclipse.core.runtime.Path;
37 import org.eclipse.core.runtime.Status;
38
39
40 import org.eclipse.ltk.core.refactoring.RefactoringCore;
41 import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
42 import org.eclipse.ltk.core.refactoring.RefactoringDescriptorProxy;
43 import org.eclipse.ltk.core.refactoring.history.IRefactoringHistoryService;
44 import org.eclipse.ltk.core.refactoring.history.RefactoringHistory;
45
46 import org.w3c.dom.Element JavaDoc;
47 import org.w3c.dom.Node JavaDoc;
48 import org.w3c.dom.NodeList JavaDoc;
49 import org.xml.sax.InputSource JavaDoc;
50 import org.xml.sax.SAXException JavaDoc;
51
52 import org.eclipse.jdt.core.IJavaElement;
53 import org.eclipse.jdt.core.IPackageFragment;
54 import org.eclipse.jdt.core.IType;
55 import org.eclipse.jdt.core.JavaCore;
56
57 import org.eclipse.jdt.internal.corext.util.Messages;
58
59 import org.eclipse.jdt.ui.jarpackager.IJarDescriptionReader;
60 import org.eclipse.jdt.ui.jarpackager.JarPackageData;
61
62 import org.eclipse.jdt.internal.ui.JavaPlugin;
63 import org.eclipse.jdt.internal.ui.IJavaStatusConstants;
64
65 /**
66  * Reads data from an InputStream and returns a JarPackage
67  */

68 public class JarPackageReader extends Object JavaDoc implements IJarDescriptionReader {
69
70     protected InputStream JavaDoc fInputStream;
71
72     private MultiStatus fWarnings;
73     
74     /**
75      * Reads a Jar Package from the underlying stream.
76      * It is the client's responsibility to close the stream.
77      */

78     public JarPackageReader(InputStream JavaDoc inputStream) {
79         Assert.isNotNull(inputStream);
80         fInputStream= new BufferedInputStream JavaDoc(inputStream);
81         fWarnings= new MultiStatus(JavaPlugin.getPluginId(), 0, JarPackagerMessages.JarPackageReader_jarPackageReaderWarnings, null);
82     }
83
84     public void read(JarPackageData jarPackage) throws CoreException {
85         try {
86             readXML(jarPackage);
87         } catch (IOException JavaDoc ex) {
88             String JavaDoc message= (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
89
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, ex));
90         } catch (SAXException JavaDoc ex) {
91             String JavaDoc message= (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
92
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, ex));
93         }
94     }
95
96
97     /**
98      * Closes this stream.
99      * It is the clients responsibility to close the stream.
100      *
101      * @exception CoreException
102      */

103     public void close() throws CoreException {
104         if (fInputStream != null)
105             try {
106                 fInputStream.close();
107             } catch (IOException JavaDoc ex) {
108                 String JavaDoc message= (ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() : ""); //$NON-NLS-1$
109
throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IJavaStatusConstants.INTERNAL_ERROR, message, ex));
110             }
111     }
112
113     public JarPackageData readXML(JarPackageData jarPackage) throws IOException JavaDoc, SAXException JavaDoc {
114         DocumentBuilderFactory JavaDoc factory= DocumentBuilderFactory.newInstance();
115         factory.setValidating(false);
116         DocumentBuilder JavaDoc parser= null;
117         
118         try {
119             parser= factory.newDocumentBuilder();
120         } catch (ParserConfigurationException JavaDoc ex) {
121             throw new IOException JavaDoc(ex.getLocalizedMessage());
122         } finally {
123             // Note: Above code is OK since clients are responsible to close the stream
124
}
125         Element JavaDoc xmlJarDesc= parser.parse(new InputSource JavaDoc(fInputStream)).getDocumentElement();
126         if (!xmlJarDesc.getNodeName().equals(JarPackagerUtil.DESCRIPTION_EXTENSION)) {
127             throw new IOException JavaDoc(JarPackagerMessages.JarPackageReader_error_badFormat);
128         }
129         NodeList JavaDoc topLevelElements= xmlJarDesc.getChildNodes();
130         for (int i= 0; i < topLevelElements.getLength(); i++) {
131             Node JavaDoc node= topLevelElements.item(i);
132             if (node.getNodeType() != Node.ELEMENT_NODE)
133                 continue;
134             Element JavaDoc element= (Element JavaDoc)node;
135             xmlReadJarLocation(jarPackage, element);
136             xmlReadOptions(jarPackage, element);
137             xmlReadRefactoring(jarPackage, element);
138             xmlReadSelectedProjects(jarPackage, element);
139             if (jarPackage.areGeneratedFilesExported())
140                 xmlReadManifest(jarPackage, element);
141             xmlReadSelectedElements(jarPackage, element);
142         }
143         return jarPackage;
144     }
145
146     private void xmlReadJarLocation(JarPackageData jarPackage, Element JavaDoc element) {
147         if (element.getNodeName().equals(JarPackagerUtil.JAR_EXTENSION))
148             jarPackage.setJarLocation(Path.fromPortableString(element.getAttribute("path"))); //$NON-NLS-1$
149
}
150
151     private void xmlReadOptions(JarPackageData jarPackage, Element JavaDoc element) throws java.io.IOException JavaDoc {
152         if (element.getNodeName().equals("options")) { //$NON-NLS-1$
153
jarPackage.setOverwrite(getBooleanAttribute(element, "overwrite")); //$NON-NLS-1$
154
jarPackage.setCompress(getBooleanAttribute(element, "compress")); //$NON-NLS-1$
155
jarPackage.setExportErrors(getBooleanAttribute(element, "exportErrors")); //$NON-NLS-1$
156
jarPackage.setExportWarnings(getBooleanAttribute(element, "exportWarnings")); //$NON-NLS-1$
157
jarPackage.setSaveDescription(getBooleanAttribute(element, "saveDescription")); //$NON-NLS-1$
158
jarPackage.setUseSourceFolderHierarchy(getBooleanAttribute(element, "useSourceFolders", false)); //$NON-NLS-1$
159
jarPackage.setDescriptionLocation(Path.fromPortableString(element.getAttribute("descriptionLocation"))); //$NON-NLS-1$
160
jarPackage.setBuildIfNeeded(getBooleanAttribute(element, "buildIfNeeded", jarPackage.isBuildingIfNeeded())); //$NON-NLS-1$
161
jarPackage.setIncludeDirectoryEntries(getBooleanAttribute(element, "includeDirectoryEntries", false)); //$NON-NLS-1$
162
jarPackage.setRefactoringAware(getBooleanAttribute(element, "storeRefactorings", false)); //$NON-NLS-1$
163
}
164     }
165
166     private void xmlReadRefactoring(JarPackageData jarPackage, Element JavaDoc element) throws java.io.IOException JavaDoc {
167         if (element.getNodeName().equals("storedRefactorings")) { //$NON-NLS-1$
168
jarPackage.setExportStructuralOnly(getBooleanAttribute(element, "structuralOnly", jarPackage.isExportStructuralOnly())); //$NON-NLS-1$
169
jarPackage.setDeprecationAware(getBooleanAttribute(element, "deprecationInfo", jarPackage.isDeprecationAware())); //$NON-NLS-1$
170
List JavaDoc elements= new ArrayList JavaDoc();
171             int count= 1;
172             String JavaDoc value= element.getAttribute("project" + count); //$NON-NLS-1$
173
while (value != null && !"".equals(value)) { //$NON-NLS-1$
174
final IProject project= ResourcesPlugin.getWorkspace().getRoot().getProject(value);
175                 if (project.exists())
176                     elements.add(project);
177                 count++;
178                 value= element.getAttribute("project" + count); //$NON-NLS-1$
179
}
180             jarPackage.setRefactoringProjects((IProject[]) elements.toArray(new IProject[elements.size()]));
181             elements.clear();
182             count= 1;
183             IRefactoringHistoryService service= RefactoringCore.getHistoryService();
184             try {
185                 service.connect();
186                 value= element.getAttribute("refactoring" + count); //$NON-NLS-1$
187
while (value != null && !"".equals(value)) { //$NON-NLS-1$
188
final ByteArrayInputStream JavaDoc stream= new ByteArrayInputStream JavaDoc(value.getBytes("UTF-8")); //$NON-NLS-1$
189
try {
190                         final RefactoringHistory history= service.readRefactoringHistory(stream, RefactoringDescriptor.NONE);
191                         if (history != null) {
192                             final RefactoringDescriptorProxy[] descriptors= history.getDescriptors();
193                             if (descriptors.length > 0) {
194                                 for (int index= 0; index < descriptors.length; index++) {
195                                     elements.add(descriptors[index]);
196                                 }
197                             }
198                         }
199                     } catch (CoreException exception) {
200                         JavaPlugin.log(exception);
201                     }
202                     count++;
203                     value= element.getAttribute("refactoring" + count); //$NON-NLS-1$
204
}
205             } finally {
206                 service.disconnect();
207             }
208             jarPackage.setRefactoringDescriptors((RefactoringDescriptorProxy[]) elements.toArray(new RefactoringDescriptorProxy[elements.size()]));
209         }
210     }
211
212     private void xmlReadManifest(JarPackageData jarPackage, Element JavaDoc element) throws java.io.IOException JavaDoc {
213         if (element.getNodeName().equals("manifest")) { //$NON-NLS-1$
214
jarPackage.setManifestVersion(element.getAttribute("manifestVersion")); //$NON-NLS-1$
215
jarPackage.setUsesManifest(getBooleanAttribute(element, "usesManifest")); //$NON-NLS-1$
216
jarPackage.setReuseManifest(getBooleanAttribute(element, "reuseManifest")); //$NON-NLS-1$
217
jarPackage.setSaveManifest(getBooleanAttribute(element,"saveManifest")); //$NON-NLS-1$
218
jarPackage.setGenerateManifest(getBooleanAttribute(element, "generateManifest")); //$NON-NLS-1$
219
jarPackage.setManifestLocation(Path.fromPortableString(element.getAttribute("manifestLocation"))); //$NON-NLS-1$
220
jarPackage.setManifestMainClass(getMainClass(element));
221             xmlReadSealingInfo(jarPackage, element);
222         }
223     }
224
225     private void xmlReadSealingInfo(JarPackageData jarPackage, Element JavaDoc element) throws java.io.IOException JavaDoc {
226         /*
227          * Try to find sealing info. Could ask for single child node
228          * but this would stop others from adding more child nodes to
229          * the manifest node.
230          */

231         NodeList JavaDoc sealingElementContainer= element.getChildNodes();
232         for (int j= 0; j < sealingElementContainer.getLength(); j++) {
233             Node JavaDoc sealingNode= sealingElementContainer.item(j);
234             if (sealingNode.getNodeType() == Node.ELEMENT_NODE
235                 && sealingNode.getNodeName().equals("sealing")) { //$NON-NLS-1$
236
// Sealing
237
Element JavaDoc sealingElement= (Element JavaDoc)sealingNode;
238                 jarPackage.setSealJar(getBooleanAttribute(sealingElement, "sealJar")); //$NON-NLS-1$
239
jarPackage.setPackagesToSeal(getPackages(sealingElement.getElementsByTagName("packagesToSeal"))); //$NON-NLS-1$
240
jarPackage.setPackagesToUnseal(getPackages(sealingElement.getElementsByTagName("packagesToUnSeal"))); //$NON-NLS-1$
241
}
242         }
243     }
244
245     private void xmlReadSelectedElements(JarPackageData jarPackage, Element JavaDoc element) throws java.io.IOException JavaDoc {
246         if (element.getNodeName().equals("selectedElements")) { //$NON-NLS-1$
247
jarPackage.setExportClassFiles(getBooleanAttribute(element, "exportClassFiles")); //$NON-NLS-1$
248
jarPackage.setExportOutputFolders(getBooleanAttribute(element, "exportOutputFolder", false)); //$NON-NLS-1$
249
jarPackage.setExportJavaFiles(getBooleanAttribute(element, "exportJavaFiles")); //$NON-NLS-1$
250
NodeList JavaDoc selectedElements= element.getChildNodes();
251             Set JavaDoc elementsToExport= new HashSet JavaDoc(selectedElements.getLength());
252             for (int j= 0; j < selectedElements.getLength(); j++) {
253                 Node JavaDoc selectedNode= selectedElements.item(j);
254                 if (selectedNode.getNodeType() != Node.ELEMENT_NODE)
255                     continue;
256                 Element JavaDoc selectedElement= (Element JavaDoc)selectedNode;
257                 if (selectedElement.getNodeName().equals("file")) //$NON-NLS-1$
258
addFile(elementsToExport, selectedElement);
259                 else if (selectedElement.getNodeName().equals("folder")) //$NON-NLS-1$
260
addFolder(elementsToExport,selectedElement);
261                 else if (selectedElement.getNodeName().equals("project")) //$NON-NLS-1$
262
addProject(elementsToExport ,selectedElement);
263                 else if (selectedElement.getNodeName().equals("javaElement")) //$NON-NLS-1$
264
addJavaElement(elementsToExport, selectedElement);
265                 // Note: Other file types are not handled by this writer
266
}
267             jarPackage.setElements(elementsToExport.toArray());
268         }
269     }
270
271     private void xmlReadSelectedProjects(JarPackageData jarPackage, Element JavaDoc element) throws java.io.IOException JavaDoc {
272         if (element.getNodeName().equals("selectedProjects")) { //$NON-NLS-1$
273
NodeList JavaDoc selectedElements= element.getChildNodes();
274             Set JavaDoc selectedProjects= new HashSet JavaDoc(selectedElements.getLength());
275             for (int index= 0; index < selectedElements.getLength(); index++) {
276                 Node JavaDoc node= selectedElements.item(index);
277                 if (node.getNodeType() != Node.ELEMENT_NODE)
278                     continue;
279                 Element JavaDoc selectedElement= (Element JavaDoc)node;
280                 if (selectedElement.getNodeName().equals("project")) //$NON-NLS-1$
281
addProject(selectedProjects ,selectedElement);
282             }
283             jarPackage.setRefactoringProjects((IProject[]) selectedProjects.toArray(new IProject[selectedProjects.size()]));
284         }
285     }
286     
287     protected boolean getBooleanAttribute(Element JavaDoc element, String JavaDoc name, boolean defaultValue) throws IOException JavaDoc {
288         if (element.hasAttribute(name))
289             return getBooleanAttribute(element, name);
290         else
291             return defaultValue;
292     }
293
294     protected boolean getBooleanAttribute(Element JavaDoc element, String JavaDoc name) throws IOException JavaDoc {
295         String JavaDoc value= element.getAttribute(name);
296         if (value != null && value.equalsIgnoreCase("true")) //$NON-NLS-1$
297
return true;
298         if (value != null && value.equalsIgnoreCase("false")) //$NON-NLS-1$
299
return false;
300         throw new IOException JavaDoc(JarPackagerMessages.JarPackageReader_error_illegalValueForBooleanAttribute);
301     }
302
303     private void addFile(Set JavaDoc selectedElements, Element JavaDoc element) throws IOException JavaDoc {
304         IPath path= getPath(element);
305         if (path != null) {
306             IFile file= JavaPlugin.getWorkspace().getRoot().getFile(path);
307             if (file != null)
308                 selectedElements.add(file);
309         }
310     }
311
312     private void addFolder(Set JavaDoc selectedElements, Element JavaDoc element) throws IOException JavaDoc {
313         IPath path= getPath(element);
314         if (path != null) {
315             IFolder folder= JavaPlugin.getWorkspace().getRoot().getFolder(path);
316             if (folder != null)
317                 selectedElements.add(folder);
318         }
319     }
320
321     private void addProject(Set JavaDoc selectedElements, Element JavaDoc element) throws IOException JavaDoc {
322         String JavaDoc name= element.getAttribute("name"); //$NON-NLS-1$
323
if (name.length() == 0)
324             throw new IOException JavaDoc(JarPackagerMessages.JarPackageReader_error_tagNameNotFound);
325         IProject project= JavaPlugin.getWorkspace().getRoot().getProject(name);
326         if (project != null)
327             selectedElements.add(project);
328     }
329
330     private IPath getPath(Element JavaDoc element) throws IOException JavaDoc {
331         String JavaDoc pathString= element.getAttribute("path"); //$NON-NLS-1$
332
if (pathString.length() == 0)
333             throw new IOException JavaDoc(JarPackagerMessages.JarPackageReader_error_tagPathNotFound);
334         return Path.fromPortableString(element.getAttribute("path")); //$NON-NLS-1$
335
}
336     
337     private void addJavaElement(Set JavaDoc selectedElements, Element JavaDoc element) throws IOException JavaDoc {
338         String JavaDoc handleId= element.getAttribute("handleIdentifier"); //$NON-NLS-1$
339
if (handleId.length() == 0)
340             throw new IOException JavaDoc(JarPackagerMessages.JarPackageReader_error_tagHandleIdentifierNotFoundOrEmpty);
341         IJavaElement je= JavaCore.create(handleId);
342         if (je == null)
343             addWarning(JarPackagerMessages.JarPackageReader_warning_javaElementDoesNotExist, null);
344         else
345             selectedElements.add(je);
346     }
347
348     private IPackageFragment[] getPackages(NodeList JavaDoc list) throws IOException JavaDoc {
349         if (list.getLength() > 1)
350             throw new IOException JavaDoc(Messages.format(JarPackagerMessages.JarPackageReader_error_duplicateTag, list.item(0).getNodeName()));
351         if (list.getLength() == 0)
352             return null; // optional entry is not present
353
NodeList JavaDoc packageNodes= list.item(0).getChildNodes();
354         List JavaDoc packages= new ArrayList JavaDoc(packageNodes.getLength());
355         for (int i= 0; i < packageNodes.getLength(); i++) {
356             Node JavaDoc packageNode= packageNodes.item(i);
357             if (packageNode.getNodeType() == Node.ELEMENT_NODE && packageNode.getNodeName().equals("package")) { //$NON-NLS-1$
358
String JavaDoc handleId= ((Element JavaDoc)packageNode).getAttribute("handleIdentifier"); //$NON-NLS-1$
359
if (handleId.equals("")) //$NON-NLS-1$
360
throw new IOException JavaDoc(JarPackagerMessages.JarPackageReader_error_tagHandleIdentifierNotFoundOrEmpty);
361                 IJavaElement je= JavaCore.create(handleId);
362                 if (je != null && je.getElementType() == IJavaElement.PACKAGE_FRAGMENT)
363                     packages.add(je);
364                 else
365                     addWarning(JarPackagerMessages.JarPackageReader_warning_javaElementDoesNotExist, null);
366             }
367         }
368         return (IPackageFragment[])packages.toArray(new IPackageFragment[packages.size()]);
369     }
370
371     private IType getMainClass(Element JavaDoc element) {
372         String JavaDoc handleId= element.getAttribute("mainClassHandleIdentifier"); //$NON-NLS-1$
373
if (handleId.equals("")) //$NON-NLS-1$
374
return null; // Main-Class entry is optional or can be empty
375
IJavaElement je= JavaCore.create(handleId);
376         if (je != null && je.getElementType() == IJavaElement.TYPE)
377             return (IType)je;
378         addWarning(JarPackagerMessages.JarPackageReader_warning_mainClassDoesNotExist, null);
379         return null;
380     }
381
382     /**
383      * Returns the status of the reader.
384      * If there were any errors, the result is a status object containing
385      * individual status objects for each error.
386      * If there were no errors, the result is a status object with error code <code>OK</code>.
387      *
388      * @return the status of this operation
389      */

390     public IStatus getStatus() {
391         if (fWarnings.getChildren().length == 0)
392             return new Status(IStatus.OK, JavaPlugin.getPluginId(), 0, "", null); //$NON-NLS-1$
393
else
394             return fWarnings;
395     }
396     
397     /**
398      * Adds a new warning to the list with the passed information.
399      * Normally the export operation continues after a warning.
400      * @param message the message
401      * @param error the throwable that caused the warning, or <code>null</code>
402      */

403     protected void addWarning(String JavaDoc message, Throwable JavaDoc error) {
404         fWarnings.add(new Status(IStatus.WARNING, JavaPlugin.getPluginId(), 0, message, error));
405     }
406 }
407
Popular Tags