1 /*2 * The contents of this file are subject to the terms of the Common Development3 * and Distribution License (the License). You may not use this file except in4 * compliance with the License.5 *6 * You can obtain a copy of the License at http://www.netbeans.org/cddl.html7 * or http://www.netbeans.org/cddl.txt.8 *9 * When distributing Covered Code, include this CDDL Header Notice in each file10 * and include the License file at http://www.netbeans.org/cddl.txt.11 * If applicable, add the following below the CDDL Header, with the fields12 * enclosed by brackets [] replaced by your own identifying information:13 * "Portions Copyrighted [year] [name of copyright owner]"14 *15 * The Original Software is NetBeans. The Initial Developer of the Original16 * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun17 * Microsystems, Inc. All Rights Reserved.18 */19 package org.netbeans.modules.xml.tools.generator;20 21 import java.io.*;22 import java.awt.*;23 import java.util.*;24 import java.beans.*;25 import java.lang.reflect.Modifier ;26 27 import javax.swing.*;28 import javax.swing.text.Document ;29 import javax.swing.text.BadLocationException ;30 31 import org.xml.sax.*;32 33 import org.openide.*;34 import org.openide.nodes.*;35 //import org.openide.src.*;36 import org.openide.cookies.*;37 import org.openide.filesystems.*;38 import org.openide.filesystems.FileSystem; // override java.io.FileSystem39 import org.openide.loaders.*;40 import org.openide.util.MapFormat;41 import org.openide.xml.*;42 43 import org.netbeans.modules.xml.core.DTDDataObject;44 import org.netbeans.modules.xml.core.lib.GuiUtil;45 import org.netbeans.modules.xml.core.lib.FileUtilities;46 import org.netbeans.modules.xml.tax.cookies.TreeEditorCookie;47 import org.netbeans.tax.*;48 49 /**50 * Generates handler that traces context. It consists from:51 * <ul>52 * <li>HandlerInterface declaring handle{ElementName}({Element type}} methods53 * <li>HandlerParslet set of parse{format}(String param)54 * <li>HandlerStub a code dispatching to such methods.55 * <li>sample HandlerImpl56 * <li>sample ParsletImpl57 * </ul>58 *59 * <p>60 * The generator is driven by {@link SAXGeneratorModel}.61 * It contains all properties driving this code generator.62 *63 * @author Petr Kuzel64 * @version 1.0, 12/7/200165 */66 public final class SAXGeneratorSupport implements XMLGenerateCookie {67 68 //TODO: Retouche69 // private static final String JAVA_EXT = "java"; // NOI18N70 //71 // private static final String SAX_PACKAGE = ""; // we import it // NOI18N72 // private static final String SAX_EXCEPTION = SAX_PACKAGE + "SAXException"; // NOI18N73 // private static final String SAX_DOCUMENT_HANDLER = SAX_PACKAGE + "DocumentHandler"; // NOI18N74 // private static final String SAX2_CONTENT_HANDLER = SAX_PACKAGE + "ContentHandler"; // NOI18N75 // private static final String SAX_LOCATOR = SAX_PACKAGE + "Locator"; // NOI18N76 // private static final String SAX_ATTRIBUTE_LIST = SAX_PACKAGE + "AttributeList"; // NOI18N77 // private static final String SAX2_ATTRIBUTES = SAX_PACKAGE + "Attributes"; // NOI18N78 //79 // private static final String SAX_INPUT_SOURCE = SAX_PACKAGE + "InputSource"; // NOI18N80 //81 // private static final String JAXP_PACKAGE = "javax.xml.parsers."; // NOI18N82 // private static final String JAXP_PARSER_CONFIGURATION_EXCEPTION = JAXP_PACKAGE + "ParserConfigurationException"; // NOI18N83 // private static final String JAXP_FACTORY_CONFIGURATION_ERROR = JAXP_PACKAGE + "FactoryConfigurationRrror"; // NOI18N84 //85 // private static final String JAVA_IOEXCEPTION = "java.io.IOException"; // NOI18N86 //87 // // generated methods names88 //89 // private static final String M_SET_DOCUMENT_LOCATOR = "setDocumentLocator"; // NOI18N90 // private static final String M_START_DOCUMENT = "startDocument"; // NOI18N91 // private static final String M_END_DOCUMENT = "endDocument"; // NOI18N92 // private static final String M_START_ELEMENT = "startElement"; // NOI18N93 // private static final String M_END_ELEMENT = "endElement"; // NOI18N94 // private static final String M_CHARACTERS = "characters"; // NOI18N95 // private static final String M_IGNORABLE_WHITESPACE = "ignorableWhitespace"; // NOI18N96 // private static final String M_PROCESSING_INSTRUCTION = "processingInstruction"; // NOI18N97 // private static final String M_SKIPPED_ENTITY = "skippedEntity"; // NOI18N98 // private static final String M_START_PREFIX_MAPPING = "startPrefixMapping"; // NOI18N99 // private static final String M_END_PREFIX_MAPPING = "endPrefixMapping"; // NOI18N100 //101 // /** emmit (dispatch) method name.*/102 // private static final String EMMIT_BUFFER = "dispatch"; // NOI18N103 // private static final String M_PARSE = "parse"; // NOI18N104 // private static final String HANDLE_PREFIX = "handle_"; // NOI18N105 // private static final String START_PREFIX = "start_"; // NOI18N106 // private static final String END_PREFIX = "end_"; // NOI18N107 //108 // private static final String FILE_COMMENT_MARK = "Mark"; // NOI18N109 //110 // //src hiearchy constants111 // private static final Type Type_STRING = Type.createFromClass (String.class);112 // private static final MethodParameter[] STRING_PARAM = new MethodParameter[] {113 // new MethodParameter("data",Type.createFromClass(String.class), true) // NOI18N114 // };115 //116 // private static final Identifier[] JAXP_PARSE_EXCEPTIONS = new Identifier[] {117 // Identifier.create(SAX_EXCEPTION),118 // Identifier.create(JAXP_PARSER_CONFIGURATION_EXCEPTION),119 // Identifier.create(JAVA_IOEXCEPTION)120 // };121 //122 // private static final String JAXP_PARSE_EXCEPTIONS_DOC =123 // "@throws " + JAVA_IOEXCEPTION + " on I/O error\n" + // NOI18N124 // "@throws " + SAX_EXCEPTION + " propagated exception thrown by a DocumentHandler\n" + // NOI18N125 // "@throws " + JAXP_PARSER_CONFIGURATION_EXCEPTION + " a parser satisfying the requested configuration cannot be created\n" + // NOI18N126 // "@throws " + JAXP_FACTORY_CONFIGURATION_ERROR + " if the implementation cannot be instantiated\n"; // NOI18N127 //128 //129 // // input fields - these control generation process130 //131 // private DataObject DO; //model DataObject132 // private TreeDTDRoot dtd; //model DTD133 //134 // private ElementBindings elementMapping = new ElementBindings(); //model mapping135 // private ParsletBindings parsletsMap = new ParsletBindings(); //model mapping136 //137 // private int sax = 1; // SAX version to be used supported {1, 2}138 //139 // private SAXGeneratorModel model; //holds strategy140 //141 //// private final MapFormat generator;142 //143 // //144 // // init145 // //146 //147 // public SAXGeneratorSupport (DTDDataObject DO) {148 // this (DO, null);149 // }150 //151 // public SAXGeneratorSupport (DataObject DO, TreeDTDRoot dtd) {152 // if (DO == null) throw new IllegalArgumentException("null"); // NOI18N153 // this.DO = DO;154 // this.dtd = dtd;155 // }156 //157 // /**158 // * The entry method coresponding to GenerateCookie.159 // * It displays a customization dialog and then generate a code and opens it160 // * in editor mode.161 // */162 public void generate () {163 //164 // try {165 // dtd = null; // invalidate cache #26745166 // if (getDTD() == null) {167 // String msg = org.openide.util.NbBundle.getMessage(SAXGeneratorSupport.class, "MSG_invalid_dtd");168 // GuiUtil.notifyWarning(msg);169 // return;170 // }171 //172 // FileObject primFile = DO.getPrimaryFile();173 //174 // String rawName = primFile.getName();175 // String name = rawName.substring(0,1).toUpperCase() + rawName.substring(1);176 //177 // final FileObject folder = primFile.getParent();178 // final String packageName = Util.findJavaPackage(folder);179 //180 // // prepare inital model181 //182 // elementMapping.clear();183 // parsletsMap.clear();184 //185 // initMappings();186 //187 // model = new SAXGeneratorModel(188 // name, new ElementDeclarations (dtd.getElementDeclarations().iterator()),189 // elementMapping, parsletsMap190 // );191 //192 // // load previous settings193 //194 // loadPrevious(folder);195 //196 // // initialize wizard panels197 //198 // final WizardDescriptor.Panel[] panels = new WizardDescriptor.Panel[] {199 // new SAXGeneratorAbstractPanel.WizardStep(SAXGeneratorVersionPanel.class),200 // new SAXGeneratorAbstractPanel.WizardStep(SAXGeneratorMethodPanel.class),201 // new SAXGeneratorAbstractPanel.WizardStep(SAXGeneratorParsletPanel.class),202 // new SAXGeneratorAbstractPanel.WizardStep(SAXGeneratorFilePanel.class)203 // };204 //205 // for (int i = 0; i< panels.length; i++) {206 // ((SAXGeneratorAbstractPanel.WizardStep)panels[i]).setBean(model);207 // ((SAXGeneratorAbstractPanel.WizardStep)panels[i]).setIndex(i);208 // }209 //210 // // setup wizard properties211 //212 // WizardDescriptor descriptor = new WizardDescriptor(panels, model);213 //214 // descriptor.setTitle(Util.THIS.getString ("SAXGeneratorSupport.title"));215 // descriptor.putProperty("WizardPanel_contentDisplayed", Boolean.TRUE); // NOI18N216 //// descriptor.putProperty("WizardPanel_helpDisplayed", Boolean.TRUE); // NOI18N217 // descriptor.putProperty("WizardPanel_contentNumbered", Boolean.TRUE); // NOI18N218 // descriptor.putProperty("WizardPanel_autoWizardStyle", Boolean.TRUE); // NOI18N219 // descriptor.putProperty("WizardPanel_leftDimension", new Dimension(500,400)); // NOI18N220 // descriptor.putProperty("WizardPanel_contentData", new String[] { // NOI18N221 // Util.THIS.getString ("SAXGeneratorVersionPanel.step"),222 // Util.THIS.getString ("SAXGeneratorMethodPanel.step"),223 // Util.THIS.getString ("SAXGeneratorParsletPanel.step"),224 // Util.THIS.getString ("SAXGeneratorFilePanel.step")225 //226 // });227 //228 // String fmt = Util.THIS.getString ("SAXGeneratorSupport.subtitle");229 // descriptor.setTitleFormat(new java.text.MessageFormat(fmt));230 //231 // // launch the wizard232 //233 // Dialog dlg = DialogDisplayer.getDefault().createDialog(descriptor);234 // dlg.show();235 //236 // if ( ( descriptor.CANCEL_OPTION.equals (descriptor.getValue()) ) ||237 // ( descriptor.CLOSED_OPTION.equals (descriptor.getValue()) ) ) {238 // return;239 // }240 //241 // // wizard finished242 //243 // GuiUtil.setStatusText(Util.THIS.getString("MSG_sax_progress_1"));244 //245 // if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug(model.toString());246 //247 // sax = model.getSAXversion();248 //249 // // prepare source elements and dataobjects250 //251 // DataObject stubDataObject = FileUtilities.createDataObject(folder, model.getStub(), JAVA_EXT, true);252 // SourceElement stubSrc = openSource(stubDataObject);253 //254 // DataObject interfaceImplDataObject = FileUtilities.createDataObject( folder, model.getHandlerImpl(), JAVA_EXT, false);255 // SourceElement interfaceImplSrc = openSource(interfaceImplDataObject);256 //257 // DataObject interfaceDataObject = FileUtilities.createDataObject( folder, model.getHandler(), JAVA_EXT, true);258 // SourceElement interfaceSrc = openSource(interfaceDataObject);259 //260 // DataObject parsletsDataObject = null;261 // DataObject parsletsImplDataObject = null;262 //263 // SourceElement parsletsSrc = null;264 // SourceElement parsletsImplSrc = null;265 //266 // if (model.hasParslets()) {267 //268 // parsletsImplDataObject = FileUtilities.createDataObject( folder, model.getParsletImpl(), JAVA_EXT, false);269 // parsletsImplSrc = openSource(parsletsImplDataObject);270 //271 // parsletsDataObject = FileUtilities.createDataObject( folder, model.getParslet(), JAVA_EXT, true);272 // parsletsSrc = openSource(parsletsDataObject);273 //274 // }275 //276 // // generate code by a model277 //278 // GuiUtil.setStatusText(Util.THIS.getString("MSG_sax_progress_1_5"));279 //280 // CodeGenerator stubGenerator = new StubGenerator(model.getStub(), model.getHandler(), model.getParslet());281 // generateCode( stubGenerator, stubSrc, packageName);282 //283 // CodeGenerator interfaceGenerator = new InterfaceGenerator(model.getHandler());284 // generateCode( interfaceGenerator, interfaceSrc, packageName);285 //286 // CodeGenerator interfaceImplGenerator = new InterfaceImplGenerator(model.getHandlerImpl());287 // generateCode( interfaceImplGenerator, interfaceImplSrc, packageName);288 //289 // if (model.hasParslets()) {290 // CodeGenerator parsletsGenerator = new ParsletGenerator(model.getParslet());291 // generateCode( parsletsGenerator, parsletsSrc, packageName);292 //293 // CodeGenerator parsletsImplGenerator = new ParsletImplGenerator(model.getParsletImpl());294 // generateCode( parsletsImplGenerator, parsletsImplSrc, packageName);295 // }296 //297 // // prepare settings data object298 //299 // DataObject settingsDataObject = null;300 // String settings = "<!-- failed -->"; // NOI18N301 //302 // if (model.getBindings() != null) {303 // settingsDataObject = FileUtilities.createDataObject(folder, model.getBindings(), "xml", true); // NOI18N304 // settings = SAXBindingsGenerator.toXML(model);305 // }306 //307 // // write generated code into filesystem308 //309 // GuiUtil.setStatusText(Util.THIS.getString("MSG_sax_progress_2"));310 //311 // trySave(stubDataObject, null);312 // trySave(interfaceDataObject, null);313 // trySave(interfaceImplDataObject, null);314 //315 // if (model.hasParslets()) {316 // trySave(parsletsDataObject, null);317 // trySave(parsletsImplDataObject, null);318 // }319 //320 // if (model.getBindings() != null) {321 // trySave(settingsDataObject, settings);322 // }323 //324 // // open files to be implemented in editor325 //326 // GuiUtil.setStatusText(Util.THIS.getString("MSG_sax_progress_3"));327 //328 // if (model.hasParslets()) {329 // GuiUtil.performDefaultAction (folder.getFileObject(model.getParsletImpl(), JAVA_EXT));330 // }331 // GuiUtil.performDefaultAction (folder.getFileObject(model.getHandlerImpl(), JAVA_EXT));332 //333 // } catch (FileStateInvalidException e) {334 // String msg = Util.THIS.getString("MSG_wizard_fail", e);335 // GuiUtil.notifyWarning(msg);336 // } catch (SourceException e) {337 // String msg = Util.THIS.getString("MSG_wizard_fail", e);338 // GuiUtil.notifyWarning(msg);339 // } catch (TreeException e) {340 // String msg = Util.THIS.getString("MSG_wizard_fail", e);341 // GuiUtil.notifyWarning(msg);342 // } catch (IOException e) {343 // String msg = Util.THIS.getString("MSG_wizard_fail", e);344 // GuiUtil.notifyWarning(msg);345 // } finally {346 // String msg = org.openide.util.NbBundle.getMessage(SAXGeneratorSupport.class, "MSG_sax_progress_done");347 // GuiUtil.setStatusText(msg); // NOI18N348 // }349 }350 //351 // /*352 // * Try to locate previous settings and reuse it.353 // */354 // private void loadPrevious(FileObject folder) {355 // InputStream in = null;356 //357 // try {358 // FileObject previous = folder.getFileObject(model.getBindings(), "xml"); // NOI18N359 // if (previous == null) return;360 //361 // if ( previous.isVirtual() ) {362 // // file is virtual -- not available363 // return;364 // }365 //366 // in = previous.getInputStream();367 // InputSource input = new InputSource(previous.getURL().toExternalForm());368 // input.setByteStream(in);369 //370 // SAXBindingsHandlerImpl handler = new SAXBindingsHandlerImpl();371 // SAXBindingsParser parser = new SAXBindingsParser(handler);372 //373 // XMLReader reader = XMLUtil.createXMLReader(true);374 // reader.setEntityResolver(EntityCatalog.getDefault());375 // reader.setContentHandler(parser);376 // reader.parse(input);377 //378 // model.loadElementBindings(handler.getElementBindings());379 // model.loadParsletBindings(handler.getParsletBindings());380 //381 // } catch (IOException ex) {382 // // last settings are not restored383 // if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug("Cannot read settings", ex); // NOI18N384 // } catch (SAXException ex) {385 // // last settings are not restored386 // if ( Util.THIS.isLoggable() ) /* then */ Util.THIS.debug("Cannot read settings", ex); // NOI18N387 // } finally {388 // try {389 // if (in != null) in.close();390 // } catch (IOException e) {391 // // let it be392 // }393 // }394 //395 // }396 //397 // /*398 // * Prepend to document file header and save it.399 // */400 // private void trySave(DataObject obj, String data) throws IOException {401 // if (obj == null) return;402 //403 // try {404 // EditorCookie editor = (EditorCookie) obj.getCookie(EditorCookie.class);405 // Document doc = editor.openDocument();406 //407 // if (data == null) {408 //409 // // file header can not be manipulated via src hiearchy410 // data = GenerateSupportUtils.getJavaFileHeader (obj.getName(), null) + "\n"; // NOI18N411 // } else {412 // doc.remove(0, doc.getLength());413 // }414 //415 // doc.insertString(0, data, null);416 // } catch (IOException ex) {417 // // ignore, there will be missing file header418 // } catch (BadLocationException ex) {419 // // ignore, there will be missing file header420 // }421 //422 // SaveCookie cake = (SaveCookie) obj.getCookie(SaveCookie.class);423 // if (cake != null) cake.save();424 // }425 //426 // /*427 // * Wait until source cookie and return SourceElement.428 // */429 // private SourceElement openSource(DataObject obj) {430 // if (obj == null) return null;431 //432 // SourceCookie cake = null;433 // while (cake == null) {434 // cake = (SourceCookie) obj.getCookie(SourceCookie.class);435 // }436 //437 // return cake.getSource();438 // }439 //440 // /**441 // * Generate code using given generator.442 // * @param target SourceElement where to place result, a null value indicates to skip443 // */444 // private void generateCode(CodeGenerator factory, SourceElement target, String packageName) throws IOException, SourceException {445 //446 // if (target == null) return;447 //448 // // kill all original stuff449 //450 // if (target.getClasses().length > 0) {451 // target.removeClasses(target.getClasses());452 // }453 //454 // // generate new one455 //456 // if (packageName != null && packageName.length() > 0) {457 // target.setPackage(Identifier.create(packageName));458 // }459 //460 // target.setImports(new Import[] {new Import(Identifier.create("org.xml.sax"), true)}); // NOI18N461 // factory.generate(target);462 //463 // }464 //465 //466 // /**467 // * Generate stub using parslet and dispatching to given handler.468 // */469 // private ClassElement generateStub(String name, String face, String let) throws SourceException {470 //471 // ClassElement clazz = new ClassElement();472 // clazz.setModifiers (Modifier.PUBLIC);473 // clazz.setName (Identifier.create (name));474 // clazz.setInterfaces (new Identifier[] { getSAXHandlerInterface() });475 //476 // clazz.getJavaDoc().setRawText(477 // "\nThe class reads XML documents according to specified DTD and " + // NOI18N478 // "\ntranslates all related events into " + face + " events." + // NOI18N479 // "\n<p>Usage sample:\n" + // NOI18N480 // "<pre>\n" + // NOI18N481 // " " + name + " parser = new " + name + "(...);\n" + // NOI18N482 // " parser.parse(new InputSource(\"...\"));\n" + // NOI18N483 // "</pre>\n" + // NOI18N484 // "<p><b>Warning:</b> the class is machine generated. DO NOT MODIFY</p>\n" // NOI18N485 // );486 //487 // ConstructorElement constructor = new ConstructorElement();488 // constructor.setModifiers(Modifier.PUBLIC);489 //490 // if (model.hasParslets()) {491 // constructor.setParameters( new MethodParameter[] {492 // new MethodParameter("handler", Type.parse(face), true), // NOI18N493 // new MethodParameter("resolver", Type.parse("EntityResolver"), true), // NOI18N494 // new MethodParameter("parslet", Type.parse(let), true), // NOI18N495 // });496 // } else {497 // constructor.setParameters( new MethodParameter[] {498 // new MethodParameter("handler", Type.parse(face), true), // NOI18N499 // new MethodParameter("resolver", Type.parse("EntityResolver"), true), // NOI18N500 // });501 // }502 //503 // String parsletInit = model.hasParslets() ? "\nthis.parslet = parslet;" : ""; // NOI18N504 //505 // constructor.setBody(parsletInit + "\nthis.handler = handler;\n" + // NOI18N506 // "this.resolver = resolver;\n" + // NOI18N507 // "buffer = new StringBuffer(111);\ncontext = new java.util.Stack();\n" // NOI18N508 // );509 //510 // String docText =511 // "\nCreates a parser instance.\n" + // NOI18N512 // "@param handler handler interface implementation (never <code>null</code>\n" + // NOI18N513 // "@param resolver SAX entity resolver implementation or <code>null</code>.\n" + // NOI18N514 // "It is recommended that it could be able to resolve at least the DTD."; // NOI18N515 //516 // if (model.hasParslets()) {517 // docText += "@param parslet convertors implementation (never <code>null</code>\n"; //NOI18N518 // }519 //520 // constructor.getJavaDoc().setRawText(docText);521 //522 // clazz.addConstructor(constructor);523 //524 // // add private class fields525 //526 // clazz.addField(createField("buffer", StringBuffer.class.getName())); // NOI18N527 // if (model.hasParslets()) clazz.addField(createField("parslet", let)); // NOI18N528 // clazz.addField(createField("handler", face)); // NOI18N529 // clazz.addField(createField("context", java.util.Stack.class.getName()));// NOI18N530 // clazz.addField(createField("resolver", "EntityResolver"));// NOI18N531 //532 // genStubClass(clazz);533 //534 // return clazz;535 // }536 //537 //538 // /**539 // * Generate ClassElement representing interface to a handler.540 // */541 // private ClassElement generateInterface(String name) throws SourceException {542 //543 // ClassElement clazz = new ClassElement();544 // clazz.setModifiers (Modifier.PUBLIC);545 // clazz.setName (Identifier.create(name));546 // if (model.isPropagateSAX()) {547 // clazz.setInterfaces (new Identifier[] { getSAXHandlerInterface() });548 // }549 // clazz.setClassOrInterface(false);550 //551 // Iterator it = model.getElementBindings().values().iterator();552 // while (it.hasNext()) {553 // ElementBindings.Entry next = (ElementBindings.Entry) it.next();554 //555 // // create a method according mapping table:556 // // public void $name($type data, $SAXattrs meta) throws SAXException;557 //558 // MethodElement method = null;559 // MethodElement startMethod = null;560 // MethodElement endMethod = null;561 //562 // final String handler = next.getType();563 // String methodName;564 // MethodParameter[] params;565 // JavaDoc jdoc;566 //567 // if (next.IGNORE.equals(handler)) {568 //569 // continue;570 //571 // } else if (next.EMPTY.equals(handler)) {572 //573 // methodName = HANDLE_PREFIX + next.getMethod();574 // params = new MethodParameter[] {575 // new MethodParameter("meta", Type.parse(getSAXAttributes()), true) // NOI18N576 // };577 //578 // method = createInterfaceMethod(methodName, params, SAX_EXCEPTION);579 //580 // jdoc = method.getJavaDoc();581 // jdoc.setRawText("\nAn empty element event handling method.\n@param data value or null\n"); // NOI18N582 //583 // }584 //585 // if (next.DATA.equals(handler) || next.MIXED.equals(handler)) {586 //587 // methodName = HANDLE_PREFIX + next.getMethod();588 // params = new MethodParameter[] {589 // parsletsMap.getReturnAsParameter(next.getParslet()),590 // new MethodParameter("meta", Type.parse(getSAXAttributes()), true) // NOI18N591 // };592 //593 // method = createInterfaceMethod(methodName, params, SAX_EXCEPTION);594 //595 // jdoc = method.getJavaDoc();596 // jdoc.setRawText("\nA data element event handling method.\n@param data value or null \n@param meta attributes\n"); // NOI18N597 //598 // }599 //600 // if (next.CONTAINER.equals(handler) || next.MIXED.equals(handler)) {601 //602 // // start method603 //604 // methodName = START_PREFIX + next.getMethod();605 // params = new MethodParameter[] {606 // new MethodParameter("meta", Type.parse(getSAXAttributes()), true) // NOI18N607 // };608 // startMethod = createInterfaceMethod(methodName, params, SAX_EXCEPTION);609 //610 // jdoc = startMethod.getJavaDoc();611 // jdoc.setRawText("\nA container element start event handling method.\n@param meta attributes\n"); // NOI18N612 //613 // // end method614 //615 // methodName = END_PREFIX + next.getMethod();616 // endMethod = createInterfaceMethod(methodName, null, SAX_EXCEPTION);617 //618 // jdoc = endMethod.getJavaDoc();619 // jdoc.setRawText("\nA container element end event handling method.\n"); // NOI18N620 //621 // }622 //623 // if (startMethod != null) clazz.addMethod(startMethod);624 // if (method != null) clazz.addMethod(method);625 // if (endMethod != null) clazz.addMethod(endMethod);626 // }627 //628 // return clazz;629 // }630 //631 // /**632 // * Generates sample handler implementation.633 // * The implementation contains debug support and attribute switch. //??? attribute switch634 // */635 // private ClassElement generateInterfaceImpl(String name) throws SourceException {636 //637 // ClassElement clazz = new ClassElement();638 // clazz.setModifiers (Modifier.PUBLIC);639 // clazz.setName (Identifier.create (name));640 // clazz.setInterfaces (new Identifier[] { Identifier.create(model.getHandler()) });641 //642 // FieldElement field = new FieldElement();643 // field.setName(Identifier.create("DEBUG")); // NOI18N644 // field.setInitValue("false"); // NOI18N645 // field.setModifiers(Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL);646 // field.setType(Type.BOOLEAN);647 //648 // clazz.addField(field);649 //650 // Iterator it = model.getElementBindings().values().iterator();651 // while (it.hasNext()) {652 // ElementBindings.Entry next = (ElementBindings.Entry) it.next();653 //654 // // create a method according mapping table:655 // // public void $name($type data, $SAXattrs meta) throws SAXException;656 //657 // MethodElement method = null;658 // MethodElement startMethod = null;659 // MethodElement endMethod = null;660 //661 // final String handler = next.getType();662 // String methodName;663 // MethodParameter[] params;664 //665 // if (next.IGNORE.equals(handler)) {666 //667 // continue;668 //669 // } else if (next.EMPTY.equals(handler)) {670 //671 // methodName = HANDLE_PREFIX + next.getMethod();672 // params = new MethodParameter[] {673 // new MethodParameter("meta", Type.parse(getSAXAttributes()), true) // NOI18N674 // };675 //676 // method = createInterfaceMethod(methodName, params, SAX_EXCEPTION);677 // method.setBody("\nif (DEBUG) System.err.println(\"" + methodName + ": \" + meta);\n"); // NOI18N678 // }679 //680 // if (next.DATA.equals(handler) || next.MIXED.equals(handler)) {681 //682 // methodName = HANDLE_PREFIX + next.getMethod();683 // params = new MethodParameter[] {684 // parsletsMap.getReturnAsParameter(next.getParslet()),685 // new MethodParameter("meta", Type.parse(getSAXAttributes()), true) // NOI18N686 // };687 //688 // method = createInterfaceMethod(methodName, params, SAX_EXCEPTION);689 // method.setBody("\nif (DEBUG) System.err.println(\"" + methodName + ": \" + data);\n"); // NOI18N690 //691 // }692 //693 // if (next.CONTAINER.equals(handler) || next.MIXED.equals(handler)) {694 //695 // // start method696 //697 // methodName = START_PREFIX + next.getMethod();698 // params = new MethodParameter[] {699 // new MethodParameter("meta", Type.parse(getSAXAttributes()), true) // NOI18N700 // };701 // startMethod = createInterfaceMethod(methodName, params, SAX_EXCEPTION);702 //703 // startMethod.setBody("\nif (DEBUG) System.err.println(\"" + methodName + ": \" + meta);\n"); // NOI18N704 //705 // // end method706 //707 // methodName = END_PREFIX + next.getMethod();708 // endMethod = createInterfaceMethod(methodName, null, SAX_EXCEPTION);709 //710 // endMethod.setBody("\nif (DEBUG) System.err.println(\"" + methodName + "()\");\n"); // NOI18N711 //712 // }713 //714 // if (startMethod != null) clazz.addMethod(startMethod);715 // if (method != null) clazz.addMethod(method);716 // if (endMethod != null) clazz.addMethod(endMethod);717 // }718 //719 //720 // return clazz;721 //722 // }723 //724 //725 // /**726 // * Generate a ClassElement representing interface for parslets727 // */728 // private ClassElement generateParslet(String name) throws SourceException {729 //730 // ClassElement clazz = new ClassElement();731 // clazz.setModifiers (Modifier.PUBLIC);732 // clazz.setName (Identifier.create (name));733 // clazz.setClassOrInterface(false);734 //735 // ParsletBindings parslets = model.getParsletBindings();736 // Iterator it = parslets.keySet().iterator();737 // while (it.hasNext()) {738 // clazz.addMethod(parslets.getMethod((String)it.next()));739 // }740 //741 // return clazz;742 // }743 //744 //745 // /**746 // * Generate sample parslet implementation for well known types.747 // * Iterate over all customized parslets.748 // */749 // private ClassElement generateParsletImpl(String name) throws SourceException {750 //751 // ClassElement clazz = new ClassElement();752 // clazz.setModifiers (Modifier.PUBLIC);753 // clazz.setName (Identifier.create (name));754 // clazz.setInterfaces (new Identifier[] { Identifier.create(model.getParslet()) });755 //756 // MethodElement method = null;757 // String code = null;758 //759 // Iterator it = parsletsMap.keySet().iterator();760 // while (it.hasNext()) {761 // method = parsletsMap.getMethod((String)it.next());762 // code = createParsletCode(method);763 // method.setBody(code);764 // clazz.addMethod(method);765 // }766 //767 // return clazz;768 //769 // }770 //771 // /**772 // * Create a sample convertor/parslet body.773 // */774 // private String createParsletCode(MethodElement parslet) throws SourceException {775 // String returnType = parslet.getReturn().getFullString();776 // String fragment = ""; // NOI18N777 // String exception = "new SAXException(\"" + parslet.getName() + "(\" + data.trim() + \")\", ex)"; // NOI18N778 // String catchBlock = "\n} catch (IllegalArgumentException ex) {\n throw " + exception + ";\n}"; // NOI18N779 //780 // if ("int".equals(returnType)) { // NOI18N781 // fragment = "try {"; // NOI18N782 // fragment+= "\nreturn Integer.parseInt(data.trim());"; // NOI18N783 // fragment+= catchBlock;784 // } else if ("boolean".equals(returnType)) { // NOI18N785 // fragment = "return \"true\".equals(data.trim());"; // NOI18N786 // } else if ("long".equals(returnType)) { // NOI18N787 // fragment = "try {\nreturn Long.parseLong(data.trim());"; // NOI18N788 // fragment+= catchBlock;789 // } else if ("java.util.Date".equals(returnType)) { // NOI18N790 // fragment = "try {"; // NOI18N791 // fragment+= "\nreturn java.text.DateFormat.getDateInstance().parse(data.trim());"; // NOI18N792 // fragment+= "\n}catch(java.text.ParseException ex) {"; // NOI18N793 // fragment+= "\nthrow "+ exception + ";\n}"; // NOI18N794 // } else if ("java.net.URL".equals(returnType)) { // NOI18N795 // fragment = "try {"; // NOI18N796 // fragment+= "\n return new java.net.URL(data.trim());"; // NOI18N797 // fragment+= "\n} catch (java.net.MalformedURLException ex) {"; // NOI18N798 // fragment+= "\n throw " + exception +";\n}"; // NOI18N799 // } else if ("java.lang.String[]".equals(returnType)) { // NOI18N800 // fragment = "java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(data.trim());"; // NOI18N801 // fragment+= "\njava.util.ArrayList list = new java.util.ArrayList();"; // NOI18N802 // fragment+= "\nwhile (tokenizer.hasMoreTokens()) {"; // NOI18N803 // fragment+= "\nlist.add(tokenizer.nextToken());"; // NOI18N804 // fragment+= "\n}"; // NOI18N805 // fragment+= "\nreturn (String[]) list.toArray(new String[0]);"; // NOI18N806 // } else {807 // fragment = "throw new SAXException(\"Not implemented yet.\");"; // NOI18N808 // }809 //810 // return "\n" + fragment + "\n"; // NOI18N811 // }812 //813 // //~~~~~~~~~~~~~~~~~~~~ guess initial mapping ~~~~~~~~~~~~~~~~~~~~~~814 //815 // private void initMappings() {816 // try {817 // getDTD();818 //819 // Iterator it = dtd.getElementDeclarations().iterator();820 // while (it.hasNext()) {821 // TreeElementDecl next = (TreeElementDecl) it.next();822 // addElementMapping(next);823 // }824 // } catch (IOException ex) {825 // // let the map empty826 // } catch (TreeException ex) {827 // // let the map empty828 // }829 // }830 //831 // private void addElementMapping(TreeElementDecl decl) {832 // String name = decl.getName();833 // String javaName = GenerateSupportUtils.getJavaName(name);834 //835 // String defaultMapping = ElementBindings.Entry.DATA;836 //837 // if (decl.isMixed()) {838 // defaultMapping = ElementBindings.Entry.MIXED;839 // } else if (decl.allowElements()) {840 // defaultMapping = ElementBindings.Entry.CONTAINER;841 // } else if (decl.isEmpty()) {842 // defaultMapping = ElementBindings.Entry.EMPTY;843 // }844 //845 // elementMapping.put(name, javaName, null, defaultMapping);846 // }847 //848 //849 // //~~~~~~~~~~~~~~~~~~~~~~~~ generator methods ~~~~~~~~~~~~~~~~~~~~~~~~850 //851 //852 // /**853 // * Stub's startElement() method has two forms one for SAX 1.0 and one for SAX 2.0854 // */855 // private MethodElement genStartElementMethod() throws SourceException {856 // MethodElement method = null;857 // if (sax == 1) {858 // method = createImplementationMethod (859 // M_START_ELEMENT,860 // new MethodParameter [] {861 // new MethodParameter ("name", Type_STRING, false), // NOI18N862 // new MethodParameter ("attrs", Type.parse (getSAXAttributes()), false) // NOI18N863 // },864 // SAX_EXCEPTION865 // );866 //867 // StringBuffer code = new StringBuffer();868 // code.append("\n" + EMMIT_BUFFER + "(true);"); // NOI18N869 // code.append("\ncontext.push(new Object[] {name, new org.xml.sax.helpers.AttributeListImpl(attrs)});"); // NOI18N870 //871 // // generate start events for container methods872 //873 // code.append(createStartEndEvents(START_PREFIX, "attrs", HANDLE_PREFIX)); // NOI18N874 //875 // if (model.isPropagateSAX())876 // code.append("\nhandler." + M_START_ELEMENT + "(name, attrs);"); // NOI18N877 //878 // code.append("\n"); // NOI18N879 // method.setBody(code.toString());880 //881 // } else if (sax == 2) {882 // method = createImplementationMethod (883 // M_START_ELEMENT,884 // new MethodParameter [] {885 // new MethodParameter ("ns", Type_STRING, false), // NOI18N886 // new MethodParameter ("name", Type_STRING, false), // NOI18N887 // new MethodParameter ("qname", Type_STRING, false), // NOI18N888 // new MethodParameter ("attrs", Type.parse (getSAXAttributes()), false) // NOI18N889 // },890 // SAX_EXCEPTION891 // );892 //893 // StringBuffer code = new StringBuffer();894 // code.append("\n" + EMMIT_BUFFER + "(true);"); // NOI18N895 // code.append("\ncontext.push(new Object[] {qname, new org.xml.sax.helpers.AttributesImpl(attrs)});"); // NOI18N896 //897 // code.append(createStartEndEvents(START_PREFIX, "attrs", HANDLE_PREFIX)); // NOI18N898 //899 // if (model.isPropagateSAX())900 // code.append("\nhandler." + M_START_ELEMENT + "(ns, name, qname, attrs);"); // NOI18N901 //902 // code.append("\n"); // NOI18N903 // method.setBody(code.toString());904 //905 // };906 //907 // return method;908 // }909 //910 //911 // /**912 // * Stub's endElement() method has two forms one for SAX 1.0 and one for SAX 2.0913 // */914 // private MethodElement genEndElementMethod() throws SourceException {915 // MethodElement method = null;916 // if (sax == 1) {917 // method = createImplementationMethod (918 // M_END_ELEMENT,919 // new MethodParameter [] {920 // new MethodParameter ("name", Type_STRING, false) // NOI18N921 // },922 // SAX_EXCEPTION923 // );924 //925 // StringBuffer code = new StringBuffer();926 // code.append("\n" + EMMIT_BUFFER + "(false);"); // NOI18N927 // code.append("\ncontext.pop();"); // NOI18N928 //929 // code.append(createStartEndEvents(END_PREFIX, "", null)); // NOI18N930 //931 // if (model.isPropagateSAX())932 // code.append("\nhandler." + M_END_ELEMENT + "(name);"); // NOI18N933 //934 // code.append("\n"); // NOI18N935 // method.setBody(code.toString());936 //937 // } else if (sax == 2) {938 //939 // method = createImplementationMethod (940 // M_END_ELEMENT,941 // new MethodParameter [] {942 // new MethodParameter ("ns", Type_STRING, false), // NOI18N943 // new MethodParameter ("name", Type_STRING, false), // NOI18N944 // new MethodParameter ("qname", Type_STRING, false) // NOI18N945 // },946 // SAX_EXCEPTION947 // );948 //949 // StringBuffer code = new StringBuffer();950 // code.append("\n" + EMMIT_BUFFER + "(false);"); // NOI18N951 // code.append("\ncontext.pop();"); // NOI18N952 //953 // code.append(createStartEndEvents(END_PREFIX, "", null)); // NOI18N954 //955 // if (model.isPropagateSAX())956 // code.append("\nhandler." + M_END_ELEMENT + "(ns, name, qname);"); // NOI18N957 //958 // code.append("\n"); // NOI18N959 // method.setBody(code.toString());960 //961 // }962 //963 // return method;964 // }965 //966 //967 // /*968 // * @param prefix prefix of container method969 // * @param meta name of passed meta parameter or ""970 // * @param emptyPrefix name of empty element handler method or null971 // */972 // private String createStartEndEvents(String methodPrefix, String meta, String emptyPrefix) {973 //974 // StringBuffer code = new StringBuffer(233);975 //976 // Iterator it = model.getElementBindings().values().iterator();977 // String prefix = "\nif"; // NOI18N978 // while (it.hasNext()) {979 // ElementBindings.Entry next = (ElementBindings.Entry) it.next();980 //981 // String handling = next.getType();982 // String name = sax == 1 ? "name" : "qname"; // NOI18N983 //984 // if (next.CONTAINER.equals(handling) || next.MIXED.equals(handling)) {985 // code.append(prefix + " (\"" + next.getElement() + "\".equals(" + name + ")) {"); // NOI18N986 // code.append("\nhandler." + methodPrefix + next.getMethod() + "(" + meta + ");"); // NOI18N987 // code.append("\n}"); // NOI18N988 // prefix = " else if"; // NOI18N989 // } else if (emptyPrefix != null && next.EMPTY.equals(handling)) {990 // code.append(prefix + " (\"" + next.getElement() + "\".equals(" + name + ")) {"); // NOI18N991 // code.append("\nhandler." + emptyPrefix + next.getMethod() + "(" + meta + ");"); // NOI18N992 // code.append("\n}"); // NOI18N993 // prefix = " else if"; // NOI18N994 // }995 // }996 //997 // return code.toString();998 // }999 //1000// /**1001// * Stub's method. It is SAX 2.0 method1002// */1003// private MethodElement genStartPrefixMappingMethod() throws SourceException {1004// MethodElement method = null;1005// if (sax == 2) {1006// method = createImplementationMethod (1007// M_START_PREFIX_MAPPING,1008// new MethodParameter [] {1009// new MethodParameter ("prefix", Type_STRING, true), // NOI18N1010// new MethodParameter ("uri", Type_STRING, true) // NOI18N1011// },1012// SAX_EXCEPTION1013// );1014//1015// if (model.isPropagateSAX())1016// method.setBody ("\nhandler." + M_START_PREFIX_MAPPING + "(prefix, uri);\n"); // NOI18N1017// }1018// return method;1019// }1020//1021//1022// /**1023// * Stub's method. It is SAX 2.0 method1024// */1025// private MethodElement genEndPrefixMappingMethod() throws SourceException {1026// MethodElement method = null;1027// if (sax == 2) {1028// method= createImplementationMethod (1029// M_END_PREFIX_MAPPING,1030// new MethodParameter [] {1031// new MethodParameter ("prefix", Type_STRING, true) // NOI18N1032// },1033// SAX_EXCEPTION1034// );1035//1036// if (model.isPropagateSAX())1037// method.setBody ("\nhandler." + M_END_PREFIX_MAPPING + "(prefix);\n"); // NOI18N1038// }1039// return method;1040// }1041//1042//1043// /**1044// * Stub's method. It is SAX 2.0 method1045// */1046// private MethodElement genSkippedEntityMethod() throws SourceException {1047// MethodElement method = null;1048// if (sax == 2) {1049// method= createImplementationMethod (1050// M_SKIPPED_ENTITY,1051// new MethodParameter [] {1052// new MethodParameter ("name", Type_STRING, false) // NOI18N1053// },1054// SAX_EXCEPTION1055// );1056//1057// if (model.isPropagateSAX())1058// method.setBody ("\nhandler." + M_SKIPPED_ENTITY + "(name);\n"); // NOI18N1059// }1060// return method;1061// }1062//1063// /**1064// * Generate stub's handling methods.1065// * @param clazz to be filled with stub methods1066// */1067// private ClassElement genStubClass (ClassElement clazz) throws SourceException {1068// MethodElement method;1069//1070// // setDocumentLocator() method1071//1072// method = createImplementationMethod (1073// M_SET_DOCUMENT_LOCATOR,1074// new MethodParameter [] {1075// new MethodParameter ("locator", Type.parse (SAX_LOCATOR), false) // NOI18N1076// },1077// null1078// );1079//1080// if (model.isPropagateSAX())1081// method.setBody("\nhandler." + M_SET_DOCUMENT_LOCATOR + "(locator);\n"); // NOI18N1082// clazz.addMethod (method);1083//1084// // startDocument() method1085//1086// method = createImplementationMethod (M_START_DOCUMENT, null, SAX_EXCEPTION);1087// if (model.isPropagateSAX())1088// method.setBody("\nhandler." + M_START_DOCUMENT + "();\n"); // NOI18N1089// clazz.addMethod (method);1090//1091// // endDocument() method1092//1093// method = createImplementationMethod (M_END_DOCUMENT, null, SAX_EXCEPTION);1094// if (model.isPropagateSAX())1095// method.setBody("\nhandler." + M_END_DOCUMENT + "();\n"); // NOI18N1096// clazz.addMethod (method);1097//1098// // startElement()1099//1100// method = genStartElementMethod();1101// clazz.addMethod (method);1102//1103// // endElement()1104//1105// method = genEndElementMethod();1106// clazz.addMethod (method);1107//1108// // characters() method1109//1110// method = createImplementationMethod (1111// M_CHARACTERS,1112// new MethodParameter [] {1113// new MethodParameter ("chars", Type.createArray (Type.CHAR), false), // NOI18N1114// new MethodParameter ("start", Type.INT, false), // NOI18N1115// new MethodParameter ("len", Type.INT, false) // NOI18N1116// },1117// SAX_EXCEPTION1118// );1119//1120// StringBuffer code = new StringBuffer();1121// code.append("\nbuffer.append(chars, start, len);"); // NOI18N1122// if (model.isPropagateSAX())1123// code.append("handler." + M_CHARACTERS + "(chars, start, len);"); // NOI18N1124// code.append("\n"); // NOI18N1125// method.setBody(code.toString());1126// clazz.addMethod (method);1127//1128// // ignorableWhitespace() method1129//1130// method = createImplementationMethod (1131// M_IGNORABLE_WHITESPACE,1132// new MethodParameter [] {1133// new MethodParameter ("chars", Type.createArray (Type.CHAR), false), // NOI18N1134// new MethodParameter ("start", Type.INT, false), // NOI18N1135// new MethodParameter ("len", Type.INT, false) // NOI18N1136// },1137// SAX_EXCEPTION1138// );1139//1140// if (model.isPropagateSAX())1141// method.setBody("\nhandler." + M_IGNORABLE_WHITESPACE + "(chars, start, len);\n"); // NOI18N1142// clazz.addMethod (method);1143//1144// // processingInstruction() method1145//1146// method = createImplementationMethod (1147// M_PROCESSING_INSTRUCTION,1148// new MethodParameter [] {1149// new MethodParameter ("target", Type_STRING, false), // NOI18N1150// new MethodParameter ("data", Type_STRING, false) // NOI18N1151// },1152// SAX_EXCEPTION1153// );1154//1155// if (model.isPropagateSAX())1156// method.setBody("\nhandler." + M_PROCESSING_INSTRUCTION + "(target, data);\n"); // NOI18N1157//1158// clazz.addMethod (method);1159//1160//1161// // SAX 2.0 only methods1162//1163// method = genStartPrefixMappingMethod();1164// if (method != null) clazz.addMethod(method);1165//1166// method = genEndPrefixMappingMethod();1167// if (method != null) clazz.addMethod(method);1168//1169// method = genSkippedEntityMethod();1170// if (method != null) clazz.addMethod(method);1171//1172// // private dispatching method1173//1174// method = genEmmitBufferMethod();1175// clazz.addMethod(method);1176//1177// // optional static and dynamic methods that a user can appreciate1178//1179// method = genJAXPParseInputSourceMethod();1180// clazz.addMethod(method);1181//1182// method = genJAXPParseURLMethod();1183// clazz.addMethod(method);1184//1185// method = genJAXP_ParseInputSourceMethod();1186// clazz.addMethod(method);1187//1188// method = genJAXP_ParseURLMethod();1189// clazz.addMethod(method);1190//1191// method = genJAXP_ParseSupportMethod();1192// clazz.addMethod(method);1193//1194// method = genSampleErrorHandler();1195// clazz.addMethod(method);1196//1197// return clazz;1198// }1199//1200//1201// /**1202// * Generate stubs's switch dispatching to handler (an interface).1203// */1204// private MethodElement genEmmitBufferMethod() throws SourceException {1205//1206// MethodElement methodElement = new MethodElement();1207//1208// methodElement.setName(Identifier.create(EMMIT_BUFFER));1209// methodElement.setModifiers(Modifier.PRIVATE);1210// methodElement.setParameters( new MethodParameter[] {1211// new MethodParameter("fireOnlyIfMixed", Type.BOOLEAN, true) // NOI18N1212// });1213// methodElement.setExceptions( new Identifier[] {Identifier.create(SAX_EXCEPTION)} );1214//1215// StringBuffer buf = new StringBuffer();1216//1217// buf.append("\nif (fireOnlyIfMixed && buffer.length() == 0) return; //skip it\n"); // NOI18N1218// buf.append("\nObject[] ctx = (Object[]) context.peek();\n"); // NOI18N1219// buf.append("String here = (String) ctx[0];\n"); // NOI18N1220//1221// buf.append(getSAXAttributes() + " attrs = (" + getSAXAttributes() + ") ctx[1];\n"); // NOI18N1222//1223// String switchPrefix = "if"; // NOI18N1224//1225// Iterator it = model.getElementBindings().values().iterator();1226// while (it.hasNext()) {1227// ElementBindings.Entry next = (ElementBindings.Entry) it.next();1228//1229// String name = next.getElement();1230// String method = HANDLE_PREFIX + elementMapping.getMethod(name);1231// String parslet = elementMapping.getParslet(name);1232//1233// String data = "buffer.length() == 0 ? null : buffer.toString()"; // NOI18N1234// parslet = parslet == null ? data : "parslet." + parslet + "(" + data + ")"; // NOI18N1235//1236// String handling = next.getType();1237//1238// if (next.DATA.equals(handling) || next.MIXED.equals(handling)) {1239// buf.append(switchPrefix + " (\"" + name + "\".equals(here)) {\n" ); // NOI18N1240// if (next.DATA.equals(handling)) {1241// buf.append("if (fireOnlyIfMixed) throw new IllegalStateException(\"Unexpected characters() event! (Missing DTD?)\");\n"); // NOI18N1242// }1243// buf.append("handler." + method + "(" + parslet + ", attrs);\n"); // NOI18N1244//1245// switchPrefix = "} else if"; // NOI18N1246// }1247// }1248//1249// if (switchPrefix.equals("if") == false) { // NOI18N1250// buf.append("} else {\n //do not care\n}\n"); // NOI18N1251// }1252// buf.append("buffer.delete(0, buffer.length());\n"); // NOI18N1253//1254// methodElement.setBody(buf.toString());1255//1256// return methodElement;1257//1258// }1259//1260//1261// //1262// // JAXP related methods.1263// //1264//1265// /**1266// * Generate static JAXP support method1267// */1268// private MethodElement genJAXP_ParseSupportMethod() throws SourceException {1269// MethodElement method = new MethodElement();1270//1271// method.setName(Identifier.create(M_PARSE));1272// method.setModifiers(Modifier.PRIVATE | Modifier.STATIC);1273// method.setParameters( new MethodParameter[] {1274// new MethodParameter("input", Type.parse(SAX_INPUT_SOURCE), true), // NOI18N1275// new MethodParameter("recognizer", Type.parse(model.getStub()), true) // NOI18N1276// });1277//1278// String parser = sax == 1 ? "Parser" : "XMLReader"; // NOI18N1279// method.setBody("\n" + // NOI18N1280// JAXP_PACKAGE + "SAXParserFactory factory = " + JAXP_PACKAGE + "SAXParserFactory.newInstance();\n" + // NOI18N1281// "factory.setValidating(true); //the code was generated according DTD\n" + // NOI18N1282// "factory.setNamespaceAware(false); //the code was generated according DTD\n" + // NOI18N1283// parser + " parser = factory.newSAXParser().get" + parser + "();\n" + // NOI18N1284// "parser.set" + (sax == 1 ? "Document" : "Content") + "Handler(recognizer);\n" + // NOI18N1285// "parser.setErrorHandler(recognizer.getDefaultErrorHandler());\n" + // NOI18N1286// "if (recognizer.resolver != null) parser.setEntityResolver(recognizer.resolver);\n" + // NOI18N1287// "parser.parse(input);" + // NOI18N1288// "\n" // NOI18N1289// );1290// method.setExceptions(JAXP_PARSE_EXCEPTIONS);1291//1292// return method;1293// }1294//1295//1296// private MethodElement genSampleErrorHandler() throws SourceException {1297// MethodElement method = new MethodElement();1298//1299// method.setName(Identifier.create("getDefaultErrorHandler")); // NOI18N1300// method.setModifiers(Modifier.PROTECTED);1301// method.setReturn(Type.parse("ErrorHandler")); // NOI18N1302//1303// method.setBody("\n" + // NOI18N1304// "return new ErrorHandler() { \n" + // NOI18N1305// "public void error(SAXParseException ex) throws SAXException {\n" + // NOI18N1306// "if (context.isEmpty()) System.err.println(\"Missing DOCTYPE.\");\n" + // NOI18N1307// "throw ex;\n" + // NOI18N1308// "}\n" + // NOI18N1309// "\n" + // NOI18N1310// "public void fatalError(SAXParseException ex) throws SAXException {\n" + // NOI18N1311// "throw ex;\n" + // NOI18N1312// "}\n" + // NOI18N1313// "\n" + // NOI18N1314// "public void warning(SAXParseException ex) throws SAXException {\n" + // NOI18N1315// "// ignore\n" + // NOI18N1316// "}\n" + // NOI18N1317// "};\n" + // NOI18N1318// "\n" // NOI18N1319// );1320//1321// String docText =1322// "\nCreates default error handler used by this parser.\n" + // NOI18N1323// "@return org.xml.sax.ErrorHandler implementation\n"; //NOI18N1324//1325// method.getJavaDoc().setRawText(docText);1326//1327// return method;1328// }1329//1330// /**1331// * Generate JAXP compatible static method1332// */1333// private MethodElement genJAXP_ParseInputSourceMethod() throws SourceException {1334// MethodElement method = new MethodElement();1335//1336// method.setName(Identifier.create(M_PARSE));1337// method.setModifiers(Modifier.PUBLIC | Modifier.STATIC);1338//1339// if (model.hasParslets()) {1340// method.setParameters( new MethodParameter[] {1341// new MethodParameter("input", Type.parse(SAX_INPUT_SOURCE), true), // NOI18N1342// new MethodParameter("handler", Type.parse(model.getHandler()), true), // NOI18N1343// new MethodParameter("parslet", Type.parse(model.getParslet()), true) // NOI18N1344// });1345// } else {1346// method.setParameters( new MethodParameter[] {1347// new MethodParameter("input", Type.parse(SAX_INPUT_SOURCE), true), // NOI18N1348// new MethodParameter("handler", Type.parse(model.getHandler()), true) // NOI18N1349// });1350// }1351//1352// String parsletParam = model.hasParslets() ? ", parslet" : ""; // NOI18N1353// method.setBody("\n" + // NOI18N1354// M_PARSE + "(input, new " + model.getStub() + "(handler, null" + parsletParam + "));\n" // NOI18N1355// );1356// method.setExceptions(JAXP_PARSE_EXCEPTIONS);1357//1358// JavaDoc jdoc = method.getJavaDoc();1359// jdoc.setRawText("\nThe recognizer entry method taking an Inputsource.\n" + // NOI18N1360// "@param input InputSource to be parsed.\n" + // NOI18N1361// JAXP_PARSE_EXCEPTIONS_DOC1362// );1363// return method;1364// }1365//1366//1367// /**1368// * Generate JAXP compatible static method1369// */1370// private MethodElement genJAXP_ParseURLMethod() throws SourceException {1371// MethodElement method = new MethodElement();1372//1373// method.setName(Identifier.create(M_PARSE));1374// method.setModifiers(Modifier.PUBLIC | Modifier.STATIC);1375//1376// if (model.hasParslets()) {1377// method.setParameters( new MethodParameter[] {1378// new MethodParameter("url", Type.parse("java.net.URL"), true), // NOI18N1379// new MethodParameter("handler", Type.parse(model.getHandler()), true), // NOI18N1380// new MethodParameter("parslet", Type.parse(model.getParslet()), true) // NOI18N1381// });1382// } else {1383// method.setParameters( new MethodParameter[] {1384// new MethodParameter("url", Type.parse("java.net.URL"), true), // NOI18N1385// new MethodParameter("handler", Type.parse(model.getHandler()), true) // NOI18N1386// });1387// }1388//1389// String parsletParam = model.hasParslets() ? ", parslet" : ""; // NOI18N1390// method.setBody(1391// "\n" + M_PARSE + "(new " + SAX_INPUT_SOURCE + "(url.toExternalForm()), handler" + parsletParam + ");\n" // NOI18N1392// );1393// method.setExceptions(JAXP_PARSE_EXCEPTIONS);1394//1395// JavaDoc jdoc = method.getJavaDoc();1396// jdoc.setRawText("\nThe recognizer entry method taking a URL.\n" + // NOI18N1397// "@param url URL source to be parsed.\n" + // NOI18N1398// JAXP_PARSE_EXCEPTIONS_DOC1399// );1400// return method;1401// }1402//1403//1404// /**1405// * Generate dynamic JAXP compatible method1406// */1407// private MethodElement genJAXPParseInputSourceMethod() throws SourceException {1408//1409// MethodElement method = new MethodElement();1410//1411// method.setName(Identifier.create(M_PARSE));1412// method.setModifiers(Modifier.PUBLIC);1413// method.setParameters( new MethodParameter[] {1414// new MethodParameter("input", Type.parse(SAX_INPUT_SOURCE), true) // NOI18N1415// });1416//1417// method.setBody("\n" + M_PARSE + "(input, this);\n"); // NOI18N1418// method.setExceptions(JAXP_PARSE_EXCEPTIONS);1419//1420// JavaDoc jdoc = method.getJavaDoc();1421// jdoc.setRawText("\nThe recognizer entry method taking an InputSource.\n" + // NOI18N1422// "@param input InputSource to be parsed.\n" + // NOI18N1423// JAXP_PARSE_EXCEPTIONS_DOC1424// );1425// return method;1426//1427// }1428//1429// /**1430// * Generate dynamic JAXP compatible method1431// */1432// private MethodElement genJAXPParseURLMethod() throws SourceException {1433//1434// MethodElement method = new MethodElement();1435//1436// method.setName(Identifier.create(M_PARSE));1437// method.setModifiers(Modifier.PUBLIC);1438// method.setParameters( new MethodParameter[] {1439// new MethodParameter("url", Type.parse("java.net.URL"), true) // NOI18N1440// });1441//1442// method.setBody(1443// "\n" + M_PARSE + "(new " + SAX_INPUT_SOURCE + "(url.toExternalForm()), this);\n" // NOI18N1444// );1445// method.setExceptions(JAXP_PARSE_EXCEPTIONS);1446//1447// JavaDoc jdoc = method.getJavaDoc();1448// jdoc.setRawText("\nThe recognizer entry method taking a URL.\n" + // NOI18N1449// "@param url URL source to be parsed.\n" + // NOI18N1450// JAXP_PARSE_EXCEPTIONS_DOC1451// );1452// return method;1453// }1454//1455// //~~~~~~~~~~~~~~~~~~~~ utility methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~1456//1457//1458// /** Create specified field as private. */1459// private static FieldElement createField(String name, String clzz) throws SourceException {1460// FieldElement field = new FieldElement();1461// field.setName(Identifier.create(name));1462// field.setModifiers(Modifier.PRIVATE);1463// field.setType(Type.createClass(Identifier.create(clzz)));1464//1465// return field;1466// }1467//1468// /** Utility method creating common MethodElement. */1469// private static MethodElement createInterfaceMethod (String name, MethodParameter[] params, String exception) throws SourceException {1470// MethodElement method = new MethodElement ();1471// method.setModifiers (Modifier.PUBLIC);1472// method.setReturn (Type.VOID);1473// method.setName (Identifier.create (name));1474// if (params != null)1475// method.setParameters (params);1476// if (exception != null)1477// method.setExceptions (new Identifier[] { org.openide.src.Identifier.create (exception) });1478// method.setBody ("\n"); // NOI18N1479// return method;1480// }1481//1482// /** Utility method creating common implementation MethodElement. */1483// private static MethodElement createImplementationMethod (String name, MethodParameter[] params, String exception) throws SourceException {1484// MethodElement method = createInterfaceMethod(name, params, exception);1485// method.setModifiers(Modifier.PUBLIC | Modifier.FINAL);1486// String docText = "\nThis SAX interface method is implemented by the parser.\n"; // NOI18N1487// method.getJavaDoc().setRawText(docText);1488// return method;1489// }1490//1491// /** Get Schema. */1492// private TreeDTDRoot getDTD () throws IOException, TreeException {1493// if (dtd == null) {1494// TreeDocumentRoot result;1495//1496// TreeEditorCookie cake = (TreeEditorCookie) ((DTDDataObject)DO).getCookie(TreeEditorCookie.class);1497// if (cake != null) {1498// result = cake.openDocumentRoot();1499// } else {1500// throw new TreeException("DTDDataObject:INTERNAL ERROR"); // NOI18N1501// }1502// dtd = (TreeDTDRoot)result;1503// }1504// return dtd;1505// }1506//1507// /**1508// * Return a Identifier of content handler interface in current sax version.1509// */1510// private Identifier getSAXHandlerInterface() {1511// if (sax == 1) {1512// return Identifier.create (SAX_DOCUMENT_HANDLER);1513// } else if (sax == 2) {1514// return Identifier.create (SAX2_CONTENT_HANDLER);1515// } else {1516// return null;1517// }1518// }1519//1520// /**1521// * Return a name of attributes class in current sax version.1522// */1523// private String getSAXAttributes() {1524// if (sax == 1) {1525// return SAX_ATTRIBUTE_LIST;1526// } else if (sax == 2) {1527// return SAX2_ATTRIBUTES;1528// } else {1529// return null;1530// }1531// }1532//1533//1534//1535//1536//1537// /**1538// * A factory of ClassElement producers used in code generation code.1539// * @see generateCode1540// */1541// private interface CodeGenerator {1542//1543// public void generate(SourceElement target) throws SourceException;1544//1545// }1546//1547// private class StubGenerator implements CodeGenerator {1548// private final String name;1549// private final String face;1550// private final String let;1551//1552// StubGenerator(String name, String face, String let) {1553// this.name = name;1554// this.face = face;1555// this.let = let;1556// }1557//1558// public void generate(SourceElement target) throws SourceException {1559// target.addClass(generateStub(name, face, let));1560// }1561// }1562//1563// private class InterfaceGenerator implements CodeGenerator {1564//1565// private final String name;1566//1567// InterfaceGenerator(String name) {1568// this.name = name;1569// }1570//1571// public void generate(SourceElement target) throws SourceException {1572// target.addClass(generateInterface(name));1573// }1574// }1575//1576// private class InterfaceImplGenerator implements CodeGenerator {1577//1578// private final String name;1579//1580// InterfaceImplGenerator(String name) {1581// this.name = name;1582// }1583//1584// public void generate(SourceElement target) throws SourceException {1585// target.addClass(generateInterfaceImpl(name));1586// }1587// }1588//1589// private class ParsletGenerator implements CodeGenerator {1590//1591// private final String name;1592//1593// ParsletGenerator(String name) {1594// this.name = name;1595// }1596//1597// public void generate(SourceElement target) throws SourceException {1598// target.addClass(generateParslet(name));1599// }1600// }1601//1602// private class ParsletImplGenerator implements CodeGenerator {1603//1604// private final String name;1605//1606// ParsletImplGenerator(String name) {1607// this.name = name;1608// }1609//1610// public void generate(SourceElement target) throws SourceException {1611// target.addClass(generateParsletImpl(name));1612// }1613// }16141615}1616