コード例 #1
1
ファイル: PipeDocument.java プロジェクト: nuxleus/lcmc
  /**
   * Uses a Vector of TransformerHandlers to pipe XML input document through a series of 1 or more
   * transformations. Called by {@link #pipeDocument}.
   *
   * @param vTHandler Vector of Transformation Handlers (1 per stylesheet).
   * @param source absolute URI to XML input
   * @param target absolute path to transformation output.
   */
  public void usePipe(Vector vTHandler, String source, String target)
      throws TransformerException, TransformerConfigurationException, FileNotFoundException,
          IOException, SAXException, SAXNotRecognizedException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    TransformerHandler tHFirst = (TransformerHandler) vTHandler.firstElement();
    reader.setContentHandler(tHFirst);
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHFirst);
    for (int i = 1; i < vTHandler.size(); i++) {
      TransformerHandler tHFrom = (TransformerHandler) vTHandler.elementAt(i - 1);
      TransformerHandler tHTo = (TransformerHandler) vTHandler.elementAt(i);
      tHFrom.setResult(new SAXResult(tHTo));
    }
    TransformerHandler tHLast = (TransformerHandler) vTHandler.lastElement();
    Transformer trans = tHLast.getTransformer();
    Properties outputProps = trans.getOutputProperties();
    Serializer serializer = SerializerFactory.getSerializer(outputProps);

    FileOutputStream out = new FileOutputStream(target);
    try {
      serializer.setOutputStream(out);
      tHLast.setResult(new SAXResult(serializer.asContentHandler()));
      reader.parse(source);
    } finally {
      // Always clean up the FileOutputStream,
      // even if an exception was thrown in the try block
      if (out != null) out.close();
    }
  }
コード例 #2
0
  private void updateWiretap() {
    if (contentHandler != null) {
      if (wiretapContentHander != null) {
        wrappedReader.setContentHandler(
            new CombineContentHandler(wiretapContentHander, contentHandler));
      } else {
        wrappedReader.setContentHandler(contentHandler);
      }
    } else {
      wrappedReader.setContentHandler(wiretapContentHander);
    }

    try {
      if (lexicalHandler != null) {
        if (wiretapLexicalHandler != null) {
          wrappedReader.setProperty(
              "http://xml.org/sax/properties/lexical-handler",
              new CombineLexicalHandler(wiretapLexicalHandler, lexicalHandler));
        } else {
          wrappedReader.setProperty(
              "http://xml.org/sax/properties/lexical-handler", lexicalHandler);
        }
      } else {
        wrappedReader.setProperty(
            "http://xml.org/sax/properties/lexical-handler", wiretapLexicalHandler);
      }
    } catch (SAXNotRecognizedException e) {
    } catch (SAXNotSupportedException e) {
    }
  }
コード例 #3
0
ファイル: HTTPConnection.java プロジェクト: fredjean/svnkit
 private SVNErrorMessage readData(
     InputStream is, String method, String path, DefaultHandler handler)
     throws FactoryConfigurationError, UnsupportedEncodingException, IOException {
   try {
     if (mySAXParser == null) {
       mySAXParser = getSAXParserFactory().newSAXParser();
     }
     XMLReader reader = new XMLReader(is);
     while (!reader.isClosed()) {
       org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader();
       xmlReader.setContentHandler(handler);
       xmlReader.setDTDHandler(handler);
       xmlReader.setErrorHandler(handler);
       xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       xmlReader.parse(new InputSource(reader));
     }
   } catch (SAXException e) {
     if (e instanceof SAXParseException) {
       if (handler instanceof DAVErrorHandler) {
         // failed to read svn-specific error, return null.
         return null;
       }
     } else if (e.getException() instanceof SVNException) {
       return ((SVNException) e.getException()).getErrorMessage();
     } else if (e.getCause() instanceof SVNException) {
       return ((SVNException) e.getCause()).getErrorMessage();
     }
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "Processing {0} request response failed: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (ParserConfigurationException e) {
     return SVNErrorMessage.create(
         SVNErrorCode.RA_DAV_REQUEST_FAILED,
         "XML parser configuration error while processing {0} request response: {1} ({2}) ",
         new Object[] {method, e.getMessage(), path});
   } catch (EOFException e) {
     // skip it.
   } finally {
     if (mySAXParser != null) {
       // to avoid memory leaks when connection is cached.
       org.xml.sax.XMLReader xmlReader = null;
       try {
         xmlReader = mySAXParser.getXMLReader();
       } catch (SAXException e) {
       }
       if (xmlReader != null) {
         xmlReader.setContentHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER);
         xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
       }
     }
     myRepository.getDebugLog().flushStream(is);
   }
   return null;
 }
