private void chargerPresentation(ZipInputStream projectZip)
      throws ParserConfigurationException, SAXException, IOException, FichierException {
    ZipEntry zipEntry = projectZip.getNextEntry();

    while (zipEntry != null && !this.presentationTrouve) {
      DataInputStream data = new DataInputStream(new BufferedInputStream(projectZip));
      if (zipEntry.getName().equals("Presentation.xml")) {
        this.presentationTrouve = true;
        this.print(Application.getApplication().getTraduction("SAX_initialisation"));
        // preparation du parsing
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxparser = factory.newSAXParser();
        this.print(Application.getApplication().getTraduction("presentation_parsing"));
        PresentationHandler handler = new PresentationHandler();
        saxparser.parse(data, handler);
        this.print(Application.getApplication().getTraduction("Presentation_charge"));
      } else {
        zipEntry = projectZip.getNextEntry();
      }
    }
    projectZip.close();
    if (!this.presentationTrouve) {
      throw new FichierException("Presentation");
    }
  }
 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);
   }
 }
示例#3
0
    /**
     * Return a <code>SAXParserFactory</code> instance that is non-validating and is namespace
     * aware.
     *
     * @return configured <code>SAXParserFactory</code>
     */
    private SAXParserFactory getConfiguredFactory() {

      SAXParserFactory factory = SAXParserFactory.newInstance();
      factory.setValidating(false);
      factory.setNamespaceAware(true);
      return factory;
    } // END getConfiguredFactory
  /** 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);
      }
    }
  }
示例#5
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;
   }
 }
示例#6
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 {
    }
  }
示例#7
0
 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;
 }
  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;
  }
示例#9
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;
  }
示例#10
0
  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();
    }
  }
示例#11
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;
  }
示例#12
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();
   }
 }
  public ArrayList<String> recomendaciones() {
    try {
      String direccion = "http://www.thetvdb.com/api/User_Favorites.php?accountid=7FB13C3CF230D455";

      URL url = new URL(direccion);

      HttpURLConnection conexion = (HttpURLConnection) url.openConnection();

      if (conexion.getResponseCode() == HttpURLConnection.HTTP_OK) {
        SAXParserFactory fabrica = SAXParserFactory.newInstance();
        SAXParser parser = fabrica.newSAXParser();
        XMLReader lector = parser.getXMLReader();
        ManejadorSerWeb manejadorXML = new ManejadorSerWeb();
        lector.setContentHandler(manejadorXML);
        lector.parse(new InputSource(conexion.getInputStream()));

        return manejadorXML.getRecomendaciones();
      } else {
        Log.e("ANDseries", conexion.getResponseMessage());
        return null;
      }
    } catch (Exception e) {
      Log.e("ANDseries", e.getMessage(), e);
      return null;
    }
  }
示例#14
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    PrintStream out = null;
    try {
      out = new PrintStream(new FileOutputStream("parser.txt"));
      System.setOut(out);

    } catch (FileNotFoundException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    saxParserFactory = SAXParserFactory.newInstance();
    try {
      saxParser = saxParserFactory.newSAXParser();
    } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    configReader = new RulesXMLConfigReader();
    loadRulesConfigfromXML();
    out.close();
  }
  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;
    }
  }
  /**
   * 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();
  }
  /**
   * {@link SAXParserFactoryUtil#setXIncludeAware}のテストです。
   *
   * @throws Exception
   */
  public void testSetXIncludeAware() throws Exception {
    SAXParserFactory spf = SAXParserFactoryUtil.newInstance();
    SAXParserFactoryUtil.setXIncludeAware(spf, true);
    spf.setNamespaceAware(true);
    SAXParser parser = SAXParserFactoryUtil.newSAXParser(spf);

    InputSource is =
        new InputSource(ResourceUtil.getResourceAsStream("org/seasar/framework/util/include.xml"));
    is.setSystemId("include.xml");
    parser.parse(
        is,
        new DefaultHandler() {

          @Override
          public void startElement(
              String uri, String localName, String qName, Attributes attributes)
              throws SAXException {
            if ("bar".equals(qName)) {
              included = true;
            }
          }

          @Override
          public InputSource resolveEntity(String publicId, String systemId)
              throws IOException, SAXException {
            InputSource is =
                new InputSource(
                    ResourceUtil.getResourceAsStream("org/seasar/framework/util/included.xml"));
            is.setSystemId("included.xml");
            return is;
          }
        });
    assertTrue(included);
  }
 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;
 }
  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;
  }
 /**
  * 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;
 }
  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()");
    }
  }
示例#22
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);
    }
  }
示例#23
0
  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();
  }
示例#24
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());
  }
 // 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;
 }
示例#26
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;
  }
示例#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
  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;
    }
  }
 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();
 }
示例#30
0
  private XMLReader getXMLReader(ContentHandler contentHandler, ErrorHandler errorHandler)
      throws ParserConfigurationException, SAXException {

    // setup sax factory ; be sure just one instance!
    SAXParserFactory saxFactory = SAXParserFactory.newInstance();

    // Enable validation stuff
    saxFactory.setValidating(true);
    saxFactory.setNamespaceAware(true);

    // Create xml reader
    SAXParser saxParser = saxFactory.newSAXParser();
    XMLReader xmlReader = saxParser.getXMLReader();

    // Setup xmlreader
    xmlReader.setProperty(
        XMLReaderObjectFactory.APACHE_PROPERTIES_INTERNAL_GRAMMARPOOL, grammarPool);

    xmlReader.setFeature(Namespaces.SAX_VALIDATION, true);
    xmlReader.setFeature(Namespaces.SAX_VALIDATION_DYNAMIC, false);
    xmlReader.setFeature(XMLReaderObjectFactory.APACHE_FEATURES_VALIDATION_SCHEMA, true);
    xmlReader.setFeature(XMLReaderObjectFactory.APACHE_PROPERTIES_LOAD_EXT_DTD, true);
    xmlReader.setFeature(Namespaces.SAX_NAMESPACES_PREFIXES, true);

    xmlReader.setContentHandler(contentHandler);
    xmlReader.setErrorHandler(errorHandler);

    return xmlReader;
  }