示例#1
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
    }
  }
  @NotNull
  private MostlySingularMultiMap<String, AnnotationData> getDataFromFile(
      @NotNull final PsiFile file) {
    Pair<MostlySingularMultiMap<String, AnnotationData>, Long> cached =
        annotationFileToDataAndModStamp.get(file);
    final long fileModificationStamp = file.getModificationStamp();
    if (cached != null && cached.getSecond() == fileModificationStamp) {
      return cached.getFirst();
    }
    DataParsingSaxHandler handler = new DataParsingSaxHandler(file);
    try {
      SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
      saxParser.parse(new InputSource(new StringReader(escapeAttributes(file.getText()))), handler);
    } catch (IOException e) {
      LOG.error(e);
    } catch (ParserConfigurationException e) {
      LOG.error(e);
    } catch (SAXException e) {
      LOG.error(e);
    }

    Pair<MostlySingularMultiMap<String, AnnotationData>, Long> pair =
        Pair.create(handler.getResult(), file.getModificationStamp());
    annotationFileToDataAndModStamp.put(file, pair);

    return pair.first;
  }
示例#3
0
    @Override
    protected void realRun() throws SAXException, IOException, OsmTransferException {
      String urlString = useserver.url + java.net.URLEncoder.encode(searchExpression, "UTF-8");

      try {
        getProgressMonitor().indeterminateSubTask(tr("Querying name server ..."));
        URL url = new URL(urlString);
        synchronized (this) {
          connection = Utils.openHttpConnection(url);
        }
        connection.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect", 15) * 1000);
        InputStream inputStream = connection.getInputStream();
        InputSource inputSource = new InputSource(new InputStreamReader(inputStream, "UTF-8"));
        NameFinderResultParser parser = new NameFinderResultParser();
        SAXParserFactory.newInstance().newSAXParser().parse(inputSource, parser);
        this.data = parser.getResult();
      } catch (Exception e) {
        if (canceled)
          // ignore exception
          return;
        OsmTransferException ex = new OsmTransferException(e);
        ex.setUrl(urlString);
        lastException = ex;
      }
    }
示例#4
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();
   }
 }
 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);
   }
 }
 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;
 }
示例#7
0
 /** Private constructor */
 private XMLReaders(int validate) {
   SAXParserFactory fac = SAXParserFactory.newInstance();
   boolean val = false;
   // All JDOM parsers are namespace aware.
   fac.setNamespaceAware(true);
   switch (validate) {
     case 0:
       fac.setValidating(false);
       break;
     case 1:
       fac.setValidating(true);
       val = true;
       break;
     case 2:
       fac.setValidating(false);
       try {
         SchemaFactory sfac = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
         Schema schema = sfac.newSchema();
         fac.setSchema(schema);
         val = true;
       } catch (SAXException se) {
         // we could not get a validating system, set the fac to null
         fac = null;
       }
       break;
   }
   jaxpfactory = fac;
   validates = val;
 }
示例#8
0
  protected void validateXmlString(final String xml) throws Exception {
    if (getSchemaFile() == null) {
      LOG.warn("skipping validation, schema file not set");
      return;
    }

    final SchemaFactory schemaFactory =
        SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    final File schemaFile = new File(getSchemaFile());
    LOG.debug("Validating using schema file: {}", schemaFile);
    final Schema schema = schemaFactory.newSchema(schemaFile);

    final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setValidating(true);
    saxParserFactory.setNamespaceAware(true);
    saxParserFactory.setSchema(schema);

    assertTrue("make sure our SAX implementation can validate", saxParserFactory.isValidating());

    final Validator validator = schema.newValidator();
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    final Source source = new StreamSource(inputStream);

    validator.validate(source);
  }
  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;
  }
示例#10
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 {
    }
  }
