2
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
4
* Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
6
* The contents of this file are subject to the terms of either the GNU
7
* General Public License Version 2 only ("GPL") or the Common
8
* Development and Distribution License("CDDL") (collectively, the
9
* "License"). You may not use this file except in compliance with the
10
* License. You can obtain a copy of the License at
11
* http://www.netbeans.org/cddl-gplv2.html
12
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
13
* specific language governing permissions and limitations under the
14
* License. When distributing the software, include this License Header
15
* Notice in each file and include the License file at
16
* nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
17
* particular file as subject to the "Classpath" exception as provided
18
* by Sun in the GPL Version 2 section of the License file that
19
* accompanied this code. If applicable, add the following below the
20
* License Header, with the fields enclosed by brackets [] replaced by
21
* your own identifying information:
22
* "Portions Copyrighted [year] [name of copyright owner]"
26
* The Original Software is NetBeans. The Initial Developer of the Original
27
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
28
* Microsystems, Inc. All Rights Reserved.
30
* If you wish your version of this file to be governed by only the CDDL
31
* or only the GPL Version 2, indicate your decision by adding
32
* "[Contributor] elects to include this software in this distribution
33
* under the [CDDL or GPL Version 2] license." If you do not indicate a
34
* single choice of license, a recipient has the option to distribute
35
* your version of this file under either the CDDL, the GPL Version 2 or
36
* to extend the choice of license to its licensees as provided above.
37
* However, if you add GPL Version 2 code and therefore, elected the GPL
38
* Version 2 license, then the option applies only if the new code is
39
* made subject to such option by the copyright holder.
41
package org.netbeans.modules.xml.core.wizard;
43
import java.awt.event.ActionEvent;
45
import java.io.FileInputStream;
46
import java.io.IOException;
47
import java.net.MalformedURLException;
49
import java.util.ArrayList;
50
import java.util.Collections;
51
import java.util.HashMap;
52
import java.util.Iterator;
53
import java.util.List;
55
import java.util.Map.Entry;
57
import java.util.StringTokenizer;
58
import java.util.TreeSet;
60
import javax.swing.JFileChooser;
61
import javax.swing.filechooser.FileFilter;
63
import org.openide.NotifyDescriptor;
64
import org.openide.DialogDisplayer;
65
import org.openide.actions.ActionManager;
66
import org.openide.windows.WindowManager;
68
import org.netbeans.api.xml.services.UserCatalog;
70
import org.netbeans.modules.xml.core.lib.AbstractUtil;
71
import org.openide.filesystems.FileObject;
72
import org.openide.filesystems.FileUtil;
73
import org.openide.loaders.DataObject;
74
import org.openide.util.Lookup;
75
import org.openide.util.actions.SystemAction;
76
import javax.xml.xpath.XPath;
77
import javax.xml.xpath.XPathConstants;
78
import javax.xml.xpath.XPathFactory;
79
import javax.xml.namespace.NamespaceContext;
80
import org.openide.filesystems.FileStateInvalidException;
81
import org.openide.nodes.Node;
82
import org.xml.sax.InputSource;
83
import org.w3c.dom.NodeList;
87
* Collection of static support methods.
91
class Util extends AbstractUtil {
93
// last catalog directory
94
private static File lastDirectory;
96
/** Default and only one instance of this class. */
97
public static final Util THIS = new Util();
98
public static final String NO_NAME_SPACE = "NO_NAME_SPACE"; //NOI18N
100
/** Nobody can create instance of it, just me. */
105
* Prompts user for a Schema file.
106
* @param extensions a space separated list of file extensions
107
* @return filename or null if operation was cancelled.
109
public static File selectSchemaFile(final String extensions) {
110
JFileChooser chooser = new JFileChooser();
112
chooser.setFileFilter(new FileFilter() {
113
public boolean accept(File f) {
114
if (f.isDirectory()) return true;
115
StringTokenizer token = new StringTokenizer(extensions, " "); // NOI18N
116
while (token.hasMoreElements()) {
117
if (f.getName().endsWith(token.nextToken())) return true;
121
public String getDescription() {
122
return Util.THIS.getString("PROP_schema_mask"); // NOI18N
126
if (lastDirectory != null) {
127
chooser.setCurrentDirectory(lastDirectory);
130
chooser.setDialogTitle(Util.THIS.getString("PROP_schema_dialog_name"));
131
while (chooser.showDialog(WindowManager.getDefault().getMainWindow(),
132
Util.THIS.getString("PROP_schema_select_button"))
133
== JFileChooser.APPROVE_OPTION)
135
File f = chooser.getSelectedFile();
136
lastDirectory = chooser.getCurrentDirectory();
137
if (f != null && f.isFile()) {
138
StringTokenizer token = new StringTokenizer(extensions, " "); // NOI18N
139
while (token.hasMoreElements()) {
140
if (f.getName().endsWith(token.nextToken())) return f;
144
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
145
Util.THIS.getString("MSG_inValidFile"), NotifyDescriptor.WARNING_MESSAGE));
151
* Obtain all known DTD public IDs.
153
public static String[] getKnownDTDPublicIDs() {
154
UserCatalog catalog = UserCatalog.getDefault();
155
if (catalog != null) {
156
Set idSet = new TreeSet();
157
for (Iterator it = catalog.getPublicIDs(); it.hasNext(); ) {
158
String next = (String) it.next();
159
// exclude schema publicIDs
160
String nextLowerCase = next.toLowerCase();
161
if (!nextLowerCase.startsWith("schema:") && !nextLowerCase.endsWith(".xsd")) { // NOI18N
165
return (String[]) idSet.toArray(new String[idSet.size()]);
167
Util.THIS.debug("Note SourceResolver not found!"); // NOI18N
168
return new String[0];
173
* Perform default action on specified data object.
175
public static void performDefaultAction (DataObject dataObject) {
177
Node node = dataObject.getNodeDelegate();
178
SystemAction action = node.getDefaultAction();
180
if (action != null) {
181
ActionManager manager = (ActionManager) Lookup.getDefault().lookup(ActionManager.class);
182
manager.invokeAction(action, new ActionEvent (node, ActionEvent.ACTION_PERFORMED, "")); // NOI18N
186
public static String getDocumentType() {
190
public static Map getFiles2NSMappingInProj(File rootFile, String docType){
191
List fileList = getFilesWithExtension(rootFile, docType, new ArrayList());
192
Map result = new HashMap();
193
String xpathQuery = "//xsd:schema/@targetNamespace";
195
for(int i=0; i < fileList.size();i++){
196
File file = (File)fileList.get(i);
198
if(Thread.currentThread().isInterrupted())
199
//if interrupted by the client dump the result and immediately return
201
List targetNSList = null;
203
targetNSList = runXPathQuery(file, xpathQuery);
204
String targetNS = null;
205
FileObject fobj = FileUtil.toFileObject(file);
206
if(targetNSList.size() > 0){
207
//just take the first and ignore rest
208
targetNS = (String)targetNSList.get(0);
210
targetNS = NO_NAME_SPACE;
212
if( (targetNS == NO_NAME_SPACE))
213
//this is wsdl and it must have NS so ignore this file
215
result.put(fobj, targetNS);
216
} catch (Exception ex) {
217
//ex.printStackTrace();
224
public static List getFilesWithExtension(File startFile, String fileExtension, List curList) {
225
if(Thread.currentThread().isInterrupted())
226
//if interrupted by the client dump the result and immediately return
229
curList = new ArrayList();
230
if(startFile.isFile()){
231
int index = startFile.getName().lastIndexOf(".");
233
String extn = startFile.getName().substring(index+1);
234
if((extn != null) && (extn.equalsIgnoreCase(fileExtension)))
235
curList.add(startFile);
238
if(startFile.isDirectory()){
239
File[] children = startFile.listFiles();
240
if(children != null){
241
for(int i=0; i < children.length; i++ ){
242
File child = (File) children[i];
243
getFilesWithExtension(child, fileExtension, curList);
250
public static List runXPathQuery(File parsedFile, String xpathExpr) throws Exception{
251
List result = new ArrayList();
252
XPath xpath = XPathFactory.newInstance().newXPath();
253
xpath.setNamespaceContext(getNamespaceContext());
255
InputSource inputSource = new InputSource(new FileInputStream(parsedFile));
256
NodeList nodes = (NodeList) xpath.evaluate(xpathExpr, inputSource, XPathConstants.NODESET);
257
if((nodes != null) && (nodes.getLength() > 0)){
258
for(int i=0; i<nodes.getLength();i++){
259
org.w3c.dom.Node node = nodes.item(i);
260
result.add(node.getNodeValue());
266
public static String getNamespace(FileObject fobj){
267
SchemaParser parser = new SchemaParser();
268
File file = FileUtil.toFile(fobj);
269
// String systemId = file.getAbsolutePath();
271
// URL context = fobj.getURL();
272
// //#25604 workaround
273
// if (context.toExternalForm().endsWith("/") == false) {
274
// context = new URL(context.toExternalForm() + "/");
276
// if (context != null) {
277
// systemId = new URL(context, systemId).toExternalForm();
279
// } catch (MalformedURLException ex) {
280
// // ignore it use one passes by user
281
// } catch(FileStateInvalidException e){
284
SchemaParser.SchemaInfo info = parser.parse(file.toURI().toString());
286
if (info == null) return null;
288
return info.namespace;
293
public static SchemaParser.SchemaInfo getRootElements(FileObject fobj){
294
SchemaParser parser = new SchemaParser();
295
File file = FileUtil.toFile(fobj);
296
// String systemId = file.getAbsolutePath();
298
// URL context = fobj.getURL();
299
// //#25604 workaround
300
// if (context.toExternalForm().endsWith("/") == false) {
301
// context = new URL(context.toExternalForm() + "/");
303
// if (context != null) {
304
// systemId = new URL(context, systemId).toExternalForm();
306
// } catch (MalformedURLException ex) {
307
// // ignore it use one passes by user
308
// } catch(FileStateInvalidException e){
311
SchemaParser.SchemaInfo info = parser.parse(file.toURI().toString());
313
if (info == null) return null;
318
public static String getRelativePath(File file, File relativeTo) throws IOException {
319
File origFile = file;
320
File origRelativeTo = relativeTo;
321
List filePathStack = new ArrayList();
323
//are they on the same drive?
324
String origFilePath = file.getAbsolutePath();
325
String relativeFile = relativeTo.getAbsolutePath();
327
StringTokenizer str = new StringTokenizer(origFilePath, ":");
328
String drive = null, rdrive = null;
329
if(str.hasMoreTokens())
330
drive = str.nextToken();
332
str = new StringTokenizer(relativeFile, ":");
333
if(str.hasMoreTokens())
334
rdrive = str.nextToken();
335
if(drive != null && rdrive != null) {
336
if(!drive.equals(rdrive)){
337
return file.toURI().toString();
341
List relativeToPathStack = new ArrayList();
342
// build the path stack info to compare it afterwards
343
file = file.getCanonicalFile();
345
filePathStack.add(0, file);
346
file = file.getParentFile();
348
relativeTo = relativeTo.getCanonicalFile();
349
while (relativeTo!=null) {
350
relativeToPathStack.add(0, relativeTo);
351
relativeTo = relativeTo.getParentFile();
353
// compare as long it goes
355
file = (File)filePathStack.get(count);
356
relativeTo = (File)relativeToPathStack.get(count);
357
while ( (count < filePathStack.size()-1) && (count <relativeToPathStack.size()-1) && file.equals(relativeTo)) {
359
file = (File)filePathStack.get(count);
360
relativeTo = (File)relativeToPathStack.get(count);
362
if (file.equals(relativeTo)) count++;
363
// up as far as necessary
365
StringBuffer relString = new StringBuffer();
366
for (int i = count; i < relativeToPathStack.size(); i++) {
367
relString.append(".."+File.separator);
369
// now back down to the file
370
for (int i = count; i <filePathStack.size()-1; i++) {
371
relString.append(((File)filePathStack.get(i)).getName()+File.separator);
373
relString.append(((File)filePathStack.get(filePathStack.size()-1)).getName());
375
// File relFile = new File(origRelativeTo.getAbsolutePath()+File.separator+relString.toString());
376
// if (!relFile.getCanonicalFile().equals(origFile.getCanonicalFile())) {
377
// throw new IOException("Failed to find relative path.");
379
return relString.toString();
382
private static Map namespaces = new HashMap();
383
private static Map prefixes = new HashMap();
385
private static NamespaceContext getNamespaceContext() {
387
namespaces.put("xsd","http://www.w3.org/2001/XMLSchema");
388
prefixes.put("http://www.w3.org/2001/XMLSchema", "xsd");
390
return new HashNamespaceResolver(namespaces, prefixes);
393
public static final class HashNamespaceResolver implements NamespaceContext {
394
private Map prefixes; // namespace, prefix
395
private Map namespaces; // prefix, namespace
397
public HashNamespaceResolver(Map nsTable) {
398
namespaces = nsTable;
399
prefixes = new HashMap();
400
Set set = namespaces.entrySet();
401
Iterator it = set.iterator();
403
//for (Entry<String,String> e : namespaces.entrySet()) {
404
Entry e = (Entry)it.next();
405
prefixes.put(e.getValue(), e.getKey());
409
public HashNamespaceResolver(Map namespaces, Map prefixes) {
410
this.namespaces = namespaces;
411
this.prefixes = prefixes;
414
public Iterator getPrefixes(String namespaceURI) {
415
return Collections.singletonList(getPrefix(namespaceURI)).iterator();
418
public String getPrefix(String namespaceURI) {
419
return (String)prefixes.get(namespaceURI);
422
public String getNamespaceURI(String prefix) {
423
return (String)namespaces.get(prefix);