~ubuntu-branches/ubuntu/quantal/netbeans/quantal

« back to all changes in this revision

Viewing changes to xml/core/src/org/netbeans/modules/xml/core/wizard/Util.java

  • Committer: Bazaar Package Importer
  • Author(s): Marek Slama
  • Date: 2008-01-29 14:11:22 UTC
  • Revision ID: james.westby@ubuntu.com-20080129141122-fnzjbo11ntghxfu7
Tags: upstream-6.0.1
ImportĀ upstreamĀ versionĀ 6.0.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/*
 
2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 
3
 *
 
4
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 
5
 *
 
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]"
 
23
 *
 
24
 * Contributor(s):
 
25
 *
 
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.
 
29
 *
 
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.
 
40
 */
 
41
package org.netbeans.modules.xml.core.wizard;
 
42
 
 
43
import java.awt.event.ActionEvent;
 
44
import java.io.File;
 
45
import java.io.FileInputStream;
 
46
import java.io.IOException;
 
47
import java.net.MalformedURLException;
 
48
import java.net.URL;
 
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;
 
54
import java.util.Map;
 
55
import java.util.Map.Entry;
 
56
import java.util.Set;
 
57
import java.util.StringTokenizer;
 
58
import java.util.TreeSet;
 
59
 
 
60
import javax.swing.JFileChooser;
 
61
import javax.swing.filechooser.FileFilter;
 
62
 
 
63
import org.openide.NotifyDescriptor;
 
64
import org.openide.DialogDisplayer;
 
65
import org.openide.actions.ActionManager;
 
66
import org.openide.windows.WindowManager;
 
67
 
 
68
import org.netbeans.api.xml.services.UserCatalog;
 
69
 
 
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;
 
84
 
 
85
 
 
86
/**
 
87
 * Collection of static support methods.
 
88
 *
 
89
 * @author Petr Kuzel
 
90
 */
 
91
class Util extends AbstractUtil {
 
92
 
 
93
    // last catalog directory
 
94
    private static File lastDirectory;
 
95
    
 
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
 
99
 
 
100
    /** Nobody can create instance of it, just me. */
 
101
    private Util () {
 
102
    }
 
103
    
 
104
    /**
 
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.
 
108
     */
 
109
    public static File selectSchemaFile(final String extensions) {
 
110
        JFileChooser chooser = new JFileChooser();
 
111
 
 
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;
 
118
                }
 
119
                return false;
 
120
            }
 
121
            public String getDescription() {
 
122
                return Util.THIS.getString("PROP_schema_mask"); // NOI18N
 
123
            }
 
124
        });
 
125
 
 
126
        if (lastDirectory != null) {
 
127
            chooser.setCurrentDirectory(lastDirectory);
 
128
        }
 
129
 
 
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)
 
134
        {
 
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;
 
141
                }
 
142
                     }
 
143
 
 
144
            DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(
 
145
                Util.THIS.getString("MSG_inValidFile"), NotifyDescriptor.WARNING_MESSAGE));
 
146
        }
 
147
        return null;
 
148
    }    
 
149
    
 
150
    /**
 
151
     * Obtain all known DTD public IDs.
 
152
     */
 
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
 
162
                    idSet.add(next);
 
163
                }
 
164
            }
 
165
            return (String[]) idSet.toArray(new String[idSet.size()]);
 
166
        } else {
 
167
            Util.THIS.debug("Note SourceResolver not found!");            // NOI18N
 
168
            return new String[0];
 
169
        }        
 
170
    }    
 
171
    
 
172
    /**
 
173
     * Perform default action on specified data object.
 
174
     */
 
175
    public static void performDefaultAction (DataObject dataObject) {
 
176
 
 
177
        Node node = dataObject.getNodeDelegate();
 
178
        SystemAction action = node.getDefaultAction();
 
179
 
 
180
        if (action != null) {
 
181
            ActionManager manager = (ActionManager) Lookup.getDefault().lookup(ActionManager.class);
 
182
            manager.invokeAction(action, new ActionEvent (node, ActionEvent.ACTION_PERFORMED, "")); // NOI18N
 
183
        }
 
184
    }
 