示例#11
0
  public ArrayList<IProject> getProjects() {
    final ArrayList<IProject> result = new ArrayList<IProject>();
    try {
      IProject featureProject = getFeatureProject();
      IFile featureXMLFile = featureProject.getFile("feature.xml");
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

      DefaultHandler handler =
          new DefaultHandler() {
            @Override
            public void startElement(
                String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
              if ("plugin".equals(qName)) {
                String id = attributes.getValue("id");
                IProject eachProject = ResourcesPlugin.getWorkspace().getRoot().getProject(id);
                if (!eachProject.exists()) {
                  throw new BuildException(
                      MessageFormat.format(
                          "아이디가 {0}인 프로젝틀르 찾지 못했습니다. 프로젝트 아이디와 프로젝트 명은 동일한 것으로 간주합니다.", id));
                }
                result.add(eachProject);
              }
            }
          };
      parser.parse(featureXMLFile.getContents(), handler);
    } catch (Exception e) {
      throw new BuildException(e.getMessage(), e);
    }

    return result;
  }
  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;
    }
  }
  /**
   * 根据 xml 文件初始化配置信息,使用 AnalyzeHandler 进行 xml 解析
   *
   * <p>{@link AnalyzeHandler}
   *
   * @param context 上下文
   * @param xmlId xmlId(必须要在 res/raw 文件夹下)
   */
  void initVirtualLightningConfig(Context context, int xmlId) {
    String name = context.getResources().getResourceName(xmlId);

    if (!name.substring(name.indexOf(":") + 1, name.indexOf("/")).equals("raw")) {
      throw new VLInitException("资源文件后缀名不正确!必须为\".xml\"结尾放在\"res/raw\"的XML文件");
    }

    InputStream source = context.getResources().openRawResource(xmlId);

    try {
      SAXParser parser = SAXParserFactory.newInstance().newSAXParser();

      parser.parse(source, new AnalyzeHandler(this));

    } catch (ParserConfigurationException | SAXException | IOException e) {
      throw new VLInitException("解析 XML 文件发生错误:" + e.getMessage());
    } finally {
      try {
        source.close();
      } catch (IOException ignored) {
      }
    }

    initDatabase(context);
  }
示例#14
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;
    }
  }
示例#15
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;
  }
示例#16
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();
  }
示例#17
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());
    }
  }
示例#18
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;
 }
 public static SAXParser getSaxParser() throws ParserConfigurationException, SAXException {
   SAXParserFactory parserFactory = SAXParserFactory.newInstance();
   parserFactory.setNamespaceAware(false);
   parserFactory.setValidating(true);
   parserFactory.setXIncludeAware(false);
   return parserFactory.newSAXParser();
 }
  public boolean updataFeedFromServer(final int page, final int topicId, final int size) {
    Log.d(
        TAG,
        String.format("::updataFeedFromServer(page=%s,topicID=%s,size%s)", page, topicId, size));
    try {
      List<JokeBean> jokeItems = new ArrayList<JokeBean>();
      JokeClient client = new JokeClient();
      ResponseData responseData = client.getJokes(page, size, topicId);

      if (responseData.getStatus()) {
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        JokeBeanHandler handler = new JokeBeanHandler();
        InputSource is = new InputSource(new StringReader(responseData.toString()));
        parser.parse(is, handler);

        jokeItems.addAll(handler.getJokeItems());

        /* Set topic id */
        for (JokeBean item : jokeItems) {
          item.setTopic(topicId);
        }

        /* Now write the joke to cache */
        return db.addAll(jokeItems);
      }
    } catch (Exception e) {
      Log.e(TAG, "" + e.getMessage());
      e.printStackTrace();
    }
    return false;
  }
示例#21
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;
   }
 }
 private static SAXParser createParser() {
   try {
     return SAXParserFactory.newInstance().newSAXParser();
   } catch (Exception e) {
     return null;
   }
 }
 // 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;
 }
  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()");
    }
  }
示例#25
0
  // ---- main ----
  public static void main(final String[] argv) {
    if (argv.length != 1) {
      System.err.println(
          "Usage: java "
              + GpxReader.class.getSimpleName()
              + " <file>"); //$NON-NLS-1$ //$NON-NLS-2$
      System.exit(1);
    }

    final long startMillis = System.currentTimeMillis();

    try {
      final File f = new File(argv[0]);
      System.out.println("File size: " + f.length() + " bytes"); // $NON-NLS-1$ //$NON-NLS-2$

      // Use an instance of ourselves as the SAX event handler
      final DefaultHandler handler = new GpxReader();

      // Parse the input with the default (non-validating) parser
      final SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
      saxParser.parse(f, handler);
    } catch (final Exception t) {
      t.printStackTrace();
      System.exit(2);
    }

    final long millis = System.currentTimeMillis() - startMillis;
    System.out.println("Time consumed: " + millis + " ms"); // $NON-NLS-1$ //$NON-NLS-2$
  }
示例#26
0
  private static SAXParserFactory createFastSAXParserFactory()
      throws ParserConfigurationException, SAXException {
    if (fastParserFactoryClass == null) {
      try {
        fastParserFactoryClass =
            Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl"); // NOI18N
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        if (System.getProperty("java.version").startsWith("1.4")) { // NOI18N
          ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
        }
      }
    }
    if (fastParserFactoryClass != null) {
      try {
        SAXParserFactory factory = (SAXParserFactory) fastParserFactoryClass.newInstance();

        return factory;
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        throw new ParserConfigurationException(ex.getMessage());
      }
    }

    return SAXParserFactory.newInstance();
  }
示例#27
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
示例#28
0
  /** 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);
      }
    }
  }
 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
  @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());
  }