/** Writes the data provenance into xml formatted file */ public void writeXML() throws IOException { FileWriter fw; if (file.exists() == true) { file.delete(); file = new File(fileDir + File.separator + fileName); } try { fw = new FileWriter(file); bw = new BufferedWriter(fw); Vector<XMLAttributes> atVector = new Vector<XMLAttributes>(); bw.write(XML_HEADER); bw.newLine(); bw.write(DATA_PROVENANCE); bw.newLine(); openTag("provenance", true); int numEntries = pHolder.size(); ProvenanceEntry entry; for (int i = 0; i < numEntries; i++) { entry = pHolder.elementAt(i); openTag("processStep", true); atVector.add(new XMLAttributes("version", entry.getMipavVersion())); this.closedTag("program", entry.getProgramName(), atVector); atVector.add(new XMLAttributes("inputs", entry.getProgramInputs())); closedTag("programArguments", entry.getAction(), atVector); closedTag("timeStamp", entry.getTimeStamp()); closedTag("user", entry.getUser()); closedTag("hostName", entry.getHostName()); closedTag("architecture", entry.getArchitecture()); atVector.add(new XMLAttributes("version", entry.getPlatformVersion())); closedTag("platform", entry.getPlatform(), atVector); atVector.add(new XMLAttributes("version", entry.getJavaVersion())); closedTag("compiler", "java", atVector); openTag("processStep", false); } openTag("provenance", false); bw.close(); } catch (Exception e) { System.err.println("CAUGHT EXCEPTION WITHIN writeXML() of FileDataProvenance"); e.printStackTrace(); } }
private void tidyUnicode(String filename) { FileInputStream in = null; FileOutputStream out = null; InputStreamReader reader = null; OutputStreamWriter writer = null; File f0 = new File(filename + "0"); File f1 = new File(filename); f1.renameTo(f0); try { in = new FileInputStream(f0); reader = new InputStreamReader(in); out = new FileOutputStream(f1); writer = new OutputStreamWriter(out); UTF8Tidy u = new UTF8Tidy(reader, writer); u.execute(); } catch (Exception e) { { } // System.out.println("e: " + e ); } } finally { try { reader.close(); writer.close(); } catch (Exception ex) { ex.printStackTrace(); } f0.delete(); } }
public static void main(String[] pArgs) { try { AppConfig appConfig = new AppConfig(new File(pArgs[0])); System.out.println("version: " + appConfig.getAppVersion()); System.out.println("appname: " + appConfig.getAppName()); } catch (Exception e) { e.printStackTrace(System.err); } }
public void parseCPIMString(String body) { try { StringReader stringReader = new StringReader(body); InputSource inputSource = new InputSource(stringReader); saxParser.parse(inputSource); } catch (Exception e) { e.printStackTrace(); } }
/** * Creates an AppConfig using class <code>pAppClass</code> to search for the config file resource. * That class must have a resource file <code>AppConfig.xml</code>. */ private AppConfig(InputSource pInputSource) throws InvalidInputException, DataNotFoundException { try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.parse(pInputSource); mConfigFileDocument = document; } catch (Exception e) { e.printStackTrace(System.err); throw new InvalidInputException("unable to load XML configuration file", e); } }
public TrackDatabase(InputStream is) throws IOException { try { createDOM(); load(is); } catch (Exception e) { e.printStackTrace(); if (!(e instanceof IOException)) throw new IOException(e.toString()); create(); } }
/** * start the parsing * * @param file to parse * @return Vector containing the test cases */ public XMLcpimParser() { try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParser = saxParserFactory.newSAXParser().getXMLReader(); saxParser.setContentHandler(this); saxParser.setFeature("http://xml.org/sax/features/validation", true); // parse the xml specification for the event tags. } catch (Exception e) { e.printStackTrace(); } }
private void create() { try { tracks = new Vector(); hash = new Hashtable(); createDOM(); doc = db.newDocument(); docElt = doc.createElement(docElementName); doc.appendChild(docElt); } catch (Exception e) { e.printStackTrace(); } }
/** * Creates Java Source code (Object model) for the given XML Schema * @param InputSource - the InputSource representing the XML schema. * @param packageName the package for the generated source files **/ public void generateSource(InputSource source, String packageName) { //-- get default parser from Configuration Parser parser = null; try { parser = Configuration.getParser(); } catch(RuntimeException rte) {} if (parser == null) { System.out.println("fatal error: unable to create SAX parser."); return; } SchemaUnmarshaller schemaUnmarshaller = null; try { schemaUnmarshaller = new SchemaUnmarshaller(); } catch (SAXException e) { // can never happen since a SAXException is thrown // when we are dealing with an included schema e.printStackTrace(); } parser.setDocumentHandler(schemaUnmarshaller); parser.setErrorHandler(schemaUnmarshaller); try { parser.parse(source); } catch(java.io.IOException ioe) { System.out.println("error reading XML Schema file"); return; } catch(org.xml.sax.SAXException sx) { Exception except = sx.getException(); if (except == null) except = sx; if (except instanceof SAXParseException) { SAXParseException spe = (SAXParseException)except; System.out.println("SAXParseException: " + spe); System.out.print(" - occured at line "); System.out.print(spe.getLineNumber()); System.out.print(", column "); System.out.println(spe.getColumnNumber()); } else except.printStackTrace(); return; } Schema schema = schemaUnmarshaller.getSchema(); generateSource(schema, packageName); } //-- generateSource
public void parse() { try { // Create SAX Parser factory SAXParserFactory spfactory = SAXParserFactory.newInstance(); // Create SAX Parser SAXParser parser = spfactory.newSAXParser(); // Process XML file by given default handler parser.parse(new ByteArrayInputStream(data.getBytes()), new XMLParseContent(result, data)); // parser.parse(new File("tmp.xml"), new XMLParseRevId(userName,result,data)); } catch (Exception e) { e.printStackTrace(); } }
@Override public VPackage parse() { logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath()); long startParsing = System.currentTimeMillis(); try { Document document = getDocument(); Element root = document.getDocumentElement(); _package = new VPackage(xmlFile); Node name = root.getElementsByTagName(EL_NAME).item(0); _package.setName(name.getTextContent()); Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0); _package.setDescription(descr.getTextContent()); NodeList list = root.getElementsByTagName(EL_CLASS); boolean initPainters = false; for (int i = 0; i < list.getLength(); i++) { PackageClass pc = parseClass((Element) list.item(i)); if (pc.getPainterName() != null) { initPainters = true; } } if (initPainters) { _package.initPainters(); } logger.info( "Parsing the package '{}' finished in {}ms.\n", _package.getName(), (System.currentTimeMillis() - startParsing)); } catch (Exception e) { collector.collectDiagnostic(e.getMessage(), true); if (RuntimeProperties.isLogDebugEnabled()) { e.printStackTrace(); } } try { checkProblems("Error parsing package file " + xmlFile.getName()); } catch (Exception e) { return null; } return _package; }
/** * Main entry point. Expects two arguments: the schema document, and the source document. * * @param args */ public static void main(String[] args) { try { if (args.length != 2) { printUsage(); return; } SchemaFactory schemaFactory; // Set a system property to force selection of the Saxon SchemaFactory implementation System.setProperty( "javax.xml.validation.SchemaFactory:http://www.w3.org/2001/XMLSchema", "com.saxonica.schema.SchemaFactoryImpl"); schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema"); schemaFactory.setErrorHandler(new LocalErrorHandler()); // create a grammar object. Schema schemaGrammar = schemaFactory.newSchema(new File(args[0])); System.err.println("Created Grammar object for schema : " + args[0]); Resolver resolver = new Resolver(); // create a validator to validate against the schema. ValidatorHandler schemaValidator = schemaGrammar.newValidatorHandler(); schemaValidator.setResourceResolver(resolver); schemaValidator.setErrorHandler(new LocalErrorHandler()); schemaValidator.setContentHandler( new LocalContentHandler(schemaValidator.getTypeInfoProvider())); System.err.println("Validating " + args[1] + " against grammar " + args[0]); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); parserFactory.setNamespaceAware(true); SAXParser parser = parserFactory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(schemaValidator); reader.parse(new InputSource(new File(args[1]).toURI().toString())); System.err.println("Validation successful"); } catch (SAXException saxe) { exit(1, "Error: " + saxe.getMessage()); } catch (Exception e) { e.printStackTrace(); exit(2, "Fatal Error: " + e); } }
private int countResults(InputStream s) throws SocketTimeoutException { ResultHandler handler = new ResultHandler(); int count = 0; try { SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser(); // ByteArrayInputStream bis = new ByteArrayInputStream(s.getBytes("UTF-8")); saxParser.parse(s, handler); count = handler.getCount(); } catch (SocketTimeoutException e) { throw new SocketTimeoutException(); } catch (Exception e) { System.err.println("SAX Error"); e.printStackTrace(); return -1; } return count; }
/** * EPML2PNML * * @param args String[] */ private static void EPML2PNML(String[] args) { if (args.length != 2) { System.out.println("���ṩEPML�ļ�·����PNML���Ŀ¼!"); System.exit(-1); } epmlImport epml = new epmlImport(); // load the single epml file String filename = args[0]; try { EPCResult epcRes = (EPCResult) epml.importFile(new FileInputStream(filename)); // convert all epc models to pnml files ArrayList<ConfigurableEPC> alEPCs = epcRes.getAllEPCs(); PnmlExport export = new PnmlExport(); for (ConfigurableEPC epc : alEPCs) { String id = epc.getIdentifier(); if (id.equals("1An_klol") || id.equals("1An_l1y8") || id.equals("1Ex_dzq9") || id.equals("1Ex_e6dx") || id.equals("1Ku_9soy") || id.equals("1Ku_a4cg") || id.equals("1Or_lojl") || id.equals("1Pr_d1ur") || id.equals("1Pr_djki") || id.equals("1Pr_dkfa") || id.equals("1Pr_dl73") || id.equals("1Ve_musj") || id.equals("1Ve_mvwz")) continue; // save pnml files to the same folder File outFile = new File(args[1] + "/" + id + ".pnml"); if (outFile.exists()) continue; FileOutputStream fos = new FileOutputStream(outFile); PetriNet petri = AMLtoPNML.convert(epc); try { export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos); } catch (Exception ex1) { ex1.printStackTrace(System.out); } } } catch (IOException ex) { ex.printStackTrace(System.out); } System.out.println("EPML Conversion Done"); }
/** used for cut and paste. */ public void addObjectFromClipboard(String a_value) throws CircularIncludeException { Reader reader = new StringReader(a_value); Document document = null; try { document = UJAXP.getDocument(reader); } catch (Exception e) { e.printStackTrace(); return; } // try-catch Element root = document.getDocumentElement(); if (!root.getNodeName().equals("clipboard")) { return; } // if Node child; for (child = root.getFirstChild(); child != null; child = child.getNextSibling()) { if (!(child instanceof Element)) { continue; } // if Element element = (Element) child; IGlyphFactory factory = GlyphFactory.getFactory(); if (XModule.isMatch(element)) { EModuleInvoke module = (EModuleInvoke) factory.createXModule(element); addModule(module); continue; } // if if (XContour.isMatch(element)) { EContour contour = (EContour) factory.createXContour(element); addContour(contour); continue; } // if if (XInclude.isMatch(element)) { EIncludeInvoke include = (EIncludeInvoke) factory.createXInclude(element); addInclude(include); continue; } // if } // while }
private File getWorkingDirectory(File f) { try { File workingDir = new File( Properties.get(Names.WORKING_DIR) + Names.PATH_SEPARATOR + getOpType() + Names.PATH_SEPARATOR + "work" + getNewCount()); if (!workingDir.exists()) workingDir.mkdirs(); FileUtil.deleteContents(workingDir); return workingDir; } catch (Exception ignore) { // ++ notify of error - maybe out of disk space ignore.printStackTrace(); return null; } }
public void execute() { try { execExtractor(); tidyUnicode(outputFile); // eliminate invalid unicode Chars XMLReader xr = new SAXParser(); // todo: parameterize the handler DrawingHandler handler = new DrawingHandler(); handler.setGeneratePDFs(getGeneratePDFs()); xr.setContentHandler(handler); xr.setErrorHandler(handler); File xml = new File(outputFile); FileReader r = new FileReader(xml); xr.parse(new InputSource(r)); results = handler.getResults(); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] argv) { try { // SAXパーサーファクトリを生成 SAXParserFactory spfactory = SAXParserFactory.newInstance(); // SAXパーサーを生成 SAXParser parser = spfactory.newSAXParser(); // XMLファイルを指定されたデフォルトハンドラーで処理します String fileName = "dos2unix.mm"; // parser.parse(new File("helloworld.xml"), new HelloWorldSax()); parser.parse(new File(fileName), new HelloWorldSax()); } catch (Exception e) { e.printStackTrace(); } }
public void startElement( String namespaceURI, String lName, // local name String qName, // qualified name Attributes attrs) throws SAXException { element = qName; if (element.compareToIgnoreCase("presence") == 0) { presenceTag = new PresenceTag(); String entity = attrs.getValue("entity").trim(); presenceTag.setEntity(entity); } if (element.compareToIgnoreCase("presentity") == 0) { presentityTag = new PresentityTag(); String id = attrs.getValue("id").trim(); presentityTag.setId(id); } if (element.compareToIgnoreCase("tuple") == 0) { tupleTag = new TupleTag(); String id = attrs.getValue("id").trim(); tupleTag.setId(id); } if (element.compareToIgnoreCase("status") == 0) { statusTag = new StatusTag(); } if (element.compareToIgnoreCase("basic") == 0) { basicTag = new BasicTag(); } if (element.compareToIgnoreCase("contact") == 0) { contactTag = new ContactTag(); String priority = attrs.getValue("priority").trim(); if (priority != null) { try { contactTag.setPriority(Float.parseFloat(priority)); } catch (Exception e) { e.printStackTrace(); } } } if (element.compareToIgnoreCase("note") == 0) { noteTag = new NoteTag(); } }
/** * start the parsing * * @param file to parse * @return Vector containing the test cases */ public XMLcpimParser(String fileLocation) { try { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParser = saxParserFactory.newSAXParser().getXMLReader(); saxParser.setContentHandler(this); saxParser.setFeature("http://xml.org/sax/features/validation", true); // parse the xml specification for the event tags. saxParser.parse(fileLocation); } catch (SAXParseException spe) { spe.printStackTrace(); } catch (SAXException sxe) { sxe.printStackTrace(); } catch (IOException ioe) { // I/O error ioe.printStackTrace(); } catch (Exception pce) { // Parser with specified options can't be built pce.printStackTrace(); } }
public static StringProperty[] initialize(String xmlFile) { FileInputStream fi = null; StaticInitializeSaxHandler handler = null; try { handler = new StaticInitializeSaxHandler(); XMLReader parser = null; parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); parser.setContentHandler(handler); fi = new FileInputStream(xmlFile); parser.parse(new InputSource(new InputStreamReader(fi, "UTF-8"))); } catch (Exception e) { e.printStackTrace(); } finally { if (fi != null) try { fi.close(); } catch (IOException e) { e.printStackTrace(); } } return handler.getProps(); }
private static void AML2PNML(String[] args) { if (args.length != 3) { System.out.println("���ṩAML����Ŀ¼��PNML���Ŀ¼�Լ��ֵ��ļ�!"); System.exit(-1); } System.out.println("����Ŀ¼��" + args[0]); System.out.println("���Ŀ¼��" + args[1]); System.out.println("�ֵ��ļ���" + args[2]); // load the dict AMLtoPNML.loadDict(args[2]); File srcDir = new File(args[0]); File[] lstAML = srcDir.listFiles(); PnmlExport export = new PnmlExport(); for (int i = 0; i < lstAML.length; i++) { if (lstAML[i].isDirectory()) { continue; } System.out.print(lstAML[i].getName() + "==>"); try { FileInputStream fis = new FileInputStream(lstAML[i]); int idx = lstAML[i].getName().indexOf(".xml"); File outFile = new File(args[1] + "/" + lstAML[i].getName().substring(0, idx) + ".pnml"); FileOutputStream fos = new FileOutputStream(outFile); EPCResult epcRes = (EPCResult) AMLtoPNML.importFile(fis); ConfigurableEPC epc = epcRes.getMainEPC(); PetriNet petri = AMLtoPNML.convert(epc); export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos); System.out.println(outFile.getName()); } catch (FileNotFoundException ex) { ex.printStackTrace(System.out); } catch (IOException ioe) { ioe.printStackTrace(System.out); } catch (Exception e) { e.printStackTrace(System.out); } } System.out.println("Conversion Done"); }
public static void main(String[] args) throws IOException { String filename = "z.xml"; // NOT LOCALIZABLE, main try { String uri = "file:" + new File(filename).getAbsolutePath(); // NOT LOCALIZABLE, main // // turn it into an in-memory object. // Parser parser = getParser(); parser.setDocumentHandler(new XmlParser()); parser.setErrorHandler(new MyErrorHandler()); parser.parse(uri); } catch (SAXParseException err) { Debug.trace( "** Parsing error" // NOT LOCALIZABLE, main + ", line " + err.getLineNumber() // NOT LOCALIZABLE + ", uri " + err.getSystemId()); // NOT LOCALIZABLE Debug.trace(" " + err.getMessage()); } catch (SAXException e) { Exception x = e; if (e.getException() != null) x = e.getException(); x.printStackTrace(); } catch (Throwable t) { t.printStackTrace(); } byte[] buf = new byte[256]; Debug.trace("Press ENTER to exit."); // NOT LOCALIZABLE System.in.read(buf, 0, 256); System.exit(0); }
/** The main entry point */ public static void main(String[] args) throws FileNotFoundException, IOException { String xmlfile = null; int debug = 0; int maxErrs = 10; boolean nsAware = true; boolean validating = true; boolean showWarnings = (debug > 2); boolean showErrors = true; Vector catalogFiles = new Vector(); for (int i = 0; i < args.length; i++) { if (args[i].equals("-c")) { ++i; catalogFiles.add(args[i]); continue; } if (args[i].equals("-w")) { validating = false; continue; } if (args[i].equals("-v")) { validating = true; continue; } if (args[i].equals("-n")) { nsAware = false; continue; } if (args[i].equals("-N")) { nsAware = true; continue; } if (args[i].equals("-d")) { ++i; String debugstr = args[i]; try { debug = Integer.parseInt(debugstr); if (debug >= 0) { Debug.setDebug(debug); showWarnings = (debug > 2); } } catch (Exception e) { // nop } continue; } if (args[i].equals("-E")) { ++i; String errstr = args[i]; try { int errs = Integer.parseInt(errstr); if (errs >= 0) { maxErrs = errs; } } catch (Exception e) { // nop } continue; } xmlfile = args[i]; } if (xmlfile == null) { System.out.println("Usage: org.apache.xml.resolver.apps.xread [opts] xmlfile"); System.exit(1); } ResolvingXMLReader reader = new ResolvingXMLReader(); try { reader.setFeature("http://xml.org/sax/features/namespaces", nsAware); reader.setFeature("http://xml.org/sax/features/validation", validating); } catch (SAXException e) { // nop; } Catalog catalog = reader.getCatalog(); for (int count = 0; count < catalogFiles.size(); count++) { String file = (String) catalogFiles.elementAt(count); catalog.parseCatalog(file); } XParseError xpe = new XParseError(showErrors, showWarnings); xpe.setMaxMessages(maxErrs); reader.setErrorHandler(xpe); String parseType = validating ? "validating" : "well-formed"; String nsType = nsAware ? "namespace-aware" : "namespace-ignorant"; if (maxErrs > 0) { System.out.println("Attempting " + parseType + ", " + nsType + " parse"); } Date startTime = new Date(); try { reader.parse(xmlfile); } catch (SAXException sx) { System.out.println("SAX Exception: " + sx); } catch (Exception e) { e.printStackTrace(); } Date endTime = new Date(); long millisec = endTime.getTime() - startTime.getTime(); long secs = 0; long mins = 0; long hours = 0; if (millisec > 1000) { secs = millisec / 1000; millisec = millisec % 1000; } if (secs > 60) { mins = secs / 60; secs = secs % 60; } if (mins > 60) { hours = mins / 60; mins = mins % 60; } if (maxErrs > 0) { System.out.print("Parse "); if (xpe.getFatalCount() > 0) { System.out.print("failed "); } else { System.out.print("succeeded "); System.out.print("("); if (hours > 0) { System.out.print(hours + ":"); } if (hours > 0 || mins > 0) { System.out.print(mins + ":"); } System.out.print(secs + "." + millisec); System.out.print(") "); } System.out.print("with "); int errCount = xpe.getErrorCount(); int warnCount = xpe.getWarningCount(); if (errCount > 0) { System.out.print(errCount + " error"); System.out.print(errCount > 1 ? "s" : ""); System.out.print(" and "); } else { System.out.print("no errors and "); } if (warnCount > 0) { System.out.print(warnCount + " warning"); System.out.print(warnCount > 1 ? "s" : ""); System.out.print("."); } else { System.out.print("no warnings."); } System.out.println(""); } if (xpe.getErrorCount() > 0) { System.exit(1); } }
/** * Process one file. * * <p>\u0040param xmlFileName Input file name to check for part of speech/lemma mismatches.. */ protected static void processOneFile(String xmlFileName) { try { // Report document being processed. System.out.println( "(" + ++currentDocNumber + "/" + docsToProcess + ") " + "processing " + xmlFileName); // Create filter to strip <w> and <c> // elements. XMLFilter filter = new StripAllWordElementsFilter(XMLReaderFactory.createXMLReader()); // Strip path from input file name. String strippedFileName = FileNameUtils.stripPathName(xmlFileName); strippedFileName = FileNameUtils.changeFileExtension(strippedFileName, ""); // Generate output file name. String xmlOutputFileName = new File(outputDirectoryName, strippedFileName + ".xml").getAbsolutePath(); // Make sure output directory exists. FileUtils.createPathForFile(xmlOutputFileName); // Copy input xml to output xml, // stripping <w> and <c> elements. new FilterAdornedFile(xmlFileName, xmlOutputFileName, filter); // Read it back and fix spacing. String fixedXML = FileUtils.readTextFile(xmlOutputFileName, "utf-8"); fixedXML = fixedXML.replaceAll("(\\s+)", " "); fixedXML = fixedXML.replaceAll(" ([\\.?!,;:\\)])", "\u00241"); fixedXML = fixedXML.replaceAll("\\( ", "("); fixedXML = fixedXML.replaceAll("\u00b6 ", "\u00b6"); fixedXML = fixedXML.replaceAll("__NS1:", ""); fixedXML = fixedXML.replaceAll("__NS1", ""); /* fixedXML = fixedXML.replaceAll ( "</__NS1:" , "" ); */ // Emit unadorned XML. SAXBuilder builder = new SAXBuilder(); Document document = builder.build(new StringReader(fixedXML)); new AdornedXMLWriter(document, xmlOutputFileName); } catch (Exception e) { System.out.println(" Error: " + e.getMessage()); e.printStackTrace(); } }
public void addPackageClass(PackageClass pClass) { Document doc; try { doc = getDocument(); } catch (Exception e) { e.printStackTrace(); return; } String name = pClass.getName(); // check if such class exists and remove duplicates Element rootEl = doc.getDocumentElement(); NodeList classEls = rootEl.getElementsByTagName(EL_CLASS); for (int i = 0; i < classEls.getLength(); i++) { Element nameEl = getElementByName((Element) classEls.item(i), EL_NAME); if (name.equals(nameEl.getTextContent())) { rootEl.removeChild(classEls.item(i)); } } Element classNode = doc.createElement(EL_CLASS); doc.getDocumentElement().appendChild(classNode); classNode.setAttribute(ATR_TYPE, PackageClass.ComponentType.SCHEME.getXmlName()); classNode.setAttribute(ATR_STATIC, "false"); Element className = doc.createElement(EL_NAME); className.setTextContent(name); classNode.appendChild(className); Element desrc = doc.createElement(EL_DESCRIPTION); desrc.setTextContent(pClass.getDescription()); classNode.appendChild(desrc); Element icon = doc.createElement(EL_ICON); icon.setTextContent(pClass.getIcon()); classNode.appendChild(icon); // graphics classNode.appendChild(generateGraphicsNode(doc, pClass.getGraphics())); // ports List<Port> ports = pClass.getPorts(); if (!ports.isEmpty()) { Element portsEl = doc.createElement(EL_PORTS); classNode.appendChild(portsEl); for (Port port : ports) { portsEl.appendChild(generatePortNode(doc, port)); } } // fields Collection<ClassField> fields = pClass.getFields(); if (!fields.isEmpty()) { Element fieldsEl = doc.createElement(EL_FIELDS); classNode.appendChild(fieldsEl); for (ClassField cf : fields) { fieldsEl.appendChild(generateFieldNode(doc, cf)); } } // write try { writeDocument(doc, new FileOutputStream(xmlFile)); } catch (FileNotFoundException e) { e.printStackTrace(); } }
public void actionPerformed(ActionEvent e) { JButton b = (JButton) e.getSource(); if (b.getText() == "PLAY") { if (scoreP != null) scoreP.playScale(sp.getScale(), tempoP.getValue()); } else if (b.getText() == "New") { try { saveUnsaved(); } catch (SaveAbortedException ex) { return; } sp.notes.removeAllElements(); sp.repaint(); nameTF.setText(""); loadedFile = null; } else if (b.getText() == "Save") { if (nameTF.getText().equals("")) { JOptionPane.showMessageDialog( this, new JLabel("Please type in the Scale Name"), "Warning", JOptionPane.WARNING_MESSAGE); return; } fileChooser.setFileFilter(filter); int option = fileChooser.showSaveDialog(this); if (option == JFileChooser.APPROVE_OPTION) { File target = fileChooser.getSelectedFile(); if (target.getName().indexOf(".scl") == -1) target = new File(target.getPath() + ".scl"); try { PrintStream stream = new PrintStream(new FileOutputStream(target), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } } else if (b.getText() == "Load") { try { saveUnsaved(); } catch (SaveAbortedException ex) { return; } fileChooser.setFileFilter(filter); int option = fileChooser.showOpenDialog(this); if (option == JFileChooser.APPROVE_OPTION) { loadedFile = fileChooser.getSelectedFile(); SAXParserFactory factory = SAXParserFactory.newInstance(); ScaleParser handler = new ScaleParser(false); try { SAXParser parser = factory.newSAXParser(); parser.parse(loadedFile, handler); // System.out.println("success"); } catch (Exception ex) { // System.out.println("no!!!!!! exception: "+e); // System.out.println(ex.getMessage()); ex.printStackTrace(); } // -----now :P:P--------------- System.out.println("name: " + handler.getName()); nameTF.setText(handler.getName()); sp.notes.removeAllElements(); int[] scale = handler.getScale(); for (int i = 0; i < scale.length; i++) { sp.addNote(scale[i]); } sp.repaint(); } else loadedFile = null; } }
/** * Format this XML data as a String. * * @webref xml:method * @brief Formats XML data as a String * @param indent -1 for a single line (and no declaration), >= 0 for indents and newlines * @return the content * @see XML#toString() */ public String format(int indent) { try { // entities = doctype.getEntities() boolean useIndentAmount = false; TransformerFactory factory = TransformerFactory.newInstance(); if (indent != -1) { try { factory.setAttribute("indent-number", indent); } catch (IllegalArgumentException e) { useIndentAmount = true; } } Transformer transformer = factory.newTransformer(); // Add the XML declaration at the top if this node is the root and we're // not writing to a single line (indent = -1 means single line). if (indent == -1 || parent == null) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } else { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); } // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "sample.dtd"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes"); // huh? // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, // "-//W3C//DTD XHTML 1.0 Transitional//EN"); // transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, // "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"); // For Android, because (at least 2.3.3) doesn't like indent-number if (useIndentAmount) { transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent)); } // transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); // transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS // Always indent, otherwise the XML declaration will just be jammed // onto the first line with the XML code as well. transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // Properties p = transformer.getOutputProperties(); // for (Object key : p.keySet()) { // System.out.println(key + " -> " + p.get(key)); // } // If you smell something, that's because this code stinks. No matter // the settings of the Transformer object, if the XML document already // has whitespace elements, it won't bother re-indenting/re-formatting. // So instead, transform the data once into a single line string. // If indent is -1, then we're done. Otherwise re-run and the settings // of the factory will kick in. If you know a better way to do this, // please contribute. I've wasted too much of my Sunday on it. But at // least the Giants are getting blown out by the Falcons. final String decl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; final String sep = System.getProperty("line.separator"); StringWriter tempWriter = new StringWriter(); StreamResult tempResult = new StreamResult(tempWriter); transformer.transform(new DOMSource(node), tempResult); String[] tempLines = PApplet.split(tempWriter.toString(), sep); // PApplet.println(tempLines); if (tempLines[0].startsWith("<?xml")) { // Remove XML declaration from the top before slamming into one line int declEnd = tempLines[0].indexOf("?>") + 2; // if (tempLines[0].length() == decl.length()) { if (tempLines[0].length() == declEnd) { // If it's all the XML declaration, remove it // PApplet.println("removing first line"); tempLines = PApplet.subset(tempLines, 1); } else { // PApplet.println("removing part of first line"); // If the first node has been moved to this line, be more careful // tempLines[0] = tempLines[0].substring(decl.length()); tempLines[0] = tempLines[0].substring(declEnd); } } String singleLine = PApplet.join(PApplet.trim(tempLines), ""); if (indent == -1) { return singleLine; } // Might just be whitespace, which won't be valid XML for parsing below. // https://github.com/processing/processing/issues/1796 // Since indent is not -1, that means they want valid XML, // so we'll give them the single line plus the decl... Lame? sure. if (singleLine.trim().length() == 0) { // You want whitespace? I've got your whitespace right here. return decl + sep + singleLine; } // Since the indent is not -1, bring back the XML declaration // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); StringWriter stringWriter = new StringWriter(); StreamResult xmlOutput = new StreamResult(stringWriter); // DOMSource source = new DOMSource(node); Source source = new StreamSource(new StringReader(singleLine)); transformer.transform(source, xmlOutput); String outgoing = stringWriter.toString(); // Add the XML declaration to the top if it's not there already if (outgoing.startsWith(decl)) { int declen = decl.length(); int seplen = sep.length(); if (outgoing.length() > declen + seplen && !outgoing.substring(declen, declen + seplen).equals(sep)) { // make sure there's a line break between the XML decl and the code return outgoing.substring(0, decl.length()) + sep + outgoing.substring(decl.length()); } return outgoing; } else { return decl + sep + outgoing; } } catch (Exception e) { e.printStackTrace(); } return null; }