⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xpathfilter.java

📁 java开源的企业总线.xmlBlaster
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
   }      public void shutdown() {   }   /**    * Load xpath extension functions from a semicolon separated list of classes.    *    * <p>    * <b>List syntax:</b>    * <code><pre>    *  function := prefix ":" function-name ":" class-name    *  extensionClassList := ( function (";" function)* )?    * </pre></code>    *    * The prefix may be the empty string. The class must implement the <code>org.jaxen.Function</code> interface.    * </p>    * <p>    * <b>Example string:</b>    *    * <code>engine.mime.xpath.extension_functions=:recursive-text:org.xmlBlaster.engine.mime.xpath.RecursiveTextFunction</code>    * </p>    *    * @param extensionClassList semicolon separated list of function definitions    * @throws XmlBlasterException if the syntax is incorrect, or the class could not be loaded    */    protected void loadXPathExtensionFunctions(String extensionClassList) throws XmlBlasterException {       if (extensionClassList == null) {           return;       }       StringTokenizer st = new StringTokenizer(extensionClassList, ";");       while (st.hasMoreTokens()) {           String t = st.nextToken();           // prefix : func : class           int c1 = t.indexOf(":");           int c2 = t.lastIndexOf(":");           if (c1 == -1 || c2 == -1 || c1 == c2) {               throw new XmlBlasterException(this.glob, ErrorCode.USER_ILLEGALARGUMENT, ME, "Bad xpath extension function definition: \""                                             + t + "\". Expected: prefix \":\" function-name \":\" class");           }           String prefix = t.substring(0, c1);           String func = t.substring(c1+1, c2);           String klass = t.substring(c2+1);           if (func.length() == 0 || klass.length() == 0) {               throw new XmlBlasterException(this.glob, ErrorCode.USER_ILLEGALARGUMENT, ME, "Bad xpath extension function definition: \""                                             + t + "\". Expected: prefix \":\" function-name \":\" class");           }           try {                              Object o = Class.forName(klass).newInstance();               if (!(o instanceof Function)) {                   throw new XmlBlasterException(this.glob, ErrorCode.USER_ILLEGALARGUMENT, ME, "Extension function \""                                                 + klass + "\" does not implement org.jaxen.Function");               }               ((SimpleFunctionContext)XPathFunctionContext.getInstance())                   .registerFunction(("".equals(prefix)?null:prefix), func, (Function)o);           } catch (Exception e) {               throw new XmlBlasterException(this.glob, ErrorCode.USER_ILLEGALARGUMENT, ME,  "Could not load extension function \""                                             + klass + "\": " + e.getMessage());           }       }   }   /**    * Get a dom document for message, from cache or create a new one.    */      private synchronized Document getDocument(MsgUnit msg) throws XmlBlasterException {      /*      log.trace(ME,"Number of times qued: " + msg.getEnqueueCounter());      log.trace(ME,"Timestamp: " +msg.getRcvTimestamp());      log.trace(ME,"Unique key: " +msg.getUniqueKey());      log.trace(ME,"Key: " +msg.getXmlKey().toXml());      log.trace(ME,"Message: "+msg.getMessageUnit().getContentStr());      */      Document doc = null;      String key = msg.getKeyOid()+":"+msg.getQosData().getRcvTimestamp().getTimestamp();      // try get document from cache      int index = domCache.indexOf(new Entry(key,null));      if ( index != -1) {         if (log.isLoggable(Level.FINE))log.fine("Returning doc from cache with key: " +key);         Entry e = (Entry)domCache.get(index);         doc =  e.doc;      } else {         if (log.isLoggable(Level.FINE))log.fine("Constructing new doc from with key: " +key);         doc = getDocument(getXml(msg));                  // Put into cache and check size         Entry e = new Entry(key,doc);         domCache.addFirst(e);         if ( domCache.size() >= maxCacheSize) {            domCache.removeLast();         } // end of if ()                        } // end of else      return doc;   }      /**    * Access the XML string (from QoS or content).     * @param msg    * @return Is never null    */   private String getXml(MsgUnit msg) {      if (this.matchAgainstQos)         return msg.getQos();      else         return msg.getContentStr();   }      /**    * Create a new dom document.    *     */   private Document getDocument(String xml) throws XmlBlasterException {      try {            java.io.StringReader reader = new java.io.StringReader(xml);         InputSource input = new InputSource(reader);         DocumentBuilderFactory factory = glob.getDocumentBuilderFactory();         DocumentBuilder builder = factory.newDocumentBuilder ();         return builder.parse(input);        } catch (org.xml.sax.SAXException ex) {         String reason = ex.getMessage();         if(ex instanceof org.xml.sax.SAXParseException) {            org.xml.sax.SAXParseException s = (org.xml.sax.SAXParseException)ex;            reason = reason + " at line="+s.getLineNumber() + " column=" +               s.getColumnNumber() +               " in systemID=" + s.getSystemId();         }         throw new XmlBlasterException(this.glob, ErrorCode.USER_ILLEGALARGUMENT, ME, "Could not parse xml: " + reason);      }  catch (javax.xml.parsers.ParserConfigurationException ex) {         throw new XmlBlasterException(this.glob, ErrorCode.RESOURCE_CONFIGURATION, ME, "Could not setup parser " + ex);      } catch (java.io.IOException ex) {         throw new XmlBlasterException(this.glob, ErrorCode.USER_ILLEGALARGUMENT, ME, "Could not read xml " + ex);      }         } // end of try-catch   /**    * An entry in the domCache.    */   class Entry {      String key;      Document doc;      public Entry(String key, Document doc) {         this.key = key;         this.doc = doc;      }      /**       * An object is equal if it either an Entry with a key of the same value sa this, or a String with the same value as the key of this object!.       */      public boolean equals(Object o) {         if ( o != null &&               (o instanceof Entry || o instanceof String)              ){                        String k = (o instanceof String) ? (String)o : ((Entry)o).key;                        if ( key.equals(k)) {               return true;            } // end of if ()         }         return false;      }   }         /**    * Command line helper to test your XPath syntax.     * <p>     * Please pass on command line the XML of the message content,    * you then can interactively test your XPath query.    * Type 'q' to quit.    * <p>    * <tt>    * export CLASSPATH=$CLASSPATH:$XMLBLASTER_HOME/lib/jaxen.jar    * <br />    * java org.xmlBlaster.engine.mime.xpath.XPathFilter -inFile [someFile.xml]    * <br />    * java org.xmlBlaster.engine.mime.xpath.XPathFilter -inFile [someFile.xml] -xslContentTransformerFileName [someFile.xsl]    * <br />    * Example:<br />    * cd xmlBlaster/testsuite/data/xml<br/>    * java org.xmlBlaster.engine.mime.xpath.XPathFilter -inFile Airport.xml -xslContentTransformerFileName transformToKeyValue.xsl    * </tt>     * <p>    * todo: Using http://jline.sourceforge.net/ for nicer command line input handling    * <br />Example:     * java -cp /opt/download/jline-demo.jar:/opt/download/jline-0_9_5-demo.jar jline.example.Example simple    *     * @param args -inFile [fileName.xml] OR -xml [the xml string]    */   public static void main(String[] args) {      try {         ServerScope scope = new ServerScope(args);         Global glob = scope;         XPathFilter filter = new XPathFilter();         filter.initialize(scope);         // check -matchAgainstQos and -xslContentTransformFileName command line settings          String xslFile = Args.getArg(args, "-"+XSL_CONTENT_TRANSFORMER_FILE_NAME, (String)null);         boolean isQos = Args.getArg(args, "-"+MATCH_AGAINST_QOS, false);         String xml = Args.getArg(args, "-xml", (String)null);         if (xml == null) {            String inFile = Args.getArg(args, "-inFile", (String)null);            if (inFile == null || inFile.length() < 1) {               System.out.println("\nUsage:  java org.xmlBlaster.engine.mime.xpath.XPathFilter -inFile [someFile]");               System.exit(1);            }            xml = FileLocator.readAsciiFile(inFile);         }         String content = (!isQos) ? xml : "";         String qos = (isQos) ? xml : "<qos/>";         MsgUnit msgUnit = new MsgUnit("<key oid='Hello'/>", content, qos);         msgUnit.getQosData().setRcvTimestamp(new Timestamp());         SessionInfo sessionInfo = null;         PluginInfo info = new PluginInfo(glob, null, "XPathFilter", "1.0");         info.getParameters().put(MATCH_AGAINST_QOS, ""+isQos);         if (xslFile != null)            info.getParameters().put(XSL_CONTENT_TRANSFORMER_FILE_NAME, xslFile);         filter.init(glob, info);                  BufferedReader in = new BufferedReader(new InputStreamReader(System.in));                  System.out.println("The XML to query is");         System.out.println("==================================");         System.out.println(xml);         System.out.println("==================================");         System.out.println("Enter your xpath like '//a' or type 'q' to quit");         String line = "";         while (true) {            System.out.println("");            line = ""; // Nice to have: showing old query, this does not work - use jline            System.out.print("xpath> " + line);            line = in.readLine(); // Blocking in I/O            if (line == null) continue;            line = line.trim();            if (line.length() < 1) continue;            Query query = new Query(glob, line);            if (line.toLowerCase().equals("q") || line.toLowerCase().equals("quit")) {               System.out.println("Bye");               System.exit(0);            }            try {               boolean ret = filter.match(sessionInfo, msgUnit, query);               //System.out.println("Query: " + query.getQuery());               System.out.println("Match: " + ret);               if (ret == true && xslFile != null) {                  System.out.println("Transformed content: " + msgUnit.getContentStr());               }            }            catch (Exception e) { // javap org.jaxen.XPathSyntaxException               System.out.println(e.toString());               e.printStackTrace();            }         }      } catch (XmlBlasterException e) {         log.severe(e.getMessage());         if (!e.isResource())            e.printStackTrace();      }      catch (IOException e) {         log.severe(e.toString());      }   }}

⌨️ 快捷键说明

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