コード例 #4
0
  public void loadIdea() {

    try {

      URL url = new URL(idea_url);

      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();

      XMLReader xr = sp.getXMLReader();
      IdeaDetailHandler myExampleHandler = new IdeaDetailHandler();
      xr.setContentHandler(myExampleHandler);

      InputSource is = new InputSource(url.openStream());
      is.setEncoding("UTF-8");
      xr.parse(is);

      idea = myExampleHandler.getParsedData();

      Message myMessage = new Message();
      myMessage.obj = "SUCCESS";
      handler.sendMessage(myMessage);

    } catch (Exception e) {
      // Log.e("Ideas4All", "Error", e);
    }
  }
コード例 #5
0
 /** Loads edits file, uses visitor to process all elements */
 public void loadEdits() throws IOException {
   try {
     XMLReader xr = XMLReaderFactory.createXMLReader();
     xr.setContentHandler(this);
     xr.setErrorHandler(this);
     xr.setDTDHandler(null);
     xr.parse(new InputSource(fileReader));
     visitor.close(null);
   } catch (SAXParseException e) {
     System.out.println(
         "XML parsing error: "
             + "\n"
             + "Line:    "
             + e.getLineNumber()
             + "\n"
             + "URI:     "
             + e.getSystemId()
             + "\n"
             + "Message: "
             + e.getMessage());
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (SAXException e) {
     visitor.close(e);
     throw new IOException(e.toString());
   } catch (RuntimeException e) {
     visitor.close(e);
     throw e;
   } finally {
     fileReader.close();
   }
 }
コード例 #6
0
 @Test
 public void testGeneratedFiles() throws SAXException, IOException {
   final File[] files = {
     new File("maps", "root-map-01.ditamap"),
     new File("topics", "target-topic-a.xml"),
     new File("topics", "target-topic-c.xml"),
     new File("topics", "xreffin-topic-1.xml"),
     new File("topics", "copy-to.xml"),
   };
   final Map<File, File> copyto = new HashMap<File, File>();
   copyto.put(new File("topics", "copy-to.xml"), new File("topics", "xreffin-topic-1.xml"));
   final TestHandler handler = new TestHandler();
   final XMLReader parser = XMLReaderFactory.createXMLReader();
   parser.setContentHandler(handler);
   for (final File f : files) {
     InputStream in = null;
     try {
       in = new FileInputStream(new File(tmpDir, f.getPath()));
       handler.setSource(
           new File(inputDir, copyto.containsKey(f) ? copyto.get(f).getPath() : f.getPath()));
       parser.parse(new InputSource(in));
     } finally {
       if (in != null) {
         in.close();
       }
     }
   }
 }
コード例 #7
0
 // This method is executed in the background thread on our Survey object
 private String uploadSurveyData(String myXML) {
   // Set up communication with the server
   DefaultHttpClient client = new DefaultHttpClient();
   String result = null;
   //
   HttpPost httpPost;
   httpPost =
       new HttpPost(
           "http://YOUR DOMAIN HERE/survey-webApp/index.php/webUser_Controllers/android_controller/save_survey_xml");
   try {
     // Encode the xml, add header and set it to POST request
     StringEntity entity = new StringEntity(myXML, HTTP.UTF_8);
     // entity.setContentType("text/xml");
     httpPost.setEntity(entity);
     // Execute POST request and get response
     HttpResponse response = client.execute(httpPost);
     HttpEntity responseEntity = response.getEntity();
     // System.out.print(EntityUtils.toString(responseEntity));
     // Set up XML parsing objects
     SAXParserFactory spf = SAXParserFactory.newInstance();
     SAXParser sp = spf.newSAXParser();
     XMLReader xr = sp.getXMLReader();
     // Set up an instance of our class to parse the status response
     HttpResponseHandler myResponseHandler = new HttpResponseHandler();
     xr.setContentHandler(myResponseHandler);
     xr.parse(retrieveInputStream(responseEntity));
     // check myResponseHandler for response
     result = myResponseHandler.getStatus();
   } catch (Exception e) {
     result = "Exception - " + e.getMessage();
   }
   return result;
 }
コード例 #8
0
 private CloudServersException parseCloudServersException(HttpResponse response) {
   CloudServersException cse = new CloudServersException();
   try {
     BasicResponseHandler responseHandler = new BasicResponseHandler();
     String body = responseHandler.handleResponse(response);
     CloudServersFaultXMLParser parser = new CloudServersFaultXMLParser();
     SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
     XMLReader xmlReader = saxParser.getXMLReader();
     xmlReader.setContentHandler(parser);
     xmlReader.parse(new InputSource(new StringReader(body)));
     cse = parser.getException();
   } catch (ClientProtocolException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (IOException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (ParserConfigurationException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (SAXException e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   } catch (FactoryConfigurationError e) {
     cse = new CloudServersException();
     cse.setMessage(e.getLocalizedMessage());
   }
   return cse;
 }
コード例 #9
0
ファイル: Processor.java プロジェクト: vibe13/asm
  private void processEntry(
      final ZipInputStream zis, final ZipEntry ze, final ContentHandlerFactory handlerFactory) {
    ContentHandler handler = handlerFactory.createContentHandler();
    try {

      // if (CODE2ASM.equals(command)) { // read bytecode and process it
      // // with TraceClassVisitor
      // ClassReader cr = new ClassReader(readEntry(zis, ze));
      // cr.accept(new TraceClassVisitor(null, new PrintWriter(os)),
      // false);
      // }

      boolean singleInputDocument = inRepresentation == SINGLE_XML;
      if (inRepresentation == BYTECODE) { // read bytecode and process it
        // with handler
        ClassReader cr = new ClassReader(readEntry(zis, ze));
        cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0);

      } else { // read XML and process it with handler
        XMLReader reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.parse(
            new InputSource(
                singleInputDocument
                    ? (InputStream) new ProtectedInputStream(zis)
                    : new ByteArrayInputStream(readEntry(zis, ze))));
      }
    } catch (Exception ex) {
      update(ze.getName(), 0);
      update(ex, 0);
    }
  }
 static Object load(InputStream is, String name, Handler handler) {
   try {
     try {
       XMLReader reader = XMLUtil.createXMLReader();
       reader.setEntityResolver(handler);
       reader.setContentHandler(handler);
       reader.parse(new InputSource(is));
       return handler.getResult();
     } finally {
       is.close();
     }
   } catch (SAXException ex) {
     if (System.getProperty("org.netbeans.optionsDialog") != null) {
       System.out.println("File: " + name);
       ex.printStackTrace();
     }
     return handler.getResult();
   } catch (IOException ex) {
     if (System.getProperty("org.netbeans.optionsDialog") != null) {
       System.out.println("File: " + name);
       ex.printStackTrace();
     }
     return handler.getResult();
   } catch (Exception ex) {
     if (System.getProperty("org.netbeans.optionsDialog") != null) {
       System.out.println("File: " + name);
       ex.printStackTrace();
     }
     return handler.getResult();
   }
 }
コード例 #11
0
ファイル: RSSReader.java プロジェクト: yzhao1/YuZhao_COMP225
  private RSSFeed getFeed(String urlToRssFeed) {
    try {
      // setup the url
      URL url = new URL(urlToRssFeed);

      // create the factory
      SAXParserFactory factory = SAXParserFactory.newInstance();
      // create a parser
      SAXParser parser = factory.newSAXParser();

      // create the reader (scanner)
      XMLReader xmlreader = parser.getXMLReader();
      // instantiate our handler
      RSSHandler theRssHandler = new RSSHandler();
      // assign our handler
      xmlreader.setContentHandler(theRssHandler);
      // get our data via the url class
      InputSource is = new InputSource(url.openStream());
      // perform the synchronous parse
      xmlreader.parse(is);
      // get the results - should be a fully populated RSSFeed instance,
      // or null on error
      return theRssHandler.getFeed();
    } catch (Exception ee) {
      // if we have a problem, simply return null
      return null;
    }
  }
コード例 #12
0
  @Test
  public void testParserHandling() throws Exception {
    final StringBuilder chars = new StringBuilder();
    XMLReader r = XMLReaderFactory.createXMLReader();
    r.setErrorHandler(
        new ErrorHandler() {
          public void warning(SAXParseException e) throws SAXException {
            throw e;
          }

          public void fatalError(SAXParseException e) throws SAXException {
            throw e;
          }

          public void error(SAXParseException e) throws SAXException {
            throw e;
          }
        });
    r.setContentHandler(
        new DefaultHandler() {
          @Override
          public void characters(char[] ch, int start, int length) throws SAXException {
            chars.append(ch, start, length);
          }
        });

    r.parse(new InputSource(new ByteArrayInputStream(utf8Xml)));
    assertThat(chars.toString()).isEqualTo(" \u0096 ");
  }
コード例 #13
0
  @Override
  protected RssItem doInBackground(RssParser... params) {

    RssParser parser = params[0];
    RssItem item = null;

    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();
      XMLReader xr = sp.getXMLReader();
      xr.setContentHandler(parser);

      // chamar arquivo xml
      // xr.parse(new InputSource(activity.getAssets().open("image_of_the_day.xml")));

      // chamar link na internet
      URL url = new URL("http://www.nasa.gov/rss/dyn/image_of_the_day.rss");
      xr.parse(new InputSource(url.openConnection().getInputStream()));

      item = parser.getFirstItem();
      if (item != null) {
        /*item.setImagem(
        BitmapFactory.decodeResource(
        		activity.getResources(), R.drawable.image_of_the_day));*/
        item.setImagem(getBitmap(item.getImagemUrl()));
      }

    } catch (Exception e) {
      e.printStackTrace();
    }

    return item;
  }
コード例 #14
0
  private Authentication getConnectionData(String stFile) {
    Authentication sr = null;
    try {
      // open the file and parse it to retrieve the four required information
      File file = new File(stFile);
      InputStream inputStream;
      inputStream = new FileInputStream(file);
      Reader reader = new InputStreamReader(inputStream, "ISO-8859-1");

      InputSource is = new InputSource(reader);
      is.setEncoding("UTF-8");

      XMLReader saxReader = XMLReaderFactory.createXMLReader();
      sr = new Authentication();
      saxReader.setContentHandler(sr);
      saxReader.parse(is);

    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    return sr;
  }
コード例 #15
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.flash_card_activity);

    // Initialize fields
    initialize();

    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();
      XMLReader xr = sp.getXMLReader();
      myParser = new XMLParser();
      xr.setContentHandler(myParser);
      xr.parse(new InputSource(this.getResources().openRawResource(R.raw.words)));
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      words = myParser.getWordsList();
      // db = dbh.getWritableDatabase();
      // myWords = dbh.getMyWordsList();
      displayWord(words.get(index));
    }

    pbProgress.setMax(words.size());
  }
