public void load(PageProcessor processor) {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {

      SAXParser parser = factory.newSAXParser();
      XMLReader xmlReader = parser.getXMLReader();
      // String file = "enwiki-20151201-pages-meta-current.xml.bz2";

      xmlReader.setContentHandler(new PageHandler(xmlReader));
      FileInputStream fis = new FileInputStream(fileName);
      BZip2CompressorInputStream bzIn = new BZip2CompressorInputStream(fis);
      InputSource inputSource = new InputSource(bzIn);
      xmlReader.parse(inputSource);
      System.out.println("###### " + threadName + " processing completed ######");

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      // System.out.println("Closing Thread- " + threadName);
      DataIndexer.getInstance().threadClosing();
    }
  }
 // 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;
 }
Beispiel #3
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();
   }
 }
  public GpxReader()
      throws javax.xml.parsers.ParserConfigurationException, org.xml.sax.SAXException {
    javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);

    this.parser = factory.newSAXParser();
  }
 public static SAXParser getSaxParser() throws ParserConfigurationException, SAXException {
   SAXParserFactory parserFactory = SAXParserFactory.newInstance();
   parserFactory.setNamespaceAware(false);
   parserFactory.setValidating(true);
   parserFactory.setXIncludeAware(false);
   return parserFactory.newSAXParser();
 }
  /**
   * Does the actual parsing of a devices.xml file.
   *
   * @param deviceXml the {@link File} to load/parse. This must be an existing file.
   * @param list the list in which to write the parsed {@link LayoutDevice}.
   */
  private void parseLayoutDevices(File deviceXml, List<LayoutDevice> list) {
    // first we validate the XML
    try {
      Source source = new StreamSource(new FileReader(deviceXml));

      CaptureErrorHandler errorHandler = new CaptureErrorHandler(deviceXml.getAbsolutePath());

      Validator validator = LayoutDevicesXsd.getValidator(errorHandler);
      validator.validate(source);

      if (errorHandler.foundError() == false) {
        // do the actual parsing
        LayoutDeviceHandler handler = new LayoutDeviceHandler();

        SAXParser parser = mParserFactory.newSAXParser();
        parser.parse(new InputSource(new FileInputStream(deviceXml)), handler);

        // get the parsed devices
        list.addAll(handler.getDevices());
      }
    } catch (SAXException e) {
      AdtPlugin.log(e, "Error parsing %1$s", deviceXml.getAbsoluteFile());
    } catch (FileNotFoundException e) {
      // this shouldn't happen as we check above.
    } catch (IOException e) {
      AdtPlugin.log(e, "Error reading %1$s", deviceXml.getAbsoluteFile());
    } catch (ParserConfigurationException e) {
      AdtPlugin.log(e, "Error parsing %1$s", deviceXml.getAbsoluteFile());
    }
  }
Beispiel #7
0
  /**
   * Create a SAX parser from the JAXP factory. The result can be used to parse XML files.
   *
   * <p>See class Javadoc for hints on setting an entity resolver. This parser has its entity
   * resolver set to the system entity resolver chain.
   *
   * @param validate if true, a validating parser is returned
   * @param namespaceAware if true, a namespace aware parser is returned
   * @throws FactoryConfigurationError Application developers should never need to directly catch
   *     errors of this type.
   * @throws SAXException if a parser fulfilling given parameters can not be created
   * @return XMLReader configured according to passed parameters
   */
  public static XMLReader createXMLReader(boolean validate, boolean namespaceAware)
      throws SAXException {

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

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

    try {
      return factory.newSAXParser().getXMLReader();
    } catch (ParserConfigurationException ex) {
      throw new SAXException(
          "Cannot create parser satisfying configuration parameters", ex); // NOI18N
    }
  }
 public VersionInfo getNewestVersionInfo() {
   VersionInfo versionInfo = new VersionInfo();
   HttpClient hc = new DefaultHttpClient();
   HttpGet get = new HttpGet(server_address + "/VersionInfo.xml");
   try {
     HttpResponse response = hc.execute(get);
     if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
       HttpEntity he = response.getEntity();
       try {
         SAXParserFactory factory = SAXParserFactory.newInstance();
         SAXParser parser = factory.newSAXParser();
         parser.parse(he.getContent(), new VersionSaxHandler(versionInfo));
       } catch (Exception e) {
         Log.e(tag, "xml解析错误");
         return null;
       }
       he.consumeContent();
     }
   } catch (ClientProtocolException e) {
     Log.e(tag, "协议错误");
     return null;
   } catch (IOException e) {
     Log.e(tag, "读写错误");
     return null;
   }
   return versionInfo;
 }
 /**
  * Deconstructs response into given content handler
  *
  * @param entity returned HttpEntity
  * @return deconstructed response
  * @throws java.io.IOException
  * @see org.apache.http.HttpEntity
  */
 @Override
 protected byte[] getResponseData(HttpEntity entity) throws IOException {
   if (entity != null) {
     InputStream instream = entity.getContent();
     InputStreamReader inputStreamReader = null;
     if (instream != null) {
       try {
         SAXParserFactory sfactory = SAXParserFactory.newInstance();
         SAXParser sparser = sfactory.newSAXParser();
         XMLReader rssReader = sparser.getXMLReader();
         rssReader.setContentHandler(handler);
         inputStreamReader = new InputStreamReader(instream, DEFAULT_CHARSET);
         rssReader.parse(new InputSource(inputStreamReader));
       } catch (SAXException e) {
         Log.e(LOG_TAG, "getResponseData exception", e);
       } catch (ParserConfigurationException e) {
         Log.e(LOG_TAG, "getResponseData exception", e);
       } finally {
         AsyncHttpClient.silentCloseInputStream(instream);
         if (inputStreamReader != null) {
           try {
             inputStreamReader.close();
           } catch (IOException e) {
             /*ignore*/
           }
         }
       }
     }
   }
   return null;
 }
