Exemplo n.º 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();
    }
  }
Exemplo n.º 2
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());
  }
 /** 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();
   }
 }
 @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();
       }
     }
   }
 }
 // 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;
 }
Exemplo n.º 6
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);
    }
  }
Exemplo n.º 7
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();
 }
Exemplo n.º 8
0
 @SuppressWarnings("unchecked")
 public static <T> T unmarshal(final InputStream in) throws IOException {
   final Unmarshaller unmarshaller = SardineUtil.createUnmarshaller();
   try {
     final XMLReader reader = XMLReaderFactory.createXMLReader();
     try {
       reader.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature(
           "http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     try {
       reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
     } catch (final SAXException e) {; // Not all parsers will support this attribute
     }
     return (T) unmarshaller.unmarshal(new SAXSource(reader, new InputSource(in)));
   } catch (final SAXException e) {
     throw new RuntimeException(e.getMessage(), e);
   } catch (final JAXBException e) {
     // Server does not return any valid WebDAV XML that matches our JAXB context
     final IOException failure = new IOException("Not a valid DAV response");
     // Backward compatibility
     failure.initCause(e);
     throw failure;
   }
 }
 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;
 }
Exemplo n.º 10
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;
    }
  }
 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();
   }
 }
  @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 ");
  }
Exemplo n.º 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;
  }
Exemplo n.º 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;
  }
Exemplo n.º 15
0
 static {
   try {
     xmlReader = XMLReaderFactory.createXMLReader();
     xmlReader.setFeature("http://xml.org/sax/features/validation", false);
     if (false) {
       // FIXME AK: we need  real handling for the normal case (HTML->FOP XML)
       EntityResolver resolver =
           new EntityResolver() {
             public InputSource resolveEntity(String arg0, String arg1)
                 throws SAXException, IOException {
               log.info(arg0 + "::" + arg1);
               InputSource source =
                   new InputSource(
                       (new URL("file:///Volumes/Home/Desktop/dtd/xhtml1-transitional.dtd"))
                           .openStream());
               source.setSystemId(arg1);
               return source;
             }
           };
       xmlReader.setEntityResolver(resolver);
     }
   } catch (SAXException e) {
     e.printStackTrace();
   }
 }
  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;
  }
Exemplo n.º 17
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();
 }
Exemplo n.º 18
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);
   }
 }
Exemplo n.º 19
0
 private void processCommentLines(File file) throws SAXException, IOException {
   SAXParser parser = newSaxParser(false);
   XMLReader xmlReader = parser.getXMLReader();
   commentHandler = new CommentHandler();
   xmlReader.setProperty("http://xml.org/sax/properties/lexical-handler", commentHandler);
   parser.parse(FileUtils.openInputStream(file), commentHandler);
 }
 /**
  * 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;
 }
 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;
 }
Exemplo n.º 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();
    }
  }
Exemplo n.º 23
0
  /** 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);
    }
  }
Exemplo n.º 24
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()");
    }
  }
 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);
   }
 }
Exemplo n.º 26
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);
  }
Exemplo n.º 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();
   }
 }
Exemplo n.º 28
0
  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);
    }
  }
Exemplo n.º 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);
    }
  }
Exemplo n.º 30
0
  public void readSourceFile(String sourceFile) throws IOException, SAXException {
    TacSourceSaxHandler handler = new TacSourceSaxHandler();
    XMLReader xr = TacSaxHelper.createXMLReader(handler);
    FileReader r = new FileReader(sourceFile);

    xr.parse(new InputSource(r));
  }