示例#1
1
  /**
   * 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();
    }
  }
  /**
   * Test XMLSequence reading using XML Parsers.
   *
   * @throws Exception if something goes wrong
   */
  public void testXMLSequence() throws Exception {
    File testFile = new File(testDir, "XMLSequence.txt");

    XMLSequence sequence = new XMLSequence(new BufferedInputStream(new FileInputStream(testFile)));

    if (!sequence.markSupported())
      throw new AssertionFailedError("Mark is not supported for XMLSequence");

    sequence.mark((int) testFile.length() + 1);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);
    XMLReader xmlReader = factory.newSAXParser().getXMLReader();

    int i = 0;
    while (sequence.hasNext()) {
      InputStream input = sequence.next();
      InputSource source = new InputSource(input);
      xmlReader.parse(source);
      input.close();
      i++;
    }

    sequence.reset();
    i = 0;
    while (sequence.hasNext()) {
      InputStream input = sequence.next();
      InputSource source = new InputSource(input);
      xmlReader.parse(source);
      input.close();
      i++;
    }
    sequence.close();
  }
示例#3
0
  /**
   * Note that if file starts with 'classpath:' the resource is looked up on the classpath instead.
   */
  public static Configuration load(String file) throws IOException, SAXException {
    ConfigurationImpl cfg = new ConfigurationImpl();

    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(new ConfigHandler(cfg, file));
    if (file.startsWith("classpath:")) {
      String resource = file.substring("classpath:".length());
      ClassLoader cloader = Thread.currentThread().getContextClassLoader();
      InputStream istream = cloader.getResourceAsStream(resource);
      parser.parse(new InputSource(istream));
    } else parser.parse(file);

    return cfg;
  }
示例#4
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();
 }
 /**
  * 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;
 }
 /** 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();
   }
 }
示例#7
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;
  }
 // 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;
 }
 @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();
       }
     }
   }
 }
示例#10
0
  public synchronized int unpack(ISOComponent c, byte[] b) throws ISOException {
    LogEvent evt = new LogEvent(this, "unpack");
    try {
      if (!(c instanceof ISOMsg)) throw new ISOException("Can't call packager on non Composite");

      stk.clear();

      InputSource src = new InputSource(new ByteArrayInputStream(b));
      reader.parse(src);
      if (stk.empty()) throw new ISOException("error parsing");

      ISOMsg m = (ISOMsg) c;
      m.merge((ISOMsg) stk.pop());

      if (logger != null) evt.addMessage(m);
      return b.length;
    } catch (ISOException e) {
      evt.addMessage(e);
      throw e;
    } catch (IOException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } catch (SAXException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } finally {
      Logger.log(evt);
    }
  }
 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;
 }
示例#12
0
 /**
  * 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);
   }
 }
示例#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;
  }
  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;
  }
 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;
 }
 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();
   }
 }
示例#17
0
  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;
    }
  }
  @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 ");
  }
示例#19
0
 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();
 }
示例#20
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);
    }
  }
示例#21
0
  public synchronized void unpack(ISOComponent c, InputStream in) throws ISOException, IOException {
    LogEvent evt = new LogEvent(this, "unpack");
    try {
      if (!(c instanceof ISOMsg)) throw new ISOException("Can't call packager on non Composite");

      while (!stk.empty())
        // purge from possible previous error
        stk.pop();

      reader.parse(new InputSource(in));
      if (stk.empty()) throw new ISOException("error parsing");

      ISOMsg m = (ISOMsg) c;
      m.merge((ISOMsg) stk.pop());

      if (logger != null) evt.addMessage(m);
    } catch (ISOException e) {
      evt.addMessage(e);
      throw e;
    } catch (SAXException e) {
      evt.addMessage(e);
      throw new ISOException(e.toString());
    } finally {
      Logger.log(evt);
    }
  }
示例#22
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();
    }
  }
示例#23
0
  @Override
  public void read(final String filename) {
    if (matchList.isEmpty()) {
      throw new IllegalStateException("matchList not initialized");
    }

    match = false;
    needResolveEntity = true;
    inputFile = new File(filename);
    filePath = inputFile.getParent();
    inputFile.getPath();
    if (indexEntries.length() != 0) {
      // delete all the content in indexEntries
      indexEntries = new StringBuffer(INT_1024);
    }

    try {
      reader.setErrorHandler(new DITAOTXMLErrorHandler(filename, logger));
      final InputSource source =
          URIResolverAdapter.convertToInputSource(
              DitaURIResolverFactory.getURIResolver().resolve(filename, null));
      reader.parse(source);
    } catch (final Exception e) {
      logger.logException(e);
    }
  }
  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()");
    }
  }
 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
  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;
  }
示例#27
0
 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
  public static void main(String argv[]) {
    if (argv.length != 1) {
      System.err.println("Usage: java Validate [filename.xml | URLToFile]");
      System.exit(1);
    }

    try {
      // get a parser
      XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");

      // request validation
      reader.setFeature("http://xml.org/sax/features/validation", true);
      reader.setFeature("http://apache.org/xml/features/validation/schema", true);
      reader.setErrorHandler(new Validate());

      // associate an InputSource object with the file name or URL
      InputSource inputSource = new InputSource(argv[0]);

      // go ahead and parse
      reader.parse(inputSource);
    } catch (org.xml.sax.SAXException e) {
      System.out.println("Error in parsing " + e);
      valid = false;

    } catch (java.io.IOException e) {
      System.out.println("Error in I/O " + e);
      System.exit(0);
    }
    System.out.println("Valid Document is " + valid);
  }
示例#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
文件: 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);
    }
  }