185
    
 
186
    public static String getDocumentType() {
 
187
        return "xsd";
 
188
    }
 
189
    
 
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";
 
194
        
 
195
        for(int i=0; i < fileList.size();i++){
 
196
            File file = (File)fileList.get(i);
 
197
        
 
198
            if(Thread.currentThread().isInterrupted())
 
199
                //if interrupted by the client dump the result and immediately return
 
200
                break;
 
201
            List targetNSList = null;
 
202
            try {
 
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);
 
209
                } else{
 
210
                    targetNS = NO_NAME_SPACE;
 
211
                }
 
212
                if( (targetNS == NO_NAME_SPACE))
 
213
                    //this is wsdl and it must have NS so ignore this file
 
214
                    continue;
 
215
                result.put(fobj, targetNS);
 
216
            } catch (Exception ex) {
 
217
                //ex.printStackTrace();
 
218
                //ignore this route
 
219
            }
 
220
        }
 
221
        return result;
 
222
    }
 
223
     
 
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
 
227
            return curList;
 
228
        if(curList == null)
 
229
            curList = new ArrayList();
 
230
        if(startFile.isFile()){
 
231
            int index = startFile.getName().lastIndexOf(".");
 
232
            if(index != -1){
 
233
                String extn = startFile.getName().substring(index+1);
 
234
                if((extn != null) && (extn.equalsIgnoreCase(fileExtension)))
 
235
                    curList.add(startFile);
 
236
            }
 
237
        }
 
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);
 
244
                }
 
245
            }
 
246
        }
 
247
        return curList;
 
248
    }
 
249
    
 
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());
 
254
        
 
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());
 
261
            }
 
262
        }
 
263
        return result;
 
264
    }
 
265
    
 
266
    public static String getNamespace(FileObject fobj){
 
267
        SchemaParser parser = new SchemaParser();
 
268
        File file = FileUtil.toFile(fobj);
 
269
//        String systemId = file.getAbsolutePath();
 
270
//        try {
 
271
//            URL context = fobj.getURL();
 
272
//            //#25604 workaround
 
273
//            if (context.toExternalForm().endsWith("/") == false) {
 
274
//                context = new URL(context.toExternalForm() + "/");
 
275
//            }
 
276
//            if (context != null) {
 
277
//                systemId = new URL(context, systemId).toExternalForm();
 
278
//            }
 
279
//        } catch (MalformedURLException ex) {
 
280
//            // ignore it use one passes by user
 
281
//        } catch(FileStateInvalidException e){
 
282
//            
 
283
//        }
 
284
        SchemaParser.SchemaInfo info = parser.parse(file.toURI().toString());
 
285
            
 
286
        if (info == null) return null;
 
287
        
 
288
        return info.namespace;
 
289
        
 
290
    }
 
291
    
 
292
    
 
293
    public static SchemaParser.SchemaInfo getRootElements(FileObject fobj){
 
294
        SchemaParser parser = new SchemaParser();
 
295
        File file = FileUtil.toFile(fobj);
 
296
//        String systemId = file.getAbsolutePath();
 
297
//        try {
 
298
//            URL context = fobj.getURL();
 
299
//            //#25604 workaround
 
300
//            if (context.toExternalForm().endsWith("/") == false) {
 
301
//                context = new URL(context.toExternalForm() + "/");
 
302
//            }
 
303
//            if (context != null) {
 
304
//                systemId = new URL(context, systemId).toExternalForm();
 
305
//            }
 
306
//        } catch (MalformedURLException ex) {
 
307
//            // ignore it use one passes by user
 
308
//        } catch(FileStateInvalidException e){
 
309
//            
 
310
//        }
 
311
        SchemaParser.SchemaInfo info = parser.parse(file.toURI().toString());
 
312
            
 
313
        if (info == null) return null;
 
314
        else return info;
 
315
        
 
316
    }
 
317
    
 
318
    public  static String getRelativePath(File file, File relativeTo) throws IOException {
 
319
        File origFile = file;
 
320
        File origRelativeTo = relativeTo;
 
321
        List filePathStack = new ArrayList();
 
322
        
 
323
        //are they on the same drive?
 
324
        String origFilePath = file.getAbsolutePath();
 
325
        String relativeFile = relativeTo.getAbsolutePath();
 
326
        
 
327
        StringTokenizer str = new StringTokenizer(origFilePath, ":");
 
328
        String drive = null, rdrive = null;
 
329
        if(str.hasMoreTokens())
 
330
            drive = str.nextToken();
 
331
        
 
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();
 
338
            }
 
339
        }
 
340
        
 
341
        List relativeToPathStack = new ArrayList();
 
342
        // build the path stack info to compare it afterwards
 
343
        file = file.getCanonicalFile();
 
344
        while (file!=null) {
 
345
            filePathStack.add(0, file);
 
346
            file = file.getParentFile();
 
347
        }
 
348
        relativeTo = relativeTo.getCanonicalFile();
 
349
        while (relativeTo!=null) {
 
350
            relativeToPathStack.add(0, relativeTo);
 
351
            relativeTo = relativeTo.getParentFile();
 
352
        }
 
353
        // compare as long it goes
 
354
        int count = 0;
 
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)) {
 
358
            count++;
 
359
            file = (File)filePathStack.get(count);
 
360
            relativeTo = (File)relativeToPathStack.get(count);
 
361
        }
 
362
        if (file.equals(relativeTo)) count++;
 
363
        // up as far as necessary
 
364
        
 
365
        StringBuffer relString = new StringBuffer();
 
366
        for (int i = count; i < relativeToPathStack.size(); i++) {
 
367
             relString.append(".."+File.separator);
 
368
        }
 
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);
 
372
        }
 
373
            relString.append(((File)filePathStack.get(filePathStack.size()-1)).getName());
 
374
        // just to test
 
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.");
 
378
     //   }
 
379
        return relString.toString();
 
380
        }
 
381
    
 
382
    private static Map namespaces = new HashMap();
 
383
    private static Map prefixes = new HashMap();
 
384
    
 
385
    private static NamespaceContext getNamespaceContext() {
 
386
        //schema related
 
387
        namespaces.put("xsd","http://www.w3.org/2001/XMLSchema");
 
388
        prefixes.put("http://www.w3.org/2001/XMLSchema", "xsd");
 
389
        
 
390
       return new HashNamespaceResolver(namespaces, prefixes);
 
391
    }
 
392
           
 
393
    public static final class HashNamespaceResolver implements NamespaceContext {
 
394
        private Map prefixes; // namespace, prefix
 
395
        private Map namespaces;  // prefix, namespace
 
396
        
 
397
        public HashNamespaceResolver(Map nsTable) {
 
398
            namespaces = nsTable;
 
399
            prefixes = new HashMap();
 
400
            Set set = namespaces.entrySet();
 
401
            Iterator it = set.iterator();
 
402
            while(it.hasNext()){
 
403
            //for (Entry<String,String> e : namespaces.entrySet()) {
 
404
                Entry e = (Entry)it.next();
 
405
                prefixes.put(e.getValue(), e.getKey());
 
406
            }
 
407
        }
 
408
        
 
409
        public HashNamespaceResolver(Map namespaces, Map prefixes) {
 
410
            this.namespaces = namespaces;
 
411
            this.prefixes = prefixes;
 
412
        }
 
413
        
 
414
        public Iterator getPrefixes(String namespaceURI) {
 
415
            return Collections.singletonList(getPrefix(namespaceURI)).iterator();
 
416
        }
 
417
        
 
418
        public String getPrefix(String namespaceURI) {
 
419
            return (String)prefixes.get(namespaceURI);
 
420
        }
 
421
        
 
422
        public String getNamespaceURI(String prefix) {
 
423
            return (String)namespaces.get(prefix);
 
424
        }
 
425
    }
 
426
    
 
427
}