コード例 #16
0
  private void fetchComments() {
    try {
      final URL newUrl = new URL(book.get().getCommentsUrl());

      // sax stuff
      final SAXParserFactory factory = SAXParserFactory.newInstance();
      final SAXParser parser = factory.newSAXParser();

      final XMLReader reader = parser.getXMLReader();

      // initialize our parser logic
      final CommentsHandler commentsHandler = new CommentsHandler(book.get().getComments());
      reader.setContentHandler(commentsHandler);

      // get the xml feed
      reader.parse(new InputSource(newUrl.openStream()));
    } catch (MalformedURLException e) {
      COMMENTS_ERROR = MALFORMED_URL;
      Log.e(TAG, "MalformedURLException: " + e + "\nIn fetchComments()");
    } catch (ParserConfigurationException pce) {
      COMMENTS_ERROR = PARSER_CONFIG_ERROR;
      Log.e(TAG, "ParserConfigurationException: " + pce + "\nIn fetchComments()");
    } catch (SAXException se) {
      COMMENTS_ERROR = SAX_ERROR;
      Log.e(TAG, "SAXException: " + se + "\nIn fetchComments()");
    } catch (IOException ioe) {
      COMMENTS_ERROR = IO_ERROR;
      Log.e(TAG, "IOException: " + ioe + "\nIn fetchComments()");
    }
  }