Beispiel #10
0
  /** Responsible for parsing the document */
  public ArrayList<String> parseDocument(URL url) {

    snippets.clear();

    // Adds a factory
    SAXParserFactory factory = SAXParserFactory.newInstance();

    try {

      // adds a new instance of parser
      SAXParser parser = factory.newSAXParser();

      // TODO SHOULD THIS BE MOVED TO MORE PROPER PLACE?
      // Sets user Agent
      System.setProperty("http.agent", "ChaosPoemSearch");

      // Stream xml to parser
      parser.parse(new InputSource(url.openStream()), this);

    } catch (SAXException se) {

    } catch (ParserConfigurationException pce) {

    } catch (ConnectException e) {

    } catch (IOException ie) {

    }

    return snippets;
  }
  /**
   * 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();
  }
Beispiel #12
0
 public Source resolve(String href, String base) throws TransformerException {
   if (href == null || href.trim().length() == 0) {
     throw new TransformerException("href is null");
   }
   try {
     String aname = defaultXslStylesheetBase + href;
     if (aname.indexOf("..") != -1) {
       aname = new File(aname).getCanonicalPath().toString();
     }
     if (m_bundleContect.getBundle().getEntry(aname) == null) {
       aname = defaultXslStylesheetBase2 + href;
     }
     if (m_bundleContect.getBundle().getEntry(aname) == null) {
       aname = defaultXslStylesheetBase3 + href;
     }
     SAXSource ss =
         new SAXSource(new InputSource(m_bundleContect.getBundle().getEntry(aname).openStream()));
     XMLReader reader = m_saxParserFactory.newSAXParser().getXMLReader();
     ReaderConfig rc = ((WstxSAXParser) reader).getStaxConfig();
     rc.setXMLResolver(new XslURIResolver(m_bundleContect, m_saxParserFactory));
     ss.setXMLReader(reader);
     return ss;
   } catch (Exception e) {
     throw new RuntimeException("XslURIResolver.resolve", e);
   }
 }
  private boolean loadParticleXML() {
    InputStream is = null;
    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();

      QuickTiGame2dParticleParser handler = new QuickTiGame2dParticleParser(this);

      XMLReader xr = sp.getXMLReader();
      xr.setContentHandler(handler);

      is = QuickTiGame2dUtil.getFileInputStream(image);
      xr.parse(new InputSource(new BufferedInputStream(is)));

      emissionRate = maxParticles / particleLifespan;

      sourcePosition.x = x;
      sourcePosition.y = y;

    } catch (Exception e) {
      if (debug)
        Log.w(Quicktigame2dModule.LOG_TAG, String.format("failed to load particle: %s", image), e);
      return false;
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (IOException e) {
          // nothing to do
        }
      }
    }

    return true;
  }
Beispiel #14
0
  private static Service parseServicePayload(String payload) throws ResponseParseException {

    JAXBContext jaxbContext;
    Service service = null;

    try {
      jaxbContext = JAXBContext.newInstance(Service.class);
      Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

      InputStream inputStream =
          new ByteArrayInputStream(payload.getBytes(Charset.forName("UTF-8")));

      SAXParserFactory spf = SAXParserFactory.newInstance();
      spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
      SAXParser sp = spf.newSAXParser();
      XMLReader xmlReader = sp.getXMLReader();
      InputSource inputSource = new InputSource(inputStream);
      SAXSource saxSource = new SAXSource(xmlReader, inputSource);

      service = (Service) jaxbUnmarshaller.unmarshal(saxSource);

    } catch (JAXBException
        | FactoryConfigurationError
        | ParserConfigurationException
        | SAXException e) {
      throw new ResponseParseException(e);
    }

    return service;
  }
  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 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);
    }
  }
 public List<Customer> readDataFromXML(String filename)
     throws ParserConfigurationException, SAXException, IOException {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser parser = factory.newSAXParser();
   parser.parse(new File(filename), this);
   return data;
 }
  @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());
  }
  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()");
    }
  }
Beispiel #20
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;
  }
  /** Creates new form JPanelButtons */
  public JPanelButtons(String sConfigKey, JPanelTicket panelticket) {
    initComponents();

    // Load categories default thumbnail
    tnbmacro = new ThumbNailBuilder(24, 24, "com/openbravo/images/run_script.png");

    this.panelticket = panelticket;

    props = new Properties();
    events = new HashMap<String, String>();

    String sConfigRes = panelticket.getResourceAsXML(sConfigKey);

    if (sConfigRes != null) {
      try {
        if (m_sp == null) {
          SAXParserFactory spf = SAXParserFactory.newInstance();
          m_sp = spf.newSAXParser();
        }
        m_sp.parse(new InputSource(new StringReader(sConfigRes)), new ConfigurationHandler());

      } catch (ParserConfigurationException ePC) {
        logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
      } catch (SAXException eSAX) {
        logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
      } catch (IOException eIO) {
        logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
      }
    }
  }
