You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@xalan.apache.org by mu...@apache.org on 2025/02/28 01:03:27 UTC

(xalan-java) branch xalan-j_xslt3.0_mvn updated: committing implementation of xpath function fn:collection. this is wip.

This is an automated email from the ASF dual-hosted git repository.

mukulg pushed a commit to branch xalan-j_xslt3.0_mvn
in repository https://gitbox.apache.org/repos/asf/xalan-java.git


The following commit(s) were added to refs/heads/xalan-j_xslt3.0_mvn by this push:
     new 658d527fb committing implementation of xpath function fn:collection. this is wip.
658d527fb is described below

commit 658d527fb70341b9488d78a971046b564df9b723
Author: Mukul Gandhi <ga...@gmail.com>
AuthorDate: Fri Feb 28 06:33:10 2025 +0530

    committing implementation of xpath function fn:collection. this is wip.
---
 .../org/apache/xpath/compiler/FunctionTable.java   |   9 +-
 .../java/org/apache/xpath/compiler/Keywords.java   |   3 +
 .../org/apache/xpath/functions/FuncCollection.java | 228 +++++++++++++++++++++
 3 files changed, 239 insertions(+), 1 deletion(-)

diff --git a/src/main/java/org/apache/xpath/compiler/FunctionTable.java b/src/main/java/org/apache/xpath/compiler/FunctionTable.java
index 1d748f9c1..50abdd945 100644
--- a/src/main/java/org/apache/xpath/compiler/FunctionTable.java
+++ b/src/main/java/org/apache/xpath/compiler/FunctionTable.java
@@ -532,6 +532,9 @@ public class FunctionTable
   
   /** The 'unparsed-text-lines()' id. */
   public static final int FUNC_UNPARSED_TEXT_LINES = 169;
+  
+  /** The 'collection()' id. */
+  public static final int FUNC_COLLECTION = 170;
 
   // Proprietary
 
@@ -625,7 +628,7 @@ public class FunctionTable
    * Number of built in functions. Be sure to update this as
    * built-in functions are added.
    */
-  private static final int NUM_BUILT_IN_FUNCS = 170;
+  private static final int NUM_BUILT_IN_FUNCS = 171;
 
   /**
    * Number of built-in functions that may be added.
@@ -726,6 +729,8 @@ public class FunctionTable
       org.apache.xpath.functions.FuncUnparsedText.class;
     m_functions[FUNC_UNPARSED_TEXT_LINES] = 
       org.apache.xpath.functions.FuncUnparsedTextLines.class;
+    m_functions[FUNC_COLLECTION] = 
+      org.apache.xpath.functions.FuncCollection.class;
     m_functions[FUNC_STRING_JOIN] = 
       org.apache.xpath.functions.FuncStringJoin.class;
     m_functions[FUNC_CURRENT_DATETIME] = 
@@ -1006,6 +1011,8 @@ public class FunctionTable
                           new Integer(FunctionTable.FUNC_UNPARSED_TEXT));
           m_functionId.put(Keywords.FUNC_UNPARSED_TEXT_LINES,
                           new Integer(FunctionTable.FUNC_UNPARSED_TEXT_LINES));
+          m_functionId.put(Keywords.FUNC_COLLECTION,
+                          new Integer(FunctionTable.FUNC_COLLECTION));
           m_functionId.put(Keywords.FUNC_STRING_JOIN,
                           new Integer(FunctionTable.FUNC_STRING_JOIN));
           m_functionId.put(Keywords.FUNC_CURRENT_DATETIME,
diff --git a/src/main/java/org/apache/xpath/compiler/Keywords.java b/src/main/java/org/apache/xpath/compiler/Keywords.java
index 606ae6bb6..cec063a59 100644
--- a/src/main/java/org/apache/xpath/compiler/Keywords.java
+++ b/src/main/java/org/apache/xpath/compiler/Keywords.java
@@ -694,6 +694,9 @@ public class Keywords
   /** unparsed-text-lines function string. */
   public static final String FUNC_UNPARSED_TEXT_LINES = "unparsed-text-lines";
   
+  /** collection function string. */
+  public static final String FUNC_COLLECTION = "collection";
+  
   // Proprietary, built in functions
 
   /** current function string (Proprietary). */
diff --git a/src/main/java/org/apache/xpath/functions/FuncCollection.java b/src/main/java/org/apache/xpath/functions/FuncCollection.java
new file mode 100644
index 000000000..55496b03c
--- /dev/null
+++ b/src/main/java/org/apache/xpath/functions/FuncCollection.java
@@ -0,0 +1,228 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the  "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/*
+ * $Id$
+ */
+package org.apache.xpath.functions;
+
+import java.io.File;
+import java.net.URI;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.List;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.SourceLocator;
+import javax.xml.transform.dom.DOMSource;
+
+import org.apache.xalan.xslt.util.XslTransformEvaluationHelper;
+import org.apache.xml.dtm.DTM;
+import org.apache.xml.dtm.DTMManager;
+import org.apache.xml.utils.Constants;
+import org.apache.xpath.XPathContext;
+import org.apache.xpath.functions.json.JsonFunction;
+import org.apache.xpath.objects.ResultSequence;
+import org.apache.xpath.objects.XNodeSet;
+import org.apache.xpath.objects.XObject;
+import org.apache.xpath.regex.Pattern;
+import org.w3c.dom.Document;
+
+import xml.xpath31.processor.types.XSString;
+
+/**
+ * Implementation of an XPath 3.1 function fn:collection.
+ * 
+ * @author Mukul Gandhi <mu...@apache.org>
+ * 
+ * @xsl.usage advanced
+ */
+public class FuncCollection extends JsonFunction
+{
+
+	private static final long serialVersionUID = -5613347556907647341L;
+	
+	private static final String XML = "xml";
+	
+	private static final String JSON = "json";
+	
+	private static final String TEXT = "txt";
+	
+	private static final char PERIOD_CHAR = '.';
+	
+	private static final String SLAH_CHAR_STR = "/";
+	
+	private static final String[] ALLOWED_FILE_EXTS = {XML, JSON, TEXT};
+
+	/**
+	 * Execute the function. The function must return
+	 * a valid object.
+	 * @param xctxt The current execution context.
+	 * @return A valid XObject.
+	 *
+	 * @throws javax.xml.transform.TransformerException
+	 */
+	public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException
+	{          
+		XObject result = null;
+		
+		ResultSequence resultSeq = new ResultSequence();
+		
+		XObject arg0XObj = m_arg0.execute(xctxt);
+		String arg0StrValue = XslTransformEvaluationHelper.getStrVal(arg0XObj);
+		
+		if (arg0StrValue.startsWith("file:///")) {
+			String fileSystemPathStr = arg0StrValue.substring(8);
+			resultSeq = getResultSequenceFromFileSystemPathStr(fileSystemPathStr, xctxt);
+		}
+		else if (arg0StrValue.startsWith("file:/")) {
+			String fileSystemPathStr = arg0StrValue.substring(6);			
+			resultSeq = getResultSequenceFromFileSystemPathStr(fileSystemPathStr, xctxt);
+		}
+		
+		result = resultSeq; 
+
+		return result;
+	}
+
+	/**
+	 * Given a file system local directory path string, interpreting the file name suffix as 
+	 * regex and prefix as directory (currently no regex are assumed within directory name 
+	 * prefix), return an XDM sequence containing ordered list of XML document nodes (corresponding 
+	 * to XML document files), JSON maps or/and arrays (corresponding to JSON document files), or/and 
+	 * strings correspond to other kinds of text files (for e.g, CSV or/and TSV). 
+	 */
+	private ResultSequence getResultSequenceFromFileSystemPathStr(String fileSystemPathStr, 
+			                                                      XPathContext xctxt) throws javax.xml.transform.TransformerException {
+		
+		ResultSequence resultSeq = new ResultSequence();
+		
+		SourceLocator srcLocator = xctxt.getSAXLocator();
+		
+		String[] filePathPartStringArr = fileSystemPathStr.split(SLAH_CHAR_STR);
+		
+		String dirPathStr = "";			
+		for (int idx = 0; idx < (filePathPartStringArr.length - 1); idx++) {
+			dirPathStr += filePathPartStringArr[idx];
+			if (idx != (filePathPartStringArr.length - 2)) {
+				dirPathStr += SLAH_CHAR_STR;	
+			}
+		}
+		
+		File dirFileObj = new File(dirPathStr);
+		String[] fileNameArr = dirFileObj.list();
+		
+		String fileNameRegex = filePathPartStringArr[filePathPartStringArr.length - 1];						
+		
+		for (int idx = 0; idx < fileNameArr.length; idx++) {
+			String fileNameStr = fileNameArr[idx];
+			int lastPeriodIdx = fileNameStr.lastIndexOf(PERIOD_CHAR);
+			if (Pattern.matches(fileNameRegex, fileNameStr) && 
+					                                isFileExtValid(fileNameStr.substring(lastPeriodIdx + 1))) {
+				if (fileNameStr.endsWith(PERIOD_CHAR + XML)) {
+					File fileObj = new File(dirPathStr, fileNameStr);  
+					try {
+						Document document = getXmlDomFromFileObj(fileObj);						
+						DTMManager dtmMgr = xctxt.getDTMManager();
+						DTM dtm = dtmMgr.getDTM(new DOMSource(document), true, null, false, false);
+						int docNodeDtmHandle = dtm.getDocument();							
+						XNodeSet xNodeSet = new XNodeSet(docNodeDtmHandle, dtmMgr);
+						resultSeq.add(xNodeSet);
+					}
+					catch (Exception ex) {
+						throw new javax.xml.transform.TransformerException("FODC0004 : An XPath dynamic error occured while "
+								                                           + "constructing an XML document node for file " + 
+								                                           (dirPathStr + SLAH_CHAR_STR + fileNameStr) + " during processing "
+								                                           + "with XPath function fn:collection.", srcLocator); 
+					}
+				}
+				else if (fileNameStr.endsWith(PERIOD_CHAR + JSON)) {
+					try {
+						byte[] byteArr = Files.readAllBytes(Paths.get(new URI(dirPathStr + SLAH_CHAR_STR + fileNameStr)));
+						String strValue = new String(byteArr);							
+						XObject xObj = getJsonXdmValueFromStr(strValue);							
+						resultSeq.add(xObj);
+					}
+					catch (Exception ex) {
+						throw new javax.xml.transform.TransformerException("FODC0004 : An XPath dynamic error occured while "
+                                                                           + "constructing an XDM map/array for JSON file " + (dirPathStr + 
+                                                                           SLAH_CHAR_STR + fileNameStr) + " during processing "
+                                                                           + "with XPath function fn:collection." , srcLocator);
+					}
+				}
+				else if (fileNameStr.endsWith(PERIOD_CHAR + TEXT)) {
+					try {
+						byte[] byteArr = Files.readAllBytes(Paths.get(new URI(dirPathStr + SLAH_CHAR_STR + fileNameStr)));
+						String strValue = new String(byteArr);
+						resultSeq.add(new XSString(strValue));
+					}
+					catch (Exception ex) {
+						throw new javax.xml.transform.TransformerException("FODC0004 : An XPath dynamic error occured while "
+                                                                           + "constructing string value from contents of text file " + 
+                                                                           (dirPathStr + SLAH_CHAR_STR + fileNameStr) + " during processing "
+                                                                           + "with XPath function fn:collection.", srcLocator);
+					}
+				}
+				else {
+					throw new javax.xml.transform.TransformerException("FODC0004 : Only XML (ext .xml), JSON (ext .json) and text (ext .txt) "
+							                                           + "file documents are supported for processing by XPath function fn:collection. "
+							                                           + "Invalid file "+ (dirPathStr + SLAH_CHAR_STR + fileNameStr) + " is provided as "
+							                                           + "input for processing with function fn:collection.", srcLocator);
+				}
+			}
+		}
+		
+		return resultSeq;
+	}
+	
+	/**
+     * Method definition to check whether the file extension string passed as 
+     * an argument to this method, is allowed for the function implementation 
+     * fn:collection.
+	 */
+	private boolean isFileExtValid(String fileExtStr) {
+		boolean result = false;
+		
+		List<String> allowedFileExtList = Arrays.asList(ALLOWED_FILE_EXTS);
+		if (allowedFileExtList.contains(fileExtStr)) {
+			result = true;
+		}
+		
+		return result;
+	}
+	
+	/**
+	 * Method definition to get an XML DOM object instance, represented by an XML 
+	 * document java.io.File object instance.
+	 */
+	private Document getXmlDomFromFileObj(File fileObj) throws Exception {
+		Document document = null;
+		
+		System.setProperty(Constants.XML_DOCUMENT_BUILDER_FACTORY_KEY, Constants.XML_DOCUMENT_BUILDER_FACTORY_VALUE);
+		
+		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+		dbf.setNamespaceAware(true);
+		DocumentBuilder dBuilder = dbf.newDocumentBuilder();
+		
+		document = dBuilder.parse(fileObj);
+		
+		return document;
+	}
+  
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@xalan.apache.org
For additional commands, e-mail: commits-help@xalan.apache.org