コード例 #17
0
ファイル: XMLValidator.java プロジェクト: dajester2013/Lucee
  public Struct validate(InputSource xml) throws PageException {
    CFMLEngine engine = CFMLEngineFactory.getInstance();
    warnings = engine.getCreationUtil().createArray();
    errors = engine.getCreationUtil().createArray();
    fatals = engine.getCreationUtil().createArray();

    try {
      XMLReader parser = new XMLUtilImpl().createXMLReader("org.apache.xerces.parsers.SAXParser");
      parser.setContentHandler(this);
      parser.setErrorHandler(this);
      parser.setEntityResolver(this);
      parser.setFeature("http://xml.org/sax/features/validation", true);
      parser.setFeature("http://apache.org/xml/features/validation/schema", true);
      parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
      // if(!validateNamespace)
      if (!Util.isEmpty(strSchema))
        parser.setProperty(
            "http://apache.org/xml/properties/schema/external-noNamespaceSchemaLocation",
            strSchema);
      parser.parse(xml);
    } catch (SAXException e) {
    } catch (IOException e) {
      throw engine.getExceptionUtil().createXMLException(e.getMessage());
    }

    // result
    Struct result = engine.getCreationUtil().createStruct();
    result.setEL("warnings", warnings);
    result.setEL("errors", errors);
    result.setEL("fatalerrors", fatals);
    result.setEL("status", engine.getCastUtil().toBoolean(!hasErrors));
    release();
    return result;
  }