Beispiel #22
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;
    }
  }
Beispiel #23
0
  /**
   * @see MessageBodyReader#readFrom(Class, Type, MediaType, Annotation[], MultivaluedMap,
   *     InputStream)
   */
  @Override
  public Object readFrom(
      Class<Object> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, String> httpHeaders,
      InputStream entityStream)
      throws IOException {
    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      spf.setXIncludeAware(isXIncludeAware());
      spf.setNamespaceAware(true);
      spf.setValidating(isValidatingDtd());
      spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, isSecureProcessing());
      spf.setFeature(
          "http://xml.org/sax/features/external-general-entities", isExpandingEntityRefs());
      spf.setFeature(
          "http://xml.org/sax/features/external-parameter-entities", isExpandingEntityRefs());

      XMLReader reader = spf.newSAXParser().getXMLReader();
      JAXBContext jaxbContext = getJaxbContext(type);
      Unmarshaller um = jaxbContext.createUnmarshaller();
      return um.unmarshal(new SAXSource(reader, new InputSource(entityStream)));
    } catch (Exception e) {
      throw new IOException("Could not unmarshal to " + type.getName());
    }
  }
  public static ParentalControlConcern parse(File file) {

    try {

      log.info("Parsing '" + file.getCanonicalPath() + "'...");
      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setNamespaceAware(true);
      factory.setValidating(true);
      SAXParser parser = factory.newSAXParser();
      parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
      ParentalControlConcernHandler handler = new ParentalControlConcernHandler();
      parser.parse(file, handler);
      log.info("Parsed '" + file.getCanonicalPath() + "'");
      return handler.result;

    } catch (SAXParseException ex) {

      log.error(
          "Could not validate the parental control concern XML file!  Validation error follows.");
      log.error(ex.getMessage());
      ex.printStackTrace();
      return null;

    } catch (Exception ex) {

      log.error(ex);
      return null;
    }
  }
