diff options
author | csalter | 2004-11-11 22:33:56 +0000 |
---|---|---|
committer | csalter | 2004-11-11 22:33:56 +0000 |
commit | 703f883d44c41365be34a7630d32d0654be37802 (patch) | |
tree | a68d1f82b56a74d10a035e1788597e368dc8acea /bundles/org.eclipse.wst.xml.ui/src-wizards/org | |
parent | 2c0e703d3af3c9d248187c7d501f9dce42e9304d (diff) | |
download | webtools.sourceediting-703f883d44c41365be34a7630d32d0654be37802.tar.gz webtools.sourceediting-703f883d44c41365be34a7630d32d0654be37802.tar.xz webtools.sourceediting-703f883d44c41365be34a7630d32d0654be37802.zip |
add New XML and Example wizards
Diffstat (limited to 'bundles/org.eclipse.wst.xml.ui/src-wizards/org')
9 files changed, 2113 insertions, 0 deletions
diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NamespaceInfoContentBuilder.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NamespaceInfoContentBuilder.java new file mode 100644 index 0000000000..a7d9e1d7fb --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NamespaceInfoContentBuilder.java @@ -0,0 +1,57 @@ +/******************************************************************************* + * 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.util.Hashtable; +import java.util.List; +import java.util.Vector; + +import org.eclipse.wst.common.contentmodel.CMAnyElement; +import org.eclipse.wst.common.contentmodel.CMElementDeclaration; +import org.eclipse.wst.common.contentmodel.util.ContentBuilder; +import org.eclipse.wst.common.contentmodel.util.NamespaceInfo; + +public class NamespaceInfoContentBuilder extends ContentBuilder + { + protected int count = 1; + public List list = new Vector(); + protected Hashtable table = new Hashtable(); + + public NamespaceInfoContentBuilder() + { + super(); + } + + public void visitCMElementDeclaration(CMElementDeclaration ed) + { + if (ed.getProperty("http://com.ibm.etools/cm/properties/definitionInfo") != null) + { + super.visitCMElementDeclaration(ed); + } + } + + protected void createAnyElementNode(CMAnyElement anyElement) + { + String uri = anyElement.getNamespaceURI(); + if (uri != null && !uri.startsWith("##")) + { + if (table.get(uri) == null) + { + NamespaceInfo info = new NamespaceInfo(); + info.uri = uri; + info.prefix = "p" + count++; + table.put(uri, info); + list.add(info); + } + } + } + } + diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewModelWizard.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewModelWizard.java new file mode 100644 index 0000000000..622b623f8d --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewModelWizard.java @@ -0,0 +1,326 @@ +/******************************************************************************* + * 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 org.eclipse.core.resources.IContainer; +import org.eclipse.core.resources.IFile; +import org.eclipse.core.resources.IResource; +import org.eclipse.core.resources.ResourcesPlugin; +import org.eclipse.core.runtime.CoreException; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.Wizard; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IEditorRegistry; +import org.eclipse.ui.INewWizard; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.dialogs.WizardNewFileCreationPage; +import org.eclipse.wst.xml.ui.XMLEditorPlugin; + +public class NewModelWizard extends Wizard implements INewWizard +{ + + protected IStructuredSelection selection; + protected IWorkbench workbench; + protected String currentDirectory; + + public NewModelWizard() + { + } + + public void init(IWorkbench workbench, IStructuredSelection selection) + { + this.workbench = workbench; + this.selection = selection; + } + + public boolean performFinish() + { + boolean result = true; + WizardPage currentPage = (WizardPage)getContainer().getCurrentPage(); + if (currentPage != null) + { + result = currentPage.isPageComplete(); + } + return result; + } + + /** + * showFileDialog + */ + public FileDialog showFileDialog(Shell shell, String defaultDirectory, String defaultFile, String [] filterExtensions) + { + FileDialog fileDialog = new FileDialog(shell, SWT.OPEN); + + // Get the last visit directory if we haven't defined a particular one here. + if (defaultDirectory == null || defaultDirectory.length() == 0) + { + //defaultDirectory = Locate.instance(this).getLastSelectedDirectory(getResourcePath()); + } + + if (defaultDirectory != null && defaultDirectory.length() != 0) + { + fileDialog.setFilterPath(defaultDirectory); + } + + fileDialog.setFileName(defaultFile); + fileDialog.setFilterExtensions(filterExtensions); + + fileDialog.open(); + + return fileDialog; + } + + + public void setCurrentDirectory(String currentDirectory) + { + this.currentDirectory = currentDirectory; + } + + + public void createWorkbenchResource(IContainer container, String fileName) + { + IPath path = container.getFullPath(); + path = path.append(fileName); + IFile file = container.getWorkspace().getRoot().getFile(path); + if (!file.exists()) + { + try + { + file.create(null, true, null); + } + catch (CoreException e) + { + //XMLBuilderPlugin.getPlugin().getMsgLogger().write("Encountered exception creating file: " + e.getMessage()); + } + } + } + + /** + * StartPage + */ + public class StartPage extends WizardPage implements Listener + { + protected int selectedButton; + protected String[] radioButtonLabel; + protected Button[] radioButton; + + public StartPage(String pageName, String[] radioButtonLabel) + { + super(pageName); + this.radioButtonLabel = radioButtonLabel; + radioButton = new Button[radioButtonLabel.length]; + } + + public Button getRadioButtonAtIndex(int i) + { + Button result = null; + if (i >= 0 && i < radioButton.length) + { + result = radioButton[i]; + } + return result; + } + + public int getSelectedRadioButtonIndex() + { + int result = -1; + for (int i = 0; i < radioButton.length; i++) + { + if (radioButton[i].getSelection()) + { + result = i; + } + } + return result; + } + + public void createControl(Composite parent) + { + Composite base = new Composite(parent, SWT.NONE); + //TODO... setHelp + //WorkbenchHelp.setHelp(base, XMLBuilderContextIds.XMLC_CREATE_PAGE); + base.setLayout(new GridLayout()); + + //radio buttons' container + Composite radioButtonsGroup = new Composite(base, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.makeColumnsEqualWidth = true; + layout.marginWidth = 0; + + radioButtonsGroup.setLayout(layout); + GridData gd = new GridData(GridData.FILL_BOTH); + gd.heightHint = 300; + gd.widthHint = 400; + radioButtonsGroup.setLayoutData(gd); + //TODO... set help + //WorkbenchHelp.setHelp(radioButtonsGroup, XMLBuilderContextIds.XMLC_RADIO_GROUP); + + for (int i = 0; i < radioButtonLabel.length; i++) + { + radioButton[i] = new Button(radioButtonsGroup, SWT.RADIO); + radioButton[i].setText(radioButtonLabel[i]); + radioButton[i].setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + //TODO... set help + //WorkbenchHelp.setHelp(radioButton[i], new ControlContextComputer(radioButton[i], XMLBuilderContextIds.XMLC_RADIO_BUTTON)); + //radioButton[i].addListener(SWT.Modify, this); + } + setControl(base); + setPageComplete(isPageComplete()); + } + + public void handleEvent(Event event) + { + if (event.type == SWT.Modify) + { + setPageComplete(isPageComplete()); + } + } + } + + + /** + * NewFilePage + */ + public class NewFilePage extends WizardNewFileCreationPage + { + public String defaultName = "NewFile"; + public String defaultFileExtension = ".txt"; + public String[] filterExtensions = { "*.txt"}; + + public NewFilePage(IStructuredSelection selection) + { + super("", selection); + } + + protected String computeDefaultFileName() + { + int count = 0; + String fileName = defaultName + defaultFileExtension; + IPath containerFullPath = getContainerFullPath(); + if (containerFullPath != null) + { + while (true) + { + IPath path = containerFullPath.append(fileName); + if (ResourcesPlugin.getWorkspace().getRoot().exists(path)) + { + count++; + fileName = defaultName + count + defaultFileExtension; + } + else + { + break; + } + } + } + return fileName; + } + + // returns true if file of specified name exists in any case for selected container + protected String existsFileAnyCase(String fileName) + { + if ( (getContainerFullPath() != null) && (getContainerFullPath().isEmpty() == false) + && (fileName.compareTo("") != 0)) + { + //look through all resources at the specified container - compare in upper case + IResource parent = ResourcesPlugin.getWorkspace().getRoot().findMember(getContainerFullPath()); + if (parent instanceof IContainer) + { + IContainer container = (IContainer) parent; + try + { + IResource[] members = container.members(); + String enteredFileUpper = fileName.toUpperCase(); + for (int i=0; i<members.length; i++) + { + String resourceUpperName = members[i].getName().toUpperCase(); + if (resourceUpperName.equals(enteredFileUpper)) + { + return members[i].getName(); + } + } + } + catch (CoreException e) + { + } + } + } + return null; + } + + + protected boolean validatePage() + { + String fullFileName = getFileName(); + String fileExtension = (new Path(fullFileName)).getFileExtension(); + if (fileExtension != null) + { + IEditorRegistry editorRegistry = XMLEditorPlugin.getInstance().getWorkbench().getEditorRegistry(); + IEditorDescriptor defaultEditorDescriptor = editorRegistry.getDefaultEditor(); + IEditorDescriptor[] descriptors = editorRegistry.getEditors(getFileName()); + if (descriptors.length == 0) + { + setErrorMessage(XMLWizard.getString("_ERROR_BAD_FILENAME_EXTENSION")); + return false; + } + } + else + { + // no fileExtension, let's check for this file with an .xml extension + fullFileName += ".xml"; + if ( (getContainerFullPath() != null) && (getContainerFullPath().isEmpty() == false) + && (getFileName().compareTo("") != 0)) + { + Path fullPath = new Path(getContainerFullPath().toString() + '/' + fullFileName); + IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(fullPath); + if (resource != null) + { + setErrorMessage(XMLWizard.getString("_ERROR_FILE_ALREADY_EXISTS")); + return false; + } + } + } + + // check for file should be case insensitive + String sameName = existsFileAnyCase(fullFileName); + if (sameName != null) + { + String qualifiedFileName = getContainerFullPath().toString() + '/' + fullFileName; + setErrorMessage(XMLWizard.getString("_ERROR_FILE_ALREADY_EXISTS") + " " + sameName); + return false; + } + + return super.validatePage(); + } + + public void createControl(Composite parent) + { + // inherit default container and name specification widgets + super.createControl(parent); + this.setFileName(computeDefaultFileName()); + setPageComplete(validatePage()); + } + } +} + diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewXMLGenerator.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewXMLGenerator.java new file mode 100644 index 0000000000..4c70b83729 --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewXMLGenerator.java @@ -0,0 +1,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.XMLModelPlugin; +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 = XMLModelPlugin.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://com.ibm.etools/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; + } + + +} diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewXMLWizard.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewXMLWizard.java new file mode 100644 index 0000000000..b27aadee0f --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/NewXMLWizard.java @@ -0,0 +1,937 @@ +/******************************************************************************* + * 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.text.Collator; +import java.util.Arrays; +import java.util.List; +import java.util.Vector; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.Path; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.jface.util.Assert; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.jface.wizard.IWizardPage; +import org.eclipse.jface.wizard.WizardDialog; +import org.eclipse.jface.wizard.WizardPage; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.ModifyEvent; +import org.eclipse.swt.events.ModifyListener; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.SelectionListener; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.IEditorDescriptor; +import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PartInitException; +import org.eclipse.ui.part.FileEditorInput; +import org.eclipse.ui.part.PageBook; +import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; +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.util.DOMContentBuilder; +import org.eclipse.wst.common.contentmodel.util.NamespaceInfo; +import org.eclipse.wst.xml.ui.XMLEditorPlugin; +import org.eclipse.wst.xml.ui.dialogs.NamespaceInfoErrorHelper; +import org.eclipse.wst.xml.ui.dialogs.SelectFileOrXMLCatalogIdPanel; +import org.eclipse.wst.xml.ui.dialogs.UpdateListener; +import org.eclipse.wst.xml.ui.nsedit.CommonEditNamespacesDialog; +import org.eclipse.wst.xml.uriresolver.XMLCatalogEntry; +import org.eclipse.wst.xml.uriresolver.util.URIHelper; + +public class NewXMLWizard extends NewModelWizard +{ + protected static final int CREATE_FROM_DTD = 0; + protected static final int CREATE_FROM_XSD = 1; + protected static final int CREATE_FROM_SCRATCH = 2; + + protected static final String[] createFromRadioButtonLabel + = {XMLWizard.getString("_UI_RADIO_XML_FROM_DTD"), + XMLWizard.getString("_UI_RADIO_XML_FROM_SCHEMA"), + XMLWizard.getString("_UI_RADIO_XML_FROM_SCRATCH")}; + + protected static final String[] filePageFilterExtensions = {".xml"}; + protected static final String[] browseXSDFilterExtensions = {".xsd"}; + protected static final String[] browseDTDFilterExtensions = {".dtd"}; + + protected NewFilePage newFilePage; + protected StartPage startPage; + protected SelectGrammarFilePage selectGrammarFilePage; + protected SelectRootElementPage selectRootElementPage; + + protected String cmDocumentErrorMessage; + + protected NewXMLGenerator generator; + + + public NewXMLWizard() + { + setWindowTitle(XMLWizard.getString("_UI_WIZARD_CREATE_XML_HEADING")); + setDefaultPageImageDescriptor(ImageDescriptor.createFromFile(XMLWizard.class,"icons/generatexml_wiz.gif")); + generator = new NewXMLGenerator(); + } + + + public NewXMLWizard(IFile file, CMDocument cmDocument) + { + this(); + + generator.setGrammarURI(URIHelper.getPlatformURI(file)); + generator.setCMDocument(cmDocument); + } + + + public static void showDialog(Shell shell, IFile file, IStructuredSelection structuredSelection) + { + List errorList = new Vector(); + String[] errorInfo = new String[2]; + CMDocument cmDocument = NewXMLGenerator.createCMDocument(file.getLocation().toOSString(), errorInfo); + if (errorInfo[0] == null) + { + NewXMLWizard wizard = new NewXMLWizard(file, cmDocument); + wizard.init(XMLEditorPlugin.getInstance().getWorkbench(), structuredSelection); + wizard.setNeedsProgressMonitor(true); + WizardDialog dialog = new WizardDialog(shell, wizard); + dialog.create(); + dialog.getShell().setText(XMLWizard.getString("_UI_DIALOG_NEW_TITLE")); + dialog.setBlockOnOpen(true); + dialog.open(); + } + else + { + MessageDialog.openInformation(shell, errorInfo[0], errorInfo[1]); + } + } + + + public void addPages() + { + String grammarURI = generator.getGrammarURI(); + + if (grammarURI == null) + { + // start page + startPage = new StartPage("StartPage", createFromRadioButtonLabel) + { + public void createControl(Composite parent) + { + super.createControl(parent); + } + + public void setVisible(boolean visible) + { + super.setVisible(visible); + getRadioButtonAtIndex(getCreateMode()).setSelection(true); + getRadioButtonAtIndex(getCreateMode()).setFocus(); + + // Set the help context for each button + //WorkbenchHelp.setHelp(startPage.getRadioButtonAtIndex(0), XMLBuilderContextIds.XMLC_FROM_DTD_RADIO); + //WorkbenchHelp.setHelp(startPage.getRadioButtonAtIndex(1), XMLBuilderContextIds.XMLC_XML_SCHEMA_RADIO); + //WorkbenchHelp.setHelp(startPage.getRadioButtonAtIndex(2), XMLBuilderContextIds.XMLC_SCRATCH_RADIO); + } + }; + + + startPage.setTitle(XMLWizard.getString("_UI_WIZARD_CREATE_XML_HEADING")); + startPage.setDescription(XMLWizard.getString("_UI_WIZARD_CREATE_XML_EXPL")); + addPage(startPage); + } + + // new file page + newFilePage = new NewFilePage(selection); + newFilePage.setTitle(XMLWizard.getString("_UI_WIZARD_CREATE_XML_FILE_HEADING")); + newFilePage.setDescription(XMLWizard.getString("_UI_WIZARD_CREATE_XML_FILE_EXPL")); + newFilePage.defaultName = (grammarURI != null) ? URIHelper.removeFileExtension(URIHelper.getLastSegment(grammarURI)) : "NewFile"; + newFilePage.defaultFileExtension = ".xml"; + newFilePage.filterExtensions = filePageFilterExtensions; + addPage(newFilePage); + + // selectGrammarFilePage + selectGrammarFilePage = new SelectGrammarFilePage(); + addPage(selectGrammarFilePage); + + // select root element page + selectRootElementPage = new SelectRootElementPage(); + selectRootElementPage.setTitle(XMLWizard.getString("_UI_WIZARD_SELECT_ROOT_HEADING")); + selectRootElementPage.setDescription(XMLWizard.getString("_UI_WIZARD_SELECT_ROOT_EXPL")); + addPage(selectRootElementPage); + } + + + public IWizardPage getStartingPage() + { + WizardPage result = null; + if (startPage != null) + { + result = startPage; + } + else + { + result = newFilePage; + } + return result; + } + + + public int getCreateMode() + { + String grammarURI = generator.getGrammarURI(); + + int result = CREATE_FROM_SCRATCH; + if (grammarURI != null) + { + if (grammarURI.endsWith(".dtd")) + { + result = CREATE_FROM_DTD; + } + else if (grammarURI.endsWith(".xsd")) + { + result = CREATE_FROM_XSD; + } + } + else if (startPage != null) + { + int selectedIndex = startPage.getSelectedRadioButtonIndex(); + if (selectedIndex != -1) + { + result = selectedIndex; + } + } + return result; + } + + + public IWizardPage getNextPage(IWizardPage currentPage) + { + WizardPage nextPage = null; + if (currentPage == startPage) + { + nextPage = newFilePage; + } + else if (currentPage == newFilePage) + { + if (getCreateMode() == CREATE_FROM_SCRATCH) + { + nextPage = null; + } + else if (generator.getGrammarURI() == null) + { + nextPage = selectGrammarFilePage; + } + else + { + nextPage = selectRootElementPage; + } + } + else if (currentPage == selectGrammarFilePage) + { + nextPage = selectRootElementPage; + } + return nextPage; + } + + + public boolean canFinish() + { + boolean result = false; + + IWizardPage currentPage = getContainer().getCurrentPage(); + + if ((startPage != null && startPage.getSelectedRadioButtonIndex() == CREATE_FROM_SCRATCH && currentPage == newFilePage) || + (currentPage == selectRootElementPage)) + { + result = currentPage.isPageComplete(); + } + return result; + } + + + public boolean performFinish() + { + boolean result = true; + super.performFinish(); + try + { + + String[] namespaceErrors = generator.getNamespaceInfoErrors(); + if (namespaceErrors != null) + { + String title = namespaceErrors[0]; + String message = namespaceErrors[1]; + result = MessageDialog.openQuestion(getShell(), title, message); + } + + if (result) + { + String fileName = newFilePage.getFileName(); + if ((new Path(fileName)).getFileExtension() == null) + { + newFilePage.setFileName(fileName.concat(".xml")); + } + + IFile newFile = newFilePage.createNewFile(); + String xmlFileName = newFile.getLocation().toOSString(); + + if (getContainer().getCurrentPage() == selectRootElementPage) + { + + generator.createXMLDocument(newFile, xmlFileName); + } + else + { + generator.createEmptyXMLDocument(newFile); + } + + newFile.refreshLocal(1, null); + + IWorkbenchWindow workbenchWindow = XMLEditorPlugin.getInstance().getWorkbench().getActiveWorkbenchWindow(); + BasicNewResourceWizard.selectAndReveal(newFile, workbenchWindow); + openEditor(newFile); + } + } + catch (Exception e) + { + //e.printStackTrace(); + } + return result; + } + + public void openEditor(IFile file) + { + // Open editor on new file. + String editorId = null; + IEditorDescriptor editor = XMLEditorPlugin.getInstance().getWorkbench().getEditorRegistry().getDefaultEditor(file.getLocation().toOSString()); + if(editor != null){ + editorId = editor.getId(); + } + IWorkbenchWindow dw = XMLEditorPlugin.getInstance().getWorkbench().getActiveWorkbenchWindow(); + try { + if (dw != null) { + IWorkbenchPage page = dw.getActivePage(); + if (page != null) + page.openEditor(new FileEditorInput(file), editorId, true); + } + } catch (PartInitException e) { + } + } + + + protected String getDefaultSystemId() + { + String relativePath = "platform:/resource/" + newFilePage.getContainerFullPath().toString() + "/dummy"; + return URIHelper.getRelativeURI(generator.getGrammarURI(), relativePath); + } + + + /** + * SelectGrammarFilePage + */ + class SelectGrammarFilePage extends WizardPage + { + protected SelectFileOrXMLCatalogIdPanel panel; + + SelectGrammarFilePage() + { + super("SelectGrammarFilePage"); + } + + public void createControl(Composite parent) + { + Composite composite = new Composite(parent, SWT.NONE); + //WorkbenchHelp.setHelp(composite, XMLBuilderContextIds.XMLC_GRAMMAR_PAGE); + composite.setLayout(new GridLayout()); + composite.setLayoutData(new GridData(GridData.FILL_BOTH)); + setControl(composite); + + panel = new SelectFileOrXMLCatalogIdPanel(composite); + panel.setLayoutData(new GridData(GridData.FILL_BOTH)); + + SelectFileOrXMLCatalogIdPanel.Listener listener = new SelectFileOrXMLCatalogIdPanel.Listener() + { + public void completionStateChanged() + { + updateErrorMessage(); + } + }; + panel.setListener(listener); + } + + public void setVisible(boolean visible) + { + super.setVisible(visible); + if (visible) + { + if (getCreateMode() == CREATE_FROM_DTD) + { + setTitle(XMLWizard.getString("_UI_WIZARD_SELECT_DTD_FILE_TITLE")); + setDescription(XMLWizard.getString("_UI_WIZARD_SELECT_DTD_FILE_DESC")); + panel.setFilterExtensions(browseDTDFilterExtensions); + } + else + { + setTitle(XMLWizard.getString("_UI_WIZARD_SELECT_XSD_FILE_TITLE")); + setDescription(XMLWizard.getString("_UI_WIZARD_SELECT_XSD_FILE_DESC")); + panel.setFilterExtensions(browseXSDFilterExtensions); + } + generator.setGrammarURI(null); + generator.setCMDocument(null); + cmDocumentErrorMessage = null; + } + panel.setVisibleHelper(visible); + } + + public String getURI() + { + String uri = panel.getXMLCatalogURI(); + if (uri == null) + { + IFile file = panel.getFile(); + if (file != null) + { + uri = URIHelper.getPlatformURI(file); + } + } + return uri; + } + + public boolean isPageComplete() + { + return getURI() != null && getErrorMessage() == null; + } + + public String getXMLCatalogId() + { + return panel.getXMLCatalogId(); + } + + public XMLCatalogEntry getXMLCatalogEntry() + { + return panel.getXMLCatalogEntry(); + } + + public String computeErrorMessage() + { + String errorMessage = null; + String uri = getURI(); + if (uri != null) + { + if (!URIHelper.isReadableURI(uri,false)) + { + errorMessage = XMLWizard.getString("_UI_LABEL_ERROR_CATALOG_ENTRY_INVALID"); + } + } + return errorMessage; + } + + + public void updateErrorMessage() + { + String errorMessage = computeErrorMessage(); + setErrorMessage(errorMessage); + setPageComplete(isPageComplete()); + } + } + + + /** + * SelectRootElementPage + */ + class SelectRootElementPage extends WizardPage implements SelectionListener + { + protected Combo combo; + protected Button[] radioButton; + protected PageBook pageBook; + protected XSDOptionsPanel xsdOptionsPanel; + protected DTDOptionsPanel dtdOptionsPanel; + + + SelectRootElementPage() + { + super("SelectRootElementPage"); + } + + public void createControl(Composite parent) + { + // container group + Composite containerGroup = new Composite(parent,SWT.NONE); + //WorkbenchHelp.setHelp(containerGroup, XMLBuilderContextIds.XMLC_ROOT_PAGE); + containerGroup.setLayout(new GridLayout()); + containerGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + setControl(containerGroup); + + // select root element + Label containerLabel = new Label(containerGroup, SWT.NONE); + containerLabel.setText(XMLWizard.getString("_UI_LABEL_ROOT_ELEMENT")); + combo = new Combo(containerGroup, SWT.DROP_DOWN | SWT.READ_ONLY); + combo.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + combo.addSelectionListener(this); + //WorkbenchHelp.setHelp(combo, XMLBuilderContextIds.XMLC_ROOT_ROOT); + + // Options + { + Group group = new Group(containerGroup, SWT.NONE); + group.setText(XMLWizard.getString("_UI_WIZARD_CONTENT_OPTIONS")); + //WorkbenchHelp.setHelp(group, XMLBuilderContextIds.XMLC_CURRENT_GROUP); + + GridLayout layout = new GridLayout(); + layout.numColumns = 1; + layout.makeColumnsEqualWidth = true; + layout.marginWidth = 0; + group.setLayout(layout); + group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + radioButton = new Button[4]; + + radioButton[0] = new Button(group, SWT.CHECK); + radioButton[0].setText(XMLWizard.getString("_UI_WIZARD_CREATE_OPTIONAL_ATTRIBUTES")); + radioButton[0].setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + radioButton[0].setSelection(false); + //WorkbenchHelp.setHelp(radioButton[0], XMLBuilderContextIds.XMLC_CREATE_OPTIONAL_ATTRIBUTES); + + radioButton[1] = new Button(group, SWT.CHECK); + radioButton[1].setText(XMLWizard.getString("_UI_WIZARD_CREATE_OPTIONAL_ELEMENTS")); + radioButton[1].setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + radioButton[1].setSelection(false); + //WorkbenchHelp.setHelp(radioButton[1], XMLBuilderContextIds.XMLC_CREATE_OPTIONAL_ELEMENTS); + + radioButton[2] = new Button(group, SWT.CHECK); + radioButton[2].setText(XMLWizard.getString("_UI_WIZARD_CREATE_FIRST_CHOICE")); + radioButton[2].setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + radioButton[2].setSelection(true); + //WorkbenchHelp.setHelp(radioButton[2], XMLBuilderContextIds.XMLC_CREATE_FIRST_CHOICE); + + radioButton[3] = new Button(group, SWT.CHECK); + radioButton[3].setText(XMLWizard.getString("_UI_WIZARD_FILL_ELEMENTS_AND_ATTRIBUTES")); + radioButton[3].setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + radioButton[3].setSelection(true); + //WorkbenchHelp.setHelp(radioButton[3], XMLBuilderContextIds.XMLC_FILL_ELEMENTS_AND_ATTRIBUTES); +/* + radioButton = new Button[2]; + + radioButton[0] = new Button(group, SWT.RADIO); + radioButton[0].setText(XMLWizard.getString("_UI_WIZARD_CREATE_REQUIRED")); + radioButton[0].setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + radioButton[0].setSelection(true); + WorkbenchHelp.setHelp(radioButton[0], XMLBuilderContextIds.XMLC_CREATE_REQUIRED_ONLY); + + radioButton[1] = new Button(group, SWT.RADIO); + radioButton[1].setText(XMLWizard.getString("_UI_WIZARD_CREATE_OPTIONAL")); + radioButton[1].setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + WorkbenchHelp.setHelp(radioButton[1], XMLBuilderContextIds.XMLC_CREATE_REQUIRED_AND_OPTION); +*/ + } + + // add the grammar specific generation options + // + { + pageBook = new PageBook(containerGroup, SWT.NONE); + pageBook.setLayoutData(new GridData(GridData.FILL_BOTH)); + xsdOptionsPanel = new XSDOptionsPanel(this, pageBook); + dtdOptionsPanel = new DTDOptionsPanel(this, pageBook); + pageBook.showPage(xsdOptionsPanel); + } + } + + public void widgetSelected(SelectionEvent event) + { + int index = combo.getSelectionIndex(); + String rootElementName = (index != -1) ? combo.getItem(index) : null; + generator.setRootElementName(rootElementName); + } + + public void widgetDefaultSelected(SelectionEvent event) + { + } + + public void setVisible(boolean visible) + { + super.setVisible(visible); + + if (visible) + { + try + { + if (generator.getGrammarURI() == null) + { + generator.setGrammarURI(selectGrammarFilePage.getURI()); + generator.setXMLCatalogEntry(selectGrammarFilePage.getXMLCatalogEntry()); + } + Assert.isNotNull(generator.getGrammarURI()); + + if (generator.getCMDocument() == null) + { + final String[] errorInfo = new String[2]; + final CMDocument[] cmdocs = new CMDocument[1]; + Runnable r = new Runnable() + { + public void run() + { + cmdocs[0] = NewXMLGenerator.createCMDocument(generator.getGrammarURI(), errorInfo); + } + }; + org.eclipse.swt.custom.BusyIndicator.showWhile(Display.getCurrent(),r); + + generator.setCMDocument(cmdocs[0]); + cmDocumentErrorMessage = errorInfo[1]; + } + + if (generator.getCMDocument() != null && cmDocumentErrorMessage == null) + { + CMNamedNodeMap nameNodeMap = generator.getCMDocument().getElements(); + Vector nameNodeVector = new Vector(); + + for (int i = 0; i < nameNodeMap.getLength(); i++) + { + CMElementDeclaration cmElementDeclaration = (CMElementDeclaration)nameNodeMap.item(i); + Object value = cmElementDeclaration.getProperty("Abstract"); + if (value != Boolean.TRUE) + { + nameNodeVector.add(cmElementDeclaration.getElementName()); + } + } + + Object[] nameNodeArray = nameNodeVector.toArray(); + if (nameNodeArray.length > 0 ) + { + Arrays.sort(nameNodeArray, Collator.getInstance()); + } + + String defaultRootName = (String) (generator.getCMDocument()).getProperty("http://com.ibm.etools/cm/properties/defaultRootName"); + int defaultRootIndex = -1; + combo.removeAll(); + + + for (int i = 0; i < nameNodeArray.length; i++) + { + String elementName = (String)nameNodeArray[i]; + + combo.add(elementName); + if (defaultRootName != null && defaultRootName.equals(elementName)) + { + defaultRootIndex = i; + } + } + + if (nameNodeArray.length > 0) + { + defaultRootIndex = defaultRootIndex != -1 ? defaultRootIndex : 0; + combo.select(defaultRootIndex); + generator.setRootElementName(combo.getItem(defaultRootIndex)); + } + } + + if (generator.getGrammarURI().endsWith("xsd")) + { + pageBook.showPage(xsdOptionsPanel); + generator.setDefaultSystemId(getDefaultSystemId()); + generator.createNamespaceInfoList(); + + // Provide default namespace prefix if none + for (int i=0; i<generator.namespaceInfoList.size(); i++) + { + NamespaceInfo nsinfo = + (NamespaceInfo)generator.namespaceInfoList.get(i); + if ((nsinfo.prefix == null || nsinfo.prefix.trim().length() == 0) + && (nsinfo.uri != null && nsinfo.uri.trim().length() != 0)) + { + nsinfo.prefix = getDefaultPrefix(generator.namespaceInfoList); + } + } + xsdOptionsPanel.setNamespaceInfoList(generator.namespaceInfoList); + } + else if (generator.getGrammarURI().endsWith("dtd")) + { + pageBook.showPage(dtdOptionsPanel); + dtdOptionsPanel.update(); + } + } + catch(Exception e) + { + //XMLBuilderPlugin.getPlugin().getMsgLogger().writeCurrentThread(); + } + + /* + String errorMessage = computeErrorMessage(); + if (errorMessage == null) + super.setVisible(visible); + */ + + updateErrorMessage(); + } + } + + private String getDefaultPrefix(List nsInfoList) + { + String defaultPrefix = "p"; + if (nsInfoList == null) + return defaultPrefix; + + Vector v = new Vector(); + for (int i=0; i<nsInfoList.size(); i++) + { + NamespaceInfo nsinfo = (NamespaceInfo)nsInfoList.get(i); + if (nsinfo.prefix != null) + v.addElement(nsinfo.prefix); + } + + if (v.contains(defaultPrefix)) + { + String s = defaultPrefix; + for (int j=0; v.contains(s); j++) + { + s = defaultPrefix + Integer.toString(j); + } + return s; + } + else + return defaultPrefix; + } + + public boolean isPageComplete() + { + boolean complete = (generator.getRootElementName() != null && generator.getRootElementName().length() > 0) && getErrorMessage() == null; + + if (complete) { + /* + int buildPolicy = radioButton[0].getSelection() ? + DOMContentBuilder.BUILD_ONLY_REQUIRED_CONTENT : + DOMContentBuilder.BUILD_ALL_CONTENT; + */ + int buildPolicy = 0; + if (radioButton[0].getSelection()) + buildPolicy = buildPolicy | DOMContentBuilder.BUILD_OPTIONAL_ATTRIBUTES; + if (radioButton[1].getSelection()) + buildPolicy = buildPolicy | DOMContentBuilder.BUILD_OPTIONAL_ELEMENTS; + if (radioButton[2].getSelection()) + buildPolicy = buildPolicy | DOMContentBuilder.BUILD_FIRST_CHOICE | DOMContentBuilder.BUILD_FIRST_SUBSTITUTION; + if (radioButton[3].getSelection()) + buildPolicy = buildPolicy | DOMContentBuilder.BUILD_TEXT_NODES; + + generator.setBuildPolicy(buildPolicy); + } + + return complete; + } + + public String computeErrorMessage() + { + String errorMessage = null; + + if (cmDocumentErrorMessage != null) + { + errorMessage = cmDocumentErrorMessage; + } + else if (generator.getRootElementName() == null || generator.getRootElementName().length() == 0) + { + errorMessage = XMLWizard.getString("_ERROR_ROOT_ELEMENT_MUST_BE_SPECIFIED"); + } + + return errorMessage; + } + + + public void updateErrorMessage() + { + String errorMessage = computeErrorMessage(); + if (errorMessage == null) + { + if (xsdOptionsPanel.isVisible()) + { + + errorMessage = xsdOptionsPanel.computeErrorMessage(); + } + else if (dtdOptionsPanel.isVisible()) + { + errorMessage = dtdOptionsPanel.computeErrorMessage(); + } + } + setErrorMessage(errorMessage); + setPageComplete(isPageComplete()); + } + } + ////////////////End SelectRootElementPage + + + + public static GridLayout createOptionsPanelLayout() + { + GridLayout gridLayout = new GridLayout(); + gridLayout.marginWidth = 0; + gridLayout.horizontalSpacing = 0; + return gridLayout; + } + + + + /** + * + */ + class XSDOptionsPanel extends Composite + { + protected String errorMessage = null; + protected SelectRootElementPage parentPage; + protected CommonEditNamespacesDialog editNamespaces; + + public XSDOptionsPanel(SelectRootElementPage parentPage, Composite parent) + { + super(parent, SWT.NONE); + this.parentPage = parentPage; + + setLayout(createOptionsPanelLayout()); + setLayoutData(new GridData(GridData.FILL_BOTH)); + + Composite co = new Composite(this, SWT.NONE); + co.setLayout(new GridLayout()); + + if (newFilePage != null && newFilePage.getContainerFullPath() != null) + { + // todo... this is a nasty mess. I need to revist this code. + // + String resourceURI = "platform:/resource" + newFilePage.getContainerFullPath().toString() + "/dummy"; + String resolvedPath = URIHelper.normalize(resourceURI, null, null); + if (resolvedPath.startsWith("file:/")) + { + resolvedPath = resolvedPath.substring(6); + } + // end nasty messs + String tableTitle = XMLWizard.getString("_UI_LABEL_NAMESPACE_INFORMATION"); + editNamespaces = new CommonEditNamespacesDialog(co, new Path(resolvedPath), tableTitle, true, true); + } + + UpdateListener updateListener = new UpdateListener() + { + public void updateOccured(Object object, Object arg) + { + updateErrorMessage((List)arg); + } + }; + } + + public void setNamespaceInfoList(List list) + { + editNamespaces.setNamespaceInfoList(list); + editNamespaces.updateErrorMessage(list); + } + + public void updateErrorMessage(List namespaceInfoList) + { + NamespaceInfoErrorHelper helper = new NamespaceInfoErrorHelper(); + errorMessage = helper.computeErrorMessage(namespaceInfoList, null); + parentPage.updateErrorMessage(); + } + + + public String computeErrorMessage() + { + return errorMessage; + } + } + + + /** + * + */ + public class DTDOptionsPanel extends Composite implements ModifyListener + { + protected Group group; + protected Text systemIdField; + protected Text publicIdField; + protected SelectRootElementPage parentPage; + + public DTDOptionsPanel(SelectRootElementPage parentPage, Composite parent) + { + super(parent, SWT.NONE); + this.parentPage = parentPage; + setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + setLayout(createOptionsPanelLayout()); + Group group = new Group(this, SWT.NONE); + group.setText(XMLWizard.getString("_UI_LABEL_DOCTYPE_INFORMATION")); + //WorkbenchHelp.setHelp(group, XMLBuilderContextIds.XMLC_DOCUMENTATION_GROUP); + + GridLayout layout = new GridLayout(); + layout.numColumns = 2; + group.setLayout(layout); + group.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + + Label publicIdLabel = new Label(group, SWT.NONE); + publicIdLabel.setText(XMLWizard.getString("_UI_LABEL_PUBLIC_ID")); + publicIdField = new Text(group, SWT.SINGLE | SWT.BORDER); + publicIdField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + publicIdField.addModifyListener(this); + //WorkbenchHelp.setHelp(publicIdField, XMLBuilderContextIds.XMLC_PUBLIC); + + Label systemIdLabel = new Label(group, SWT.NONE); + systemIdLabel.setText(XMLWizard.getString("_UI_LABEL_SYSTEM_ID")); + systemIdField = new Text(group, SWT.SINGLE | SWT.BORDER); + systemIdField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); + systemIdField.addModifyListener(this); + //WorkbenchHelp.setHelp(systemIdField, XMLBuilderContextIds.XMLC_SYSTEM); + } + + public void update() + { + String thePublicId = null; + String theSystemId = null; + XMLCatalogEntry xmlCatalogEntry = generator.getXMLCatalogEntry(); + + if (xmlCatalogEntry != null) + { + if (xmlCatalogEntry.getType() == XMLCatalogEntry.PUBLIC) + { + thePublicId = xmlCatalogEntry.getKey(); + theSystemId = xmlCatalogEntry.getWebAddress(); + if (theSystemId == null) + { + theSystemId = generator.getGrammarURI().startsWith("http:") ? generator.getGrammarURI() : URIHelper.getLastSegment(generator.getGrammarURI()); + } + } + else + { + theSystemId = xmlCatalogEntry.getKey(); + } + } + else + { + theSystemId = getDefaultSystemId(); + } + + publicIdField.setText(thePublicId != null ? thePublicId : ""); + systemIdField.setText(theSystemId != null ? theSystemId : ""); + } + + public void modifyText(ModifyEvent e) + { + generator.setSystemId(systemIdField.getText()); + generator.setPublicId(publicIdField.getText()); + parentPage.updateErrorMessage(); + } + + public String computeErrorMessage() + { + return null; + } + } + + +} diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLExampleProjectCreationWizard.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLExampleProjectCreationWizard.java new file mode 100644 index 0000000000..657bbe5c63 --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLExampleProjectCreationWizard.java @@ -0,0 +1,33 @@ +/******************************************************************************* + * 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 org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.wst.ui.wizards.ExampleProjectCreationWizard; + +/** + * Wizard used for creating the HelloWord sample. + * Most functionality is inherited from ExampleProjectCreationWizard. + */ +public class XMLExampleProjectCreationWizard extends ExampleProjectCreationWizard { + + public XMLExampleProjectCreationWizard() { + super(); + + } + + /* (non-Javadoc) + * @see com.ibm.samplegallery.wizards.ExampleProjectCreationWizard#getImageDescriptor(java.lang.String) + */ + protected ImageDescriptor getImageDescriptor(String banner) { + return XMLWizard.getInstance().getImageDescriptor(banner); + } +} diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLImportActionDelegate.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLImportActionDelegate.java new file mode 100644 index 0000000000..0ba438a361 --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLImportActionDelegate.java @@ -0,0 +1,203 @@ +/******************************************************************************* + * 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.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Iterator; + +import org.eclipse.core.resources.IFile; +import org.eclipse.core.runtime.IPath; +import org.eclipse.core.runtime.Platform; +import org.eclipse.core.runtime.Plugin; +import org.eclipse.jface.action.IAction; +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.viewers.ISelection; +import org.eclipse.jface.viewers.IStructuredSelection; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IActionDelegate; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.wst.xml.ui.XMLEditorPlugin; +import org.eclipse.wst.xml.uriresolver.util.URIHelper; + +public class XMLImportActionDelegate implements IActionDelegate +{ +// TODO verify these + private static final String validateXSDPluginID = "org.eclipse.wst.xsd.validation"; + private static final String xsdValidatorClassName = "org.eclipse.wst.xsd.validation.internal.ui.eclipse.XSDValidator"; + + private static final String validateDTDPluginID = "org.eclipse.wst.dtd.validation"; + private static final String dtdValidatorClassName = "org.eclipse.wst.dtd.validation.internal.ui.eclipse.DTDValidator"; + + private static final String validationReportClassName = "org.eclipse.wst.validation.xmltools.ValidationReport"; + + + /** + * Checks the current selection and runs the separate browser + * to show the content of the Readme file. This code shows how + * to launch separate browsers that are not VA/Base desktop parts. + * + * @param action the action that was performed + */ + public void run(IAction action) + { + IWorkbenchWindow workbenchWindow = XMLEditorPlugin.getInstance().getWorkbench().getActiveWorkbenchWindow(); + ISelection selection = workbenchWindow.getSelectionService().getSelection(); + Object selectedObject = getSelection(selection); + + if (selectedObject instanceof IFile && selection instanceof IStructuredSelection) + { + IFile file = (IFile)selectedObject; + IStructuredSelection structuredSelection = (IStructuredSelection)selection; + + if (file.getName().endsWith(".dtd") || file.getName().endsWith(".xsd")) + { + IPath path = file.getLocation(); + String uri = URIHelper.getURIForFilePath(path.toString()); + + boolean validationPluginsFound = false; + + Boolean isValid = null; + + Class[] parameterTypes = new Class[] {String.class}; + Object[] arguments = new Object[] {uri}; + + try + { + + if (file.getName().endsWith(".xsd")) + { +// Here is the Reflection equivalent way of performing the following lines +// XSDValidator xsdValidator = XSDValidator.getInstance(); +// ValidationReport valreport = xsdValidator.validate(uri); + + Plugin validateXSDPlugin = Platform.getPlugin(validateXSDPluginID); + if (validateXSDPlugin != null) + { + Class xsdValidatorClass, validationReportClass; + Object xsdValidatorObject, validationReportObject; + + ClassLoader classLoader = validateXSDPlugin.getClass().getClassLoader(); // getDescriptor().getPluginClassLoader(); + xsdValidatorClass = Class.forName(xsdValidatorClassName, true, classLoader); + + Method getInstanceMethod = xsdValidatorClass.getMethod("getInstance", null); + xsdValidatorObject = getInstanceMethod.invoke(null, null); // static and no parameters + + Method validateMethod = xsdValidatorClass.getMethod("validate", parameterTypes); + validationReportObject = validateMethod.invoke(xsdValidatorObject, arguments); + + validationReportClass = Class.forName(validationReportClassName, true, classLoader); + + Method isValidMethod = validationReportClass.getMethod("isValid", null); + isValid = (Boolean)isValidMethod.invoke(validationReportObject, null); + + validationPluginsFound = true; // made it this far, so declare that validation can be performed + } + } + else + { +// Here is the Reflection equivalent way of performing the following lines +// DTDValidator dtdValidator = DTDValidator.getInstance(); +// ValidationReport valreport = dtdValidator.validate(uri); + + Plugin validateDTDPlugin = Platform.getPlugin(validateDTDPluginID); + + if (validateDTDPlugin != null) + { + Class dtdValidatorClass, validationReportClass; + Object dtdValidatorObject, validationReportObject; + + ClassLoader classLoader = validateDTDPlugin.getClass().getClassLoader(); + + dtdValidatorClass = Class.forName(dtdValidatorClassName, true, classLoader); + + Method getInstanceMethod = dtdValidatorClass.getMethod("getInstance", null); + dtdValidatorObject = getInstanceMethod.invoke(null, null); // static and no parameters + + Method validateMethod = dtdValidatorClass.getMethod("validate", parameterTypes); + validationReportObject = validateMethod.invoke(dtdValidatorObject, arguments); + + validationReportClass = Class.forName(validationReportClassName, true, classLoader); + + Method isValidMethod = validationReportClass.getMethod("isValid", null); + isValid = (Boolean)isValidMethod.invoke(validationReportObject, null); + + validationPluginsFound = true; // made it this far, so declare that validation can be performed + } + } + } + catch (ClassNotFoundException e) + { + } + catch (NoSuchMethodException e) + { + } + catch (IllegalAccessException e) + { + } + catch (InvocationTargetException e) + { + } + + if (validationPluginsFound) + { + if (isValid != null && !isValid.booleanValue()) + { + String title = XMLWizard.getString("_UI_DIALOG_TITLE_INVALID_GRAMMAR"); + String message = XMLWizard.getString("_UI_DIALOG_MESSAGE_INVALID_GRAMMAR"); + boolean answer = MessageDialog.openQuestion(Display.getDefault().getActiveShell(), title, message); + if (!answer) + return; + } + } + else + { + // TODO externalize these strings + String title = "Validation Plugins Unavailable"; + String message = "Validation cannot be performed because the validation plugins were disabled or not found. The generated file may be invalid. Do you wish to continue?"; + boolean answer = MessageDialog.openQuestion(Display.getDefault().getActiveShell(), title, message); + if (!answer) + return; + } + NewXMLWizard.showDialog(workbenchWindow.getShell(), file, structuredSelection); + } + } + } + + /** + * unused + */ + public void selectionChanged(IAction action, ISelection selection) + { + } + + // scammed from WindowUtility + // + public static Object getSelection(ISelection selection) + { + if (selection == null) + { + return null; + } // end of if () + + Object result = null; + if (selection instanceof IStructuredSelection) + { + IStructuredSelection es= (IStructuredSelection)selection; + Iterator i= es.iterator(); + if (i.hasNext()) + { + result= i.next(); + } + } + return result; + } +} diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLSchemaValidationChecker.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLSchemaValidationChecker.java new file mode 100644 index 0000000000..654f6d6f3f --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLSchemaValidationChecker.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * 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 org.eclipse.core.resources.IFile; +import org.eclipse.wst.xml.uriresolver.util.URIHelper; +import org.xml.sax.ErrorHandler; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +public class XMLSchemaValidationChecker { + public boolean isValid(IFile ifile) { + String xsdFileName = ifile.getLocation().toString(); + return isValid(xsdFileName); + } + /** + * Should this be implemented as a Validator and simply called as such with + * a reporter that only checks the results for severity = error? Or should +// * the Xerces requirement be broken using a plug-in extension? + */ + + public boolean isValid(String xsdFileName) { +// DOMASBuilderImpl builder = new DOMASBuilderImpl(); +// DOMErrorHandler errorHandler = new DOMErrorHandler(); +// builder.setErrorHandler(errorHandler); + try { + String uri = URIHelper.getURIForFilePath(xsdFileName); +// ASModel model = builder.parseASURI(uri); +// if (errorHandler.hasError()) +// return false; + } + catch (Exception e) // invalid schema + { + return false; + } + + return true; + } + + // inner class + class DOMErrorHandler implements ErrorHandler { + private boolean hasError = false; + + public boolean hasError() { + return hasError; + } + + public void error(SAXParseException err) { + hasError = true; + } + public void fatalError(SAXParseException exception) throws SAXException { + hasError = true; + } + public void warning(SAXParseException exception) throws SAXException { + // not an error + } + } // end DOMErrorHandlerImpl + +} diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLWizard.java b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLWizard.java new file mode 100644 index 0000000000..419bb6b18b --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/XMLWizard.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * 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.net.MalformedURLException; +import java.net.URL; +import java.util.MissingResourceException; +import java.util.ResourceBundle; + +import org.eclipse.jface.resource.ImageDescriptor; +import org.eclipse.wst.xml.ui.XMLEditorPlugin; + +public class XMLWizard +{ + private ResourceBundle wizardResourceBundle; + protected static XMLWizard instance = new XMLWizard(); + + public synchronized static XMLWizard getInstance() { + return instance; + } + + public XMLWizard() + { + instance = this; + try { + wizardResourceBundle = ResourceBundle.getBundle("wizardResource"); //$NON-NLS-1$ + } + catch (java.util.MissingResourceException exception) { + wizardResourceBundle = null; + } + } + + public ResourceBundle getWizardResourceBundle() + { + return wizardResourceBundle; + } + + public static String getString(String key) + { + try { + ResourceBundle bundle = getInstance().getWizardResourceBundle(); + return bundle.getString(key); + } + catch (MissingResourceException e) { + return key; + } + } + + public ImageDescriptor getImageDescriptor(String name) + { + try { + URL url= new URL(XMLEditorPlugin.getInstance().getBundle().getEntry("/"), name); + return ImageDescriptor.createFromURL(url); + } + catch (MalformedURLException e) { + return ImageDescriptor.getMissingImageDescriptor(); + } + } +} diff --git a/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/icons/generatexml_wiz.gif b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/icons/generatexml_wiz.gif Binary files differnew file mode 100644 index 0000000000..2e4f667655 --- /dev/null +++ b/bundles/org.eclipse.wst.xml.ui/src-wizards/org/eclipse/wst/xml/ui/internal/wizards/icons/generatexml_wiz.gif |