コード例 #18
0
  /**
   * Must account for multipart/alternative Content, that is, multiple Content nodes nested inside
   * another Content node.
   */
  public void characters(char[] ch, int start, int length) throws SAXException {
    String full = String.valueOf(ch);

    // if it is multipart it should contain more Content,
    // and thus we have to look for the last <content> in
    // this entry.
    if (contentType != null && contentType.equals("multipart/alternative")) {
      // find the first nested Content
      int nextContent = full.indexOf("<content", start);
      int lastIndex = full.indexOf(closingTag, start);

      // nextContent cannot begin after next closingTag
      if (nextContent > 0 && nextContent < lastIndex) {
        // we found the next tag, get content up to that point
        lastIndex = nextContent;
      }

      try {
        value = full.substring(start, lastIndex);
      } catch (IndexOutOfBoundsException e) {
        // there was no lastIndex found - bad
      }
    }
    // it isn't multipart, so find next occurence of closingTag.
    else {
      int endContent = full.indexOf(closingTag, start);
      if (endContent > 0) value += full.substring(start, endContent);
    }

    xmlReader.setContentHandler(oldHandler);
  }
コード例 #19
0
 protected List<NodeTypeDefinition> importFromXml(InputSource source) throws RepositoryException {
   XmlNodeTypeReader handler = new XmlNodeTypeReader(session);
   try {
     XMLReader parser = XMLReaderFactory.createXMLReader();
     parser.setContentHandler(handler);
     parser.parse(source);
   } catch (EnclosingSAXException ese) {
     Exception cause = ese.getException();
     if (cause instanceof RepositoryException) {
       throw (RepositoryException) cause;
     }
     throw new RepositoryException(cause);
   } catch (SAXParseException se) {
     throw new InvalidSerializedDataException(se);
   } catch (SAXException se) {
     throw new RepositoryException(se);
   } catch (IOException ioe) {
     throw new RepositoryException(ioe);
   } catch (RuntimeException t) {
     throw t;
   } catch (Throwable t) {
     throw new RepositoryException(t);
   }
   return handler.getNodeTypeDefinitions();
 }
コード例 #20
0
 public List<ExtensionInfo> parse() {
   List<ExtensionInfo> result = Lists.newArrayList();
   try {
     XMLReader reader = XMLReaderFactory.createXMLReader();
     PluginXMLContentHandler handler = new PluginXMLContentHandler();
     reader.setContentHandler(handler);
     for (URL u : getAllPluginResourceURLs()) {
       InputStream openStream = null;
       try {
         openStream = u.openStream();
         reader.parse(new InputSource(openStream));
       } catch (IOException e) {
         throw new RuntimeException(e);
       } finally {
         if (openStream != null)
           try {
             openStream.close();
           } catch (IOException e) {
             throw new RuntimeException(e);
           }
       }
     }
     for (ExtensionPointHandler h : handler.getFinishedHandlers())
       for (ExtensionInfo pi : h.getInfo()) result.add(pi);
   } catch (SAXException e) {
     throw new RuntimeException(e);
   }
   return result;
 }
コード例 #21
0
ファイル: Design.java プロジェクト: kpfalzer/macplacer
 public Design(String xmlFname) throws SAXException, IOException {
   FileInputStream fis = new FileInputStream(xmlFname);
   XMLReader rdr = XMLReaderFactory.createXMLReader();
   rdr.setContentHandler(new MyContentHandler());
   rdr.parse(new InputSource(fis));
   fis.close();
 }
コード例 #22
0
  public static BehavioralPatternsCatalog load(final Reader reader) {
    BehavioralPatternsCatalog catalog = null;

    try {
      final BehavioralPatternsCatalogSaxHandler handler = new BehavioralPatternsCatalogSaxHandler();

      final SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setValidating(true);
      factory.setNamespaceAware(true);

      final XMLReader xmlReader = factory.newSAXParser().getXMLReader();
      xmlReader.setContentHandler(handler);
      xmlReader.setErrorHandler(handler);
      xmlReader.setEntityResolver(handler);

      xmlReader.parse(new InputSource(reader));

      catalog = handler.getCatalog();

      reader.close();
    } catch (final SAXException e) {
      BehavioralAnalysisPlugin.logError("Error parsing Behavioral Patterns Catalog.", e);
    } catch (final ParserConfigurationException e) {
      BehavioralAnalysisPlugin.logError("Error parsing Behavioral Patterns Catalog.", e);
    } catch (final IOException e) {
      BehavioralAnalysisPlugin.logError("Error opening Behavioral Patterns Catalog.", e);
    }

    return catalog;
  }
コード例 #23
0
ファイル: MapLinksReader.java プロジェクト: componize/dita-ot
  /** Default constructor of MapLinksReader class. */
  public MapLinksReader() {
    super();
    map = new HashMap<String, Map<String, String>>();
    ancestorList = new ArrayList<String>(INT_16);
    matchList = new ArrayList<String>(INT_16);
    indexEntries = new StringBuffer(INT_1024);
    firstMatchElement = null;
    lastMatchElement = new HashSet<String>();
    level = 0;
    match = false;
    validHref = true;
    needResolveEntity = false;
    topicPath = null;
    inputFile = null;

    try {
      reader = StringUtils.getXMLReader();
      reader.setContentHandler(this);
      reader.setProperty(LEXICAL_HANDLER_PROPERTY, this);
      // Added by william on 2009-11-8 for ampbug:2893664 start
      reader.setFeature("http://apache.org/xml/features/scanner/notify-char-refs", true);
      reader.setFeature("http://apache.org/xml/features/scanner/notify-builtin-refs", true);
      // Added by william on 2009-11-8 for ampbug:2893664 end
      reader.setFeature("http://xml.org/sax/features/namespaces", false);
    } catch (final Exception e) {
      logger.logException(e);
    }
  }