Beispiel #25
0
 /**
  * Uses PackInHandler to update AD.
  *
  * @param fileName xml file to read
  * @return status message
  */
 public String importXML(String fileName, Properties ctx, String trxName) throws Exception {
   log.info("importXML:" + fileName);
   File in = new File(fileName);
   if (!in.exists()) {
     String msg = "File does not exist: " + fileName;
     log.info("importXML:" + msg);
     return msg;
   }
   try {
     log.info("starting");
     System.setProperty(
         "javax.xml.parsers.SAXParserFactory", "org.apache.xerces.jaxp.SAXParserFactoryImpl");
     PackInHandler handler = new PackInHandler();
     handler.set_TrxName(trxName);
     handler.setCtx(ctx);
     handler.setProcess(this);
     SAXParserFactory factory = SAXParserFactory.newInstance();
     SAXParser parser = factory.newSAXParser();
     String msg = "Start Parser";
     log.info(msg);
     parser.parse(in, handler);
     msg = "End Parser";
     log.info(msg);
     return "OK.";
   } catch (Exception e) {
     log.log(Level.SEVERE, "importXML:", e);
     throw e;
   }
 }
  /** {@inheritDoc} */
  public ParseResult parse(RSyntaxDocument doc, String style) {

    result.clearNotices();
    Element root = doc.getDefaultRootElement();
    result.setParsedLines(0, root.getElementCount() - 1);

    if (spf == null || doc.getLength() == 0) {
      return result;
    }

    try {
      SAXParser sp = spf.newSAXParser();
      Handler handler = new Handler(doc);
      DocumentReader r = new DocumentReader(doc);
      InputSource input = new InputSource(r);
      sp.parse(input, handler);
      r.close();
    } catch (SAXParseException spe) {
      // A fatal parse error - ignore; a ParserNotice was already created.
    } catch (Exception e) {
      // e.printStackTrace(); // Will print if DTD specified and can't be found
      result.addNotice(
          new DefaultParserNotice(this, "Error parsing XML: " + e.getMessage(), 0, -1, -1));
    }

    return result;
  }
 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);
   }
 }
Beispiel #28
0
  /**
   * @param filename
   * @param docs
   */
  public void parse(String filename, Collection<WikipediaDocument> docs) {
    // System.out.println("::Parser::parse\nFilename=" + filename+ " Docs_size=" + docs.size());
    if (filename == null || filename.isEmpty()) {
      return;
    }
    try {

      InputStreamReader inReader = new InputStreamReader(new FileInputStream(filename), "UTF-8");
      BufferedReader reader = new BufferedReader(inReader);
      InputSource is = new InputSource(reader);
      is.setEncoding("UTF-8");

      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser saxParser = spf.newSAXParser();
      DefaultHandler handler = new XMLParser(docs);

      saxParser.parse(is, handler);

    } catch (IOException x) {
      System.err.println(x);
    } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      System.out.println("Parsing Terminated");
      e.printStackTrace();
    } finally {
    }
  }
 Parser(String uri) {
   try {
     SAXParserFactory parserFactory = SAXParserFactory.newInstance();
     SAXParser parser = parserFactory.newSAXParser();
     ConfigHandler handler = new ConfigHandler();
     parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", true);
     parser.parse(new File(uri), handler);
   } catch (IOException e) {
     System.out.println("Error reading URI: " + e.getMessage());
   } catch (SAXException e) {
     System.out.println("Error in parsing: " + e.getMessage());
   } catch (ParserConfigurationException e) {
     System.out.println("Error in XML parser configuration: " + e.getMessage());
   }
   // System.out.println("Number of Persons : " + Person.numberOfPersons());
   // nameLengthStatistics();
   // System.out.println("Number of Publications with authors/editors: " +
   //                   Publication.getNumberOfPublications());
   // System.out.println("Maximum number of authors/editors in a publication: " +
   //                           Publication.getMaxNumberOfAuthors());
   // publicationCountStatistics();
   // Person.enterPublications();
   // Person.printCoauthorTable();
   // Person.printNamePartTable();
   // Person.findSimilarNames();
 }
Beispiel #30
0
 /**
  * This method parses the data from the BBC XML link, via the SAX Parser and XMLHandler class.
  *
  * @see XMLHandler
  */
 private void getNews() {
   try {
     URL xmlUrl = new URL("http://feeds.bbci.co.uk/news/uk/rss.xml");
     SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
     SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
     XMLReader myXMLReader = mySAXParser.getXMLReader();
     XMLHandler myXMLHandler = new XMLHandler();
     myXMLReader.setContentHandler(myXMLHandler);
     InputSource myInputSource = new InputSource(xmlUrl.openStream());
     myXMLReader.parse(myInputSource);
     myXMLFeed = myXMLHandler.getFeed();
   }
   // catch a bunch of exceptions
   catch (MalformedURLException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (ParserConfigurationException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (SAXException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }