Example #1
0
  /**
   * Create a SAX parser from the JAXP factory. The result can be used to parse XML files.
   *
   * <p>See class Javadoc for hints on setting an entity resolver. This parser has its entity
   * resolver set to the system entity resolver chain.
   *
   * @param validate if true, a validating parser is returned
   * @param namespaceAware if true, a namespace aware parser is returned
   * @throws FactoryConfigurationError Application developers should never need to directly catch
   *     errors of this type.
   * @throws SAXException if a parser fulfilling given parameters can not be created
   * @return XMLReader configured according to passed parameters
   */
  public static XMLReader createXMLReader(boolean validate, boolean namespaceAware)
      throws SAXException {

    SAXParserFactory factory;
    if (!validate && useFastSAXParserFactory) {
      try {
        factory = createFastSAXParserFactory();
      } catch (ParserConfigurationException ex) {
        factory = SAXParserFactory.newInstance();
      } catch (SAXException ex) {
        factory = SAXParserFactory.newInstance();
      }
    } else {
      useFastSAXParserFactory = false;
      factory = SAXParserFactory.newInstance();
    }

    factory.setValidating(validate);
    factory.setNamespaceAware(namespaceAware);

    try {
      return factory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
      throw new SAXException(
          "Cannot create parser satisfying configuration parameters", ex); // NOI18N
    }
  }
 Parser(String uri) {
   try {
     SAXParserFactory parserFactory = SAXParserFactory.newInstance();
     SAXParser parser = parserFactory.newSAXParser();
     ConfigHandler handler = new ConfigHandler();
     parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", true);
     parser.parse(new File(uri), handler);
   } catch (IOException e) {
     System.out.println("Error reading URI: " + e.getMessage());
   } catch (SAXException e) {
     System.out.println("Error in parsing: " + e.getMessage());
   } catch (ParserConfigurationException e) {
     System.out.println("Error in XML parser configuration: " + e.getMessage());
   }
   // System.out.println("Number of Persons : " + Person.numberOfPersons());
   // nameLengthStatistics();
   // System.out.println("Number of Publications with authors/editors: " +
   //                   Publication.getNumberOfPublications());
   // System.out.println("Maximum number of authors/editors in a publication: " +
   //                           Publication.getMaxNumberOfAuthors());
   // publicationCountStatistics();
   // Person.enterPublications();
   // Person.printCoauthorTable();
   // Person.printNamePartTable();
   // Person.findSimilarNames();
 }
Example #3
0
  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();
  }
  public static void main(String argv[]) {
    if (argv.length != 3) {
      System.err.println(
          "Usage: java -server TestSAXOutput <xml file> <times to parse> <output file>");
      System.exit(-1);
    }

    String xmlFile = argv[0];
    int times = (new Integer(argv[1])).intValue();
    outFileName = argv[2];

    try {

      SAXParserFactory factory = SAXParserFactory.newInstance();
      SAXParser parser = factory.newSAXParser();
      TestSAXOutput tsp = new TestSAXOutput();
      for (int i = 0; i < times; i++) {
        parser.parse(xmlFile, tsp);
      }
    } catch (FactoryConfigurationError e) {
      System.err.print("factory configuration error:\n" + e);
    } catch (ParserConfigurationException e) {
      System.err.print("parser configuration error:\n" + e);
    } catch (SAXException e) {
      System.err.print("sax configuration error:\n" + e);
    } catch (IOException e) {
      System.err.print("io error:\n" + e);
    }
  }
Example #5
0
 private void readCommentTemplates(InputStream stream) throws IOException, TeamException {
   try {
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser parser = factory.newSAXParser();
     parser.parse(new InputSource(stream), new CommentTemplatesContentHandler());
   } catch (SAXException ex) {
     IStatus status =
         new CVSStatus(
             IStatus.ERROR,
             CVSStatus.ERROR,
             NLS.bind(
                 CVSUIMessages.RepositoryManager_parsingProblem,
                 new String[] {COMMENT_TEMPLATES_FILE}),
             ex);
     throw new CVSException(status);
   } catch (ParserConfigurationException ex) {
     IStatus status =
         new CVSStatus(
             IStatus.ERROR,
             CVSStatus.ERROR,
             NLS.bind(
                 CVSUIMessages.RepositoryManager_parsingProblem,
                 new String[] {COMMENT_TEMPLATES_FILE}),
             ex);
     throw new CVSException(status);
   }
 }
Example #6
0
 private void readState(InputStream stream) throws IOException, TeamException {
   try {
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser parser = factory.newSAXParser();
     parser.parse(new InputSource(stream), new RepositoriesViewContentHandler(this));
   } catch (SAXException ex) {
     IStatus status =
         new CVSStatus(
             IStatus.ERROR,
             CVSStatus.ERROR,
             NLS.bind(
                 CVSUIMessages.RepositoryManager_parsingProblem,
                 new String[] {REPOSITORIES_VIEW_FILE}),
             ex);
     throw new CVSException(status);
   } catch (ParserConfigurationException ex) {
     IStatus status =
         new CVSStatus(
             IStatus.ERROR,
             CVSStatus.ERROR,
             NLS.bind(
                 CVSUIMessages.RepositoryManager_parsingProblem,
                 new String[] {REPOSITORIES_VIEW_FILE}),
             ex);
     throw new CVSException(status);
   }
 }
Example #7
0
  public static void main(String[] args)
      throws SAXException, IOException, ParserConfigurationException {
    FileInputStream input = new FileInputStream("pages_current.xml");

    SAXParser xmlParser = SAXParserFactory.newInstance().newSAXParser();

    DefaultHandler handler = new RecipeParseHandler();

    xmlParser.parse(input, handler);
  }
 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();
   }
 }
Example #9
0
  public void init() throws LagoonException {
    try {
      spf = SAXParserFactory.newInstance();
      spf.setNamespaceAware(true);
      spf.setValidating(false);
      spf.setFeature("http://xml.org/sax/features/namespaces", true);
      spf.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
      spf.setFeature("http://xml.org/sax/features/validation", false);
    } catch (ParserConfigurationException e) {
      throw new Error("Unable to configure XML parser");
    } catch (SAXException e) {
      throw new Error("Unable to configure XML parser");
    }

    target = null;
  }
 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;
 }
Example #11
0
  private static SAXParserFactory makeParserFactory(boolean validating, boolean ns) {
    SAXParserFactory factory = null;

    // create factory according to javax.xml.parsers.SAXParserFactory property
    // or platform default (i.e. com.sun...)
    try {
      factory = SAXParserFactory.newInstance();
      factory.setValidating(validating);
      factory.setNamespaceAware(ns);

    } catch (FactoryConfigurationError err) {
      notifyFactoryErr(err, "javax.xml.parsers.SAXParserFactory"); // NOI18N
      throw err;
    }

    return factory;
  }
Example #12
0
  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();
    }
  }
Example #13
0
 protected static SAXParser getParser(boolean validate)
     throws SAXException, ParserConfigurationException {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   factory.setValidating(validate);
   return factory.newSAXParser();
 }
  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;
    }
  }
Example #15
0
  public static void main(String args[]) {

    if (args.length < 3) {
      System.err.println("Usage: Generate model-file ( -s length | -c count length )");
      System.exit(1);
    }

    try {
      SAXParserFactory saxFactory = SAXParserFactory.newInstance();
      saxFactory.setNamespaceAware(true);
      SAXParser saxParser = saxFactory.newSAXParser();
      XMLReader xmlReader = saxParser.getXMLReader();

      XMLModelReader modelReader = new XMLModelReader(xmlReader);
      FileReader modelInput = new FileReader(args[0]);
      InputSource source = new InputSource(modelInput);

      Model model = modelReader.load(source);

      modelInput.close();

      model.check();

      if (args[1].equals("-s")) {
        int[][] result = model.generateSequence(Integer.parseInt(args[2]));

        List lexicon = model.getLexicon();
        for (int i = 0; i < result[0].length; i++) {
          System.out.print((Character) lexicon.get(result[0][i]));
        }
        System.out.println();
        int numberOfStates = model.getNumberOfStates();
        if (numberOfStates > 9) {
          for (int i = 0; i < result[1].length; i++) {
            System.out.print(result[1][i]);
            System.out.print(',');
          }
        } else {
          for (int i = 0; i < result[1].length; i++) {
            System.out.print(result[1][i]);
          }
        }
        System.out.println();
        for (int i = 1; i < numberOfStates; i++) {
          System.out.println(i + " = " + model.getStateName(i));
        }
      } else if (args[1].equals("-c")) {
        List lexicon = model.getLexicon();
        int count = Integer.parseInt(args[2]);
        int length = Integer.parseInt(args[3]);
        ListOfSequences uniqueSeqs = new ListOfSequences();
        for (int i = 0; i < count; i++) {
          int[][] result = model.generateSequence(length);
          uniqueSeqs.addSequence(result[0]);
        }
        Iterator seqs = uniqueSeqs.iterator();
        while (seqs.hasNext()) {
          SequenceCount seq = (SequenceCount) seqs.next();
          int[] key = seq.getSequence();
          for (int i = 0; i < key.length; i++) {
            System.out.print((Character) lexicon.get(key[i]));
          }
          System.out.print(',');
          System.out.println(seq.getCount());
        }
      }

    } catch (java.io.IOException ex) {
      ex.printStackTrace();
    } catch (org.xml.sax.SAXException ex) {
      System.err.println(ex.getMessage());
    } catch (javax.xml.parsers.ParserConfigurationException ex) {
      ex.printStackTrace();
    }
  }