コード例 #24
0
ファイル: EventCMLReader.java プロジェクト: jaypat87/cdk
 /**
  * Starts the reading of the CML file. Whenever a new Molecule is read, a event is thrown to the
  * ReaderListener.
  */
 public void process() throws CDKException {
   logger.debug("Started parsing from input...");
   try {
     parser.setFeature("http://xml.org/sax/features/validation", false);
     logger.info("Deactivated validation");
   } catch (SAXException e) {
     logger.warn("Cannot deactivate validation.");
   }
   parser.setContentHandler(new EventCMLHandler(this, builder));
   parser.setEntityResolver(new CMLResolver());
   parser.setErrorHandler(new CMLErrorHandler());
   try {
     logger.debug("Parsing from Reader");
     parser.parse(new InputSource(input));
   } catch (IOException e) {
     String error = "Error while reading file: " + e.getMessage();
     logger.error(error);
     logger.debug(e);
     throw new CDKException(error, e);
   } catch (SAXParseException saxe) {
     SAXParseException spe = (SAXParseException) saxe;
     String error = "Found well-formedness error in line " + spe.getLineNumber();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   } catch (SAXException saxe) {
     String error = "Error while parsing XML: " + saxe.getMessage();
     logger.error(error);
     logger.debug(saxe);
     throw new CDKException(error, saxe);
   }
 }
コード例 #25
0
 private static SVG parse(
     InputStream in, Integer searchColor, Integer replaceColor, boolean whiteMode)
     throws SVGParseException {
   //        Util.debug("Parsing SVG...");
   try {
     //            long start = System.currentTimeMillis();
     SAXParserFactory spf = SAXParserFactory.newInstance();
     SAXParser sp = spf.newSAXParser();
     XMLReader xr = sp.getXMLReader();
     final Picture picture = new Picture();
     SVGHandler handler = new SVGHandler(picture);
     handler.setColorSwap(searchColor, replaceColor);
     handler.setWhiteMode(whiteMode);
     xr.setContentHandler(handler);
     xr.parse(new InputSource(in));
     //        Util.debug("Parsing complete in " + (System.currentTimeMillis() - start) + "
     // millis.");
     SVG result = new SVG(picture, handler.bounds);
     // Skip bounds if it was an empty pic
     if (!Float.isInfinite(handler.limits.top)) {
       result.setLimits(handler.limits);
     }
     return result;
   } catch (Exception e) {
     throw new SVGParseException(e);
   }
 }
コード例 #26
0
 /**
  * Read key definition XML configuration file
  *
  * @param keydefFile key definition file
  * @return list of key definitions
  * @throws DITAOTException if reading configuration file failed
  */
 public static Collection<KeyDef> readKeydef(final File keydefFile) throws DITAOTException {
   final Collection<KeyDef> res = new ArrayList<KeyDef>();
   try {
     final XMLReader parser = StringUtils.getXMLReader();
     parser.setContentHandler(
         new DefaultHandler() {
           @Override
           public void startElement(
               final String uri, final String localName, final String qName, final Attributes atts)
               throws SAXException {
             final String n = localName != null ? localName : qName;
             if (n.equals(ELEMENT_KEYDEF)) {
               res.add(
                   new KeyDef(
                       atts.getValue(ATTRIBUTE_KEYS),
                       atts.getValue(ATTRIBUTE_HREF),
                       atts.getValue(ATTRIUBTE_SOURCE)));
             }
           }
         });
     parser.parse(keydefFile.toURI().toString());
   } catch (final Exception e) {
     throw new DITAOTException(
         "Failed to read key definition file " + keydefFile + ": " + e.getMessage(), e);
   }
   return res;
 }
