Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 6ad0dd44d22c619f5d4ad0be6efe66ec4d72714e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*******************************************************************************
 * Copyright (c) 2001, 2004 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.wst.xml.ui.internal.wizards;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.Preferences;
import org.eclipse.jface.util.Assert;
import org.eclipse.wst.common.contentmodel.CMDocument;
import org.eclipse.wst.common.contentmodel.CMElementDeclaration;
import org.eclipse.wst.common.contentmodel.CMNamedNodeMap;
import org.eclipse.wst.common.contentmodel.CMPlugin;
import org.eclipse.wst.common.contentmodel.util.ContentBuilder;
import org.eclipse.wst.common.contentmodel.util.DOMContentBuilderImpl;
import org.eclipse.wst.common.contentmodel.util.DOMWriter;
import org.eclipse.wst.common.contentmodel.util.NamespaceInfo;
import org.eclipse.wst.sse.core.preferences.CommonModelPreferenceNames;
import org.eclipse.wst.xml.core.internal.XMLCorePlugin;
import org.eclipse.wst.xml.uriresolver.XMLCatalog;
import org.eclipse.wst.xml.uriresolver.XMLCatalogEntry;
import org.eclipse.wst.xml.uriresolver.XMLCatalogPlugin;
import org.eclipse.wst.xml.uriresolver.util.IdResolver;
import org.eclipse.wst.xml.uriresolver.util.IdResolverImpl;
import org.eclipse.wst.xml.uriresolver.util.URIHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class NewXMLGenerator
{                                  

  protected String grammarURI;  
  protected CMDocument cmDocument;  
  protected int buildPolicy;
  protected String rootElementName;

  protected XMLCatalogEntry xmlCatalogEntry;
  
  // info for dtd   
  protected String publicId;
  protected String systemId;  
  protected String defaultSystemId;  
                           
  // info for xsd
  public List namespaceInfoList;

  public NewXMLGenerator() 
  {
  }

  public NewXMLGenerator(String grammarURI, CMDocument cmDocument) 
  {
    this.grammarURI = grammarURI;
    this.cmDocument = cmDocument;
  }


  public static CMDocument createCMDocument(String uri, String[] errorInfo)
  {                          
    String title = null;
    String message = null;   
    List errorList = new Vector();
    CMDocument cmDocument = null;

    if (URIHelper.isReadableURI(uri,true))
    {
      uri = URIHelper.normalize(uri, null, null); 
      cmDocument = CMPlugin.getInstance().createCMDocument(uri, null);

      if (uri.endsWith(".dtd"))
      {
        if (errorList.size() > 0)
        {                 
          title = XMLWizard.getString("_UI_INVALID_GRAMMAR_ERROR");
          message = XMLWizard.getString("_UI_LABEL_ERROR_DTD_INVALID_INFO");
        }
      }
      else // ".xsd"
      {
        // To be consistent with the schema editor validation
        XMLSchemaValidationChecker validator = new XMLSchemaValidationChecker();
        if (!validator.isValid(uri))
        {
          title = XMLWizard.getString("_UI_INVALID_GRAMMAR_ERROR");
          message = XMLWizard.getString("_UI_LABEL_ERROR_SCHEMA_INVALID_INFO");
        }
        else if (cmDocument != null)
        {             
          int globalElementCount = cmDocument.getElements().getLength();
          if (globalElementCount == 0)
          {      
            title = XMLWizard.getString("_UI_WARNING_TITLE_NO_ROOT_ELEMENTS");
            message=XMLWizard.getString("_UI_WARNING_MSG_NO_ROOT_ELEMENTS");
          }
        }
      }
    }
    else
    {
      title = XMLWizard.getString("_UI_WARNING_TITLE_NO_ROOT_ELEMENTS");
      message = 
        XMLWizard.getString("_UI_WARNING_URI_NOT_FOUND_COLON")
        + " "
        + uri;
    }
    errorInfo[0] = title;                                     
    errorInfo[1] = message;

    return cmDocument;
  }


  public void createEmptyXMLDocument(IFile newFile) throws Exception
  {                                                                                       
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    Preferences preference = XMLCorePlugin.getDefault().getPluginPreferences();
	String charSet = preference.getString(CommonModelPreferenceNames.OUTPUT_CODESET);	
	
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, charSet));
    writer.println("<?xml version=\"1.0\" encoding=\"" + charSet + "\"?>");
    writer.flush();
    outputStream.close(); 

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); 
    newFile.setContents(inputStream, true, true, null);  
    inputStream.close(); 
  } 
  
  public void createXMLDocument(String xmlFileName) throws Exception
  {
    ByteArrayOutputStream outputStream = createXMLDocument(xmlFileName, false);

    File file = new File(xmlFileName);
    FileOutputStream fos = new FileOutputStream(file);
    outputStream.writeTo(fos);
    fos.close();
  }


  public void createXMLDocument(IFile newFile, String xmlFileName) throws Exception
  {
    ByteArrayOutputStream outputStream = createXMLDocument(xmlFileName, false);

    ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); 
    newFile.setContents(inputStream, true, true, null);  
    inputStream.close();
  }


  public ByteArrayOutputStream createXMLDocument(String xmlFileName, boolean junk) throws Exception
  {
    CMDocument cmDocument = getCMDocument();
    
    Assert.isNotNull(cmDocument);
    Assert.isNotNull(getRootElementName());
    
    // create the xml model
    CMNamedNodeMap nameNodeMap = cmDocument.getElements();
    CMElementDeclaration cmElementDeclaration = (CMElementDeclaration)nameNodeMap.getNamedItem(getRootElementName());
    
    Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    DOMContentBuilderImpl contentBuilder = new DOMContentBuilderImpl(xmlDocument);
    
    contentBuilder.setBuildPolicy(buildPolicy);                                                  
    contentBuilder.setExternalCMDocumentSupport(new MyExternalCMDocumentSupport(namespaceInfoList, xmlFileName));
    contentBuilder.uglyTempHack = true; // todo... this line should be removed when 169191 is fixed  
    contentBuilder.createDefaultRootContent(cmDocument, cmElementDeclaration, namespaceInfoList);     
    
    String[] encodingInfo = (String[])cmDocument.getProperty("encodingInfo");
    if (encodingInfo == null)
    {
      encodingInfo = new String[2];
    } 
    
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    OutputStreamWriter outputStreamWriter = encodingInfo[0] != null ? 
                                              new OutputStreamWriter(outputStream, encodingInfo[1]) :
                                              new OutputStreamWriter(outputStream);

    DOMWriter domWriter = new DOMWriter(outputStreamWriter);
    domWriter.print(xmlDocument, encodingInfo[1], cmDocument.getNodeName(), getNonWhitespaceString(getPublicId()), getNonWhitespaceString(getSystemId())); // todo... replace with domWriter.print(xmlDocument); when 169191 is fixed
    outputStream.flush();
    outputStream.close();  
    
    return outputStream;
  }


  public void createNamespaceInfoList()
  {                     
    List result = new Vector();
    XMLCatalog xmlCatalog = XMLCatalogPlugin.getInstance().getDefaultXMLCatalog();
    if (cmDocument != null)
    {  
      result = (List)cmDocument.getProperty("http://org.eclipse.wst/cm/properties/namespaceInfo");
      if (result != null)
      {
        int size = result.size();
        for (int i = 0; i < size; i++)
        {
          NamespaceInfo info = (NamespaceInfo)result.get(i);        
          if (i == 0)
          {                                         
            String locationInfo = null;                            
            if (xmlCatalogEntry != null)
            {                              
              if (xmlCatalogEntry.getType() == XMLCatalogEntry.PUBLIC)
              {
                locationInfo = xmlCatalogEntry.getWebAddress();  
              }
              else
              {
                locationInfo = xmlCatalogEntry.getKey(); 
              }    
            }       
            if (locationInfo == null)
            {
              locationInfo = defaultSystemId; 
            } 
            info.locationHint = locationInfo;    
            info.setProperty("locationHint-readOnly", "true"); 
          }                                                                                
          info.setProperty("uri-readOnly", "true");
          info.setProperty("unremovable", "true");
        }
      }       
                                      
      NamespaceInfoContentBuilder builder = new NamespaceInfoContentBuilder();  
      builder.setBuildPolicy(ContentBuilder.BUILD_ONLY_REQUIRED_CONTENT);
      builder.visitCMNode(cmDocument);  
      result.addAll(builder.list);    
    }                 
    namespaceInfoList = result;
  }  


  public boolean isMissingNamespaceLocation()
  {          
    boolean result = false;
    for (Iterator i = namespaceInfoList.iterator(); i.hasNext(); )
    {
      NamespaceInfo info = (NamespaceInfo)i.next();
      if (info.locationHint == null)
      {
        result = true; 
        break;
      }
    }
    return result;
  }


  public String[] getNamespaceInfoErrors() 
  {
    String[] errorList = null;

    if (namespaceInfoList != null && isMissingNamespaceLocation())
    {
      String title = XMLWizard.getString("_UI_LABEL_NO_LOCATION_HINT");
      String message = XMLWizard.getString("_UI_WARNING_MSG_NO_LOCATION_HINT_1") + " " +
                       XMLWizard.getString("_UI_WARNING_MSG_NO_LOCATION_HINT_2") + "\n\n" + 
                       XMLWizard.getString("_UI_WARNING_MSG_NO_LOCATION_HINT_3");

      errorList = new String[2];
      errorList[0] = title;
      errorList[1] = message;
    }

      return errorList;
  }
  

  public void setXMLCatalogEntry(XMLCatalogEntry catalogEntry) 
  {
    xmlCatalogEntry = catalogEntry;
  }

  public XMLCatalogEntry getXMLCatalogEntry() 
  {
    return xmlCatalogEntry;
  }


  public void setBuildPolicy(int policy) 
  {
    buildPolicy = policy;
  }


  public void setDefaultSystemId(String sysId) 
  {
    defaultSystemId = sysId;
  }
  
  public String getDefaultSystemId() 
  {
    return defaultSystemId;
  }

  public void setSystemId(String sysId) 
  {
    systemId = sysId;
  }
  
  public String getSystemId() 
  {
    return systemId;
  }

  public void setPublicId(String pubId) 
  {
    publicId = pubId;
  }

  public String getPublicId() 
  {
    return publicId;
  }

  public void setGrammarURI(String gramURI) 
  {
    grammarURI = gramURI;
  }

  public String getGrammarURI() 
  {
    return grammarURI;
  }

  public void setCMDocument(CMDocument cmDoc) 
  {
    cmDocument = cmDoc;
  }

  public CMDocument getCMDocument() 
  {
    return cmDocument;
  }

  public void setRootElementName(String rootName) 
  {
    rootElementName = rootName;
  }

  public String getRootElementName() 
  {
    return rootElementName;
  }


  protected class MyExternalCMDocumentSupport implements DOMContentBuilderImpl.ExternalCMDocumentSupport 
  {           
    protected List namespaceInfoList;
    protected IdResolver idResolver;   

    protected MyExternalCMDocumentSupport(List namespaceInfoList, String resourceLocation)
    {
      this.namespaceInfoList = namespaceInfoList;
      idResolver = new IdResolverImpl(resourceLocation);
    }                                            

    public CMDocument getCMDocument(Element element, String namespaceURI)
    {         
      CMDocument result = null;
      if (namespaceURI != null && namespaceURI.trim().length() > 0)
      {
        String locationHint = null; 
        for (Iterator i = namespaceInfoList.iterator(); i.hasNext(); )
        {
          NamespaceInfo info = (NamespaceInfo)i.next();
          if (namespaceURI.equals(info.uri))
          {
            locationHint = info.locationHint;
            break;
          }
        }   
        if (locationHint != null)
        {                     
          grammarURI = idResolver.resolveId(locationHint, locationHint);
          result = CMPlugin.getInstance().createCMDocument(getGrammarURI(), null);
        }
      }   
      else
      {
        result = cmDocument;
      }                                                                      
      return result;
    }       
  }

	public static String getNonWhitespaceString(String string)
	{
		String result = null;
		if (string != null)
		{
			if (string.trim().length() > 0)
			{
				result = string;
			}
		}
		return result;
	}

  
}

Back to the top