public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws ParserException { Caller targeting = (Caller) targetMap.get(qName); if (null == targeting) throw new ParserException("No target found for tag: " + qName + "!"); targeting = (Caller) targeting.duplicate(); XMLOp actor = (XMLOp) actionMap.get(qName); if (null == actor) throw new ParserException("No action found for tag: " + qName + "!"); if (null == targeting.getTargetObject() && 0 < stack.size()) { Caller parent = null; try { parent = (Caller) stack.peek(); } catch (Exception e) { throw new ParserException( "Typecast exception, unknown object placed in stack! " + e.getMessage()); } Object targetObject = parent.parameter(0); int idx = stack.indexOf(parent); // climb stack for next available parent (stack may have no-ops in it. while (null == targetObject && 0 < idx) { { } // System.out.println("Climbing stack for next available parent.."); try { parent = (Caller) stack.get(--idx); } catch (Exception e) { throw new ParserException( "Typecast exception, unknown object placed in stack! " + e.getMessage()); } targetObject = parent.parameter(0); } targeting.setTargetObject(targetObject); } Object o; try { actor.initialize(attributeMap(qName, atts)); o = actor.process(); } catch (Exception e) { try { actor.initialize(attributeMap(qName, atts)); o = actor.process(); } catch (Exception r) { throw new ParserException( "Could not execute action for tag: " + qName + "! " + e.getMessage()); } } targeting.resetParameters(new Object[] {o}); stack.push(targeting); }
private static SAXParserFactory createFastSAXParserFactory() throws ParserConfigurationException, SAXException { if (fastParserFactoryClass == null) { try { fastParserFactoryClass = Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl"); // NOI18N } catch (Exception ex) { useFastSAXParserFactory = false; if (System.getProperty("java.version").startsWith("1.4")) { // NOI18N ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex); } } } if (fastParserFactoryClass != null) { try { SAXParserFactory factory = (SAXParserFactory) fastParserFactoryClass.newInstance(); return factory; } catch (Exception ex) { useFastSAXParserFactory = false; throw new ParserConfigurationException(ex.getMessage()); } } return SAXParserFactory.newInstance(); }
/** * This creates an empty <code>Document</code> object based on a specific parser implementation. * * @return <code>Document</code> - created DOM Document. * @throws JDOMException when errors occur. */ public Document createDocument() throws JDOMException { try { return (Document) Class.forName("org.apache.xerces.dom.DocumentImpl").newInstance(); } catch (Exception e) { throw new JDOMException( e.getClass().getName() + ": " + e.getMessage() + " when creating document", e); } }
private Map attributeMap(String tagName, Attributes atts) throws ParserException { if (null == tagName || null == atts) return null; Map mapping = null; try { mapping = (Map) attributeMaps.get(tagName); } catch (Exception e) { throw new ParserException( "Typecast error, unknown element found in attribute list mappings! " + e.getMessage()); } if (null == mapping) return null; Map resultMapping = new HashMap(); for (int i = 0; i < atts.getLength(); i++) { String xmlName = atts.getQName(i); String value = atts.getValue(i); TagMap.AttributeMapping aMap = null; try { aMap = (TagMap.AttributeMapping) mapping.get(xmlName); } catch (Exception e) { throw new ParserException( "Typecast error, unknown element found in property mapping! " + e.getMessage()); } if (null == aMap) throw new ParserException( "No attribute mapping specified for attribute: " + xmlName + " in tag: " + tagName); String propertyName = aMap.getPropertyName(); try { resultMapping.put(propertyName, aMap.convertValue(value)); } catch (Exception e) { throw new ParserException( "Can not convert given value: \"" + value + "\" to specified type: " + aMap.getType() + " for attribute: " + xmlName + " in tag: " + tagName + "! " + e.getMessage()); } } checkForRequiredAttributes(tagName, resultMapping, mapping); addDefaultValues(resultMapping, mapping); return resultMapping; }
public void endElement(String namespaceURI, String localName, String qName) throws ParserException { { } // System.out.println("end Element"); Caller targeting = (Caller) stack.pop(); try { targeting.process(); } catch (Exception e) { throw new ParserException("Could not place " + qName + " into system!\n" + e.getMessage()); } }
/** * This creates a new <code>{@link Document}</code> from an existing <code>InputStream</code> by * letting a DOM parser handle parsing using the supplied stream. * * @param in <code>InputStream</code> to parse. * @param validate <code>boolean</code> to indicate if validation should occur. * @return <code>Document</code> - instance ready for use. * @throws IOException when I/O error occurs. * @throws JDOMException when errors occur in parsing. */ public Document getDocument(InputStream in, boolean validate) throws IOException, JDOMException { try { // Load the parser class Class parserClass = Class.forName("org.apache.xerces.parsers.DOMParser"); Object parser = parserClass.newInstance(); // Set validation Method setFeature = parserClass.getMethod("setFeature", new Class[] {java.lang.String.class, boolean.class}); setFeature.invoke( parser, new Object[] {"http://xml.org/sax/features/validation", new Boolean(validate)}); // Set namespaces true setFeature.invoke( parser, new Object[] {"http://xml.org/sax/features/namespaces", new Boolean(true)}); // Set the error handler if (validate) { Method setErrorHandler = parserClass.getMethod("setErrorHandler", new Class[] {ErrorHandler.class}); setErrorHandler.invoke(parser, new Object[] {new BuilderErrorHandler()}); } // Parse the document Method parse = parserClass.getMethod("parse", new Class[] {org.xml.sax.InputSource.class}); parse.invoke(parser, new Object[] {new InputSource(in)}); // Get the Document object Method getDocument = parserClass.getMethod("getDocument", null); Document doc = (Document) getDocument.invoke(parser, null); return doc; } catch (InvocationTargetException e) { Throwable targetException = e.getTargetException(); if (targetException instanceof org.xml.sax.SAXParseException) { SAXParseException parseException = (SAXParseException) targetException; throw new JDOMException( "Error on line " + parseException.getLineNumber() + " of XML document: " + parseException.getMessage(), e); } else if (targetException instanceof IOException) { IOException ioException = (IOException) targetException; throw ioException; } else { throw new JDOMException(targetException.getMessage(), e); } } catch (Exception e) { throw new JDOMException(e.getClass().getName() + ": " + e.getMessage(), e); } }
@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; }
public static void runScript(Script script, int scriptType) { if (scriptType == SHUTDOWN_SCRIPT) { try { script.process(); } catch (Exception e) { System.out.println(e.getMessage()); } } else { // Create a new Thread ScriptThread scriptThread = new ScriptThread(script, scriptType); // Run the Thread scriptThread.start(); } }
/** * Main program. * * <p>\u0040param args Program parameters. */ public static void main(String[] args) { // Initialize. try { if (!initialize(args)) { System.exit(1); } // Process all files. long startTime = System.currentTimeMillis(); int filesProcessed = processFiles(args); long processingTime = (System.currentTimeMillis() - startTime + 999) / 1000; // Terminate. terminate(filesProcessed, processingTime); } catch (Exception e) { System.out.println(e.getMessage()); } }
private boolean importRecord(DataRecord r, ArrayList<String> fieldsInInport) { try { if (Logger.isDebugLogging()) { Logger.log(Logger.DEBUG, Logger.MSG_DEBUG_DATA, "importing " + r.toString()); } DataRecord[] otherVersions = null; if (importMode.equals(IMPORTMODE_ADD) && logbookEntryNoHandling != null && logbookEntryNoHandling.equals(ENTRYNO_ALWAYS_ADDEND)) { // determine new EntryId for logbook r.set(keyFields[0], ((Logbook) storageObject).getNextEntryNo()); } if (isLogbook && (importMode.equals(IMPORTMODE_ADD) || importMode.equals(IMPORTMODE_ADDUPD))) { LogbookRecord lr = ((LogbookRecord) r); if (lr.getEntryId() == null || !lr.getEntryId().isSet() || lr.getEntryId().toString().length() == 0) { r.set(keyFields[0], ((Logbook) storageObject).getNextEntryNo()); } } DataKey key = r.getKey(); if (key.getKeyPart1() == null || overrideKeyField != null) { // first key field is *not* set, or we're overriding the default key field DataKey[] keys = null; if (overrideKeyField == null) { // -> search for record by QualifiedName keys = dataAccess.getByFields( r.getQualifiedNameFields(), r.getQualifiedNameValues(r.getQualifiedName()), (versionized ? validAt : -1)); } else { // -> search for record by user-specified key field keys = dataAccess.getByFields( new String[] {overrideKeyField}, new String[] {r.getAsString(overrideKeyField)}, (versionized ? validAt : -1)); } if (keys != null && keys.length > 0) { for (int i = 0; i < keyFields.length; i++) { if (!keyFields[i].equals(DataRecord.VALIDFROM)) { r.set(keyFields[i], keys[0].getKeyPart(i)); } } } else { for (int i = 0; i < keyFields.length; i++) { if (!keyFields[i].equals(DataRecord.VALIDFROM) && r.get(keyFields[i]) == null) { if (dataAccess.getMetaData().getFieldType(keyFields[i]) == IDataAccess.DATA_UUID) { r.set(keyFields[i], UUID.randomUUID()); } else { logImportFailed(r, "KeyField(s) not set", null); return false; } } } } } key = r.getKey(); if (versionized) { otherVersions = dataAccess.getValidAny(key); } else { DataRecord r1 = dataAccess.get(key); otherVersions = (r1 != null ? new DataRecord[] {r1} : null); } if (importMode.equals(IMPORTMODE_ADD) && otherVersions != null && otherVersions.length > 0 && logbookEntryNoHandling != null && logbookEntryNoHandling.equals(ENTRYNO_DUPLICATE_ADDEND)) { r.set(keyFields[0], ((Logbook) storageObject).getNextEntryNo()); otherVersions = null; } if (importMode.equals(IMPORTMODE_ADD)) { if (otherVersions != null && otherVersions.length > 0) { logImportFailed(r, International.getString("Datensatz existiert bereits"), null); return false; } else { addRecord(r); return true; } } if (importMode.equals(IMPORTMODE_UPD)) { if (otherVersions == null || otherVersions.length == 0) { logImportFailed(r, International.getString("Datensatz nicht gefunden"), null); return false; } else { updateRecord(r, fieldsInInport); return true; } } if (importMode.equals(IMPORTMODE_ADDUPD)) { if (otherVersions != null && otherVersions.length > 0) { updateRecord(r, fieldsInInport); } else { addRecord(r); } return true; } } catch (Exception e) { logImportFailed(r, e.getMessage(), e); } return false; }
/** * 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 saveUnsaved() throws SaveAbortedException { if (!saved) { int option = 0; if (loadedFile == null) option = JOptionPane.showConfirmDialog( this, new JLabel("Save changes to UNTITLED?"), "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); else option = JOptionPane.showConfirmDialog( this, new JLabel("Save changes to " + loadedFile.getName() + "?"), "Warning", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); if (option == JOptionPane.YES_OPTION) { if (loadedFile == null) // SAVE NEW FILE { if (nameTF.getText().equals("")) { JOptionPane.showMessageDialog( this, new JLabel("Please type in the Scale Name"), "Warning", JOptionPane.WARNING_MESSAGE); throw new SaveAbortedException(); } fileChooser.setFileFilter(filter); int option2 = fileChooser.showSaveDialog(this); if (option2 == JFileChooser.APPROVE_OPTION) { File target = fileChooser.getSelectedFile(); 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 throw new SaveAbortedException(); ; } else // save LOADED FILE { try { PrintStream stream = new PrintStream(new FileOutputStream(loadedFile), true); save(stream); stream.close(); } catch (Exception ex) { JOptionPane.showMessageDialog( this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE); } } } else if (option == JOptionPane.CANCEL_OPTION) throw new SaveAbortedException(); ; } }
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; } }
private TypedValues guessUntypedValue(String name, String value) { TypedValues list = new TypedValues(name); if (value.startsWith("java:")) { // possible java static reference int dot; if (value.equals("java:null")) { list.add(new TypedValue(Object.class, null)); } else if (value.charAt(5) == '$') { // reference to a local object (assemble @id) ElementInfo element = _local.get(value.substring(6)); if (element != null) { list.add(new TypedValue(element.type, element.data)); } } else if ((dot = value.lastIndexOf('.')) > 5) { try { // public static refernce? (don't override access control) _logger.fine("public static refernce? " + value); Object object = Class.forName(value.substring(5, dot)).getField(value.substring(dot + 1)).get(null); Class<?> type = object.getClass(); list.add(new TypedValue(type, object)); // automatic upscaling to larger types if (type == Byte.class) { object = new Short(((Byte) object).byteValue()); list.add(new TypedValue(Short.class, object)); type = Short.class; } if (type == Short.class) { object = new Integer(((Short) object).shortValue()); list.add(new TypedValue(Integer.class, object)); type = Integer.class; } if (type == Integer.class) { object = new Long(((Integer) object).intValue()); list.add(new TypedValue(Long.class, object)); type = Long.class; } if (type == Long.class) { object = new Float(((Long) object).longValue()); list.add(new TypedValue(Float.class, object)); type = Float.class; } if (type == Float.class) { object = new Double(((Float) object).floatValue()); list.add(new TypedValue(Double.class, object)); } } catch (Exception x) { _logger.fine(value + " looked like a static reference but is not: " + x.getMessage()); // class reference? guessClassReference(list, value.substring(5)); } } else { // no '.' at all // class reference? guessClassReference(list, value.substring(5)); } } else if (value.equals("true")) { list.add(new TypedValue(Boolean.class, Boolean.TRUE)); } else if (value.equals("false")) { list.add(new TypedValue(Boolean.class, Boolean.FALSE)); } else { // numbers? multiple possibilities try { list.add(new TypedValue(Integer.class, Integer.valueOf(value))); } catch (Exception x) { } try { list.add(new TypedValue(Long.class, Long.valueOf(value))); } catch (Exception x) { } try { list.add(new TypedValue(Float.class, Float.valueOf(value))); } catch (Exception x) { } try { list.add(new TypedValue(Double.class, Double.valueOf(value))); } catch (Exception x) { } } // always try String as the last resort list.add(new TypedValue(String.class, value)); return list; }