コード例 #27
0
ファイル: DMOZParser.java プロジェクト: blouke/IRProject
 public static void main(String[] args) {
   String fileSeparator = System.getProperty("file.separator");
   try {
     FileInputStream fileInput =
         new FileInputStream(
             System.getProperty("user.dir")
                 + fileSeparator
                 + "resources"
                 + fileSeparator
                 + "content.rdf.u8");
     InputSource is;
     is = new InputSource(fileInput);
     SAXParserFactory spf = SAXParserFactory.newInstance();
     spf.setValidating(false);
     XMLReader r;
     r = spf.newSAXParser().getXMLReader();
     r.setContentHandler(new RDFHandler());
     r.parse(is);
   } catch (ParserConfigurationException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   } catch (SAXException e) {
     e.printStackTrace();
   }
 }
コード例 #28
0
  /**
   * Reads malformed XML from the InputStream original and returns a new InputStream which can be
   * used to read a well-formed version of the input
   *
   * @param original original input
   * @return an {@link InputStream} which can be used to read a well-formed version of the input XML
   * @throws ParseException if an exception occurs while parsing the input
   */
  public static InputStream xmlizeInputStream(InputStream original) throws ParseException {
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();

      HTMLSchema schema = new HTMLSchema();
      XMLReader reader = new Parser();

      // TODO walk through the javadoc and tune more settings
      // see tagsoup javadoc for details
      reader.setProperty(Parser.schemaProperty, schema);
      reader.setFeature(Parser.bogonsEmptyFeature, false);
      reader.setFeature(Parser.ignorableWhitespaceFeature, true);
      reader.setFeature(Parser.ignoreBogonsFeature, false);

      Writer writeger = new OutputStreamWriter(out);
      XMLWriter x = new XMLWriter(writeger);

      reader.setContentHandler(x);

      InputSource s = new InputSource(original);

      reader.parse(s);
      return new ByteArrayInputStream(out.toByteArray());
    } catch (SAXException e) {
      throw new ParseException(R("PBadXML"), e);
    } catch (IOException e) {
      throw new ParseException(R("PBadXML"), e);
    }
  }
コード例 #29
0
  private CharSequence readFile(String href, String baseURI) throws XPathException {
    try {

      // Use resolver as it does a series of tasks for us, and use "binary" mode
      final TransformerURIResolver resolver =
          new TransformerURIResolver(
              null, PipelineContext.get(), null, XMLParsing.ParserConfiguration.PLAIN, "binary");

      final StringBuilder sb = new StringBuilder(1024);

      // Get SAX source using crazy SAX API
      // Source produces a binary document (content Base64-encoded)
      final SAXSource source = (SAXSource) resolver.resolve(href, baseURI);
      final XMLReader xmlReader = source.getXMLReader();
      xmlReader.setContentHandler(
          new XMLReceiverAdapter() {
            public void characters(char ch[], int start, int length) throws SAXException {
              // Append Base64-encoded text only
              sb.append(ch, start, length);
            }
          });
      xmlReader.parse(source.getInputSource());

      // Return content formatted as Base64
      return sb.toString();
    } catch (Exception e) {
      throw new XPathException(e);
    }
  }
コード例 #30
0
  public static void main(String[] args) {
    try {
      // Creamos nuestro objeto libro vac�o
      Libro libro = new Libro();

      // Creamos la factoria de parseadores por defecto
      XMLReader reader = XMLReaderFactory.createXMLReader();

      //
      LibroXML libroleido = new LibroXML(libro);

      // A�adimos nuestro manejador al reader pasandole el objeto libro
      reader.setContentHandler(libroleido);

      // Procesamos el xml de ejemplo
      reader.parse(new InputSource(new FileInputStream("libros.xml")));

      // System.out.println(libro.toString());
      System.out.println(libroleido.getColeccionLibros());

    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }