incrementalsaxsource_xerces.java

来自「JAVA 所有包」· Java 代码 · 共 453 行 · 第 1/2 页

JAVA
453
字号
  {    // Not supported by all SAX2 parsers but should work in Xerces:    try     {      // Typecast required in Xerces2; SAXParser doesn't inheret XMLReader      // %OPT% Cast at asignment?      ((XMLReader)fIncrementalParser).setProperty("http://xml.org/sax/properties/lexical-handler",                                     handler);    }    catch(org.xml.sax.SAXNotRecognizedException e)    {      // Nothing we can do about it    }    catch(org.xml.sax.SAXNotSupportedException e)    {      // Nothing we can do about it    }  }    // Register handler directly with the incremental parser  public void setDTDHandler(org.xml.sax.DTDHandler handler)  {    // Typecast required in Xerces2; SAXParser doesn't inheret XMLReader    // %OPT% Cast at asignment?    ((XMLReader)fIncrementalParser).setDTDHandler(handler);  }  //================================================================  /** startParse() is a simple API which tells the IncrementalSAXSource   * to begin reading a document.   *   * @throws SAXException is parse thread is already in progress   * or parsing can not be started.   * */  public void startParse(InputSource source) throws SAXException  {    if (fIncrementalParser==null)      throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_NEEDS_SAXPARSER, null)); //"startParse needs a non-null SAXParser.");    if (fParseInProgress)      throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_STARTPARSE_WHILE_PARSING, null)); //"startParse may not be called while parsing.");    boolean ok=false;    try    {      ok = parseSomeSetup(source);    }    catch(Exception ex)    {      throw new SAXException(ex);    }        if(!ok)      throw new SAXException(XMLMessages.createXMLMessage(XMLErrorResources.ER_COULD_NOT_INIT_PARSER, null)); //"could not initialize parser with");  }    /** deliverMoreNodes() is a simple API which tells the coroutine   * parser that we need more nodes.  This is intended to be called   * from one of our partner routines, and serves to encapsulate the   * details of how incremental parsing has been achieved.   *   * @param parsemore If true, tells the incremental parser to generate   * another chunk of output. If false, tells the parser that we're   * satisfied and it can terminate parsing of this document.   * @return Boolean.TRUE if the CoroutineParser believes more data may be available   * for further parsing. Boolean.FALSE if parsing ran to completion.   * Exception if the parser objected for some reason.   * */  public Object deliverMoreNodes (boolean parsemore)  {    if(!parsemore)    {      fParseInProgress=false;      return Boolean.FALSE;    }    Object arg;    try {      boolean keepgoing = parseSome();      arg = keepgoing ? Boolean.TRUE : Boolean.FALSE;    } catch (SAXException ex) {      arg = ex;    } catch (IOException ex) {      arg = ex;    } catch (Exception ex) {      arg = new SAXException(ex);    }    return arg;  }		// Private methods -- conveniences to hide the reflection details	private boolean parseSomeSetup(InputSource source) 		throws SAXException, IOException, IllegalAccessException, 					 java.lang.reflect.InvocationTargetException,					 java.lang.InstantiationException	{		if(fConfigSetInput!=null)		{			// Obtain input from SAX inputSource object, construct XNI version of			// that object. Logic adapted from Xerces2.			Object[] parms1={source.getPublicId(),source.getSystemId(),null};			Object xmlsource=fConfigInputSourceCtor.newInstance(parms1);			Object[] parmsa={source.getByteStream()};			fConfigSetByteStream.invoke(xmlsource,parmsa);			parmsa[0]=source.getCharacterStream();			fConfigSetCharStream.invoke(xmlsource,parmsa);			parmsa[0]=source.getEncoding();			fConfigSetEncoding.invoke(xmlsource,parmsa);			// Bugzilla5272 patch suggested by Sandy Gao.			// Has to be reflection to run with Xerces2			// after compilation against Xerces1. or vice			// versa, due to return type mismatches.			Object[] noparms=new Object[0];			fReset.invoke(fIncrementalParser,noparms);						parmsa[0]=xmlsource;			fConfigSetInput.invoke(fPullParserConfig,parmsa);						// %REVIEW% Do first pull. Should we instead just return true?			return parseSome();		}		else		{			Object[] parm={source};			Object ret=fParseSomeSetup.invoke(fIncrementalParser,parm);			return ((Boolean)ret).booleanValue();		}	}//  Would null work???    private static final Object[] noparms=new Object[0];    private static final Object[] parmsfalse={Boolean.FALSE};    private boolean parseSome()		throws SAXException, IOException, IllegalAccessException,					 java.lang.reflect.InvocationTargetException	{		// Take next parsing step, return false iff parsing complete:		if(fConfigSetInput!=null)		{			Object ret=(Boolean)(fConfigParse.invoke(fPullParserConfig,parmsfalse));			return ((Boolean)ret).booleanValue();		}		else		{			Object ret=fParseSome.invoke(fIncrementalParser,noparms);			return ((Boolean)ret).booleanValue();		}	}	  //================================================================  /** Simple unit test. Attempt coroutine parsing of document indicated   * by first argument (as a URI), report progress.   */  public static void _main(String args[])  {    System.out.println("Starting...");    CoroutineManager co = new CoroutineManager();    int appCoroutineID = co.co_joinCoroutineSet(-1);    if (appCoroutineID == -1)    {      System.out.println("ERROR: Couldn't allocate coroutine number.\n");      return;    }    IncrementalSAXSource parser=      createIncrementalSAXSource();    // Use a serializer as our sample output    com.sun.org.apache.xml.internal.serialize.XMLSerializer trace;    trace=new com.sun.org.apache.xml.internal.serialize.XMLSerializer(System.out,null);    parser.setContentHandler(trace);    parser.setLexicalHandler(trace);    // Tell coroutine to begin parsing, run while parsing is in progress    for(int arg=0;arg<args.length;++arg)    {      try      {        InputSource source = new InputSource(args[arg]);        Object result=null;        boolean more=true;        parser.startParse(source);        for(result = parser.deliverMoreNodes(more);            result==Boolean.TRUE;            result = parser.deliverMoreNodes(more))        {          System.out.println("\nSome parsing successful, trying more.\n");                      // Special test: Terminate parsing early.          if(arg+1<args.length && "!".equals(args[arg+1]))          {            ++arg;            more=false;          }                    }                if (result instanceof Boolean && ((Boolean)result)==Boolean.FALSE)        {          System.out.println("\nParser ended (EOF or on request).\n");        }        else if (result == null) {          System.out.println("\nUNEXPECTED: Parser says shut down prematurely.\n");        }        else if (result instanceof Exception) {          throw new com.sun.org.apache.xml.internal.utils.WrappedRuntimeException((Exception)result);          //          System.out.println("\nParser threw exception:");          //          ((Exception)result).printStackTrace();        }              }      catch(SAXException e)      {        e.printStackTrace();      }    }      }  } // class IncrementalSAXSource_Xerces

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?