|
From: <pm_...@us...> - 2011-06-08 08:54:41
|
Revision: 4393
http://mxquery.svn.sourceforge.net/mxquery/?rev=4393&view=rev
Author: pm_fischer
Date: 2011-06-08 08:54:35 +0000 (Wed, 08 Jun 2011)
Log Message:
-----------
- removed unneeded b:log function, use fn:trace instead
- support annotations also for inline functions
Modified Paths:
--------------
trunk/MXQuery/src/ch/ethz/mxquery/query/parser/Parser.java
Removed Paths:
-------------
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/Log.java
Modified: trunk/MXQuery/src/ch/ethz/mxquery/query/parser/Parser.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/query/parser/Parser.java 2011-06-08 08:52:53 UTC (rev 4392)
+++ trunk/MXQuery/src/ch/ethz/mxquery/query/parser/Parser.java 2011-06-08 08:54:35 UTC (rev 4393)
@@ -1751,10 +1751,12 @@
logger.log(LogLevel.INFO, "Completed parsing function "+qname.toString()+ " took "+(System.currentTimeMillis()-startTime));
return true;
- } else {
- index = declareIndex;
- }
-
+ } else
+ if (annotations.size() > 0)
+ generateParseError("function");
+ else
+ index = declareIndex;
+
if (parseKeyword("option")) {
XQName qname = EQName();
@@ -6586,8 +6588,9 @@
private Iterator InlineFunction() throws MXQueryException {
int startIndex = index;
+ Hashtable annotations = Annotation();
if (parseKeyword("function")) {
- Function fn = parseFunctionDef(new Hashtable(), null, false);
+ Function fn = parseFunctionDef(annotations, null, false);
if (fn == null) {
index = startIndex;
return null;
@@ -6599,6 +6602,9 @@
FunctionItemToken fTok = new FunctionItemToken(fn);
return new TokenIterator(getCurrentContext(), fTok, getCurrentLoc(),false);
}
+ } else {
+ if (annotations.size() > 0)
+ generateParseError("function");
}
return null;
}
Deleted: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/Log.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/Log.java 2011-06-08 08:52:53 UTC (rev 4392)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/Log.java 2011-06-08 08:54:35 UTC (rev 4393)
@@ -1,80 +0,0 @@
-package ch.ethz.mxquery.functions.b;
-
-import java.util.Vector;
-
-import com.google.gwt.user.client.Window;
-
-import ch.ethz.mxqjs.client.Environment;
-import ch.ethz.mxquery.contextConfig.Context;
-import ch.ethz.mxquery.datamodel.MXQueryBigDecimal;
-import ch.ethz.mxquery.datamodel.MXQueryDouble;
-import ch.ethz.mxquery.datamodel.MXQueryFloat;
-import ch.ethz.mxquery.datamodel.types.Type;
-import ch.ethz.mxquery.datamodel.types.TypeInfo;
-import ch.ethz.mxquery.datamodel.xdm.DecimalToken;
-import ch.ethz.mxquery.datamodel.xdm.DoubleToken;
-import ch.ethz.mxquery.datamodel.xdm.FloatToken;
-import ch.ethz.mxquery.datamodel.xdm.LongToken;
-import ch.ethz.mxquery.datamodel.xdm.Token;
-import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
-import ch.ethz.mxquery.exceptions.DynamicException;
-import ch.ethz.mxquery.exceptions.ErrorCodes;
-import ch.ethz.mxquery.exceptions.MXQueryException;
-import ch.ethz.mxquery.exceptions.TypeException;
-import ch.ethz.mxquery.functions.fn.Abs;
-import ch.ethz.mxquery.model.TokenBasedIterator;
-import ch.ethz.mxquery.model.XDMIterator;
-
-public class Log extends TokenBasedIterator {
-
- @Override
- protected void init() throws MXQueryException {
- currentToken = Token.END_SEQUENCE_TOKEN;
- if (subIters[0] == null) {
- throw new IllegalArgumentException();
- }
- XDMIterator iter = subIters[0];
- //if (iter instanceof DataValuesIterator) ((DataValuesIterator)iter).setFnData(true);
- TokenInterface tok;
- try {
- tok = iter.next();
- } catch (TypeException de) {
- if (de.getErrorCode().equals(ErrorCodes.E0004_TYPE_INAPPROPRIATE_TYPE))
- throw new DynamicException(ErrorCodes.F0023_INVALID_VALUE_FOR_CAST_CONSTRUCTOR,de.getMessage(), loc);
- else throw de;
- }
-
- int type = Type.getEventTypeSubstituted(tok.getEventType(), Context.getDictionary());
-
- if ( Type.isAttribute(type) ){
- type = Type.getAttributeValueType(type);
- }
-
- switch (type) {
- case Type.END_SEQUENCE:
- break;
- default:
- Environment.log(tok.getValueAsString());
-
- }
-
- }
-
-
-
- @Override
- public TypeInfo getStaticType() {
- return new TypeInfo();
- }
-
-
- @Override
- protected XDMIterator copy(Context context, XDMIterator[] subIters,
- Vector nestedPredCtxStack) throws MXQueryException {
- XDMIterator copy = new Log();
- copy.setContext(context, true);
- copy.setSubIters(subIters);
- return copy;
- }
-
-}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <max...@us...> - 2011-06-13 18:57:22
|
Revision: 4400
http://mxquery.svn.sourceforge.net/mxquery/?rev=4400&view=rev
Author: maxspeicher
Date: 2011-06-13 18:57:15 +0000 (Mon, 13 Jun 2011)
Log Message:
-----------
- improved method discovery in NativeFuncCall.java
- added helper classes UiListener and BackgroundTask to Android branch
- extended MXQuery helper class in Android branch with certain methods for using prepared expressions + some minor changes
- added Android-specific version of fn:doc-available() (cf. fn:doc())
Modified Paths:
--------------
trunk/MXQuery/android/src/ch/ethz/mxquery/android/MXQuery.java
trunk/MXQuery/android/src/ch/ethz/mxquery/android/UiListener.java
trunk/MXQuery/src/ch/ethz/mxquery/iterators/NativeFuncCall.java
Added Paths:
-----------
trunk/MXQuery/android/src/ch/ethz/mxquery/android/BackgroundTask.java
trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/DocAvailable.java
Added: trunk/MXQuery/android/src/ch/ethz/mxquery/android/BackgroundTask.java
===================================================================
--- trunk/MXQuery/android/src/ch/ethz/mxquery/android/BackgroundTask.java (rev 0)
+++ trunk/MXQuery/android/src/ch/ethz/mxquery/android/BackgroundTask.java 2011-06-13 18:57:15 UTC (rev 4400)
@@ -0,0 +1,72 @@
+package ch.ethz.mxquery.android;
+
+import android.app.Activity;
+import android.os.AsyncTask;
+
+public class BackgroundTask extends AsyncTask<Void, Void, Void> {
+
+ private Activity current;
+ private String dialogTitle, whileFunction, postFunction;
+
+ public BackgroundTask(String dialogTitle, String whileFunction, String postFunction) {
+ this.current = MXQuery.getActivity();
+ this.dialogTitle = dialogTitle;
+ this.whileFunction = whileFunction;
+ this.postFunction = postFunction;
+ }
+
+ public void execute() {
+ this.execute(null, null, null);
+ }
+
+ @Override
+ protected void onPreExecute() {
+ MXQuery.setDialogTitle(dialogTitle);
+ current.showDialog(1);
+ }
+
+ @Override
+ protected Void doInBackground(Void... arg0) {
+// try {
+// XQPreparedExpression xqjp;
+//
+// if ((xqjp = MXQuery.getPreparedExpression()) != null) {
+// xqjp.bindString(new QName("yyExt"), whileFunction, null);
+// Log.i("BackgroundTask", "Query result: " + MXQuery.doPreparedQuery(xqjp));
+// }
+// } catch (XQException xqe) {
+// xqe.printStackTrace();
+// Log.e("BackgroundTask", "Error: " + xqe.getMessage());
+// }
+
+ MXQuery.doQuery(
+ MXQuery.getXQueryFile() +
+ whileFunction + "()"
+ );
+
+ return null;
+ }
+
+ @Override
+ protected void onPostExecute(Void unused) {
+ current.removeDialog(1);
+
+// try {
+// XQPreparedExpression xqjp;
+//
+// if ((xqjp = MXQuery.getPreparedExpression()) != null) {
+// xqjp.bindString(new QName("yyExt"), postFunction, null);
+// Log.i("BackgroundTask", "Query result: " + MXQuery.doPreparedQuery(xqjp));
+// }
+// } catch (XQException xqe) {
+// xqe.printStackTrace();
+// Log.e("BackgroundTask", "Error: " + xqe.getMessage());
+// }
+
+ MXQuery.doQuery(
+ MXQuery.getXQueryFile() +
+ postFunction + "()"
+ );
+ }
+
+}
Modified: trunk/MXQuery/android/src/ch/ethz/mxquery/android/MXQuery.java
===================================================================
--- trunk/MXQuery/android/src/ch/ethz/mxquery/android/MXQuery.java 2011-06-12 23:50:51 UTC (rev 4399)
+++ trunk/MXQuery/android/src/ch/ethz/mxquery/android/MXQuery.java 2011-06-13 18:57:15 UTC (rev 4400)
@@ -1,18 +1,13 @@
package ch.ethz.mxquery.android;
import java.io.BufferedReader;
-import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
+import java.util.HashMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
-import ch.ethz.mxquery.xqj.MXQueryXQDataSource;
-import ch.ethz.repackaged.xquery.XQConnection;
-import ch.ethz.repackaged.xquery.XQDataSource;
-import ch.ethz.repackaged.xquery.XQException;
-import ch.ethz.repackaged.xquery.XQExpression;
-import ch.ethz.repackaged.xquery.XQSequence;
-
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
@@ -21,14 +16,26 @@
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
+import android.widget.Toast;
+import ch.ethz.mxquery.xqj.MXQueryXQDataSource;
+import ch.ethz.repackaged.xquery.XQConnection;
+import ch.ethz.repackaged.xquery.XQDataSource;
+import ch.ethz.repackaged.xquery.XQException;
+import ch.ethz.repackaged.xquery.XQExpression;
+import ch.ethz.repackaged.xquery.XQPreparedExpression;
+import ch.ethz.repackaged.xquery.XQSequence;
public class MXQuery {
private static Activity act;
private static Context ctx;
+ private static Object[] arguments;
+ private static String dialogTitle;
private static String xQueryFile;
private static XQDataSource xqjd = new MXQueryXQDataSource(MXQueryXQDataSource.XQJ_SCRIPTING_MODE);
+ private static HashMap<Activity, XQPreparedExpression> preparedExpressions = new HashMap<Activity, XQPreparedExpression>();
+
public static void init(Activity act) {
MXQuery.ctx = act.getApplicationContext();
MXQuery.act = act;
@@ -42,10 +49,6 @@
return act;
}
- public static void startActivity(Class<?> next) {
- act.startActivity(new Intent(act, next));
- }
-
public static String getXQueryFile() {
return xQueryFile;
}
@@ -54,6 +57,30 @@
xQueryFile = readXQueryFile(rawResourceId);
}
+ public static XQPreparedExpression getPreparedExpression() {
+ if (preparedExpressions.containsKey(act)) {
+ return preparedExpressions.get(act);
+ } else {
+ return null;
+ }
+ }
+
+ public static XQPreparedExpression getPreparedExpression(Activity a) {
+ if (preparedExpressions.containsKey(a)) {
+ return preparedExpressions.get(a);
+ } else {
+ return null;
+ }
+ }
+
+ public static Object getArgument(int index) {
+ return arguments[index];
+ }
+
+ public static void setArguments(Object[] args) {
+ arguments = args;
+ }
+
public static Button getButton(int id) {
return (Button) act.findViewById(id);
}
@@ -66,6 +93,91 @@
return (TextView) act.findViewById(id);
}
+ public static String getDialogTitle() {
+ return dialogTitle;
+ }
+
+ public static void setDialogTitle(String title) {
+ dialogTitle = title;
+ }
+
+ public static void startActivity(String className) {
+ try {
+ act.startActivity(new Intent(act, Class.forName(className)));
+ } catch (ClassNotFoundException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public static void makeToast(String msg) {
+ Toast.makeText(act, msg, 1).show();
+ }
+
+ public static void prepareExpression(Activity a, int rawResourceId) throws XQException {
+ String xQueryFile = readXQueryFile(rawResourceId);
+ String funcSignature = "declare( simple| sequential| updating)? function ([^\\s(]+) ?\\(([^)]*)\\)";
+
+ Pattern funcSignaturePattern = Pattern.compile(funcSignature);
+ Matcher funcSignatureMatcher = funcSignaturePattern.matcher(xQueryFile);
+
+ xQueryFile += "\ndeclare variable $yyExt external;\n";
+
+ boolean updating = false;
+ boolean sequential = false;
+ int i = 0;
+ String temp = "";
+ String funcModifier, funcName, argString;
+
+ while (funcSignatureMatcher.find()) {
+ funcModifier = funcSignatureMatcher.group(1);
+ funcName = funcSignatureMatcher.group(2);
+ argString = funcSignatureMatcher.group(3);
+
+ if (funcModifier != null && funcModifier.contains("updating")) {
+ updating = true;
+ } else if (funcModifier != null && funcModifier.contains("sequential")) {
+ sequential = true;
+ }
+
+ temp += (i == 0 ? " if " : " else if ");
+ temp += "($x eq '" + funcName + "') then\n " + funcName + "(";
+
+ int dollarSigns = 0;
+
+ for (int j=0; j<argString.length(); ++j) {
+ if (argString.charAt(j) == '$') {
+ temp += (dollarSigns > 0 ? ", " : "");
+ temp += ("m:getArgument(" + dollarSigns + ")");
+ ++dollarSigns;
+ }
+ }
+
+ temp += ")\n";
+
+ ++i;
+ }
+
+ xQueryFile += "declare ";
+
+ if (updating) {
+ xQueryFile += "updating ";
+ } else if (sequential) {
+ xQueryFile += "sequential ";
+ }
+
+ xQueryFile += (
+ "function local:yyChooseFunction($x) {\n" +
+ " $x,\n" + temp +
+ " else\n 'Error! No function chosen!'\n};\n" +
+ "local:yyChooseFunction($yyExt)"
+ );
+
+ XQConnection xqjc = xqjd.getConnection();
+ XQPreparedExpression xqjp = xqjc.prepareExpression(xQueryFile);
+
+ preparedExpressions.put(a, xqjp);
+ }
+
public static String doQuery(String query) {
StringWriter result = new StringWriter();
@@ -78,11 +190,29 @@
xqjc.close();
} catch (XQException xqe) {
xqe.printStackTrace();
+
return xqe.getMessage();
}
+
return result.toString();
}
+
+ public static String doPreparedQuery(XQPreparedExpression xqjp) {
+ StringWriter result = new StringWriter();
+ try {
+ XQSequence xqjs = xqjp.executeQuery();
+
+ xqjs.writeSequence(result, null);
+ } catch (XQException xqe) {
+ xqe.printStackTrace();
+
+ return xqe.getMessage();
+ }
+
+ return result.toString();
+ }
+
public static String readXQueryFile(int rawResourceId) {
BufferedReader in = new BufferedReader(new InputStreamReader(
act.getResources().openRawResource(rawResourceId)));
Modified: trunk/MXQuery/android/src/ch/ethz/mxquery/android/UiListener.java
===================================================================
--- trunk/MXQuery/android/src/ch/ethz/mxquery/android/UiListener.java 2011-06-12 23:50:51 UTC (rev 4399)
+++ trunk/MXQuery/android/src/ch/ethz/mxquery/android/UiListener.java 2011-06-13 18:57:15 UTC (rev 4400)
@@ -2,25 +2,40 @@
import android.view.View;
import android.view.View.OnClickListener;
-import ch.ethz.mxquery.android.MXQuery;
public class UiListener implements OnClickListener {
- public String methodName;
+ private String methodName;
public static View view;
public UiListener(String methodName) {
- this.methodName = methodName;
+ this.methodName = methodName;
}
public void onClick(View v) {
- view = v;
-
- MXQuery.doQuery(
- MXQuery.getXQueryFile() +
- methodName +
- "(uil:view())"
- );
+ view = v;
+
+// Object[] args = new Object[1];
+// args[0] = v;
+// MXQuery.setArguments(args);
+//
+// try {
+// XQPreparedExpression xqjp;
+//
+// if ((xqjp = MXQuery.getPreparedExpression()) != null) {
+// xqjp.bindString(new QName("yyExt"), methodName, null);
+// Log.i("UiListener", "Query result: " + MXQuery.doPreparedQuery(xqjp));
+// }
+// } catch (XQException xqe) {
+// xqe.printStackTrace();
+// Log.e("UiListener", "Error: " + xqe.getMessage());
+// }
+
+ MXQuery.doQuery(
+ MXQuery.getXQueryFile() +
+ methodName +
+ "(uil:view())"
+ );
}
}
Added: trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/DocAvailable.java
===================================================================
--- trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/DocAvailable.java (rev 0)
+++ trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/DocAvailable.java 2011-06-13 18:57:15 UTC (rev 4400)
@@ -0,0 +1,133 @@
+/* Copyright 2006 - 2009 ETH Zurich
+ *
+ * Licensed 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.
+ */
+
+package ch.ethz.mxquery.functions.fn;
+
+import java.io.BufferedReader;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.MalformedURLException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.util.Vector;
+
+import ch.ethz.mxquery.android.MXQuery;
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.types.TypeInfo;
+import ch.ethz.mxquery.datamodel.types.TypeLexicalConstraints;
+import ch.ethz.mxquery.datamodel.xdm.BooleanToken;
+import ch.ethz.mxquery.exceptions.DynamicException;
+import ch.ethz.mxquery.exceptions.ErrorCodes;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.model.TokenBasedIterator;
+import ch.ethz.mxquery.model.XDMIterator;
+import ch.ethz.mxquery.util.IOLib;
+
+public class DocAvailable extends TokenBasedIterator {
+
+ protected void init() throws MXQueryException {
+ String add = getStringValueOrEmpty(subIters[0]);
+
+ if (add == null) {
+ currentToken = BooleanToken.FALSE_TOKEN;
+ return;
+ }
+ URI uri;
+
+ if (!TypeLexicalConstraints.isValidURI(add))
+ throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC,"Invalid URI given to fn:doc-available", loc);
+ try {
+ if (TypeLexicalConstraints.isAbsoluteURI(add)) {
+ uri = new URI(add);
+ } else {
+// String base = context.getBaseURI();
+// String add1 = add;
+// if (add1.startsWith("/"))
+// add1 = add1.substring(1);
+ uri = new URI(IOLib.convertToAndroid(add));
+ }
+ } catch (URISyntaxException se) {
+ throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC,"Invalid URI given to fn:doc-available", loc);
+ }
+ if(add.startsWith("http://")){
+
+ URL url;
+ try {
+ url = uri.toURL();
+ } catch (MalformedURLException e) {
+ throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC,"Invalid URI given to fn:doc-available", loc);
+ }
+ try {
+ InputStream in = url.openStream();
+ in.close();
+ } catch (IOException e) {
+ currentToken = BooleanToken.FALSE_TOKEN;
+ return;
+ }
+ currentToken = BooleanToken.TRUE_TOKEN;
+ // }
+ // catch(Exception e){
+ // throw new DynamicException(ErrorCodes.A0006_EC_URI_NOT_FOUND, "Remote Data cannot be accessed: " + e);
+ // }
+ }
+ else {
+// File xml;
+// try {
+// xml = new File(uri);
+// }catch(IllegalArgumentException ia) {
+// try {
+// xml = new File(add);
+// } catch (IllegalArgumentException ia2) {
+// throw new DynamicException(ErrorCodes.F0017_INVALID_ARGUMENT_TO_FN_DOC,"Invalid URI given to fn:doc-available", loc);
+// }
+// }
+// if (xml.exists()) {
+// currentToken = BooleanToken.TRUE_TOKEN;
+// } else {
+// currentToken = BooleanToken.FALSE_TOKEN;
+// }
+
+ try {
+ BufferedReader in = new BufferedReader(
+ new InputStreamReader(
+ MXQuery.getContext().openFileInput(uri.toString())
+ )
+ );
+ currentToken = BooleanToken.TRUE_TOKEN;
+ } catch (FileNotFoundException e) {
+ currentToken = BooleanToken.FALSE_TOKEN;
+ } catch (IOException e) {
+ currentToken = BooleanToken.FALSE_TOKEN;
+ }
+ }
+ }
+
+ public TypeInfo getStaticType() {
+ return new TypeInfo(Type.BOOLEAN,Type.OCCURRENCE_IND_EXACTLY_ONE);
+ }
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack)
+ throws MXQueryException {
+ XDMIterator copy = new DocAvailable();
+ copy.setContext(context, true);
+ copy.setSubIters(subIters);
+ return copy;
+ }
+
+}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/iterators/NativeFuncCall.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/iterators/NativeFuncCall.java 2011-06-12 23:50:51 UTC (rev 4399)
+++ trunk/MXQuery/src/ch/ethz/mxquery/iterators/NativeFuncCall.java 2011-06-13 18:57:15 UTC (rev 4400)
@@ -149,40 +149,59 @@
*/
for (int i=0; i<methods.length; ++i) {
if (methodName.equals(methods[i].getName())) {
+// System.out.println("[CAND] " + methods[i].toGenericString());
Class[] params = methods[i].getParameterTypes();
- boolean add = true;
-
- if (params.length == invocationParams.length) {
+
+ if (invocationParams.length == params.length) {
+ boolean add = true;
+
for (int j=0; j<params.length; ++j) {
+ if (params[j].equals(byte.class)) {
+ params[j] = Byte.class;
+ } else if (params[j].equals(short.class)) {
+ params[j] = Short.class;
+ } else if (params[j].equals(int.class)) {
+ params[j] = Integer.class;
+ } else if (params[j].equals(long.class)) {
+ params[j] = Long.class;
+ } else if (params[j].equals(float.class)) {
+ params[j] = Float.class;
+ } else if (params[j].equals(double.class)) {
+ params[j] = Double.class;
+ } else if (params[j].equals(boolean.class)) {
+ params[j] = Boolean.class;
+ } else if (params[j].equals(char.class)) {
+ params[j] = Character.class;
+ }
+
if (!params[j].isInstance(invocationParams[j])) {
+// System.out.println("failure: "
+// + invocationParams[j].toString() + ", "
+// + invocationParamsTypes[j].getName() + " -> "
+// + params[j].getName());
add = false;
+ } else {
+// System.out.println("success: "
+// + invocationParams[j].toString() + ", "
+// + invocationParamsTypes[j].getName() + " -> "
+// + params[j].getName());
}
}
-
+
if (add) {
+// System.out.println("[ADD] " + methods[i].toGenericString());
candidates.add(methods[i]);
}
}
- }
+ }
}
- try {
- meth = native_function.getMethod(methodName, invocationParamsTypes);
+ if (candidates.size() > 0) {
+ meth = (Method) candidates.get(0);
res = meth.invoke(instanceToCall, invocationParams);
- } catch (NoSuchMethodException e) {
- /*
- * The method name provided by XQuery is either the
- * name of a field, or the method could not be
- * retrieved b/c the parameter types of the signature
- * are interfaces or abstract classes.
- */
- if (candidates.size() == 1) {
- meth = (Method) candidates.get(0);
- res = meth.invoke(instanceToCall, invocationParams);
- } else {
- field = native_function.getField(methodName);
- res = field.get(instanceToCall);
- }
+ } else {
+ field = native_function.getField(methodName);
+ res = field.get(instanceToCall);
}
}
@@ -197,19 +216,19 @@
this.current = new TokenIterator(context, wrap, loc, false);
}
} catch (SecurityException e) {
- throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Native call failed: "+e.getMessage(), loc);
+ throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "SecurityException: Native call failed: "+e.getMessage(), loc);
} catch (NoSuchFieldException e) {
- throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Native call failed: "+e.getMessage(), loc);
+ throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "NoSuchFieldException: Native call failed: "+e.getMessage(), loc);
} catch (NoSuchMethodException e) {
- throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Native call failed: "+e.getMessage(), loc);
+ throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "NoSuchMethodException: Native call failed: "+e.getMessage(), loc);
} catch (IllegalArgumentException e) {
- throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Native call failed: "+e.getMessage(), loc);
+ throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "IllegalArgumentException: Native call failed: "+e.getMessage(), loc);
} catch (IllegalAccessException e) {
- throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Native call failed: "+e.getMessage(), loc);
+ throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "IllegalAccessException: Native call failed: "+e.getMessage(), loc);
} catch (InvocationTargetException e) {
- throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Native call failed: "+e.getMessage(), loc);
+ throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "InvocationTargetException: Native call failed: "+e.getMessage(), loc);
} catch (InstantiationException e) {
- throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Native call failed: "+e.getMessage(), loc);
+ throw new DynamicException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "InstantiationException: Native call failed: "+e.getMessage(), loc);
}
//this.current = new TokenIterator(context, 42,Type.INT, loc);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <et...@us...> - 2011-06-14 01:51:53
|
Revision: 4401
http://mxquery.svn.sourceforge.net/mxquery/?rev=4401&view=rev
Author: etterth
Date: 2011-06-14 01:51:42 +0000 (Tue, 14 Jun 2011)
Log Message:
-----------
- Added js-call(functionname,arg0,arg1,...) with up to 6 arguments
Modified Paths:
--------------
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/MxQueryToJs.java
trunk/MXQuery/xqib_src/functiongallerytojava.xsl
Added Paths:
-----------
trunk/MXQuery/xqib_samples/js-call1.html
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/JsCall.java
Added: trunk/MXQuery/xqib_samples/js-call1.html
===================================================================
--- trunk/MXQuery/xqib_samples/js-call1.html (rev 0)
+++ trunk/MXQuery/xqib_samples/js-call1.html 2011-06-14 01:51:42 UTC (rev 4401)
@@ -0,0 +1,19 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <title>XQIB: Sample page</title>
+ <meta charset="UTF-8"/>
+ <script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
+<script type="text/javascript">
+ foo = function (arg1){ return 'the text was ' + arg1;};
+</script>
+ <script type="application/xquery">
+ let $x := b:js-call('window.foo', string(b:dom()/id('a')/text()))
+ return
+ replace value of node b:dom()/id('a') with $x
+ </script>
+ </head>
+ <body>
+ <h1 id='a'>Some text.</h1>
+ </body>
+</html>
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml 2011-06-13 18:57:15 UTC (rev 4400)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml 2011-06-14 01:51:42 UTC (rev 4401)
@@ -1,7 +1,65 @@
<?xml version='1.0' encoding='UTF-8' ?>
<functionGallery basePackage="ch.ethz.mxquery.functions.">
<functionGroup prefix="b" namespace="http://xqib.org">
+<!-- js-call -->
+ <functionDescription>
+ <functionName>js-call</functionName>
+ <parameters>
+ <paramType>xs:string</paramType>
+ </parameters>
+ <className>JsCall</className>
+ </functionDescription>
<functionDescription>
+ <functionName>js-call</functionName>
+ <parameters>
+ <paramType>xs:string</paramType>
+ <paramType>item()*</paramType>
+ </parameters>
+ <className>JsCall</className>
+ </functionDescription>
+ <functionDescription>
+ <functionName>js-call</functionName>
+ <parameters>
+ <paramType>xs:string</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ </parameters>
+ <className>JsCall</className>
+ </functionDescription>
+ <functionDescription>
+ <functionName>js-call</functionName>
+ <parameters>
+ <paramType>xs:string</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ </parameters>
+ <className>JsCall</className>
+ </functionDescription>
+ <functionDescription>
+ <functionName>js-call</functionName>
+ <parameters>
+ <paramType>xs:string</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ </parameters>
+ <className>JsCall</className>
+ </functionDescription> <functionDescription>
+ <functionName>js-call</functionName>
+ <parameters>
+ <paramType>xs:string</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ <paramType>item()*</paramType>
+ </parameters>
+ <className>JsCall</className>
+ </functionDescription>
+<!-- js-call -->
+ <functionDescription>
<functionName>js-eval</functionName>
<parameters>
<paramType>xs:string</paramType>
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java 2011-06-13 18:57:15 UTC (rev 4400)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java 2011-06-14 01:51:42 UTC (rev 4401)
@@ -37,6 +37,7 @@
ctx.addNamespace(XQStaticContext.NS_BROWSER,
XQStaticContext.URI_BROWSER);
TypeInfo xs_string = new TypeInfo(FunctionGallery.getType("xs:string",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
+ TypeInfo item___star = new TypeInfo(FunctionGallery.getType("item()*",ctx), Type.OCCURRENCE_IND_ZERO_OR_MORE,null);
TypeInfo xs_integer = new TypeInfo(FunctionGallery.getType("xs:integer",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
TypeInfo function__ = new TypeInfo(FunctionGallery.getType("function()",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
TypeInfo xs_dateTime = new TypeInfo(FunctionGallery.getType("xs:dateTime",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
@@ -52,7 +53,6 @@
TypeInfo xs_time_quest = new TypeInfo(FunctionGallery.getType("xs:time?",ctx), Type.OCCURRENCE_IND_ZERO_OR_ONE,null);
TypeInfo xs_time = new TypeInfo(FunctionGallery.getType("xs:time",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
TypeInfo xs_anyAtomicType_star = new TypeInfo(FunctionGallery.getType("xs:anyAtomicType*",ctx), Type.OCCURRENCE_IND_ZERO_OR_MORE,null);
- TypeInfo item___star = new TypeInfo(FunctionGallery.getType("item()*",ctx), Type.OCCURRENCE_IND_ZERO_OR_MORE,null);
TypeInfo xs_integer_star = new TypeInfo(FunctionGallery.getType("xs:integer*",ctx), Type.OCCURRENCE_IND_ZERO_OR_MORE,null);
TypeInfo xs_anyAtomicType_quest = new TypeInfo(FunctionGallery.getType("xs:anyAtomicType?",ctx), Type.OCCURRENCE_IND_ZERO_OR_ONE,null);
TypeInfo xs_duration_quest = new TypeInfo(FunctionGallery.getType("xs:duration?",ctx), Type.OCCURRENCE_IND_ZERO_OR_ONE,null);
@@ -102,50 +102,186 @@
qn = new QName(
"http://xqib.org",
"b",
- "js-eval");
+ "js-call");
paramTypes = new TypeInfo[1];
- paramTypes[0] = xs_string;
+ paramTypes[0] = xs_string;
+ signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+ {
+ ch.ethz.mxquery.functions.b.JsCall iter = new ch.ethz.mxquery.functions.b.JsCall();
+ iter.setContext(context, false);
+
+ type = null;
+
+ function = new Function(
+ null,signature,
+ iter, null, type );
+ fg.add(function);
+ }
+
+ qn = new QName(
+ "http://xqib.org",
+ "b",
+ "js-call");
+ paramTypes = new TypeInfo[2];
+
+ paramTypes[0] = xs_string;
+ paramTypes[1] = item___star;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+ {
+ ch.ethz.mxquery.functions.b.JsCall iter = new ch.ethz.mxquery.functions.b.JsCall();
+ iter.setContext(context, false);
- {
- ch.ethz.mxquery.functions.b.JsEval iter = new ch.ethz.mxquery.functions.b.JsEval();
+ type = null;
+
+ function = new Function(
+ null,signature,
+ iter, null, type );
+ fg.add(function);
+ }
+
+ qn = new QName(
+ "http://xqib.org",
+ "b",
+ "js-call");
+ paramTypes = new TypeInfo[3];
+
+ paramTypes[0] = xs_string;
+ paramTypes[1] = item___star;
+ paramTypes[2] = item___star;
+ signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+
+ {
+ ch.ethz.mxquery.functions.b.JsCall iter = new ch.ethz.mxquery.functions.b.JsCall();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
"b",
- "timer");
- paramTypes = new TypeInfo[2];
+ "js-call");
+ paramTypes = new TypeInfo[4];
- paramTypes[0] = xs_integer;
+ paramTypes[0] = xs_string;
+ paramTypes[1] = item___star;
+ paramTypes[2] = item___star;
+ paramTypes[3] = item___star;
+ signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
- paramTypes[1] = function__;
+ {
+ ch.ethz.mxquery.functions.b.JsCall iter = new ch.ethz.mxquery.functions.b.JsCall();
+ iter.setContext(context, false);
+ type = null;
+
+ function = new Function(
+ null,signature,
+ iter, null, type );
+ fg.add(function);
+ }
+
+ qn = new QName(
+ "http://xqib.org",
+ "b",
+ "js-call");
+ paramTypes = new TypeInfo[5];
+
+ paramTypes[0] = xs_string;
+ paramTypes[1] = item___star;
+ paramTypes[2] = item___star;
+ paramTypes[3] = item___star;
+ paramTypes[4] = item___star;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+ {
+ ch.ethz.mxquery.functions.b.JsCall iter = new ch.ethz.mxquery.functions.b.JsCall();
+ iter.setContext(context, false);
- {
+ type = null;
+
+ function = new Function(
+ null,signature,
+ iter, null, type );
+ fg.add(function);
+ }
+
+ qn = new QName(
+ "http://xqib.org",
+ "b",
+ "js-call");
+ paramTypes = new TypeInfo[6];
+
+ paramTypes[0] = xs_string;
+ paramTypes[1] = item___star;
+ paramTypes[2] = item___star;
+ paramTypes[3] = item___star;
+ paramTypes[4] = item___star;
+ paramTypes[5] = item___star;
+ signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+
+ {
+ ch.ethz.mxquery.functions.b.JsCall iter = new ch.ethz.mxquery.functions.b.JsCall();
+ iter.setContext(context, false);
+
+ type = null;
+
+ function = new Function(
+ null,signature,
+ iter, null, type );
+ fg.add(function);
+ }
+
+ qn = new QName(
+ "http://xqib.org",
+ "b",
+ "js-eval");
+ paramTypes = new TypeInfo[1];
+
+ paramTypes[0] = xs_string;
+ signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+
+ {
+ ch.ethz.mxquery.functions.b.JsEval iter = new ch.ethz.mxquery.functions.b.JsEval();
+ iter.setContext(context, false);
+
+ type = null;
+
+ function = new Function(
+ null,signature,
+ iter, null, type );
+ fg.add(function);
+ }
+
+ qn = new QName(
+ "http://xqib.org",
+ "b",
+ "timer");
+ paramTypes = new TypeInfo[2];
+
+ paramTypes[0] = xs_integer;
+ paramTypes[1] = function__;
+ signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+
+ {
ch.ethz.mxquery.functions.b.Timer iter = new ch.ethz.mxquery.functions.b.Timer();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -155,18 +291,17 @@
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.GetCookieNames iter = new ch.ethz.mxquery.functions.b.GetCookieNames();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -174,22 +309,20 @@
"getCookie");
paramTypes = new TypeInfo[1];
- paramTypes[0] = xs_string;
-
+ paramTypes[0] = xs_string;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.GetCookie iter = new ch.ethz.mxquery.functions.b.GetCookie();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -197,22 +330,20 @@
"removeCookie");
paramTypes = new TypeInfo[1];
- paramTypes[0] = xs_string;
-
+ paramTypes[0] = xs_string;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.RemoveCookie iter = new ch.ethz.mxquery.functions.b.RemoveCookie();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -220,24 +351,21 @@
"setCookie");
paramTypes = new TypeInfo[2];
- paramTypes[0] = xs_string;
-
- paramTypes[1] = xs_string;
-
+ paramTypes[0] = xs_string;
+ paramTypes[1] = xs_string;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.SetCookie iter = new ch.ethz.mxquery.functions.b.SetCookie();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -245,26 +373,22 @@
"setCookie");
paramTypes = new TypeInfo[3];
- paramTypes[0] = xs_string;
-
- paramTypes[1] = xs_string;
-
- paramTypes[2] = xs_dateTime;
-
+ paramTypes[0] = xs_string;
+ paramTypes[1] = xs_string;
+ paramTypes[2] = xs_dateTime;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.SetCookie iter = new ch.ethz.mxquery.functions.b.SetCookie();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -274,18 +398,17 @@
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.LocUri iter = new ch.ethz.mxquery.functions.b.LocUri();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -293,22 +416,20 @@
"setHref");
paramTypes = new TypeInfo[1];
- paramTypes[0] = xs_string;
-
+ paramTypes[0] = xs_string;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.SetHref iter = new ch.ethz.mxquery.functions.b.SetHref();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -318,18 +439,17 @@
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.GetLocation iter = new ch.ethz.mxquery.functions.b.GetLocation();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -337,22 +457,20 @@
"alert");
paramTypes = new TypeInfo[1];
- paramTypes[0] = xs_string;
-
+ paramTypes[0] = xs_string;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.Alert iter = new ch.ethz.mxquery.functions.b.Alert();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -360,24 +478,21 @@
"removeClass");
paramTypes = new TypeInfo[2];
- paramTypes[0] = node___plus;
-
- paramTypes[1] = xs_string;
-
+ paramTypes[0] = node___plus;
+ paramTypes[1] = xs_string;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.RemoveClassName iter = new ch.ethz.mxquery.functions.b.RemoveClassName();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -385,22 +500,20 @@
"getClasses");
paramTypes = new TypeInfo[1];
- paramTypes[0] = node___plus;
-
+ paramTypes[0] = node___plus;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.GetClasses iter = new ch.ethz.mxquery.functions.b.GetClasses();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -408,24 +521,21 @@
"addClass");
paramTypes = new TypeInfo[2];
- paramTypes[0] = node___plus;
-
- paramTypes[1] = xs_string;
-
+ paramTypes[0] = node___plus;
+ paramTypes[1] = xs_string;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.AddClassName iter = new ch.ethz.mxquery.functions.b.AddClassName();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -433,28 +543,23 @@
"addEventListener");
paramTypes = new TypeInfo[4];
- paramTypes[0] = node___plus;
-
- paramTypes[1] = xs_string;
-
- paramTypes[2] = QName;
-
- paramTypes[3] = xs_integer;
-
+ paramTypes[0] = node___plus;
+ paramTypes[1] = xs_string;
+ paramTypes[2] = QName;
+ paramTypes[3] = xs_integer;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.AddEventListener iter = new ch.ethz.mxquery.functions.b.AddEventListener();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -462,26 +567,22 @@
"addEventListener");
paramTypes = new TypeInfo[3];
- paramTypes[0] = node___plus;
-
- paramTypes[1] = xs_string;
-
- paramTypes[2] = function__;
-
+ paramTypes[0] = node___plus;
+ paramTypes[1] = xs_string;
+ paramTypes[2] = function__;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.AddEventListener iter = new ch.ethz.mxquery.functions.b.AddEventListener();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -489,28 +590,23 @@
"removeEventListener");
paramTypes = new TypeInfo[4];
- paramTypes[0] = node___plus;
-
- paramTypes[1] = xs_string;
-
- paramTypes[2] = QName;
-
- paramTypes[3] = xs_integer;
-
+ paramTypes[0] = node___plus;
+ paramTypes[1] = xs_string;
+ paramTypes[2] = QName;
+ paramTypes[3] = xs_integer;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
-
- {
+ {
ch.ethz.mxquery.functions.b.RemoveEventListener iter = new ch.ethz.mxquery.functions.b.RemoveEventListener();
iter.setContext(context, false);
- type = null;
+ type = null;
function = new Function(
null,signature,
iter, null, type );
fg.add(function);
- }
+ }
qn = new QName(
"http://xqib.org",
@@ -518,26 +614,22 @@
"removeEventListener");
paramTypes = new TypeInfo[3];
- paramTypes[0] = node__;
-
- paramTypes[1] = xs_string;
-
- paramTypes[2] = function__;
-
+ paramTypes[0] = node__;
+ paramTyp...
[truncated message content] |
|
From: <et...@us...> - 2011-06-16 01:37:16
|
Revision: 4406
http://mxquery.svn.sourceforge.net/mxquery/?rev=4406&view=rev
Author: etterth
Date: 2011-06-16 01:37:09 +0000 (Thu, 16 Jun 2011)
Log Message:
-----------
- Window events added
- Diverse bug fixes
Modified Paths:
--------------
trunk/MXQuery/xqib_src/ch/ethz/mxqjs/client/Environment.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/GetLocation.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/WindowInfo.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/EventIterator.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/SingleNodeIterator.java
Added Paths:
-----------
trunk/MXQuery/xqib_samples/lateresolve-behavior.html
trunk/MXQuery/xqib_samples/window-event.html
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/AddWindowListener.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/RemoveWindowListener.java
Added: trunk/MXQuery/xqib_samples/lateresolve-behavior.html
===================================================================
--- trunk/MXQuery/xqib_samples/lateresolve-behavior.html (rev 0)
+++ trunk/MXQuery/xqib_samples/lateresolve-behavior.html 2011-06-16 01:37:09 UTC (rev 4406)
@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <title>XQIB: Sample page</title>
+ <meta charset="UTF-8"/>
+ <script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
+ <script type="application/xquery">
+ declare updating function local:update() {
+ replace node b:dom()//div with <div>{concat('The window height is ', b:windowInfo()/b:client-height/text())}<br/>{concat('The window width is ', b:windowInfo()/b:client-width/text())}</div>
+ };
+ declare updating function local:listener($loc, $evtObj) {
+ local:update()
+ };
+local:update(),
+ b:addWindowListener("resize", local:listener#2)
+ </script>
+ </head>
+ <body>
+ <h1 id='a'>Window event</h1>
+<div/>
+ </body>
+</html>
Added: trunk/MXQuery/xqib_samples/window-event.html
===================================================================
--- trunk/MXQuery/xqib_samples/window-event.html (rev 0)
+++ trunk/MXQuery/xqib_samples/window-event.html 2011-06-16 01:37:09 UTC (rev 4406)
@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <title>XQIB: Sample page</title>
+ <meta charset="UTF-8"/>
+ <script type="application/xquery">
+module namespace up = "update";
+ declare updating function up:update() {
+ replace node b:dom()//div with <div>{concat('The window height is ', b:windowInfo()/b:client-height/text())}<br/>{concat('The window width is ', b:windowInfo()/b:client-width/text())}</div>
+ };
+ </script>
+ <script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
+ <script type="application/xquery">
+import module namespace up = "update";
+ declare updating function local:listener($loc, $evtObj) {
+ up:update()
+ };
+up:update(),
+ b:addWindowListener("resize", local:listener#2)
+ </script>
+ </head>
+ <body>
+ <h1 id='a'>Window event</h1>
+<div/>
+ </body>
+</html>
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxqjs/client/Environment.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxqjs/client/Environment.java 2011-06-15 17:51:06 UTC (rev 4405)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxqjs/client/Environment.java 2011-06-16 01:37:09 UTC (rev 4406)
@@ -17,6 +17,7 @@
import ch.ethz.mxquery.iterators.browser.EventIterator;
import ch.ethz.mxquery.iterators.browser.ListBasedIterator;
import ch.ethz.mxquery.iterators.browser.SingleNodeIterator;
+import ch.ethz.mxquery.model.EmptySequenceIterator;
import ch.ethz.mxquery.model.Iterator;
import ch.ethz.mxquery.model.XDMIterator;
import ch.ethz.mxquery.query.PreparedStatement;
@@ -34,6 +35,7 @@
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Document;
+import com.google.gwt.dom.client.EventTarget;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.dom.client.Text;
@@ -47,6 +49,7 @@
static Context modCtx = new Context();
static CompilerOptions co;
static int contextcounter = 0;
+ private static Hashtable<String, List<FunctionItemToken>> windowhandlers;
public static CompilerOptions getCompilerOptions() {
if (co != null)
@@ -102,18 +105,17 @@
// modCtx = null;
co = null;
handlers = null;
+ windowhandlers = null;
}
- public static void addEventListener(JavaScriptObject obj, String eventName,
+ public static void addEventListener(Element el, String eventName,
FunctionItemToken fi, Context ctx) {
if (eventName.startsWith("on"))
eventName = eventName.substring(2);
- if (handlers == null)
+ if (handlers == null)
handlers = new Hashtable<NodeAndEventName, List<FunctionItemToken>>();
+
- if (JsToMxQuery.isNode(obj)) {
- //node
- Element el = (Element) obj;
NodeAndEventName test = new NodeAndEventName(el, eventName);
List<FunctionItemToken> lst = handlers.get(test);
if (lst == null) {
@@ -121,17 +123,37 @@
handlers.put(test, lst);
}
lst.add(fi);
+
+
+
+ nativeAddEventListener(el, eventName);
+ }
+
+ public static void addWindowListener(String eventName,
+ FunctionItemToken fi, Context ctx) {
+ if (eventName.startsWith("on"))
+ eventName = eventName.substring(2);
+ if (windowhandlers == null) {
+ windowhandlers = new Hashtable<String, List<FunctionItemToken>>();
}
- else {
- //window
- //TODO
-
- }
- nativeAddEventListener(obj, eventName);
+ List<FunctionItemToken> lst = windowhandlers.get(eventName);
+ if (lst == null) {
+ lst = new ArrayList<FunctionItemToken>();
+ windowhandlers.put(eventName, lst);
+ }
+ lst.add(fi);
+
+
+
+ nativeAddWindowListener(eventName);
}
- public static void removeEventListener(JavaScriptObject obj, String eventName,
+ private static native JavaScriptObject getWindowObject() /*-{
+ return $wnd;
+ }-*/;
+
+ public static void removeEventListener(Element el, String eventName,
FunctionItemToken fi, Context ctx) throws MXQueryException {
if (eventName.startsWith("on"))
eventName = eventName.substring(2);
@@ -140,8 +162,6 @@
"handler to remove cannot be found", null);
- if (JsToMxQuery.isNode(obj)) {
- Element el = (Element) obj;
NodeAndEventName test = new NodeAndEventName(el, eventName);
List<FunctionItemToken> lst = handlers.get(test);
if (lst == null) {
@@ -165,13 +185,46 @@
handlers.put(test, null);
nativeRemoveEventListener(el, eventName);
}
- } else {
- //window
- //TODO
- }
+
}
+
+ public static void removeWindowListener(String eventName,
+ FunctionItemToken fi, Context ctx) throws MXQueryException {
+ if (eventName.startsWith("on"))
+ eventName = eventName.substring(2);
+ if (windowhandlers == null)
+ throw new MXQueryException("Eventlistener cannot be removed",
+ "handler to remove cannot be found", null);
+
+ String test = eventName;
+ List<FunctionItemToken> lst = windowhandlers.get(test);
+ if (lst == null) {
+ throw new MXQueryException("Eventlistener cannot be removed",
+ "handler to remove cannot be found", null);
+ }
+ List<FunctionItemToken> lstnew = new ArrayList<FunctionItemToken>();
+ ListIterator<FunctionItemToken> it = lst.listIterator();
+
+ while (it.hasNext()) {
+ FunctionItemToken ft = it.next();
+ FunctionSignature fts = ft.getFunction().getFunctionSignature();
+ FunctionSignature fis = fi.getFunction().getFunctionSignature();
+ if (!fis.getName().equals(fts.getName())
+ || fts.getArity() != fis.getArity())
+ lstnew.add(ft);
+ }
+ windowhandlers.remove(test);
+ windowhandlers.put(test, lstnew);
+ if (lst.isEmpty()) {
+ windowhandlers.put(test, null);
+ nativeRemoveWindowListener(eventName);
+ }
+
+
+ }
+
public static void removeAnonymousEventListeners(Element el,
String eventName, Context ctx) throws MXQueryException {
if (eventName.startsWith("on"))
@@ -217,7 +270,15 @@
test.node = test.node.getParentElement();
}
for (FunctionItemToken fi : handlers.get(test)) {
- SingleNodeIterator nodeiter = new SingleNodeIterator(test.node);
+ Iterator nodeiter;
+ final EventTarget eventTarget = event.getEventTarget();
+ if (JsToMxQuery.isNode(eventTarget)) {
+
+ nodeiter = new SingleNodeIterator((Node) (Object)eventTarget);
+ }
+ else {
+ nodeiter = new EmptySequenceIterator(null, null);
+ }
try {
// TODO: remove name reference - inline functions don't have a
// name
@@ -244,7 +305,53 @@
event.stopPropagation();
event.preventDefault();
}
+ /**
+ * the callback called by any listened window event
+ *
+ * @param event
+ */
+ public static void windowEventCallback(NativeEvent event) {
+ // TODO add arity
+ Logger log = Logger.getLogger(Environment.class.toString());
+ log.log(LogLevel.FINER, "Got a window event: " + event.getString());
+ for (FunctionItemToken fi : windowhandlers.get(event.getType())) {
+ Iterator nodeiter;
+ final EventTarget eventTarget = event.getEventTarget();
+ if (JsToMxQuery.isNode(eventTarget)) {
+
+ nodeiter = new SingleNodeIterator((Node) (Object)eventTarget);
+ }
+ else {
+ nodeiter = new EmptySequenceIterator(null, null);
+ }
+ try {
+ // TODO: remove name reference - inline functions don't have a
+ // name
+ // log.log(LogLevel.FINER, "Calling eventcallback " +
+ // fi.getFunction().getFunctionSignature().getName().toString());
+ ListBasedIterator eventiter = new EventIterator(event);
+ eventiter.setContext(new Context(), true);
+ Iterator[] subiterators = { nodeiter, eventiter };
+
+ Environment.invokeModule(fi, subiterators);
+ // log.log(LogLevel.FINER, "Eventcallback " +
+ // fi.getFunction().getFunctionSignature().getName().toString()
+ // + " done");
+ eventiter = null;
+ subiterators = null;
+ nodeiter = null;
+ } catch (MXQueryException e) {
+ Environment.displayErrorMessage(new StringBuffer(), null, e,
+ true);
+ e.printStackTrace();
+ }
+ }
+ // TODO decide this dynamically
+ event.stopPropagation();
+ event.preventDefault();
+ }
+
public static void invokeModule(FunctionItemToken ft,
XDMIterator[] subiterators) throws MXQueryException {
preProcessDocument();
@@ -340,24 +447,32 @@
// }
// }
private static final native void nativeAddEventListener(
- JavaScriptObject obj, String eventName)/*-{
- // el.addEventListener('click', function (ev) {$wnd.alert('test');}, false);
- if (el.addEventListener){//good browser
- el.addEventListener(eventName, @ch.ethz.mxqjs.client.Environment::eventCallback(Lcom/google/gwt/dom/client/NativeEvent;), false);
- }
- else {//bad browser
- el.attachEvent('on' + eventName, @ch.ethz.mxqjs.client.Environment::eventCallback(Lcom/google/gwt/dom/client/NativeEvent;));
-
- }
-
- }-*/;
+ Element el, String eventName)/*-{
+ // el.addEventListener('click', function (ev) {$wnd.alert('test');}, false);
+ el.addEventListener(eventName, @ch.ethz.mxqjs.client.Environment::eventCallback(Lcom/google/gwt/dom/client/NativeEvent;), false);
+
+ }-*/;
+ private static final native void nativeAddWindowListener(String eventName)/*-{
+
+ $wnd.addEventListener(eventName, @ch.ethz.mxqjs.client.Environment::windowEventCallback(Lcom/google/gwt/dom/client/NativeEvent;), false);
+
+
+ }-*/;
+
private static final native void nativeRemoveEventListener(Element el,
String eventName)/*-{
// el.addEventListener('click', function (ev) {$wnd.alert('test');}, false);
el.removeEventListener(eventName, @ch.ethz.mxqjs.client.Environment::eventCallback(Lcom/google/gwt/dom/client/NativeEvent;), false);
}-*/;
+
+ private static final native void nativeRemoveWindowListener(String eventName)/*-{
+ // el.addEventListener('click', function (ev) {$wnd.alert('test');}, false);
+ $wnd.removeEventListener(eventName, @ch.ethz.mxqjs.client.Environment::windowEventCallback(Lcom/google/gwt/dom/client/NativeEvent;), false);
+ }-*/;
+
+
public static void displayErrorMessage(StringBuffer queryResult,
String query, MXQueryException err, boolean compiled) {
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml 2011-06-15 17:51:06 UTC (rev 4405)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FG.xml 2011-06-16 01:37:09 UTC (rev 4406)
@@ -154,35 +154,33 @@
<paramType>xs:string</paramType>
</parameters>
<className>AddClassName</className>
- </functionDescription><functionDescription>
- <functionName>addEventListener</functionName>
+ </functionDescription>
+ <functionDescription>
+ <functionName>addWindowListener</functionName>
<parameters>
- <paramType>node()+</paramType>
+
<paramType>xs:string</paramType>
- <paramType>QName</paramType>
- <paramType>xs:integer</paramType>
+ <paramType>function()</paramType>
</parameters>
- <className>AddEventListener</className>
+ <className>AddWindowListener</className>
</functionDescription>
<functionDescription>
- <functionName>addEventListener</functionName>
+ <functionName>removeWindowListener</functionName>
<parameters>
- <paramType>node()+</paramType>
<paramType>xs:string</paramType>
<paramType>function()</paramType>
</parameters>
- <className>AddEventListener</className>
+ <className>RemoveWindowListener</className>
</functionDescription>
<functionDescription>
- <functionName>removeEventListener</functionName>
+ <functionName>addEventListener</functionName>
<parameters>
<paramType>node()+</paramType>
<paramType>xs:string</paramType>
- <paramType>QName</paramType>
- <paramType>xs:integer</paramType>
+ <paramType>function()</paramType>
</parameters>
- <className>RemoveEventListener</className>
- </functionDescription>
+ <className>AddEventListener</className>
+ </functionDescription>
<functionDescription>
<functionName>removeEventListener</functionName>
<parameters>
@@ -192,7 +190,16 @@
</parameters>
<className>RemoveEventListener</className>
</functionDescription>
+
<functionDescription>
+ <functionName>removeAnonymousEventListeners</functionName>
+ <parameters>
+ <paramType>node()</paramType>
+ <paramType>xs:string</paramType>
+ </parameters>
+ <className>RemoveAnonymousEventListener</className>
+ </functionDescription>
+ <functionDescription>
<functionName>dom</functionName>
<className>Dom</className>
</functionDescription>
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java 2011-06-15 17:51:06 UTC (rev 4405)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/FGPopulator.java 2011-06-16 01:37:09 UTC (rev 4406)
@@ -42,7 +42,6 @@
TypeInfo function__ = new TypeInfo(FunctionGallery.getType("function()",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
TypeInfo xs_dateTime = new TypeInfo(FunctionGallery.getType("xs:dateTime",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
TypeInfo node___plus = new TypeInfo(FunctionGallery.getType("node()+",ctx), Type.OCCURRENCE_IND_ONE_OR_MORE,null);
- TypeInfo QName = new TypeInfo(FunctionGallery.getType("QName",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
TypeInfo node__ = new TypeInfo(FunctionGallery.getType("node()",ctx), Type.OCCURRENCE_IND_EXACTLY_ONE,null);
TypeInfo xs_string_quest = new TypeInfo(FunctionGallery.getType("xs:string?",ctx), Type.OCCURRENCE_IND_ZERO_OR_ONE,null);
TypeInfo numeric_quest = new TypeInfo(FunctionGallery.getType("numeric?",ctx), Type.OCCURRENCE_IND_ZERO_OR_ONE,null);
@@ -540,17 +539,15 @@
qn = new QName(
"http://xqib.org",
"b",
- "addEventListener");
- paramTypes = new TypeInfo[4];
+ "addWindowListener");
+ paramTypes = new TypeInfo[2];
- paramTypes[0] = node___plus;
- paramTypes[1] = xs_string;
- paramTypes[2] = QName;
- paramTypes[3] = xs_integer;
+ paramTypes[0] = xs_string;
+ paramTypes[1] = function__;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
{
- ch.ethz.mxquery.functions.b.AddEventListener iter = new ch.ethz.mxquery.functions.b.AddEventListener();
+ ch.ethz.mxquery.functions.b.AddWindowListener iter = new ch.ethz.mxquery.functions.b.AddWindowListener();
iter.setContext(context, false);
type = null;
@@ -564,6 +561,28 @@
qn = new QName(
"http://xqib.org",
"b",
+ "removeWindowListener");
+ paramTypes = new TypeInfo[2];
+
+ paramTypes[0] = xs_string;
+ paramTypes[1] = function__;
+ signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
+
+ {
+ ch.ethz.mxquery.functions.b.RemoveWindowListener iter = new ch.ethz.mxquery.functions.b.RemoveWindowListener();
+ iter.setContext(context, false);
+
+ type = null;
+
+ function = new Function(
+ null,signature,
+ iter, null, type );
+ fg.add(function);
+ }
+
+ qn = new QName(
+ "http://xqib.org",
+ "b",
"addEventListener");
paramTypes = new TypeInfo[3];
@@ -588,12 +607,11 @@
"http://xqib.org",
"b",
"removeEventListener");
- paramTypes = new TypeInfo[4];
+ paramTypes = new TypeInfo[3];
- paramTypes[0] = node___plus;
+ paramTypes[0] = node__;
paramTypes[1] = xs_string;
- paramTypes[2] = QName;
- paramTypes[3] = xs_integer;
+ paramTypes[2] = function__;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
{
@@ -611,16 +629,15 @@
qn = new QName(
"http://xqib.org",
"b",
- "removeEventListener");
- paramTypes = new TypeInfo[3];
+ "removeAnonymousEventListeners");
+ paramTypes = new TypeInfo[2];
paramTypes[0] = node__;
paramTypes[1] = xs_string;
- paramTypes[2] = function__;
signature = new FunctionSignature(qn, paramTypes, FunctionSignature.SYSTEM_FUNCTION, new Hashtable());
{
- ch.ethz.mxquery.functions.b.RemoveEventListener iter = new ch.ethz.mxquery.functions.b.RemoveEventListener();
+ ch.ethz.mxquery.functions.b.RemoveAnonymousEventListener iter = new ch.ethz.mxquery.functions.b.RemoveAnonymousEventListener();
iter.setContext(context, false);
type = null;
Added: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/AddWindowListener.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/AddWindowListener.java (rev 0)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/AddWindowListener.java 2011-06-16 01:37:09 UTC (rev 4406)
@@ -0,0 +1,51 @@
+package ch.ethz.mxquery.functions.b;
+
+import java.util.Vector;
+
+import ch.ethz.mxqjs.client.Environment;
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.xdm.FunctionItemToken;
+import ch.ethz.mxquery.datamodel.xdm.Token;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.ErrorCodes;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.exceptions.TypeException;
+import ch.ethz.mxquery.model.TokenBasedIterator;
+import ch.ethz.mxquery.model.XDMIterator;
+
+public class AddWindowListener extends TokenBasedIterator {
+
+ @Override
+ protected void init() throws MXQueryException {
+ currentToken = Token.END_SEQUENCE_TOKEN;
+ String eventname;
+
+ eventname = getStringValue(subIters[0]);
+ XDMIterator functioniter = subIters[1];
+ TokenInterface functiontoken = functioniter.next();
+
+ if (functiontoken.getEventType() != Type.FUNCTION_ITEM || functioniter.next().getEventType() != Type.END_SEQUENCE)
+ throw new TypeException(ErrorCodes.E0004_TYPE_INAPPROPRIATE_TYPE, "Function Item expected", loc);
+
+ addWindowHandler(eventname, (FunctionItemToken)functiontoken);
+ }
+
+ private void addWindowHandler( String eventname,
+ FunctionItemToken fi) throws MXQueryException {
+
+ Context ctx = this.getContext().getRootContext();
+ Environment.addWindowListener(eventname, fi,ctx);
+
+ }
+
+ @Override
+ protected XDMIterator copy(Context context, XDMIterator[] subIters,
+ Vector nestedPredCtxStack) throws MXQueryException {
+ XDMIterator copy = new AddWindowListener();
+ copy.setContext(context, true);
+ copy.setSubIters(subIters);
+ return copy;
+ }
+
+}
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/GetLocation.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/GetLocation.java 2011-06-15 17:51:06 UTC (rev 4405)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/GetLocation.java 2011-06-16 01:37:09 UTC (rev 4406)
@@ -32,7 +32,10 @@
protected void init() throws MXQueryException {
lst = new LinkedList<TokenInterface>();
- this.addTextElement("hash", Location.getHash());
+
+ QName qn = new QName(namespace.getURI(),namespace.getNamespacePrefix(),"location");
+ lst.add(new ElementToken(Type.START_TAG, null, qn,scope));
+ this.addTextElement("hash", Location.getHash());
this.addTextElement("host", Location.getHost());
this.addTextElement("hostname", Location.getHostName());
this.addTextElement("href", Location.getHref());
@@ -41,7 +44,8 @@
this.addTextElement("protocol", Location.getProtocol());
// this.addTextElement("search", Location.getSearch());
appendParameters();
-
+
+ lst.add(new ElementToken(Type.END_TAG, null, qn,scope));
// addTextElement(tagname, content);
// TODO Auto-generated method stub
Added: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/RemoveWindowListener.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/RemoveWindowListener.java (rev 0)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/RemoveWindowListener.java 2011-06-16 01:37:09 UTC (rev 4406)
@@ -0,0 +1,50 @@
+package ch.ethz.mxquery.functions.b;
+
+import java.util.Vector;
+
+import ch.ethz.mxqjs.client.Environment;
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.xdm.FunctionItemToken;
+import ch.ethz.mxquery.datamodel.xdm.Token;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.ErrorCodes;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.exceptions.TypeException;
+import ch.ethz.mxquery.model.TokenBasedIterator;
+import ch.ethz.mxquery.model.XDMIterator;
+
+public class RemoveWindowListener extends TokenBasedIterator {
+
+ @Override
+ protected void init() throws MXQueryException {
+ currentToken = Token.END_SEQUENCE_TOKEN;
+ String eventname;
+
+ eventname = getStringValue(subIters[0]);
+ XDMIterator functioniter = subIters[1];
+ TokenInterface functiontoken = functioniter.next();
+
+ if (functiontoken.getEventType() != Type.FUNCTION_ITEM || functioniter.next().getEventType() != Type.END_SEQUENCE)
+ throw new TypeException(ErrorCodes.E0004_TYPE_INAPPROPRIATE_TYPE, "Function Item expected", loc);
+
+ addWindowHandler(eventname, (FunctionItemToken)functiontoken);
+ }
+
+ private void addWindowHandler( String eventname,
+ FunctionItemToken fi) throws MXQueryException {
+
+ Context ctx = this.getContext().getRootContext();
+ Environment.removeWindowListener(eventname, fi,ctx);
+
+ }
+ @Override
+ protected XDMIterator copy(Context context, XDMIterator[] subIters,
+ Vector nestedPredCtxStack) throws MXQueryException {
+ XDMIterator copy = new RemoveWindowListener();
+ copy.setContext(context, true);
+ copy.setSubIters(subIters);
+ return copy;
+ }
+
+}
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/WindowInfo.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/WindowInfo.java 2011-06-15 17:51:06 UTC (rev 4405)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/b/WindowInfo.java 2011-06-16 01:37:09 UTC (rev 4406)
@@ -1,28 +1,46 @@
package ch.ethz.mxquery.functions.b;
+import java.util.LinkedList;
import java.util.Vector;
import com.google.gwt.user.client.Window;
import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.Namespace;
+import ch.ethz.mxquery.datamodel.QName;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.xdm.ElementToken;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
import ch.ethz.mxquery.exceptions.MXQueryException;
import ch.ethz.mxquery.iterators.browser.ListBasedIterator;
import ch.ethz.mxquery.model.XDMIterator;
public class WindowInfo extends ListBasedIterator {
+ public WindowInfo() {
+ this.namespace = new Namespace(Context.NS_BROWSER, Context.URI_BROWSER);
+ }
+
@Override
protected void init() throws MXQueryException {
+ lst = new LinkedList<TokenInterface>();
+
+ QName qn = new QName(namespace.getURI(),namespace.getNamespacePrefix(),"window-info");
+
+ lst.add(new ElementToken(Type.START_TAG, null, qn,scope));
addIntegerElement("client-height", Window.getClientHeight());
- addIntegerElement("client-height", Window.getClientWidth());
+ addIntegerElement("client-width", Window.getClientWidth());
addIntegerElement("scroll-left", Window.getScrollLeft());
addIntegerElement("scroll-top", Window.getScrollTop());
+ lst.add(new ElementToken(Type.END_TAG, null, qn,scope));
}
@Override
- protected XDMIterator copy(Context context, XDMIterator[] subIters,
- Vector nestedPredCtxStack) throws MXQueryException {
- return new WindowInfo();
- }
-
+ protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack)
+ throws MXQueryException {
+ XDMIterator ret = new WindowInfo();
+ ret.setSubIters(subIters);
+ ret.setContext(context, false);
+ return ret;
+ }
}
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/EventIterator.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/EventIterator.java 2011-06-15 17:51:06 UTC (rev 4405)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/EventIterator.java 2011-06-16 01:37:09 UTC (rev 4406)
@@ -30,8 +30,8 @@
@Override
protected void init() throws MXQueryException {
lst = new LinkedList<TokenInterface>();
- QName qn = new QName("event");
- lst.add(new ElementToken(Type.START_TAG, null, qn,null));
+ QName qn = new QName(namespace.getURI(),namespace.getNamespacePrefix(),"event");
+ lst.add(new ElementToken(Type.START_TAG, null, qn,scope));
String type = event.getType();
if (isMouseEvent(type)){
addIntegerElement("screenX", event.getScreenX());
@@ -44,8 +44,7 @@
addElementIfTrue("metaKey", event.getMetaKey());
addTextElement("button", buttonToString(event.getButton()));
}
- lst.add(new ElementToken(Type.END_TAG, null, qn,null));
- lst.add(Token.END_SEQUENCE_TOKEN);
+ lst.add(new ElementToken(Type.END_TAG, null, qn,scope));
}
protected boolean isMouseEvent(String type) {
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/SingleNodeIterator.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/SingleNodeIterator.java 2011-06-15 17:51:06 UTC (rev 4405)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/b...
[truncated message content] |
|
From: <pm_...@us...> - 2011-06-20 14:07:59
|
Revision: 4413
http://mxquery.svn.sourceforge.net/mxquery/?rev=4413&view=rev
Author: pm_fischer
Date: 2011-06-20 14:07:49 +0000 (Mon, 20 Jun 2011)
Log Message:
-----------
fix a context-scoping problem affecting the invocation of UDFs in XQIB
Modified Paths:
--------------
trunk/MXQuery/src/ch/ethz/mxquery/functions/Function.java
trunk/MXQuery/src/ch/ethz/mxquery/iterators/UserdefFuncCallLateBinding.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/Function.java
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/Function.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/Function.java 2011-06-20 08:27:16 UTC (rev 4412)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/Function.java 2011-06-20 14:07:49 UTC (rev 4413)
@@ -43,7 +43,7 @@
FunctionSignature signature;
protected XDMIterator iter;
-
+
TypeInfo returnType = null;
String operation = null;
@@ -99,8 +99,9 @@
//iter.setContext(targetContext, true);
Context contextToUse = targetContext;
// external functions reside in their original context
- if (signature.type == FunctionSignature.EXTERNAL_FUNCTION && iter.getContext() != null)
+ if (signature.type != FunctionSignature.SYSTEM_FUNCTION && iter.getContext() != null && iter.getContext().getParent() != null) {
contextToUse = iter.getContext().getParent();
+ }
if (iter instanceof UserdefFuncCall) {
return ((UserdefFuncCall)iter).copyInstance(contextToUse);
} else
Modified: trunk/MXQuery/src/ch/ethz/mxquery/iterators/UserdefFuncCallLateBinding.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/iterators/UserdefFuncCallLateBinding.java 2011-06-20 08:27:16 UTC (rev 4412)
+++ trunk/MXQuery/src/ch/ethz/mxquery/iterators/UserdefFuncCallLateBinding.java 2011-06-20 14:07:49 UTC (rev 4413)
@@ -111,7 +111,7 @@
f = context.getFunction(funcName, arity);
if (f==null)
- throw new StaticException(ErrorCodes.E0017_STATIC_DOESNT_MATCH_FUNCTION_SIGNATURE,"Function "+funcName+" with arity"+arity+" not available",loc);
+ throw new StaticException(ErrorCodes.E0017_STATIC_DOESNT_MATCH_FUNCTION_SIGNATURE,"Function "+funcName+" with arity "+arity+" not available",loc);
}
XDMIterator func = f.getFunctionImplementation(context);
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/Function.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/Function.java 2011-06-20 08:27:16 UTC (rev 4412)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/Function.java 2011-06-20 14:07:49 UTC (rev 4413)
@@ -29,6 +29,7 @@
import ch.ethz.mxquery.model.XDMIterator;
import ch.ethz.mxquery.util.Hashtable;
+
/**
* Holds information on the function metadata and methods to retrieve the
* implementation, either by an explicit iterator or by the name of a class to
@@ -44,7 +45,7 @@
FunctionSignature signature;
protected XDMIterator iter;
-
+
TypeInfo returnType = null;
String operation = null;
@@ -100,8 +101,9 @@
//iter.setContext(targetContext, true);
Context contextToUse = targetContext;
// external functions reside in their original context
- if (signature.type == FunctionSignature.EXTERNAL_FUNCTION && iter.getContext() != null)
+ if (signature.type != FunctionSignature.SYSTEM_FUNCTION && iter.getContext() != null && iter.getContext().getParent() != null) {
contextToUse = iter.getContext().getParent();
+ }
if (iter instanceof UserdefFuncCall) {
return ((UserdefFuncCall)iter).copyInstance(contextToUse);
} else {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pm_...@us...> - 2011-06-20 16:06:46
|
Revision: 4414
http://mxquery.svn.sourceforge.net/mxquery/?rev=4414&view=rev
Author: pm_fischer
Date: 2011-06-20 16:06:40 +0000 (Mon, 20 Jun 2011)
Log Message:
-----------
- Fix reusability of PreparedExpressions in XQJ
- TokenSequenceIterator now takes a Context in its constructor
Modified Paths:
--------------
trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java
trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java
trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/AvailEnvVars.java
trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java
trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Fold.java
trunk/MXQuery/src/ch/ethz/mxquery/functions/ft/ScoreSequence.java
trunk/MXQuery/src/ch/ethz/mxquery/iterators/ft/FTContainsIterator.java
trunk/MXQuery/src/ch/ethz/mxquery/model/TokenSequenceIterator.java
trunk/MXQuery/src/ch/ethz/mxquery/xqj/FlatItem.java
trunk/MXQuery/src/ch/ethz/mxquery/xqj/Item.java
trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java
trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java
trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQPreparedExpression.java
trunk/MXQuery/src/ch/ethz/mxquery/xqj/TreeItem.java
trunk/MXQuery/src/examples/XQJExample.java
Modified: trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java
===================================================================
--- trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -236,13 +236,15 @@
if (value.isClosed())
throw new XQException("Item is closed, cannot bind it");
+ Context ctx = this.getRuntime();
+
if (value instanceof MXQueryXQItem) {
MXQueryXQItem mxqItem = (MXQueryXQItem) value;
try {
if(this instanceof MXQueryXQPreparedExpression)
- this.getRuntime().setVariableValue(qn, mxqItem.curIt.getAsIterator(), true);
+ ctx.setVariableValue(qn, mxqItem.curIt.getAsIterator(ctx), true);
else
- this.getRuntime().bindVariableValue(qn, mxqItem.curIt.getAsIterator());
+ ctx.bindVariableValue(qn, mxqItem.curIt.getAsIterator(ctx));
} catch (MXQueryException e) {
throw new XQQueryException(e.toString(),PlatformDependentUtils.getJavaxQName(e.getErrorCode()));
}
@@ -429,19 +431,22 @@
while (value.next()) {
items.add( value.getItem());
}
+
+ Context ctx = this.getRuntime();
+
XDMIterator [] seqIters = new XDMIterator[items.size()];
for (int i=0;i<seqIters.length;i++) {
- seqIters[i] = ((MXQueryXQItem)items.get(i)).curIt.getAsIterator();
+ seqIters[i] = ((MXQueryXQItem)items.get(i)).curIt.getAsIterator(ctx);
}
- SequenceIterator seq = new SequenceIterator(new Context(),seqIters,QueryLocation.OUTSIDE_QUERY_LOC);
+ SequenceIterator seq = new SequenceIterator(ctx,seqIters,QueryLocation.OUTSIDE_QUERY_LOC);
try {
if(this instanceof MXQueryXQPreparedExpression)
- this.getRuntime().setVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq, true);
+ ctx.setVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq, true);
else
- this.getRuntime().bindVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq);
+ ctx.bindVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq);
} catch (MXQueryException e) {
throw new XQQueryException(e.toString(),PlatformDependentUtils.getJavaxQName(e.getErrorCode()));
}
Modified: trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java
===================================================================
--- trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/android/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -171,7 +171,7 @@
throw new XQException("Cannot write to null handler");
Token2SaxAdapter toS;
try {
- toS = new Token2SaxAdapter(curIt.getAsIterator(),saxHandler);
+ toS = new Token2SaxAdapter(curIt.getAsIterator(new Context()),saxHandler);
toS.convertItemToSax();
} catch (MXQueryException e) {
throw new XQException(e.toString());
Modified: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -276,7 +276,7 @@
sendPayloadValues
.addElement(ser
.eventsToXML(new TokenSequenceIterator(
- item)));
+ context,item)));
}
}
curPlToken = subIters[1].next();// closing
@@ -298,7 +298,7 @@
sendPayloadValues
.addElement(ser
.eventsToXML(new TokenSequenceIterator(
- item)));
+ context,item)));
sendPayloadTypes.addElement("text/xml");
if (contentType.equals(""))
contentType = "text/xml";
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/AvailEnvVars.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/AvailEnvVars.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/AvailEnvVars.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -22,7 +22,7 @@
TokenInterface tok = new TextToken(null,(String)envVars.next());
vars.add(tok);
}
- current = new TokenSequenceIterator(vars);
+ current = new TokenSequenceIterator(context,vars);
}
return current.next();
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -160,7 +160,7 @@
lines.addElement(new TextToken(null, line));
line = lr.readLine();
}
- cur = new TokenSequenceIterator(lines);
+ cur = new TokenSequenceIterator(context,lines);
break;
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Fold.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Fold.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Fold.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -94,7 +94,7 @@
acc.addElement(tok);
tok = reduceFunc.next();
}
- current = WindowFactory.getNewWindow(context, new TokenSequenceIterator(acc));
+ current = WindowFactory.getNewWindow(context, new TokenSequenceIterator(context,acc));
reduceFunc.reset();
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/ft/ScoreSequence.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/ft/ScoreSequence.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/ft/ScoreSequence.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -76,7 +76,7 @@
compScores.addElement(score);
}
adaptScoreToExpectedRange(compScores);
- TokenSequenceIterator ts = new TokenSequenceIterator(compScores);
+ TokenSequenceIterator ts = new TokenSequenceIterator(context,compScores);
current = WindowFactory.getNewWindow(context, ts);
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/iterators/ft/FTContainsIterator.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/iterators/ft/FTContainsIterator.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/iterators/ft/FTContainsIterator.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -128,7 +128,7 @@
VariableHolder ignHolder = context.getVariable(Parser.FT_IGNORE_SCOPES);
if (ignIds.size() > 0) {
- ignHolder.setIter(new TokenSequenceIterator(ignIds));
+ ignHolder.setIter(new TokenSequenceIterator(context,ignIds));
}
else
ignHolder.setIter(new EmptySequenceIterator(context,loc));
Modified: trunk/MXQuery/src/ch/ethz/mxquery/model/TokenSequenceIterator.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/model/TokenSequenceIterator.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/model/TokenSequenceIterator.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -24,6 +24,14 @@
public class TokenSequenceIterator extends Iterator {
protected TokenInterface [] tokens;
+
+ public TokenSequenceIterator(Context ctx, Vector inp) {
+ super(ctx,null);
+ tokens = new TokenInterface[inp.size()];
+ for (int i=0;i<tokens.length;i++) {
+ tokens[i] = (TokenInterface)inp.elementAt(i);
+ }
+ }
public TokenSequenceIterator(Vector inp) {
super(null,null);
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xqj/FlatItem.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xqj/FlatItem.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xqj/FlatItem.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -149,9 +149,9 @@
return new TypeInfo(tk.getEventType(),Type.OCCURRENCE_IND_EXACTLY_ONE);
}
- public XDMIterator getAsIterator() throws XQException{
+ public XDMIterator getAsIterator(Context ctx) throws XQException{
try {
- return new TokenIterator(null,tk,null, false);
+ return new TokenIterator(ctx,tk,null, false);
} catch (MXQueryException me) {
throw new XQException(me.toString());
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xqj/Item.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xqj/Item.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xqj/Item.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -22,6 +22,7 @@
import org.w3c.dom.Node;
+import ch.ethz.mxquery.contextConfig.Context;
import ch.ethz.mxquery.datamodel.types.TypeInfo;
import ch.ethz.mxquery.model.XDMIterator;
@@ -43,7 +44,7 @@
String getItemAsString(Properties props) throws XQException;
- XDMIterator getAsIterator() throws XQException;
+ XDMIterator getAsIterator(Context ctx) throws XQException;
long getLong() throws XQException;
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQDynamicContext.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -239,13 +239,15 @@
if (value.isClosed())
throw new XQException("Item is closed, cannot bind it");
+ Context ctx = this.getRuntime();
+
if (value instanceof MXQueryXQItem) {
MXQueryXQItem mxqItem = (MXQueryXQItem) value;
try {
if(this instanceof MXQueryXQPreparedExpression)
- this.getRuntime().setVariableValue(qn, mxqItem.curIt.getAsIterator(), true);
+ ctx.setVariableValue(qn, mxqItem.curIt.getAsIterator(ctx), true);
else
- this.getRuntime().bindVariableValue(qn, mxqItem.curIt.getAsIterator());
+ ctx.bindVariableValue(qn, mxqItem.curIt.getAsIterator(ctx));
} catch (MXQueryException e) {
throw new XQQueryException(e.toString(),PlatformDependentUtils.getJavaxQName(e.getErrorCode()));
}
@@ -432,19 +434,24 @@
while (value.next()) {
items.add( value.getItem());
}
+
+ Context ctx = this.getRuntime();
+
XDMIterator [] seqIters = new XDMIterator[items.size()];
for (int i=0;i<seqIters.length;i++) {
- seqIters[i] = ((MXQueryXQItem)items.get(i)).curIt.getAsIterator();
+ seqIters[i] = ((MXQueryXQItem)items.get(i)).curIt.getAsIterator(ctx);
}
+
- SequenceIterator seq = new SequenceIterator(new Context(),seqIters,QueryLocation.OUTSIDE_QUERY_LOC);
+
+ SequenceIterator seq = new SequenceIterator(ctx,seqIters,QueryLocation.OUTSIDE_QUERY_LOC);
try {
if(this instanceof MXQueryXQPreparedExpression)
- this.getRuntime().setVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq, true);
+ ctx.setVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq, true);
else
- this.getRuntime().bindVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq);
+ ctx.bindVariableValue(new ch.ethz.mxquery.datamodel.QName(varName.toString()), seq);
} catch (MXQueryException e) {
throw new XQQueryException(e.toString(),PlatformDependentUtils.getJavaxQName(e.getErrorCode()));
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQItem.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -172,7 +172,7 @@
throw new XQException("Cannot write to null handler");
Token2SaxAdapter toS;
try {
- toS = new Token2SaxAdapter(curIt.getAsIterator(),saxHandler);
+ toS = new Token2SaxAdapter(curIt.getAsIterator(new Context()),saxHandler);
toS.convertItemToSax();
} catch (MXQueryException e) {
throw new XQException(e.toString());
@@ -188,7 +188,8 @@
}
public XMLStreamReader getItemAsStream() throws XQException {
- return new Token2StaxAdapter(new Context(), curIt.getAsIterator(), true);
+ Context ctx = new Context();
+ return new Token2StaxAdapter(ctx, curIt.getAsIterator(ctx), true);
}
public String getItemAsString(Properties props) throws XQException {
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQPreparedExpression.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQPreparedExpression.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xqj/MXQueryXQPreparedExpression.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -31,7 +31,6 @@
import javax.xml.xquery.XQStaticContext;
//import javax.xml.xquery.XQWarning;
import ch.ethz.mxquery.model.VariableHolder;
-import ch.ethz.mxquery.model.XDMIterator;
import ch.ethz.mxquery.query.PreparedStatement;
import ch.ethz.mxquery.query.impl.PreparedStatementImpl;
import ch.ethz.mxquery.util.PlatformDependentUtils;
@@ -85,23 +84,23 @@
}
public XQResultSequence executeQuery() throws XQException {
- checkNotClosed();
- //try {
- //XDMIterator iter = exp.evaluate();
- //exp = pristineCopy.copy();
- if(connection.getStaticContext().getScrollability() == XQConstants.SCROLLTYPE_FORWARD_ONLY)
- return new MXQueryXQForwardSequence(exp, connection,this);
- Vector store = new Vector();
- int i = 0;
- MXQueryXQForwardSequence mSeq = new MXQueryXQForwardSequence(exp, connection,this);
- while(mSeq.next()){
- store.add(i++,mSeq.getItem());
- }
- this.seq = new MXQueryXQSequence(store, connection);
- return seq;
-// } catch (MXQueryException de) {
-// throw new XQQueryException(de.toString(),PlatformDependentUtils.getJavaxQName(de.getErrorCode()));
-// }
+ checkNotClosed();
+ try {
+ //XDMIterator iter = exp.evaluate();
+ exp = pristineCopy.copy();
+ if(connection.getStaticContext().getScrollability() == XQConstants.SCROLLTYPE_FORWARD_ONLY)
+ return new MXQueryXQForwardSequence(exp, connection,this);
+ Vector store = new Vector();
+ int i = 0;
+ MXQueryXQForwardSequence mSeq = new MXQueryXQForwardSequence(exp, connection,this);
+ while(mSeq.next()){
+ store.add(i++,mSeq.getItem());
+ }
+ this.seq = new MXQueryXQSequence(store, connection);
+ return seq;
+ } catch (MXQueryException de) {
+ throw new XQQueryException(de.toString(),PlatformDependentUtils.getJavaxQName(de.getErrorCode()));
+ }
}
public QName[] getAllExternalVariables() throws XQException {
@@ -169,14 +168,14 @@
//@Override
protected Context getRuntime() {
if(exp instanceof PreparedStatementImpl){
- return (Context)((PreparedStatementImpl)this.exp).getContext();
+ return (Context)((PreparedStatementImpl)this.pristineCopy).getContext();
}
return null;
}
public QName[] getAllUnboundExternalVariables() throws XQException {
checkNotClosed();
- Vector vec = exp.getUnresolvedExternalVariables();
+ Vector vec = pristineCopy.getUnresolvedExternalVariables();
QName [] ret = new QName[vec.size()];
for (int i=0;i<vec.size();i++) {
ch.ethz.mxquery.datamodel.QName qn = (ch.ethz.mxquery.datamodel.QName)vec.elementAt(i);
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xqj/TreeItem.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xqj/TreeItem.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xqj/TreeItem.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -21,6 +21,7 @@
import java.util.Properties;
import java.util.Vector;
+import ch.ethz.mxquery.contextConfig.Context;
import ch.ethz.mxquery.datamodel.types.Type;
import ch.ethz.mxquery.datamodel.types.TypeInfo;
import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
@@ -93,7 +94,7 @@
}
ser.setOmitXMLDeclaration(true);
XDMSerializer ip = new XDMSerializer(ser);
- TokenSequenceIterator to = new TokenSequenceIterator(v);
+ TokenSequenceIterator to = new TokenSequenceIterator(null,v);
String sb;
try {
sb = ip.eventsToXML(to);
@@ -104,8 +105,8 @@
return result;
}
- public XDMIterator getAsIterator() {
- return new TokenSequenceIterator(v);
+ public XDMIterator getAsIterator(Context ctx) {
+ return new TokenSequenceIterator(ctx,v);
}
public long getLong() throws XQException {
Modified: trunk/MXQuery/src/examples/XQJExample.java
===================================================================
--- trunk/MXQuery/src/examples/XQJExample.java 2011-06-20 14:07:49 UTC (rev 4413)
+++ trunk/MXQuery/src/examples/XQJExample.java 2011-06-20 16:06:40 UTC (rev 4414)
@@ -34,15 +34,15 @@
public class XQJExample {
public static void main(String[] args) throws XQException {
- //String query = "declare variable $ext external; (14 + $ext, $ext * $ext)";
- String query = "<tag><tag1>text</tag1></tag>";
+ String query = "declare variable $ext external; (14 + $ext, $ext * $ext)";
+ //String query = "<tag><tag1>text</tag1></tag>";
XQDataSource ds = new MXQueryXQDataSource();
XQConnection conn = ds.getConnection();
System.out.println("Running query: " + query);
XQPreparedExpression exp = conn.prepareExpression(query);
-// exp.bindInt(new QName("ext"), 7, null);
+ exp.bindInt(new QName("ext"), 7, null);
XQResultSequence result = exp.executeQuery();
XQSequence sequence = conn.createSequence(result);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pm_...@us...> - 2011-08-17 14:00:04
|
Revision: 4436
http://mxquery.svn.sourceforge.net/mxquery/?rev=4436&view=rev
Author: pm_fischer
Date: 2011-08-17 13:59:55 +0000 (Wed, 17 Aug 2011)
Log Message:
-----------
Ghislain's test cases
Added Paths:
-----------
trunk/MXQuery/aggregate2.xquery
trunk/MXQuery/notm.xml
trunk/MXQuery/tm.xml
Added: trunk/MXQuery/aggregate2.xquery
===================================================================
--- trunk/MXQuery/aggregate2.xquery (rev 0)
+++ trunk/MXQuery/aggregate2.xquery 2011-08-17 13:59:55 UTC (rev 4436)
@@ -0,0 +1,162 @@
+declare variable $tmfiles external;
+declare variable $notmfiles external;
+
+(: declare variable $tmfile as document-node() external;
+declare variable $notmfile as document-node() external; :)
+
+declare function local:read-files($files)
+{
+ <contents>
+ {
+ for $name in $files/files/file
+ return <content>{doc($name)/measurements}</content>
+ }
+ </contents>
+};
+
+declare function local:get-kinds()
+{
+ doc($tmfiles/files/file[1])/measurements/kind/data(@name)
+};
+
+
+declare function local:extract-x-axis-for-kind($kind)
+{
+ doc($tmfiles/files/file[1])/measurements/kind[@name=$kind]/values/value/data(version)
+};
+
+declare function local:normalize-kind($file, $kind, $x-axis)
+{
+ let $f := doc($file)/measurements/kind[@name=$kind]
+ return
+ <kind name="{$kind}">
+ <average>{$f/data(average)}</average>
+ <values>
+ {
+ for $v in $x-axis
+ return <value>
+ <version>{$v}</version>
+ <time>{
+ let $nv := $f/values/value[xs:integer(version) le xs:integer($v)][last()]
+ (: adding or removing [last()] on the line above changes the number of elements outputs in the FLWOR! :)
+ return
+ if ($nv) then data($nv[last()]/time) else data($f/values/value[last()]/time)
+
+ }</time>
+ </value>
+ }
+ </values>
+ </kind>
+};
+
+declare function local:compute-average($files, $kind, $x-axis)
+{
+ let $normalized-contents := for $f in $files return local:normalize-kind($f, $kind, $x-axis)
+ return
+ <kind name="{$kind}">
+ <average>{avg($normalized-contents/data(average))}</average>
+ <values>
+ {
+ for $v in $x-axis
+ return <value>
+ <version>{$v}</version>
+ <time>{
+ avg($normalized-contents/values/value[version=$v]/time)
+ }</time>
+ </value>
+ }
+ </values>
+ </kind>
+};
+
+ for $kind in "insert1"
+ let $x-axis := local:extract-x-axis-for-kind($kind)
+ let $kind-notm := local:normalize-kind($notmfiles/files/file[1],
+ $kind,
+ $x-axis)
+ return $kind-notm
+(: <html>
+ <head>
+ <meta charset="utf-8"/>
+ <style>
+ body {{font-family:Arial}}
+ div#id-display {{}}
+ span.version {{background-color:gray;color:white;width:100%;display:block}}
+ span.content {{display:block}}
+ ul.listing li {{list-style:none;border-bottom:solid 1px}}
+ ul.listing {{margin:0px;padding:0px}}
+ span.element {{color:blue}}
+ span.attribute {{color:red}}
+ span.text {{color:black}}
+ span.comment {{color:purple}}
+ span.reference {{font-size:6pt;color:gray}}
+ span.pi {{color:green}}
+ hr.document-separator {{border: 1px dashed gray}}
+ .error {{color:red}}
+ .tree-id {{font-size: 18pt; color: green}}
+ .ordpath {{font-size: 18pt; color: red}}
+ .version-id {{font-size: 18pt; color: blue}}
+ .selected {{background-color: yellow}}
+ .doselect {{color: black}}
+ .isselected {{color: green;text-weight: bold}}
+ .invisible {{display: none}}
+ .selectable {{cursor: pointer}}
+ </style>
+ <script type="text/javascript" src="https://www.google.com/jsapi"></script>
+ {
+ for $kind in local:get-kinds()
+ let $kind-tm := local:compute-average($tmfiles/files/file,
+ $kind,
+ local:extract-x-axis-for-kind($kind))
+ let $kind-notm := local:compute-average($notmfiles/files/file,
+ $kind,
+ local:extract-x-axis-for-kind($kind))
+ return
+ <script type="text/javascript">
+ google.load("visualization", "1", {{packages:["corechart"]}});
+ google.setOnLoadCallback(drawChart);
+ function drawChart() {{
+ var data = new google.visualization.DataTable();
+ data.addColumn('string', '# Versions');
+ data.addColumn('number', 'Time Travel');
+ data.addColumn('number', 'No time travel');
+ data.addRows({count($kind-tm/values/value)});
+ {
+ for $t at $p in $kind-tm/values/value
+ let $t-notm := $kind-notm/values/value[version eq $t/version]
+ return
+ <dummy>data.setValue({$p - 1}, 0, '{$t/data(version)}');data.setValue({$p - 1}, 1, {$t/data(time)});data.setValue({$p - 1}, 2, {$t-notm/data(time)});</dummy>/data(.)
+ }
+ var chart = new google.visualization.LineChart(document.getElementById('chart_div_{$kind-tm/data(@name)}'));
+ chart.draw(data, {{width: 800, height: 240, title: 'y = execution time (ms) for the x-th execution of query {$kind-tm/data(@name)}'}});
+ }}
+ </script>
+ }
+ </head>
+ <body>
+ <div>
+ <h1>Measurement summary</h1>
+ {
+ for $kind in local:get-kinds()
+ let $kind-tm := local:compute-average($tmfiles/files/file,
+ $kind,
+ local:extract-x-axis-for-kind($kind))
+ let $kind-notm := local:compute-average($notmfiles/files/file,
+ $kind,
+ local:extract-x-axis-for-kind($kind))
+ return
+ let $average-time-tm := $kind-tm/data(average)
+ let $average-time-notm := $kind-notm/data(average)
+ let $standard-deviation-time-tm := math:sqrt(avg($kind-tm/values/value/math:pow(time - $average-time-tm, 2)))
+ let $standard-deviation-time-notm := math:sqrt(avg($kind-notm/values/value/math:pow(time - $average-time-notm,2)))
+ return
+ <div>
+ <h2>Kind: {$kind-tm/data(@name)}</h2>
+ <p>Execution time with time travel-enabled Sausalito: average {round($average-time-tm)} +/- {round($standard-deviation-time-tm)} ms</p>
+ <p>Execution time in original Sausalito: average {round($average-time-notm)} +/- {round($standard-deviation-time-notm)} ms</p>
+ <div id="chart_div_{$kind-tm/data(@name)}"/>
+ </div>
+ }
+ </div>
+ </body>
+ </html> :)
\ No newline at end of file
Added: trunk/MXQuery/notm.xml
===================================================================
--- trunk/MXQuery/notm.xml (rev 0)
+++ trunk/MXQuery/notm.xml 2011-08-17 13:59:55 UTC (rev 4436)
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
@@ Diff output truncated at 100000 characters. @@
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <et...@us...> - 2011-09-22 22:27:13
|
Revision: 4449
http://mxquery.svn.sourceforge.net/mxquery/?rev=4449&view=rev
Author: etterth
Date: 2011-09-22 22:27:06 +0000 (Thu, 22 Sep 2011)
Log Message:
-----------
- fixed bug when setting attributes
- added basic version of the history sample (buggy atm)
Modified Paths:
--------------
trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java
Added Paths:
-----------
trunk/MXQuery/xqib_samples/history.html
trunk/MXQuery/xqib_samples/historysrc.xml
Added: trunk/MXQuery/xqib_samples/history.html
===================================================================
--- trunk/MXQuery/xqib_samples/history.html (rev 0)
+++ trunk/MXQuery/xqib_samples/history.html 2011-09-22 22:27:06 UTC (rev 4449)
@@ -0,0 +1,93 @@
+<!DOCTYPE html>
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <title>XQIB: Sample page</title>
+ <meta charset="UTF-8"/>
+ <link href="style.css" rel="stylesheet" type="text/css">
+ <script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
+ <script type="application/xquery" >
+ module namespace h = "http://www.XQIB.org/history";
+ declare default element namespace "http://www.w3.org/1999/xhtml";
+
+ declare function h:stateChanged($loc, $evtObj){
+ h:stateChanged()
+ };
+ declare function h:writeUrl(){
+ let $location := b:getLocation()
+ let $hashstring := (
+ let $doc := fn:doc('historysrc.xml')
+ let $newhash := '#'
+ for $activefeature in b:dom()//input[@type=checkbox and @checked=true]
+ let $activated := $activefeature/@groupid
+ group by $activated
+ return
+ '#eouoeuoeu'
+ )
+ return
+ b:setHash(if ($hashstring) then $hashstring else '#')
+ };
+
+ declare function h:stateChanged(){
+ 1
+ };
+
+ declare updating function h:recalculate(){
+ let $doc := fn:doc('historysrc.xml')
+ let $filteredcategories := for $featuregroup in $doc/*:store/*:feature-groups/*:feature-group
+ where b:dom()//input[@groupid = $featuregroup/@groupid and @checked]
+ return $featuregroup/@groupid/string-value
+ return replace node b:dom()//id('results') with <div id='results'>{
+ for $product in $doc/*:store/*:product
+ where $product
+ return
+ <div class=''>{
+ 1
+ }</div>
+ }</div>
+ };
+
+ declare updating function h:readUrl(){
+ let $hash := b:getLocation()/b:hash/text()
+ for $hashpart in fn:tokenize($hash,'#')
+ where $hashpart ne ''
+ let $categoryid := fn:tokenize($hashpart,'=')[1]
+ let $categoryvalues := fn:tokenize($hashpart,'=')[position()>1]
+ return
+
+
+ for $value in $categoryvalues
+ let $checkbox := b:dom()//input[b:getClasses(.)='categorycheckbox' and @groupvalue = $value ]
+ where $checkbox
+ return
+ replace value of node $checkbox/@checked with 'true'
+
+
+
+ };
+ </script>
+<script type="application/xquery" >
+
+ import module namespace h = "http://www.XQIB.org/history";
+ declare variable $doc := fn:doc('historysrc.xml');
+ block {
+ for $featuregroup in $doc/*:store/*:feature-groups/*:feature-group
+ return insert node <div>{data($featuregroup/@name)}{
+ for $value in fn:distinct-values($doc/*:store/*:product/*:feature[@groupid = $featuregroup/@groupid]/@value)
+ return
+ <div><input type="checkbox" class="categorycheckbox" groupvalue="{$value}" checked="no">{$featuregroup/@groupid}</input>{$value}</div>
+ }</div> as first into b:dom()//body;
+ h:readUrl();
+ (:h:writeUrl();:)
+ h:stateChanged();
+ h:recalculate();
+}
+</script>
+
+ <script type="text/javascript" >
+ </script>
+ </head>
+ <body>
+<div id="results"><p>random content</p><p/></div>
+<a href="javascript:document.location.hash='#2=1024x764=croeu#1=15"=10"';document.location.reload()">test-link</a>
+ </body>
+</html>
Added: trunk/MXQuery/xqib_samples/historysrc.xml
===================================================================
--- trunk/MXQuery/xqib_samples/historysrc.xml (rev 0)
+++ trunk/MXQuery/xqib_samples/historysrc.xml 2011-09-22 22:27:06 UTC (rev 4449)
@@ -0,0 +1,14 @@
+<store>
+ <feature-groups>
+ <feature-group groupid="1" name="screen size"/>
+ <feature-group groupid="2" name="resolution"/>
+ </feature-groups>
+ <product name="netbook 1">
+ <feature groupid="1" value="10""/>
+ <feature groupid="2" value="1024x764"/>
+ </product>
+ <product name="laptop 1">
+ <feature groupid="1" value="15""/>
+ <feature groupid="2" value="1920x1200"/>
+ </product>
+</store>
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java 2011-09-22 16:53:10 UTC (rev 4448)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java 2011-09-22 22:27:06 UTC (rev 4449)
@@ -37,11 +37,8 @@
InputElement el = (InputElement) this.getAsGwtElement();
if ("value".equals(localName)) {
el.setValue(value);
- return;
} else if ("checked".equals(localName)) {
-
el.setChecked("true".equals(value));
- return;
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <et...@us...> - 2011-09-29 23:27:03
|
Revision: 4460
http://mxquery.svn.sourceforge.net/mxquery/?rev=4460&view=rev
Author: etterth
Date: 2011-09-29 23:26:57 +0000 (Thu, 29 Sep 2011)
Log Message:
-----------
- Removed some empty folders
- Removed xqib_test (old GWT tests, not needed anymore)
Removed Paths:
-------------
trunk/MXQuery/xqib_src/ch/ethz/mxquery/contextConfig/
trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/pattern/
trunk/MXQuery/xqib_src/ch/ethz/mxquery/query/parser/
trunk/MXQuery/xqib_src/java/client/
trunk/MXQuery/xqib_test/
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <et...@us...> - 2011-10-20 19:17:54
|
Revision: 4494
http://mxquery.svn.sourceforge.net/mxquery/?rev=4494&view=rev
Author: etterth
Date: 2011-10-20 19:17:48 +0000 (Thu, 20 Oct 2011)
Log Message:
-----------
- Fixed memory
- Removed dependence of NodeStoreIterator on Window -> removed a bug that prevented fixing the memory
Modified Paths:
--------------
trunk/MXQuery/xqib_samples/prague/memory.htm
trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/NodeStoreIterator.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/SingleNodeIterator.java
Modified: trunk/MXQuery/xqib_samples/prague/memory.htm
===================================================================
--- trunk/MXQuery/xqib_samples/prague/memory.htm 2011-10-19 23:51:52 UTC (rev 4493)
+++ trunk/MXQuery/xqib_samples/prague/memory.htm 2011-10-20 19:17:48 UTC (rev 4494)
@@ -89,7 +89,7 @@
return
(if (count($opendivs) < 2) then
if (b:getClasses($loc) ='found') then () else
- b:addClass($loc, 'open')
+ b:addClass($loc/.., 'open')
else ()
,
m:testwin())
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/NodeStoreIterator.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/NodeStoreIterator.java 2011-10-19 23:51:52 UTC (rev 4493)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/NodeStoreIterator.java 2011-10-20 19:17:48 UTC (rev 4494)
@@ -26,15 +26,15 @@
import ch.ethz.mxquery.util.browser.dom.Element;
import ch.ethz.mxquery.util.browser.dom.Node;
-public class NodeStoreIterator extends Window {
+public class NodeStoreIterator extends Iterator {
protected Node store;
protected NodeToken current;
int attributeindex;
public NodeStoreIterator(Node store) {
- super();
- this.store = (Node)(Object)store;
+ super(null, null);
+ this.store = store;
}
public AttributeNodeToken getAttributeAt(Node node,int index){
@@ -138,122 +138,5 @@
called = 0;
}
- @Override
- public boolean hasItem(int position) throws MXQueryException {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public XDMIterator getItem(int position) throws MXQueryException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public boolean hasNextItem() throws MXQueryException {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public XDMIterator nextItem() throws MXQueryException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Window getNewItemWindow(IntegerList values) throws MXQueryException {
- // TODO Auto-generated method stub
- return null;
- }
-
- @Override
- public Window getNewWindow(int startPosition, int endPosition)
- throws MXQueryException {
- if (startPosition == 1
- && endPosition == Window.END_OF_STREAM_POSITION) {
- Window ret = new NodeStoreIterator(store);
- ret.setContext(context,false);
- return ret;
- } else {
- throw new MXQueryException("dont use window with integer parameters", "", null);
- }
- }
-
- @Override
- public int getStartNode() throws MXQueryException {
- // TODO Auto-generated method stub
- return 0;
- }
-
-
- public Window getNewWindow(int startPosition,
- int endPosition, long openTime, long closeTime) throws MXQueryException {
- //TODO: Add implementation
- return null;
- }
-
-
- public Window getNewWindow(int startPosition,
- int endPosition, long openTime, long closeTime, Object queryId) throws MXQueryException{
- //TODO: Add implementation
- return null;
- }
-
-
-
- public Window getEmptyWindow() throws MXQueryException{
- //TODO: Add implementation
- return null;
- }
-
- @Override
- public void destroyWindow() {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public boolean equals(Object other) {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public int getWindowId() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- protected int getNodeId() throws MXQueryException {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public boolean isWindowInUse() {
- // TODO Auto-generated method stub
- return false;
- }
-
- @Override
- public void setWindowInUse(boolean windowInUse) {
- // TODO Auto-generated method stub
-
- }
-
- @Override
- public int getPosition() {
- // TODO Auto-generated method stub
- return 0;
- }
-
- @Override
- public Source getStore() {
- // TODO Auto-generated method stub
- return null;
- }
}
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/SingleNodeIterator.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/SingleNodeIterator.java 2011-10-19 23:51:52 UTC (rev 4493)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/iterators/browser/SingleNodeIterator.java 2011-10-20 19:17:48 UTC (rev 4494)
@@ -50,18 +50,6 @@
}
- @Override
- public Window getNewWindow(int startPosition, int endPosition)
- throws MXQueryException {
- if (startPosition == 1
- && endPosition == Window.END_OF_STREAM_POSITION) {
- Window ret = new SingleNodeIterator(store);
- ret.setContext(context,false);
- return ret;
- } else {
- throw new MXQueryException("dont use window with integer parameters", "", null);
- }
- }
@Override
protected XDMIterator copy(Context context, XDMIterator[] subIters,
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <et...@us...> - 2011-10-21 14:29:52
|
Revision: 4497
http://mxquery.svn.sourceforge.net/mxquery/?rev=4497&view=rev
Author: etterth
Date: 2011-10-21 14:29:46 +0000 (Fri, 21 Oct 2011)
Log Message:
-----------
- Updated history.html (hash synchronization with checkboxes is now working)
- Fixed a bug in fn:doc (reset was faulty)
- The mapping from DOM input element properties to attributes should now be more complete
Modified Paths:
--------------
trunk/MXQuery/xqib_samples/history.html
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/fn/Doc.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/DOMImpl.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java
Modified: trunk/MXQuery/xqib_samples/history.html
===================================================================
--- trunk/MXQuery/xqib_samples/history.html 2011-10-21 07:09:22 UTC (rev 4496)
+++ trunk/MXQuery/xqib_samples/history.html 2011-10-21 14:29:46 UTC (rev 4497)
@@ -17,18 +17,18 @@
let $hashstring := (
let $doc := fn:doc('historysrc.xml')
let $newhash := '#'
- for $activefeature in b:dom()//input[@type=checkbox and @checked=true]
+ for $activefeature in b:dom()//input[@type='checkbox' and @checked='true']
let $activated := $activefeature/@groupid
group by $activated
return
- '#eouoeuoeu'
+ concat('#', $activated, '=', string-join($activefeature/following-sibling::text(), '='))
)
return
- b:setHash(if ($hashstring) then $hashstring else '#')
+ b:setHash(if (count($hashstring)) then string-join($hashstring) else '#')
};
declare function h:stateChanged(){
- 1
+ h:writeUrl()
};
declare updating function h:recalculate(){
@@ -38,11 +38,16 @@
return $featuregroup/@groupid/string-value
return replace node b:dom()//id('results') with <div id='results'>{
for $product in $doc/*:store/*:product
- where $product
+
return
- <div class=''>{
- 1
- }</div>
+ <div class=''>
+ <div>{
+ data($product/@name),
+ <div>{
+ 1
+ }</div>
+ }</div>
+ </div>
}</div>
};
@@ -59,7 +64,7 @@
let $checkbox := b:dom()//input[b:getClasses(.)='categorycheckbox' and @groupvalue = $value ]
where $checkbox
return
- replace value of node $checkbox/@checked with 'true'
+ insert node attribute checked { 'true' } into $checkbox
@@ -69,18 +74,19 @@
import module namespace h = "http://www.XQIB.org/history";
declare variable $doc := fn:doc('historysrc.xml');
- block {
for $featuregroup in $doc/*:store/*:feature-groups/*:feature-group
return insert node <div>{data($featuregroup/@name)}{
for $value in fn:distinct-values($doc/*:store/*:product/*:feature[@groupid = $featuregroup/@groupid]/@value)
return
- <div><input type="checkbox" class="categorycheckbox" groupvalue="{$value}" checked="no">{$featuregroup/@groupid}</input>{$value}</div>
+ <div><input type="checkbox" class="categorycheckbox" groupvalue="{$value}" >{$featuregroup/@groupid}</input>{$value}</div>
}</div> as first into b:dom()//body;
+ for $cb in b:dom()//input[@type='checkbox']
+ return b:addEventListener($cb, 'click', h:stateChanged#2);
h:readUrl();
- (:h:writeUrl();:)
+ h:writeUrl();
h:stateChanged();
h:recalculate();
-}
+
</script>
<script type="text/javascript" >
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/fn/Doc.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/fn/Doc.java 2011-10-21 07:09:22 UTC (rev 4496)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/fn/Doc.java 2011-10-21 14:29:46 UTC (rev 4497)
@@ -162,10 +162,13 @@
public void setReturnType(int type) throws MXQueryException {
}
+
@Override
protected void resetImpl() throws MXQueryException {
- if (baseIterator != null)
+ if (baseIterator != null) {
+ baseIterator.setResettable(true);
baseIterator.reset();
+ }
}
public String getSystemID() {
if (current != null)
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/DOMImpl.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/DOMImpl.java 2011-10-21 07:09:22 UTC (rev 4496)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/DOMImpl.java 2011-10-21 14:29:46 UTC (rev 4497)
@@ -6,6 +6,7 @@
import java.util.List;
import com.google.gwt.core.client.GWT;
+import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray;
import com.google.gwt.dom.client.IFrameElement;
import com.google.gwt.dom.client.InputElement;
@@ -61,12 +62,13 @@
// elementattributes.get(attr.getLocalName()));
//
// }
+ //TODO more input element types
if ("input".equals(ownername)) {
String attrname = attr.getNodeName();
if ("value".equals(attrname)) {
return ((InputElement) owner.getAsGwtNode()).getValue();
} else if ("checked".equals(attrname)) {
- return nativeInputGetChecked(owner);
+ return Boolean.toString(((InputElement) owner.getAsGwtNode()).isChecked());
}
}
}
@@ -76,13 +78,6 @@
// }
}
- protected native String nativeInputGetChecked(Element input)/*-{
- return input.checked
- }-*/;
- // protected native String getSpecialAttributeValue(Element owner,
- // String string) /*-{
- // return eval(attr + '.' + string);
- // }-*/;
protected native String nativeNodeGetValue(Node node)/*-{
return node.nodeValue;
@@ -106,6 +101,20 @@
for (int i = 0; i < attrs.length(); i++) {
ret.add(attrs.get(i));
}
+ //TODO more input element types
+ if ("input".equals(el.getLocalName())) {
+ if ("http://www.w3.org/1999/xhtml".equals(el.getNameSpaceURI())) {
+ InputElement input = (InputElement)(JavaScriptObject)el;
+ if ("checkbox".equals(input.getType())
+ || "radio".equals(input.getType())) {
+ el.setAttributeNS("", "checked", Boolean.toString(input.getPropertyBoolean("checked")));
+ ret.add((Attribute) el.getAttributeNode("checked"));
+ } else {
+ el.setAttributeNS("", "value", input.getValue());
+ ret.add((Attribute) el.getAttributeNode("value"));
+ }
+ }
+ }
return ret;
}
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java 2011-10-21 07:09:22 UTC (rev 4496)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/browser/dom/Element.java 2011-10-21 14:29:46 UTC (rev 4497)
@@ -36,9 +36,13 @@
if ("input".equals(this.getLocalName())) {
InputElement el = (InputElement) this.getAsGwtElement();
if ("value".equals(localName)) {
+ DOMImpl.impl.elementSetAttributeNS(this, namespace, localName, value);
el.setValue(value);
+ return;
} else if ("checked".equals(localName)) {
+ DOMImpl.impl.elementSetAttributeNS(this, namespace, localName, value);
el.setChecked("true".equals(value));
+ return;
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pm_...@us...> - 2011-12-19 13:35:42
|
Revision: 4504
http://mxquery.svn.sourceforge.net/mxquery/?rev=4504&view=rev
Author: pm_fischer
Date: 2011-12-19 13:35:31 +0000 (Mon, 19 Dec 2011)
Log Message:
-----------
Remove unneeded files
Removed Paths:
-------------
trunk/MXQuery/notm.xml
trunk/MXQuery/tm.xml
Deleted: trunk/MXQuery/notm.xml
===================================================================
--- trunk/MXQuery/notm.xml 2011-12-19 13:34:52 UTC (rev 4503)
+++ trunk/MXQuery/notm.xml 2011-12-19 13:35:31 UTC (rev 4504)
@@ -1,2 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
@@ Diff output truncated at 100000 characters. @@
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pm_...@us...> - 2011-12-20 21:59:15
|
Revision: 4505
http://mxquery.svn.sourceforge.net/mxquery/?rev=4505&view=rev
Author: pm_fischer
Date: 2011-12-20 21:59:06 +0000 (Tue, 20 Dec 2011)
Log Message:
-----------
Basic JSON support on Java platforms
Modified Paths:
--------------
trunk/MXQuery/build.xml
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml
Added Paths:
-----------
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/json/
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/json/Parse.java
trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java
trunk/MXQuery/src/org/json/
trunk/MXQuery/src/org/json/CDL.java
trunk/MXQuery/src/org/json/JSONArray.java
trunk/MXQuery/src/org/json/JSONException.java
trunk/MXQuery/src/org/json/JSONML.java
trunk/MXQuery/src/org/json/JSONObject.java
trunk/MXQuery/src/org/json/JSONString.java
trunk/MXQuery/src/org/json/JSONStringer.java
trunk/MXQuery/src/org/json/JSONTokener.java
trunk/MXQuery/src/org/json/JSONWriter.java
trunk/MXQuery/src/org/json/XML.java
trunk/MXQuery/src/org/json/XMLTokener.java
Modified: trunk/MXQuery/build.xml
===================================================================
--- trunk/MXQuery/build.xml 2011-12-19 13:35:31 UTC (rev 4504)
+++ trunk/MXQuery/build.xml 2011-12-20 21:59:06 UTC (rev 4505)
@@ -1092,6 +1092,7 @@
<!-- remove unsupported classes -->
<echo message="Removing unsupported classes"/>
<delete dir="${androidtmp.dir}/ch/ethz/mxquery/dmcq/"/>
+ <delete dir="${androidtmp.dir}/org/json/"/>
<delete>
<fileset dir="${androidtmp.dir}/ch/ethz/mxquery/functions/fn/">
<include name="NormalizeUnicode.java"/>
Modified: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml 2011-12-19 13:35:31 UTC (rev 4504)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml 2011-12-20 21:59:06 UTC (rev 4505)
@@ -208,5 +208,15 @@
</parameters>
<className>SignString</className>
</functionDescription>
+</functionGroup>
+<functionGroup prefix="json" namespace="http://www.zorba-xquery.com/modules/converters/json">
+ <functionDescription>
+ <functionName>parse</functionName>
+ <parameters>
+ <paramType>string</paramType>
+ </parameters>
+ <className op="json">Parse</className>
+ </functionDescription>
</functionGroup>
+
</functionGallery>
\ No newline at end of file
Added: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/json/Parse.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/json/Parse.java (rev 0)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/json/Parse.java 2011-12-20 21:59:06 UTC (rev 4505)
@@ -0,0 +1,86 @@
+/* Copyright 2006 - 2009 ETH Zurich
+ *
+ * Licensed 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.
+ */
+
+package ch.ethz.mxquery.extensionsModules.json;
+
+import java.util.Vector;
+
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.types.TypeInfo;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.ErrorCodes;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.functions.RequestTypeMulti;
+import ch.ethz.mxquery.model.CurrentBasedIterator;
+import ch.ethz.mxquery.model.EmptySequenceIterator;
+import ch.ethz.mxquery.model.XDMIterator;
+import ch.ethz.mxquery.xdmio.xmlAdapters.JSONAdapter;
+
+public class Parse extends CurrentBasedIterator implements RequestTypeMulti{
+
+ private boolean useJSONML;
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack)
+ throws MXQueryException {
+ Parse ret = new Parse();
+ ret.setSubIters(subIters);
+ ret.setContext(context, false);
+ ret.useJSONML = useJSONML;
+ return ret;
+ }
+
+ public TokenInterface next() throws MXQueryException {
+ if (called == 0) {
+ init();
+ called++;
+ }
+ return current.next();
+ }
+
+
+ public void init() throws MXQueryException {
+ String add = getStringValueOrEmpty(subIters[0]);
+ if (add == null || add.equals("")) {
+ current = new EmptySequenceIterator(context,loc);
+ return;
+ }
+ current = new JSONAdapter(context, loc, add, useJSONML);
+ return;
+ }
+ public TypeInfo getStaticType() {
+ return new TypeInfo(Type.START_TAG,Type.OCCURRENCE_IND_ZERO_OR_ONE);
+ }
+ public boolean isExprParameter(int valueToCheck, boolean recursive) {
+ if (valueToCheck == EXPR_PARAM_XDMGEN)
+ return true;
+ else
+ return super.isExprParameter(valueToCheck, recursive);
+ }
+
+ public void setOperation(String type) throws MXQueryException {
+ if (type.equals("json"))
+ useJSONML = false;
+ else if (type.equals("jsonml"))
+ useJSONML = true;
+
+ else throw new MXQueryException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Incorrect operation for parse/tidy", loc);
+
+ }
+
+ public void setReturnType(int type) throws MXQueryException {
+ }
+
+}
Added: trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java (rev 0)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java 2011-12-20 21:59:06 UTC (rev 4505)
@@ -0,0 +1,136 @@
+package ch.ethz.mxquery.xdmio.xmlAdapters;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.util.Vector;
+
+import org.json.JSONTokener;
+
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.QName;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.xdm.ElementToken;
+import ch.ethz.mxquery.datamodel.xdm.TextToken;
+import ch.ethz.mxquery.datamodel.xdm.Token;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.DynamicException;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.exceptions.QueryLocation;
+import ch.ethz.mxquery.model.XDMIterator;
+
+public class JSONAdapter extends XDMImportAdapter {
+ public static final String JSON_URI="http://www.zorba-xquery.com/modules/converters/json";
+ private static final QName JSON_QN = new QName(null,null,"json");
+ private static final QName TYPE_QN = new QName(null,null,"type");
+ private static final QName PAIR_QN = new QName(null,null,"pair");
+ private static final QName NAME_QN = new QName(null,null,"name");
+ private static final QName ITEM_QN = new QName(null,null,"item");
+ Vector tokens;
+ String jsonString;
+ boolean jsonML;
+
+ public JSONAdapter(Context ctx, QueryLocation loc, String jsonString, boolean useJSONML) {
+ super(ctx, loc);
+ this.jsonString = jsonString;
+ tokens = new Vector();
+ jsonML = useJSONML;
+ }
+
+ public TokenInterface next() throws MXQueryException {
+ if (called == 0) {
+ init();
+ }
+ if (called < tokens.size()) {
+ called++;
+ return (TokenInterface)tokens.elementAt(called-1);
+ }
+ return Token.END_SEQUENCE_TOKEN;
+ }
+
+ private void init() throws MXQueryException {
+ try {
+ Object jo = new JSONTokener(jsonString).nextValue();
+ tokens.addElement(new Token(Type.START_DOCUMENT, createNextTokenId(Type.START_DOCUMENT,null),curNsScope));
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "json"), JSON_QN, curNsScope));
+ //tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "unknown", TYPE_QN, curNsScope));
+ handleJSONItem(jo);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.START_TAG, "json"), JSON_QN, curNsScope));
+ tokens.addElement(new Token(Type.END_DOCUMENT, createNextTokenId(Type.END_DOCUMENT,null),curNsScope));
+ } catch (JSONException je) {
+ throw new DynamicException(new QName(JSON_URI,"json","ParseError"), je.toString(), loc);
+ }
+ }
+
+ void handleJSONItem (Object obj) throws JSONException, MXQueryException {
+ if (obj instanceof JSONObject) {
+ JSONObject jo = ((JSONObject)obj);
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "object", TYPE_QN, curNsScope));
+ JSONArray names = jo.names();
+ for (int i=0;i<names.length();i++) {
+ String nm = (String)names.get(i);
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "pair"), PAIR_QN, curNsScope));
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, nm, NAME_QN, curNsScope));
+ Object no = jo.get(nm);
+ handleJSONItem(no);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.END_TAG, "pair"), PAIR_QN, curNsScope));
+ }
+ return;
+ }
+ if (obj instanceof JSONArray) {
+ JSONArray ja = (JSONArray)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "array", TYPE_QN, curNsScope));
+ for (int i=0;i<ja.length();i++) {
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "item"), ITEM_QN, curNsScope));
+ Object o = ja.get(i);
+ handleJSONItem(o);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.START_TAG, "item"), ITEM_QN, curNsScope));
+ }
+ return;
+ }
+ if (obj instanceof String) {
+ String str = (String)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "string", TYPE_QN, curNsScope));
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), str, curNsScope));
+ return;
+ }
+ if (obj instanceof Integer) {
+ Integer it = (Integer)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "number", TYPE_QN, curNsScope));
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), it.toString(), curNsScope));
+ return;
+ }
+ if (obj instanceof Double) {
+ Double db = (Double)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "number", TYPE_QN, curNsScope));
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), db.toString(), curNsScope));
+ return;
+ }
+ if (obj instanceof Boolean) {
+ Boolean bo = (Boolean)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "boolean", TYPE_QN, curNsScope));
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), bo.toString(), curNsScope));
+ return;
+ }
+ if (obj == JSONObject.NULL) {
+ return;
+ }
+ throw new DynamicException(new QName(JSON_URI,"json","ParseError"),"Not implemented Type",loc);
+ }
+
+
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters,
+ Vector nestedPredCtxStack) throws MXQueryException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
Added: trunk/MXQuery/src/org/json/CDL.java
===================================================================
--- trunk/MXQuery/src/org/json/CDL.java (rev 0)
+++ trunk/MXQuery/src/org/json/CDL.java 2011-12-20 21:59:06 UTC (rev 4505)
@@ -0,0 +1,279 @@
+package org.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+/**
+ * This provides static methods to convert comma delimited text into a
+ * JSONArray, and to covert a JSONArray into comma delimited text. Comma
+ * delimited text is a very popular format for data interchange. It is
+ * understood by most database, spreadsheet, and organizer programs.
+ * <p>
+ * Each row of text represents a row in a table or a data record. Each row
+ * ends with a NEWLINE character. Each row contains one or more values.
+ * Values are separated by commas. A value can contain any character except
+ * for comma, unless is is wrapped in single quotes or double quotes.
+ * <p>
+ * The first row usually contains the names of the columns.
+ * <p>
+ * A comma delimited list can be converted into a JSONArray of JSONObjects.
+ * The names for the elements in the JSONObjects can be taken from the names
+ * in the first row.
+ * @author JSON.org
+ * @version 2010-12-24
+ */
+public class CDL {
+
+ /**
+ * Get the next value. The value can be wrapped in quotes. The value can
+ * be empty.
+ * @param x A JSONTokener of the source text.
+ * @return The value string, or null if empty.
+ * @throws JSONException if the quoted string is badly formed.
+ */
+ private static String getValue(JSONTokener x) throws JSONException {
+ char c;
+ char q;
+ StringBuffer sb;
+ do {
+ c = x.next();
+ } while (c == ' ' || c == '\t');
+ switch (c) {
+ case 0:
+ return null;
+ case '"':
+ case '\'':
+ q = c;
+ sb = new StringBuffer();
+ for (;;) {
+ c = x.next();
+ if (c == q) {
+ break;
+ }
+ if (c == 0 || c == '\n' || c == '\r') {
+ throw x.syntaxError("Missing close quote '" + q + "'.");
+ }
+ sb.append(c);
+ }
+ return sb.toString();
+ case ',':
+ x.back();
+ return "";
+ default:
+ x.back();
+ return x.nextTo(',');
+ }
+ }
+
+ /**
+ * Produce a JSONArray of strings from a row of comma delimited values.
+ * @param x A JSONTokener of the source text.
+ * @return A JSONArray of strings.
+ * @throws JSONException
+ */
+ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
+ JSONArray ja = new JSONArray();
+ for (;;) {
+ String value = getValue(x);
+ char c = x.next();
+ if (value == null ||
+ (ja.length() == 0 && value.length() == 0 && c != ',')) {
+ return null;
+ }
+ ja.put(value);
+ for (;;) {
+ if (c == ',') {
+ break;
+ }
+ if (c != ' ') {
+ if (c == '\n' || c == '\r' || c == 0) {
+ return ja;
+ }
+ throw x.syntaxError("Bad character '" + c + "' (" +
+ (int)c + ").");
+ }
+ c = x.next();
+ }
+ }
+ }
+
+ /**
+ * Produce a JSONObject from a row of comma delimited text, using a
+ * parallel JSONArray of strings to provides the names of the elements.
+ * @param names A JSONArray of names. This is commonly obtained from the
+ * first row of a comma delimited text file using the rowToJSONArray
+ * method.
+ * @param x A JSONTokener of the source text.
+ * @return A JSONObject combining the names and values.
+ * @throws JSONException
+ */
+ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
+ throws JSONException {
+ JSONArray ja = rowToJSONArray(x);
+ return ja != null ? ja.toJSONObject(names) : null;
+ }
+
+ /**
+ * Produce a comma delimited text row from a JSONArray. Values containing
+ * the comma character will be quoted. Troublesome characters may be
+ * removed.
+ * @param ja A JSONArray of strings.
+ * @return A string ending in NEWLINE.
+ */
+ public static String rowToString(JSONArray ja) {
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < ja.length(); i += 1) {
+ if (i > 0) {
+ sb.append(',');
+ }
+ Object object = ja.opt(i);
+ if (object != null) {
+ String string = object.toString();
+ if (string.length() > 0 && (string.indexOf(',') >= 0 ||
+ string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
+ string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
+ sb.append('"');
+ int length = string.length();
+ for (int j = 0; j < length; j += 1) {
+ char c = string.charAt(j);
+ if (c >= ' ' && c != '"') {
+ sb.append(c);
+ }
+ }
+ sb.append('"');
+ } else {
+ sb.append(string);
+ }
+ }
+ }
+ sb.append('\n');
+ return sb.toString();
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string,
+ * using the first row as a source of names.
+ * @param string The comma delimited text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException
+ */
+ public static JSONArray toJSONArray(String string) throws JSONException {
+ return toJSONArray(new JSONTokener(string));
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string,
+ * using the first row as a source of names.
+ * @param x The JSONTokener containing the comma delimited text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException
+ */
+ public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
+ return toJSONArray(rowToJSONArray(x), x);
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string
+ * using a supplied JSONArray as the source of element names.
+ * @param names A JSONArray of strings.
+ * @param string The comma delimited text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException
+ */
+ public static JSONArray toJSONArray(JSONArray names, String string)
+ throws JSONException {
+ return toJSONArray(names, new JSONTokener(string));
+ }
+
+ /**
+ * Produce a JSONArray of JSONObjects from a comma delimited text string
+ * using a supplied JSONArray as the source of element names.
+ * @param names A JSONArray of strings.
+ * @param x A JSONTokener of the source text.
+ * @return A JSONArray of JSONObjects.
+ * @throws JSONException
+ */
+ public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
+ throws JSONException {
+ if (names == null || names.length() == 0) {
+ return null;
+ }
+ JSONArray ja = new JSONArray();
+ for (;;) {
+ JSONObject jo = rowToJSONObject(names, x);
+ if (jo == null) {
+ break;
+ }
+ ja.put(jo);
+ }
+ if (ja.length() == 0) {
+ return null;
+ }
+ return ja;
+ }
+
+
+ /**
+ * Produce a comma delimited text from a JSONArray of JSONObjects. The
+ * first row will be a list of names obtained by inspecting the first
+ * JSONObject.
+ * @param ja A JSONArray of JSONObjects.
+ * @return A comma delimited text.
+ * @throws JSONException
+ */
+ public static String toString(JSONArray ja) throws JSONException {
+ JSONObject jo = ja.optJSONObject(0);
+ if (jo != null) {
+ JSONArray names = jo.names();
+ if (names != null) {
+ return rowToString(names) + toString(names, ja);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Produce a comma delimited text from a JSONArray of JSONObjects using
+ * a provided list of names. The list of names is not included in the
+ * output.
+ * @param names A JSONArray of strings.
+ * @param ja A JSONArray of JSONObjects.
+ * @return A comma delimited text.
+ * @throws JSONException
+ */
+ public static String toString(JSONArray names, JSONArray ja)
+ throws JSONException {
+ if (names == null || names.length() == 0) {
+ return null;
+ }
+ StringBuffer sb = new StringBuffer();
+ for (int i = 0; i < ja.length(); i += 1) {
+ JSONObject jo = ja.optJSONObject(i);
+ if (jo != null) {
+ sb.append(rowToString(jo.toJSONArray(names)));
+ }
+ }
+ return sb.toString();
+ }
+}
Added: trunk/MXQuery/src/org/json/JSONArray.java
===================================================================
--- trunk/MXQuery/src/org/json/JSONArray.java (rev 0)
+++ trunk/MXQuery/src/org/json/JSONArray.java 2011-12-20 21:59:06 UTC (rev 4505)
@@ -0,0 +1,920 @@
+package org.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.io.IOException;
+import java.io.Writer;
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+
+/**
+ * A JSONArray is an ordered sequence of values. Its external text form is a
+ * string wrapped in square brackets with commas separating the values. The
+ * internal form is an object having <code>get</code> and <code>opt</code>
+ * methods for accessing the values by index, and <code>put</code> methods for
+ * adding or replacing values. The values can be any of these types:
+ * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
+ * <code>Number</code>, <code>String</code>, or the
+ * <code>JSONObject.NULL object</code>.
+ * <p>
+ * The constructor can convert a JSON text into a Java object. The
+ * <code>toString</code> method converts to JSON text.
+ * <p>
+ * A <code>get</code> method returns a value if one can be found, and throws an
+ * exception if one cannot be found. An <code>opt</code> method returns a
+ * default value instead of throwing an exception, and so is useful for
+ * obtaining optional values.
+ * <p>
+ * The generic <code>get()</code> and <code>opt()</code> methods return an
+ * object which you can cast or query for type. There are also typed
+ * <code>get</code> and <code>opt</code> methods that do type checking and type
+ * coercion for you.
+ * <p>
+ * The texts produced by the <code>toString</code> methods strictly conform to
+ * JSON syntax rules. The constructors are more forgiving in the texts they will
+ * accept:
+ * <ul>
+ * <li>An extra <code>,</code> <small>(comma)</small> may appear just
+ * before the closing bracket.</li>
+ * <li>The <code>null</code> value will be inserted when there
+ * is <code>,</code> <small>(comma)</small> elision.</li>
+ * <li>Strings may be quoted with <code>'</code> <small>(single
+ * quote)</small>.</li>
+ * <li>Strings do not need to be quoted at all if they do not begin with a quote
+ * or single quote, and if they do not contain leading or trailing spaces,
+ * and if they do not contain any of these characters:
+ * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
+ * and if they are not the reserved words <code>true</code>,
+ * <code>false</code>, or <code>null</code>.</li>
+ * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
+ * well as by <code>,</code> <small>(comma)</small>.</li>
+ * </ul>
+
+ * @author JSON.org
+ * @version 2011-11-24
+ */
+public class JSONArray {
+
+
+ /**
+ * The arrayList where the JSONArray's properties are kept.
+ */
+ private final ArrayList myArrayList;
+
+
+ /**
+ * Construct an empty JSONArray.
+ */
+ public JSONArray() {
+ this.myArrayList = new ArrayList();
+ }
+
+ /**
+ * Construct a JSONArray from a JSONTokener.
+ * @param x A JSONTokener
+ * @throws JSONException If there is a syntax error.
+ */
+ public JSONArray(JSONTokener x) throws JSONException {
+ this();
+ if (x.nextClean() != '[') {
+ throw x.syntaxError("A JSONArray text must start with '['");
+ }
+ if (x.nextClean() != ']') {
+ x.back();
+ for (;;) {
+ if (x.nextClean() == ',') {
+ x.back();
+ this.myArrayList.add(JSONObject.NULL);
+ } else {
+ x.back();
+ this.myArrayList.add(x.nextValue());
+ }
+ switch (x.nextClean()) {
+ case ';':
+ case ',':
+ if (x.nextClean() == ']') {
+ return;
+ }
+ x.back();
+ break;
+ case ']':
+ return;
+ default:
+ throw x.syntaxError("Expected a ',' or ']'");
+ }
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONArray from a source JSON text.
+ * @param source A string that begins with
+ * <code>[</code> <small>(left bracket)</small>
+ * and ends with <code>]</code> <small>(right bracket)</small>.
+ * @throws JSONException If there is a syntax error.
+ */
+ public JSONArray(String source) throws JSONException {
+ this(new JSONTokener(source));
+ }
+
+
+ /**
+ * Construct a JSONArray from a Collection.
+ * @param collection A Collection.
+ */
+ public JSONArray(Collection collection) {
+ this.myArrayList = new ArrayList();
+ if (collection != null) {
+ Iterator iter = collection.iterator();
+ while (iter.hasNext()) {
+ this.myArrayList.add(JSONObject.wrap(iter.next()));
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONArray from an array
+ * @throws JSONException If not an array.
+ */
+ public JSONArray(Object array) throws JSONException {
+ this();
+ if (array.getClass().isArray()) {
+ int length = Array.getLength(array);
+ for (int i = 0; i < length; i += 1) {
+ this.put(JSONObject.wrap(Array.get(array, i)));
+ }
+ } else {
+ throw new JSONException(
+"JSONArray initial value should be a string or collection or array.");
+ }
+ }
+
+
+ /**
+ * Get the object value associated with an index.
+ * @param index
+ * The index must be between 0 and length() - 1.
+ * @return An object value.
+ * @throws JSONException If there is no value for the index.
+ */
+ public Object get(int index) throws JSONException {
+ Object object = this.opt(index);
+ if (object == null) {
+ throw new JSONException("JSONArray[" + index + "] not found.");
+ }
+ return object;
+ }
+
+
+ /**
+ * Get the boolean value associated with an index.
+ * The string values "true" and "false" are converted to boolean.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The truth.
+ * @throws JSONException If there is no value for the index or if the
+ * value is not convertible to boolean.
+ */
+ public boolean getBoolean(int index) throws JSONException {
+ Object object = this.get(index);
+ if (object.equals(Boolean.FALSE) ||
+ (object instanceof String &&
+ ((String)object).equalsIgnoreCase("false"))) {
+ return false;
+ } else if (object.equals(Boolean.TRUE) ||
+ (object instanceof String &&
+ ((String)object).equalsIgnoreCase("true"))) {
+ ...
[truncated message content] |
|
From: <pm_...@us...> - 2011-12-20 23:14:21
|
Revision: 4507
http://mxquery.svn.sourceforge.net/mxquery/?rev=4507&view=rev
Author: pm_fischer
Date: 2011-12-20 23:14:13 +0000 (Tue, 20 Dec 2011)
Log Message:
-----------
JSON support on J2ME
Modified Paths:
--------------
trunk/MXQuery/build.xml
Added Paths:
-----------
trunk/MXQuery/midp_src/ch/ethz/mxquery/xdmio/xmladapters/
trunk/MXQuery/midp_src/ch/ethz/mxquery/xdmio/xmladapters/JSONAdapter.java
trunk/MXQuery/midp_src/org/json/
trunk/MXQuery/midp_src/org/json/me/
trunk/MXQuery/midp_src/org/json/me/JSONArray.java
trunk/MXQuery/midp_src/org/json/me/JSONException.java
trunk/MXQuery/midp_src/org/json/me/JSONObject.java
trunk/MXQuery/midp_src/org/json/me/JSONString.java
trunk/MXQuery/midp_src/org/json/me/JSONStringer.java
trunk/MXQuery/midp_src/org/json/me/JSONTokener.java
trunk/MXQuery/midp_src/org/json/me/JSONWriter.java
trunk/MXQuery/midp_src/org/json/me/StringWriter.java
trunk/MXQuery/midp_src/org/json/me/util/
trunk/MXQuery/midp_src/org/json/me/util/XML.java
trunk/MXQuery/midp_src/org/json/me/util/XMLTokener.java
Modified: trunk/MXQuery/build.xml
===================================================================
--- trunk/MXQuery/build.xml 2011-12-20 22:00:54 UTC (rev 4506)
+++ trunk/MXQuery/build.xml 2011-12-20 23:14:13 UTC (rev 4507)
@@ -371,9 +371,9 @@
</fileset>
</delete>
<copy todir="${midptmp.dir}"><fileset dir="${src.dir}"/></copy>
+ <delete dir="${midptmp.dir}/org/json/"/>
<copy todir="${midptmp.dir}" overwrite="yes"><fileset dir="${midpsrc.dir}"/></copy>
<echo message="Removing unsupported classes"/>
-
<delete dir="${midptmp.dir}/ch/ethz/mxquery/parallel/"/>
<delete dir="${midptmp.dir}/javax/"/>
<delete dir="${midptmp.dir}/org/tartarus"/>
Added: trunk/MXQuery/midp_src/ch/ethz/mxquery/xdmio/xmladapters/JSONAdapter.java
===================================================================
--- trunk/MXQuery/midp_src/ch/ethz/mxquery/xdmio/xmladapters/JSONAdapter.java (rev 0)
+++ trunk/MXQuery/midp_src/ch/ethz/mxquery/xdmio/xmladapters/JSONAdapter.java 2011-12-20 23:14:13 UTC (rev 4507)
@@ -0,0 +1,129 @@
+package ch.ethz.mxquery.xdmio.xmlAdapters;
+
+import org.json.me.JSONArray;
+import org.json.me.JSONException;
+import org.json.me.JSONObject;
+
+import java.util.Vector;
+
+import org.json.me.JSONTokener;
+
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.QName;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.xdm.ElementToken;
+import ch.ethz.mxquery.datamodel.xdm.TextToken;
+import ch.ethz.mxquery.datamodel.xdm.Token;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.DynamicException;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.exceptions.QueryLocation;
+import ch.ethz.mxquery.model.XDMIterator;
+
+public class JSONAdapter extends XDMImportAdapter {
+ public static final String JSON_URI="http://www.zorba-xquery.com/modules/converters/json";
+ private static final QName JSON_QN = new QName(null,null,"json");
+ private static final QName TYPE_QN = new QName(null,null,"type");
+ private static final QName PAIR_QN = new QName(null,null,"pair");
+ private static final QName NAME_QN = new QName(null,null,"name");
+ private static final QName ITEM_QN = new QName(null,null,"item");
+ Vector tokens;
+ String jsonString;
+ boolean jsonML;
+
+ public JSONAdapter(Context ctx, QueryLocation loc, String jsonString, boolean useJSONML) {
+ super(ctx, loc);
+ this.jsonString = jsonString;
+ tokens = new Vector();
+ jsonML = useJSONML;
+ }
+
+ public TokenInterface next() throws MXQueryException {
+ if (called == 0) {
+ init();
+ }
+ if (called < tokens.size()) {
+ called++;
+ return (TokenInterface)tokens.elementAt(called-1);
+ }
+ return Token.END_SEQUENCE_TOKEN;
+ }
+
+ private void init() throws MXQueryException {
+ try {
+ Object jo = new JSONTokener(jsonString).nextValue();
+ tokens.addElement(new Token(Type.START_DOCUMENT, createNextTokenId(Type.START_DOCUMENT,null),curNsScope));
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "json"), JSON_QN, curNsScope));
+ //tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "unknown", TYPE_QN, curNsScope));
+ handleJSONItem(jo);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.START_TAG, "json"), JSON_QN, curNsScope));
+ tokens.addElement(new Token(Type.END_DOCUMENT, createNextTokenId(Type.END_DOCUMENT,null),curNsScope));
+ } catch (JSONException je) {
+ throw new DynamicException(new QName(JSON_URI,"json","ParseError"), je.toString(), loc);
+ }
+ }
+
+ void handleJSONItem (Object obj) throws JSONException, MXQueryException {
+ if (obj instanceof JSONObject) {
+ JSONObject jo = ((JSONObject)obj);
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "object", TYPE_QN, curNsScope));
+ JSONArray names = jo.names();
+ for (int i=0;i<names.length();i++) {
+ String nm = (String)names.get(i);
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "pair"), PAIR_QN, curNsScope));
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, nm, NAME_QN, curNsScope));
+ Object no = jo.get(nm);
+ handleJSONItem(no);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.END_TAG, "pair"), PAIR_QN, curNsScope));
+ }
+ return;
+ }
+ if (obj instanceof JSONArray) {
+ JSONArray ja = (JSONArray)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "array", TYPE_QN, curNsScope));
+ for (int i=0;i<ja.length();i++) {
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "item"), ITEM_QN, curNsScope));
+ Object o = ja.get(i);
+ handleJSONItem(o);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.START_TAG, "item"), ITEM_QN, curNsScope));
+ }
+ return;
+ }
+ if (obj instanceof String) {
+ String str = (String)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "string", TYPE_QN, curNsScope));
+ tokens.addElement(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), str, curNsScope));
+ return;
+ }
+ if (obj instanceof Integer) {
+ Integer it = (Integer)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "number", TYPE_QN, curNsScope));
+ tokens.addElement(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), it.toString(), curNsScope));
+ return;
+ }
+ if (obj instanceof Boolean) {
+ Boolean bo = (Boolean)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "boolean", TYPE_QN, curNsScope));
+ tokens.addElement(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), bo.toString(), curNsScope));
+ return;
+ }
+ if (obj == JSONObject.NULL) {
+ return;
+ }
+ throw new DynamicException(new QName(JSON_URI,"json","ParseError"),"Not implemented Type",loc);
+ }
+
+
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters,
+ Vector nestedPredCtxStack) throws MXQueryException {
+ // TODO Auto-generated method stub
+ return null;
+ }
+
+}
Added: trunk/MXQuery/midp_src/org/json/me/JSONArray.java
===================================================================
--- trunk/MXQuery/midp_src/org/json/me/JSONArray.java (rev 0)
+++ trunk/MXQuery/midp_src/org/json/me/JSONArray.java 2011-12-20 23:14:13 UTC (rev 4507)
@@ -0,0 +1,892 @@
+package org.json.me;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Hashtable;
+import java.util.Vector;
+
+/**
+ * A JSONArray is an ordered sequence of values. Its external text form is a
+ * string wrapped in square brackets with commas separating the values. The
+ * internal form is an object having <code>get</code> and <code>opt</code>
+ * methods for accessing the values by index, and <code>put</code> methods for
+ * adding or replacing values. The values can be any of these types:
+ * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
+ * <code>Number</code>, <code>String</code>, or the
+ * <code>JSONObject.NULL object</code>.
+ * <p>
+ * The constructor can convert a JSON text into a Java object. The
+ * <code>toString</code> method converts to JSON text.
+ * <p>
+ * A <code>get</code> method returns a value if one can be found, and throws an
+ * exception if one cannot be found. An <code>opt</code> method returns a
+ * default value instead of throwing an exception, and so is useful for
+ * obtaining optional values.
+ * <p>
+ * The generic <code>get()</code> and <code>opt()</code> methods return an
+ * object which you can cast or query for type. There are also typed
+ * <code>get</code> and <code>opt</code> methods that do type checking and type
+ * coersion for you.
+ * <p>
+ * The texts produced by the <code>toString</code> methods strictly conform to
+ * JSON syntax rules. The constructors are more forgiving in the texts they will
+ * accept:
+ * <ul>
+ * <li>An extra <code>,</code> <small>(comma)</small> may appear just
+ * before the closing bracket.</li>
+ * <li>The <code>null</code> value will be inserted when there
+ * is <code>,</code> <small>(comma)</small> elision.</li>
+ * <li>Strings may be quoted with <code>'</code> <small>(single
+ * quote)</small>.</li>
+ * <li>Strings do not need to be quoted at all if they do not begin with a quote
+ * or single quote, and if they do not contain leading or trailing spaces,
+ * and if they do not contain any of these characters:
+ * <code>{ } [ ] / \ : , = ; #</code> and if they do not look like numbers
+ * and if they are not the reserved words <code>true</code>,
+ * <code>false</code>, or <code>null</code>.</li>
+ * <li>Values can be separated by <code>;</code> <small>(semicolon)</small> as
+ * well as by <code>,</code> <small>(comma)</small>.</li>
+ * <li>Numbers may have the <code>0-</code> <small>(octal)</small> or
+ * <code>0x-</code> <small>(hex)</small> prefix.</li>
+ * <li>Comments written in the slashshlash, slashstar, and hash conventions
+ * will be ignored.</li>
+ * </ul>
+
+ * @author JSON.org
+ * @version 2
+ */
+public class JSONArray {
+
+
+ /**
+ * The Vector where the JSONArray's properties are kept.
+ */
+ private Vector myArrayList;
+
+
+ /**
+ * Construct an empty JSONArray.
+ */
+ public JSONArray() {
+ this.myArrayList = new Vector();
+ }
+
+ /**
+ * Construct a JSONArray from a JSONTokener.
+ * @param x A JSONTokener
+ * @throws JSONException If there is a syntax error.
+ */
+ public JSONArray(JSONTokener x) throws JSONException {
+ this();
+ if (x.nextClean() != '[') {
+ throw x.syntaxError("A JSONArray text must start with '['");
+ }
+ if (x.nextClean() == ']') {
+ return;
+ }
+ x.back();
+ for (;;) {
+ if (x.nextClean() == ',') {
+ x.back();
+ this.myArrayList.addElement(null);
+ } else {
+ x.back();
+ this.myArrayList.addElement(x.nextValue());
+ }
+ switch (x.nextClean()) {
+ case ';':
+ case ',':
+ if (x.nextClean() == ']') {
+ return;
+ }
+ x.back();
+ break;
+ case ']':
+ return;
+ default:
+ throw x.syntaxError("Expected a ',' or ']'");
+ }
+ }
+ }
+
+
+ /**
+ * Construct a JSONArray from a source sJSON text.
+ * @param string A string that begins with
+ * <code>[</code> <small>(left bracket)</small>
+ * and ends with <code>]</code> <small>(right bracket)</small>.
+ * @throws JSONException If there is a syntax error.
+ */
+ public JSONArray(String string) throws JSONException {
+ this(new JSONTokener(string));
+ }
+
+
+ /**
+ * Construct a JSONArray from a Collection.
+ * @param collection A Collection.
+ */
+ public JSONArray(Vector collection) {
+ if (collection == null) {
+ this.myArrayList = new Vector();
+ } else {
+ int size = collection.size();
+ this.myArrayList = new Vector(size);
+ for (int i=0; i < size; i++) {
+ this.myArrayList.addElement(collection.elementAt(i));
+ }
+ }
+ }
+
+ /**
+ * Get the object value associated with an index.
+ * @param index
+ * The index must be between 0 and length() - 1.
+ * @return An object value.
+ * @throws JSONException If there is no value for the index.
+ */
+ public Object get(int index) throws JSONException {
+ Object o = opt(index);
+ if (o == null) {
+ throw new JSONException("JSONArray[" + index + "] not found.");
+ }
+ return o;
+ }
+
+ /**
+ * Get the boolean value associated with an index.
+ * The string values "true" and "false" are converted to boolean.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The truth.
+ * @throws JSONException If there is no value for the index or if the
+ * value is not convertable to boolean.
+ */
+ public boolean getBoolean(int index) throws JSONException {
+ Object o = get(index);
+//#if CLDC!="1.0"
+//# if (o.equals(Boolean.FALSE) ||
+//#else
+ if (o.equals(JSONObject.FALSE) ||
+//#endif
+ (o instanceof String &&
+ ((String)o).toLowerCase().equals("false"))) {
+ return false;
+//#if CLDC!="1.0"
+//# } else if (o.equals(Boolean.TRUE) ||
+//#else
+ } else if (o.equals(JSONObject.TRUE) ||
+//#endif
+ (o instanceof String &&
+ ((String)o).toLowerCase().equals("true"))) {
+ return true;
+ }
+ throw new JSONException("JSONArray[" + index + "] is not a Boolean.");
+ }
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the double value associated with an index.
+//# *
+//# * @param index The index must be between 0 and length() - 1.
+//# * @return The value.
+//# * @throws JSONException If the key is not found or if the value cannot
+//# * be converted to a number.
+//# */
+//# public double getDouble(int index) throws JSONException {
+//# Object o = get(index);
+//# try {
+//# return Double.valueOf((String)o).doubleValue();
+//# } catch (Exception e) {
+//# throw new JSONException("JSONArray[" + index +
+//# "] is not a number.");
+//# }
+//# }
+//#endif
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the int value associated with an index.
+//# *
+//# * @param index The index must be between 0 and length() - 1.
+//# * @return The value.
+//# * @throws JSONException If the key is not found or if the value cannot
+//# * be converted to a number.
+//# * if the value cannot be converted to a number.
+//# */
+//# public int getInt(int index) throws JSONException {
+//# Object o = get(index);
+//# return (int)getDouble(index);
+//# }
+//#endif
+
+ /**
+ * Get the JSONArray associated with an index.
+ * @param index The index must be between 0 and length() - 1.
+ * @return A JSONArray value.
+ * @throws JSONException If there is no value for the index. or if the
+ * value is not a JSONArray
+ */
+ public JSONArray getJSONArray(int index) throws JSONException {
+ Object o = get(index);
+ if (o instanceof JSONArray) {
+ return (JSONArray)o;
+ }
+ throw new JSONException("JSONArray[" + index +
+ "] is not a JSONArray.");
+ }
+
+
+ /**
+ * Get the JSONObject associated with an index.
+ * @param index subscript
+ * @return A JSONObject value.
+ * @throws JSONException If there is no value for the index or if the
+ * value is not a JSONObject
+ */
+ public JSONObject getJSONObject(int index) throws JSONException {
+ Object o = get(index);
+ if (o instanceof JSONObject) {
+ return (JSONObject)o;
+ }
+ throw new JSONException("JSONArray[" + index +
+ "] is not a JSONObject.");
+ }
+
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the long value associated with an index.
+//# *
+//# * @param index The index must be between 0 and length() - 1.
+//# * @return The value.
+//# * @throws JSONException If the key is not found or if the value cannot
+//# * be converted to a number.
+//# */
+//# public long getLong(int index) throws JSONException {
+//# Object o = get(index);
+//# return (long)getDouble(index);
+//# }
+//#endif
+
+ /**
+ * Get the string associated with an index.
+ * @param index The index must be between 0 and length() - 1.
+ * @return A string value.
+ * @throws JSONException If there is no value for the index.
+ */
+ public String getString(int index) throws JSONException {
+ return get(index).toString();
+ }
+
+
+ /**
+ * Determine if the value is null.
+ * @param index The index must be between 0 and length() - 1.
+ * @return true if the value at the index is null, or if there is no value.
+ */
+ public boolean isNull(int index) {
+ return JSONObject.NULL.equals(opt(index));
+ }
+
+
+ /**
+ * Make a string from the contents of this JSONArray. The
+ * <code>separator</code> string is inserted between each element.
+ * Warning: This method assumes that the data structure is acyclical.
+ * @param separator A string that will be inserted between the elements.
+ * @return a string.
+ * @throws JSONException If the array contains an invalid number.
+ */
+ public String join(String separator) throws JSONException {
+ int len = length();
+ StringBuffer sb = new StringBuffer();
+
+ for (int i = 0; i < len; i += 1) {
+ if (i > 0) {
+ sb.append(separator);
+ }
+ sb.append(JSONObject.valueToString(this.myArrayList.elementAt(i)));
+ }
+ return sb.toString();
+ }
+
+
+ /**
+ * Get the number of elements in the JSONArray, included nulls.
+ *
+ * @return The length (or size).
+ */
+ public int length() {
+ return this.myArrayList.size();
+ }
+
+
+ /**
+ * Get the optional object value associated with an index.
+ * @param index The index must be between 0 and length() - 1.
+ * @return An object value, or null if there is no
+ * object at that index.
+ */
+ public Object opt(int index) {
+ return (index < 0 || index >= length()) ?
+ null : this.myArrayList.elementAt(index);
+ }
+
+ /**
+ * Get the optional boolean value associated with an index.
+ * It returns false if there is no value at that index,
+ * or if the value is not Boolean.TRUE or the String "true".
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return The truth.
+ */
+ public boolean optBoolean(int index) {
+ return optBoolean(index, false);
+ }
+
+ /**
+ * Get the optional boolean value associated with an index.
+ * It returns the defaultValue if there is no value at that index or if
+ * it is not a Boolean or the String "true" or "false" (case insensitive).
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue A boolean default.
+ * @return The truth.
+ */
+ public boolean optBoolean(int index, boolean defaultValue) {
+ try {
+ return getBoolean(index);
+ } catch (Exception e) {
+ return defaultValue;
+ }
+ }
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the optional double value associated with an index.
+//# * NaN is returned if there is no value for the index,
+//# * or if the value is not a number and cannot be converted to a number.
+//# *
+//# * @param index The index must be between 0 and length() - 1.
+//# * @return The value.
+//# */
+//# public double optDouble(int index) {
+//# return optDouble(index, Double.NaN);
+//# }
+//#endif
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the optional double value associated with an index.
+//# * The defaultValue is returned if there is no value for the index,
+//# * or if the value is not a number and cannot be converted to a number.
+//# *
+//# * @param index subscript
+//# * @param defaultValue The default value.
+//# * @return The value.
+//# */
+//# public double optDouble(int index, double defaultValue) {
+//# try {
+//# return getDouble(index);
+//# } catch (Exception e) {
+//# return defaultValue;
+//# }
+//# }
+//#endif
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the optional int value associated with an index.
+//# * Zero is returned if there is no value for the index,
+//# * or if the value is not a number and cannot be converted to a number.
+//# *
+//# * @param index The index must be between 0 and length() - 1.
+//# * @return The value.
+//# */
+//# public int optInt(int index) {
+//# return optInt(index, 0);
+//# }
+//#endif
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the optional int value associated with an index.
+//# * The defaultValue is returned if there is no value for the index,
+//# * or if the value is not a number and cannot be converted to a number.
+//# * @param index The index must be between 0 and length() - 1.
+//# * @param defaultValue The default value.
+//# * @return The value.
+//# */
+//# public int optInt(int index, int defaultValue) {
+//# try {
+//# return getInt(index);
+//# } catch (Exception e) {
+//# return defaultValue;
+//# }
+//# }
+//#endif
+
+ /**
+ * Get the optional JSONArray associated with an index.
+ * @param index subscript
+ * @return A JSONArray value, or null if the index has no value,
+ * or if the value is not a JSONArray.
+ */
+ public JSONArray optJSONArray(int index) {
+ Object o = opt(index);
+ return o instanceof JSONArray ? (JSONArray)o : null;
+ }
+
+
+ /**
+ * Get the optional JSONObject associated with an index.
+ * Null is returned if the key is not found, or null if the index has
+ * no value, or if the value is not a JSONObject.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return A JSONObject value.
+ */
+ public JSONObject optJSONObject(int index) {
+ Object o = opt(index);
+ return o instanceof JSONObject ? (JSONObject)o : null;
+ }
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the optional long value associated with an index.
+//# * Zero is returned if there is no value for the index,
+//# * or if the value is not a number and cannot be converted to a number.
+//# *
+//# * @param index The index must be between 0 and length() - 1.
+//# * @return The value.
+//# */
+//# public long optLong(int index) {
+//# return optLong(index, 0);
+//# }
+//#endif
+
+//#if CLDC!="1.0"
+//# /**
+//# * Get the optional long value associated with an index.
+//# * The defaultValue is returned if there is no value for the index,
+//# * or if the value is not a number and cannot be converted to a number.
+//# * @param index The index must be between 0 and length() - 1.
+//# * @param defaultValue The default value.
+//# * @return The value.
+//# */
+//# public long optLong(int index, long defaultValue) {
+//# try {
+//# return getLong(index);
+//# } catch (Exception e) {
+//# return defaultValue;
+//# }
+//# }
+//#endif
+
+ /**
+ * Get the optional string value associated with an index. It returns an
+ * empty string if there is no value at that index. If the value
+ * is not a string and is not null, then it is coverted to a string.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @return A String value.
+ */
+ public String optString(int index) {
+ return optString(index, "");
+ }
+
+
+ /**
+ * Get the optional string associated with an index.
+ * The defaultValue is returned if the key is not found.
+ *
+ * @param index The index must be between 0 and length() - 1.
+ * @param defaultValue The default value.
+ * @return A String value.
+ */
+ public String optString(int index, String defaultValue) {
+ Object o = opt(index);
+ return o != null ? o.toString() : defaultValue;
+ }
+
+
+ /**
+ * Append a boolean value. This increases the array's length by one.
+ *
+ * @param value A boolean value.
+ * @return this.
+ */
+ public JSONArray put(boolean value) {
+//#if CLDC!="1.0"
+//# put(value ? Boolean.TRUE : Boolean.FALSE);
+//#else
+ put(value ? JSONObject.TRUE : JSONObject.FALSE);
+//#endif
+ return this;
+ }
+
+ /**
+ * Put a value in the JSONArray, where the value will be a
+ * JSONArray which is produced from a Collection.
+ * @param value A Collection value.
+ * @return this.
+ */
+ public JSONArray put(Vector value) {
+ put(new JSONArray(value));
+ return this;
+ }
+
+
+//#if CLDC!="1.0"
+//# /**
+//# * Append a double value. This increases the array's length by one.
+//# *
+//# * @param value A double value.
+//# * @throws JSONException if the value is not finite.
+//# * @return this.
+//# */
+//# public JSONArray put(double value) throws JSONException {
+//# Double d = new Double(value);
+//# JSONObject.testValidity(d);
+//# put(d);
+//# return this;
+//# }
+//#endif
+
+ /**
+ * Append an int value. This increases the array's length by one.
+ *
+ * @param value An int value.
+ * @return this.
+ */
+ public JSONArray put(int value) {
+ put(new Integer(value));
+ return this;
+ }
+
+
+ /**
+ * Append an long value. This increases the array's length by one.
+ *
+ * @param value A long value.
+ * @return this.
+ */
+ public JSONArray put(long value) {
+ put(new Long(value));
+ return this;
+ }
+
+
+//#ifdef PRODUCER
+//# /**
+//# * Put a value in the JSONArray, where the value will be a
+//# * JSONObject which is produced from a Map.
+//# * @param value A Map value.
+//# * @return this.
+//# */
+//# public JSONArray put(Hashtable value) {
+//# put(new JSONObject(value));
+//# return this;
+//# }
+//#endif
+
+ /**
+ * Append an object value. This increases the array's length by one.
+ * @param value An object value. The value should be a
+ * Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
+ * JSONObject.NULL object.
+ * @return this.
+ */
+ public JSONArray put(Object value) {
+ this.myArrayList.addElement(value);
+ return this;
+ }
+
+
+ /**
+ * Put or replace a boolean value in the JSONArray. If the index is greater
+ * than the length of the JSONArray, then null elements will be added as
+ * necessary to pad it out.
+ * @param index The subscript.
+ * @param value A boolean value.
+ * @return this.
+ * @throws JSONException If the index is negative.
+ */
+ public JSONArray put(int index, boolean value) throws JSONException {
+//#if CLDC!="1.0"
+//# put(index, value ? Boolean.TRUE : Boolean.FALSE);
+//#else
+ put(index, value ? JSONObject.TRUE : JSONObject.FALSE);
+//#endif
+ return this;
+ }
+
+ /**
+ * Put a value in the JSONArray, where the value will be a
+ * JSONArray which is produced from a Collection.
+ * @param index The subscript.
+ * @param value A Collection value.
+ * @retu...
[truncated message content] |
|
From: <pm_...@us...> - 2011-12-22 11:00:33
|
Revision: 4510
http://mxquery.svn.sourceforge.net/mxquery/?rev=4510&view=rev
Author: pm_fischer
Date: 2011-12-22 11:00:23 +0000 (Thu, 22 Dec 2011)
Log Message:
-----------
- json:parse support on XQIB
- base 64 support
Modified Paths:
--------------
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java
trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java
Added Paths:
-----------
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/base64/Base64Ops.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java
Modified: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml 2011-12-21 06:34:33 UTC (rev 4509)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/Extensions.xml 2011-12-22 11:00:23 UTC (rev 4510)
@@ -218,5 +218,21 @@
<className op="json">Parse</className>
</functionDescription>
</functionGroup>
+<functionGroup prefix="base64" namespace="http://www.zorba-xquery.com/modules/base64">
+ <functionDescription>
+ <functionName>encode</functionName>
+ <parameters>
+ <paramType>string</paramType>
+ </parameters>
+ <className op="enc">Base64Ops</className>
+ </functionDescription>
+ <functionDescription>
+ <functionName>decode</functionName>
+ <parameters>
+ <paramType>base64Binary</paramType>
+ </parameters>
+ <className op="dec">Base64Ops</className>
+ </functionDescription>
+</functionGroup>
</functionGallery>
\ No newline at end of file
Added: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/base64/Base64Ops.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/base64/Base64Ops.java (rev 0)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/base64/Base64Ops.java 2011-12-22 11:00:23 UTC (rev 4510)
@@ -0,0 +1,86 @@
+/* Copyright 2006 - 2009 ETH Zurich
+ *
+ * Licensed 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.
+ */
+
+package ch.ethz.mxquery.extensionsModules.base64;
+
+import java.util.Vector;
+
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.MXQueryBinary;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.types.TypeInfo;
+import ch.ethz.mxquery.datamodel.xdm.BinaryToken;
+import ch.ethz.mxquery.datamodel.xdm.TextToken;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.ErrorCodes;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.exceptions.TypeException;
+import ch.ethz.mxquery.functions.RequestTypeMulti;
+import ch.ethz.mxquery.model.TokenBasedIterator;
+import ch.ethz.mxquery.model.XDMIterator;
+import ch.ethz.mxquery.util.Base64;
+
+public class Base64Ops extends TokenBasedIterator implements RequestTypeMulti{
+
+ private boolean dec = false;
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack)
+ throws MXQueryException {
+ Base64Ops ret = new Base64Ops();
+ ret.setSubIters(subIters);
+ ret.setContext(context, false);
+ ret.dec = dec;
+ return ret;
+ }
+
+
+
+ public void init() throws MXQueryException {
+ if (dec) {
+ TokenInterface arg = subIters[0].next();
+ int aType = Type.getEventTypeSubstituted(arg.getEventType(),Context.getDictionary());
+ if ( !(Type.isTypeOrSubTypeOf(aType, Type.BASE64_BINARY,Context.getDictionary()) ||aType == Type.UNTYPED_ATOMIC )) {
+ throw new TypeException(ErrorCodes.E0004_TYPE_INAPPROPRIATE_TYPE, "Item of type "+"xs:string"+" expected", loc);
+ }
+ if (subIters[0].next().getEventType() != Type.END_SEQUENCE)
+ throw new TypeException(ErrorCodes.E0004_TYPE_INAPPROPRIATE_TYPE, "Single Item expected", loc);
+ MXQueryBinary bin = arg.getBinary();
+ currentToken = new TextToken(null, new String(Base64.decode(bin.toString())));
+
+ }
+ else {
+ String add = getStringValue(subIters[0]);
+ currentToken = new BinaryToken(null,new MXQueryBinary(add, Type.BASE64_BINARY),null);
+
+ }
+ }
+ public TypeInfo getStaticType() {
+ return new TypeInfo(Type.START_TAG,Type.OCCURRENCE_IND_ZERO_OR_ONE);
+ }
+
+ public void setOperation(String type) throws MXQueryException {
+ if (type.equals("dec"))
+ dec = true;
+ else if (type.equals("enc"))
+ dec = false;
+
+ else throw new MXQueryException(ErrorCodes.A0009_EC_EVALUATION_NOT_POSSIBLE, "Incorrect operation for parse/tidy", loc);
+
+ }
+
+ public void setReturnType(int type) throws MXQueryException {
+ }
+
+}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java 2011-12-21 06:34:33 UTC (rev 4509)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java 2011-12-22 11:00:23 UTC (rev 4510)
@@ -445,7 +445,8 @@
contentType = overrideMediaType;
if (contentType.startsWith("text")
|| contentType.indexOf("+xml") >= 0
- || contentType.equals("application/xml")) {
+ || contentType.equals("application/xml")
+ || contentType.equals("application/json")) {
String enc = conn.getContentEncoding();
if (enc == null)
enc = "utf-8";
@@ -557,7 +558,7 @@
else if (contentType.indexOf("html") >= 0) {
resIts[resIts.length - 1] = XDMInputFactory.createTidyInput(
context, new StringReader(result.toString()), loc);
- } else if (contentType.startsWith("text/") || contentType.equalsIgnoreCase("application/xml-dtd")) {
+ } else if (contentType.startsWith("text/") || contentType.equalsIgnoreCase("application/xml-dtd") || contentType.equalsIgnoreCase("application/json")) {
resIts[resIts.length - 1] = new TokenIterator(context,
new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(3), result
.toString(), curNsScope), loc, false);
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java 2011-12-21 06:34:33 UTC (rev 4509)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java 2011-12-22 11:00:23 UTC (rev 4510)
@@ -69,14 +69,15 @@
if (tokens.size() > 0) // If not standalone
tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "object", TYPE_QN, curNsScope));
JSONArray names = jo.names();
- for (int i=0;i<names.length();i++) {
+ if (names != null)
+ for (int i=0;i<names.length();i++) {
String nm = (String)names.get(i);
tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "pair"), PAIR_QN, curNsScope));
- tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, nm, NAME_QN, curNsScope));
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, nm, NAME_QN, curNsScope));
Object no = jo.get(nm);
handleJSONItem(no);
tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.END_TAG, "pair"), PAIR_QN, curNsScope));
- }
+ }
return;
}
if (obj instanceof JSONArray) {
@@ -105,6 +106,14 @@
tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), it.toString(), curNsScope));
return;
}
+ if (obj instanceof Long) {
+ Long it = (Long)obj;
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "number", TYPE_QN, curNsScope));
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), it.toString(), curNsScope));
+ return;
+ }
+
if (obj instanceof Double) {
Double db = (Double)obj;
if (tokens.size() > 0) // If not standalone
@@ -129,8 +138,7 @@
protected XDMIterator copy(Context context, XDMIterator[] subIters,
Vector nestedPredCtxStack) throws MXQueryException {
- // TODO Auto-generated method stub
- return null;
+ return new JSONAdapter(context, getLoc(), this.jsonString, this.jsonML);
}
}
Copied: trunk/MXQuery/xqib_src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java (from rev 4509, trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java)
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java (rev 0)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/xdmio/xmlAdapters/JSONAdapter.java 2011-12-22 11:00:23 UTC (rev 4510)
@@ -0,0 +1,134 @@
+package ch.ethz.mxquery.xdmio.xmlAdapters;
+
+import com.google.gwt.json.client.*;
+
+import java.util.Vector;
+
+import com.google.gwt.json.client.JSONParser;
+
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.MXQueryDouble;
+import ch.ethz.mxquery.datamodel.QName;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.xdm.ElementToken;
+import ch.ethz.mxquery.datamodel.xdm.TextToken;
+import ch.ethz.mxquery.datamodel.xdm.Token;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.DynamicException;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.exceptions.QueryLocation;
+import ch.ethz.mxquery.model.XDMIterator;
+import ch.ethz.mxquery.xdmio.xmlAdapters.JSONAdapter;
+
+public class JSONAdapter extends XDMImportAdapter {
+ public static final String JSON_URI="http://www.zorba-xquery.com/modules/converters/json";
+ private static final QName JSON_QN = new QName(null,null,"json");
+ private static final QName TYPE_QN = new QName(null,null,"type");
+ private static final QName PAIR_QN = new QName(null,null,"pair");
+ private static final QName NAME_QN = new QName(null,null,"name");
+ private static final QName ITEM_QN = new QName(null,null,"item");
+ Vector tokens;
+ String jsonString;
+ boolean jsonML;
+
+ public JSONAdapter(Context ctx, QueryLocation loc, String jsonString, boolean useJSONML) {
+ super(ctx, loc);
+ this.jsonString = jsonString;
+ tokens = new Vector();
+ jsonML = useJSONML;
+ }
+
+ public TokenInterface next() throws MXQueryException {
+ if (called == 0) {
+ init();
+ }
+ if (called < tokens.size()) {
+ called++;
+ return (TokenInterface)tokens.elementAt(called-1);
+ }
+ return Token.END_SEQUENCE_TOKEN;
+ }
+
+ private void init() throws MXQueryException {
+ try {
+ JSONValue jo = JSONParser.parseStrict(jsonString);
+ tokens.addElement(new Token(Type.START_DOCUMENT, createNextTokenId(Type.START_DOCUMENT,null),curNsScope));
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "json"), JSON_QN, curNsScope));
+ //tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "unknown", TYPE_QN, curNsScope));
+ handleJSONItem(jo);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.START_TAG, "json"), JSON_QN, curNsScope));
+ tokens.addElement(new Token(Type.END_DOCUMENT, createNextTokenId(Type.END_DOCUMENT,null),curNsScope));
+ } catch (JSONException je) {
+ throw new DynamicException(new QName(JSON_URI,"json","ParseError"), je.toString(), loc);
+ }
+ }
+
+ void handleJSONItem (JSONValue obj) throws JSONException, MXQueryException {
+ if (obj.isObject() != null) {
+ JSONObject jo = obj.isObject();
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "object", TYPE_QN, curNsScope));
+ java.util.Set<java.lang.String> nameSet = jo.keySet();
+ java.util.Iterator<java.lang.String> names = nameSet.iterator();
+ while (names.hasNext()) {
+ String nm = names.next();
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "pair"), PAIR_QN, curNsScope));
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, nm, NAME_QN, curNsScope));
+ JSONValue no = jo.get(nm);
+ handleJSONItem(no);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.END_TAG, "pair"), PAIR_QN, curNsScope));
+ }
+ return;
+ }
+ if (obj.isArray() != null) {
+ JSONArray ja = obj.isArray();
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "array", TYPE_QN, curNsScope));
+ for (int i=0;i<ja.size();i++) {
+ tokens.addElement(new ElementToken(Type.START_TAG, createNextTokenId(Type.START_TAG, "item"), ITEM_QN, curNsScope));
+ JSONValue o = ja.get(i);
+ handleJSONItem(o);
+ tokens.addElement(new ElementToken(Type.END_TAG, createNextTokenId(Type.START_TAG, "item"), ITEM_QN, curNsScope));
+ }
+ return;
+ }
+ if (obj.isString() != null) {
+ JSONString str = obj.isString();
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "string", TYPE_QN, curNsScope));
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), str.stringValue(), curNsScope));
+ return;
+ }
+ if (obj.isNumber() != null) {
+ JSONNumber nm = obj.isNumber();
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "number", TYPE_QN, curNsScope));
+ MXQueryDouble db = new MXQueryDouble(nm.doubleValue());
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), db.toString(), curNsScope));
+ return;
+ }
+
+ if (obj.isBoolean() != null) {
+ JSONBoolean bo = obj.isBoolean();
+ if (tokens.size() > 0) // If not standalone
+ tokens.addElement(createAttributeToken(Type.UNTYPED_ATOMIC, "boolean", TYPE_QN, curNsScope));
+ String boolVal = "false";
+ if (bo.booleanValue())
+ boolVal = "true";
+ tokens.add(new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), boolVal, curNsScope));
+ return;
+ }
+ if (obj.isNull() != null) {
+ return;
+ }
+ throw new DynamicException(new QName(JSON_URI,"json","ParseError"),"Not implemented Type",loc);
+ }
+
+
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters,
+ Vector nestedPredCtxStack) throws MXQueryException {
+ return new JSONAdapter(context, getLoc(), this.jsonString, this.jsonML);
+ }
+
+}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pm_...@us...> - 2012-03-02 10:01:38
|
Revision: 4532
http://mxquery.svn.sourceforge.net/mxquery/?rev=4532&view=rev
Author: pm_fischer
Date: 2012-03-02 10:01:31 +0000 (Fri, 02 Mar 2012)
Log Message:
-----------
- moved readString method from Utils to PlatformDependentUtils, as InputStream is not available on GWT
- unified Utils.java for all platforms, brought encoding fix to XQIB
Modified Paths:
--------------
trunk/MXQuery/altsrc/ch/ethz/mxquery/util/PlatformDependentUtils.java
trunk/MXQuery/midp_src/ch/ethz/mxquery/util/PlatformDependentUtils.java
trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/LinguisticTokenGenerator.java
trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/WordNetRemoteThesaurus.java
trunk/MXQuery/src/ch/ethz/mxquery/util/PlatformDependentUtils.java
trunk/MXQuery/src/ch/ethz/mxquery/util/Utils.java
Removed Paths:
-------------
trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/Utils.java
Modified: trunk/MXQuery/altsrc/ch/ethz/mxquery/util/PlatformDependentUtils.java
===================================================================
--- trunk/MXQuery/altsrc/ch/ethz/mxquery/util/PlatformDependentUtils.java 2012-02-08 17:17:09 UTC (rev 4531)
+++ trunk/MXQuery/altsrc/ch/ethz/mxquery/util/PlatformDependentUtils.java 2012-03-02 10:01:31 UTC (rev 4532)
@@ -16,6 +16,8 @@
package ch.ethz.mxquery.util;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import ch.ethz.mxquery.util.PrintStream;
import java.io.UnsupportedEncodingException;
@@ -142,5 +144,22 @@
return new MXQueryDateTime(cal,
tz.getRawOffset() / (1000 * 60), MXQueryDateTime.VALUE_TYPE_DATE_TIME);
}
+
+ public static String readString(InputStream is) {
+ String text;
+ // Extract data in 256 byte chunks.
+ try {
+ byte[] data = new byte[256];
+ int len = 0;
+ StringBuffer raw = new StringBuffer();
+ while ( -1 != (len = is.read(data)) ) {
+ raw.append(new String(data, 0, len));
+ }
+ text = raw.toString();
+ } catch (IOException ex) {
+ text = ex.toString();
+ };
+ return text;
+ }
}
Modified: trunk/MXQuery/midp_src/ch/ethz/mxquery/util/PlatformDependentUtils.java
===================================================================
--- trunk/MXQuery/midp_src/ch/ethz/mxquery/util/PlatformDependentUtils.java 2012-02-08 17:17:09 UTC (rev 4531)
+++ trunk/MXQuery/midp_src/ch/ethz/mxquery/util/PlatformDependentUtils.java 2012-03-02 10:01:31 UTC (rev 4532)
@@ -16,6 +16,8 @@
package ch.ethz.mxquery.util;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import ch.ethz.mxquery.util.PrintStream;
import java.io.UnsupportedEncodingException;
@@ -113,5 +115,22 @@
return new MXQueryDateTime(cal,
tz.getRawOffset() / (1000 * 60), MXQueryDateTime.VALUE_TYPE_DATE_TIME);
}
-
+
+ public static String readString(InputStream is) {
+ String text;
+ // Extract data in 256 byte chunks.
+ try {
+ byte[] data = new byte[256];
+ int len = 0;
+ StringBuffer raw = new StringBuffer();
+ while ( -1 != (len = is.read(data)) ) {
+ raw.append(new String(data, 0, len));
+ }
+ text = raw.toString();
+ } catch (IOException ex) {
+ text = ex.toString();
+ };
+ return text;
+ }
+
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/LinguisticTokenGenerator.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/LinguisticTokenGenerator.java 2012-02-08 17:17:09 UTC (rev 4531)
+++ trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/LinguisticTokenGenerator.java 2012-03-02 10:01:31 UTC (rev 4532)
@@ -24,6 +24,7 @@
import ch.ethz.mxquery.datamodel.xdm.TextToken;
import ch.ethz.mxquery.exceptions.ErrorCodes;
import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.util.PlatformDependentUtils;
import ch.ethz.mxquery.util.Utils;
/**
@@ -302,7 +303,7 @@
abbrevTrie = new TrieNode();
try{
InputStream is = this.getClass().getResourceAsStream("abbreviations.txt");
- String strLine = Utils.readString(is);
+ String strLine = PlatformDependentUtils.readString(is);
String [] words = Utils.split(strLine, "\n", false);
for (int j=0;j<words.length;j++) {
String currentWord = words[j].trim();
Modified: trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/WordNetRemoteThesaurus.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/WordNetRemoteThesaurus.java 2012-02-08 17:17:09 UTC (rev 4531)
+++ trunk/MXQuery/src/ch/ethz/mxquery/sms/ftstore/WordNetRemoteThesaurus.java 2012-03-02 10:01:31 UTC (rev 4532)
@@ -24,6 +24,7 @@
import ch.ethz.mxquery.exceptions.QueryLocation;
import ch.ethz.mxquery.model.ft.Range;
import ch.ethz.mxquery.model.ws.SoapInvoker;
+import ch.ethz.mxquery.util.PlatformDependentUtils;
import ch.ethz.mxquery.util.Utils;
/**
@@ -97,7 +98,7 @@
posTrie = new TrieNode();
InputStream is = this.getClass().getResourceAsStream("pos.txt");
- String strLine = Utils.readString(is);
+ String strLine = PlatformDependentUtils.readString(is);
String[] triple = Utils.split(strLine, "\n", false);
for (int j = 0; j < triple.length; j++) {
String t = triple[j].trim();
Modified: trunk/MXQuery/src/ch/ethz/mxquery/util/PlatformDependentUtils.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/util/PlatformDependentUtils.java 2012-02-08 17:17:09 UTC (rev 4531)
+++ trunk/MXQuery/src/ch/ethz/mxquery/util/PlatformDependentUtils.java 2012-03-02 10:01:31 UTC (rev 4532)
@@ -16,6 +16,8 @@
package ch.ethz.mxquery.util;
import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
import java.io.OutputStream;
import ch.ethz.mxquery.util.PrintStream;
import java.io.UnsupportedEncodingException;
@@ -140,5 +142,23 @@
return new MXQueryDateTime(cal,
tz.getRawOffset() / (1000 * 60), MXQueryDateTime.VALUE_TYPE_DATE_TIME);
- }
+ }
+
+ public static String readString(InputStream is) {
+ String text;
+ // Extract data in 256 byte chunks.
+ try {
+ byte[] data = new byte[256];
+ int len = 0;
+ StringBuffer raw = new StringBuffer();
+ while ( -1 != (len = is.read(data)) ) {
+ raw.append(new String(data, 0, len));
+ }
+ text = raw.toString();
+ } catch (IOException ex) {
+ text = ex.toString();
+ };
+ return text;
+ }
+
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/util/Utils.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/util/Utils.java 2012-02-08 17:17:09 UTC (rev 4531)
+++ trunk/MXQuery/src/ch/ethz/mxquery/util/Utils.java 2012-03-02 10:01:31 UTC (rev 4532)
@@ -63,24 +63,7 @@
return strs;
}
-
- public static String readString(InputStream is) {
- String text;
- // Extract data in 256 byte chunks.
- try {
- byte[] data = new byte[256];
- int len = 0;
- StringBuffer raw = new StringBuffer();
- while ( -1 != (len = is.read(data)) ) {
- raw.append(new String(data, 0, len));
- }
- text = raw.toString();
- } catch (IOException ex) {
- text = ex.toString();
- };
- return text;
- }
-
+
/**
* Splits a string into an array of Strings
* @param source The source string
Deleted: trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/Utils.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/Utils.java 2012-02-08 17:17:09 UTC (rev 4531)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/util/Utils.java 2012-03-02 10:01:31 UTC (rev 4532)
@@ -1,524 +0,0 @@
-/* Copyright 2006 - 2009 ETH Zurich
- *
- * Licensed 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.
- */
-
-package ch.ethz.mxquery.util;
-
-import java.io.IOException;
-//import java.io.InputStream;
-import java.util.Vector;
-
-import ch.ethz.mxquery.sms.ftstore.DiacriticsUtils;
-
-
-public final class Utils {
-
- /**
- *
- * @param name - full class name
- * @return - class name without package name
- */
- public static String getSimpleClassName(String name) {
- int lastDot = name.lastIndexOf('.') + 1;
- return name.substring(lastDot);
- }
-
- /**
- * Splits a string into an array of Strings
- * @param source The source string
- * @param delimeter The delimeter String, that seperates the parts of the sequence
- * @param createEmptySegments TODO
- * @return An array of all elements of the splitted sequence
- */
- public static String[] split(String source, String delimeter, boolean createEmptySegments) {
- int next = 0;
- Vector parts = new Vector();
-
- while ((next = source.indexOf(delimeter)) > -1) {
- if (source.substring(0, next).length() > 0 || createEmptySegments) {
- parts.addElement(source.substring(0, next));
- }
-
- source = source.substring(next+delimeter.length());
- }
-
- if (source.length() > 0) {
- parts.addElement(source);
- }
-
- String[] strs = new String[parts.size()];
- parts.copyInto(strs);
-
- return strs;
- }
-
-
-// public static String readString(InputStream is) {
-// String text;
-// // Extract data in 256 byte chunks.
-// try {
-// byte[] data = new byte[256];
-// int len = 0;
-// StringBuffer raw = new StringBuffer();
-// while ( -1 != (len = is.read(data)) ) {
-// raw.append(new String(data, 0, len));
-// }
-// text = raw.toString();
-// } catch (IOException ex) {
-// text = ex.toString();
-// };
-// return text;
-// }
-
- /**
- * Splits a string into an array of Strings
- * @param source The source string
- * @param delimiters The delimiters, that seperate the parts of the sequence
- * @return An array of all elements of the splitted sequence
- */
-
- public static String[] split(String source, String[] delimiters){
-
- int begin = 0;
- Vector parts = new Vector();
- String newElement = "";
- boolean delimitersFound = false;
-
- for (int i= 0; i < source.length(); i++){
-
- for (int j = 0; j < delimiters.length;j++){
- if (source.charAt(i)== delimiters[j].toCharArray()[0]){
-
- delimitersFound = true;
-
- if (source.substring(begin,i).length() > 0) {
-
- if (begin != 0){
-
- newElement = source.substring(begin+1,i);
- if (newElement.trim().length() > 0){
- parts.addElement(newElement);
- }
-
- }
- else{
- newElement = source.substring(begin,i);
- if (newElement.length() > 0){
- parts.addElement(newElement);
- }
- }
- begin = i;
-
- }
- else{
- begin = i+1;
- }
- }
-
- }
-
- }
-
- if (delimitersFound){
- if (source.length() > 0) {
- parts.addElement(source.substring(begin+1));
- }
- }
- else{
- parts.addElement(source.substring(begin));
- }
-
-
- String[] strs = new String[parts.size()];
- parts.copyInto(strs);
- return strs;
-
- }
-
- public static String replaceAll(String original, String oldExpr, String replacement) {
- String ret = "";
- int pos = 0, index;
- while ((index = original.indexOf(oldExpr)) >= 0) {
- ret += original.substring(pos, index);
- ret += replacement;
- original = original.substring(index + 1);
- }
- ret += original;
- return ret;
- }
-
- public static String expandCharRefs(String res) {
- StringBuffer normTarget = new StringBuffer(res.length());
- int origPos = 0;
- while (origPos < res.length()) {
- if (res.charAt(origPos) == '&' && origPos+3 < res.length() && res.charAt(origPos+1)=='#') {
- // translate remaining WS char refs in order to prevent them from being "eaten"
- int endCharRef = res.indexOf(';', origPos);
- if (endCharRef > 0 && endCharRef < origPos + 10) {
- String toTranslate = res.substring(origPos+2,endCharRef);
- int codePoint = -1;
- if (toTranslate.indexOf('x') >=0) {
- // Hex digits
- String charRef = toTranslate.substring(1);
- if (charRef.length() != 0)
- codePoint = Integer.parseInt(charRef, 16);
- } else { //Decimal digits
- String charRef = toTranslate;
- if (charRef.length() != 0)
- codePoint = Integer.parseInt(charRef,10);
- }
- if (codePoint >= 0) {
- normTarget.append(PlatformDependentUtils.codepointToChars(codePoint));
- origPos = endCharRef+1;
- } else {
- normTarget.append(res.charAt(origPos));
- origPos++;
- }
- }
- } else {
- normTarget.append(res.charAt(origPos));
- origPos++;
- }
- }
- return normTarget.toString();
- }
-
- public static String normalizeEOL (String res, boolean useXML11Rules){
- StringBuffer normTarget = new StringBuffer(res.length());
- int origPos = 0;
- while (origPos < res.length()) {
- if (res.charAt(origPos) == '\r') {
- if (origPos+1<res.length() && res.charAt(origPos+1) == '\n') {
- origPos++; // skip
- }
- if (res.length() !=1)
- normTarget.append('\n');
- else
- normTarget.append('\r'); //\r constant
- }
- else
- normTarget.append(res.charAt(origPos));
- origPos++;
- }
- return new String(normTarget);
- }
-
- /**
- * Implementation of normalization in attributes and element content - remove whitespace at beginning and end + reduce whitespace in the middle to one, but only translate xD,x9 etc.
- * @param res String to be normalized
- * @return the normalized String
- */
- public static String normalizeStringContent (String res, boolean isIdAttr) {
- StringBuffer normTarget = new StringBuffer(res.length());
- int origPos = 0;
- // eat all whitespace at the beginning
- while (origPos < res.length() && isWhiteSpace(res.charAt(origPos))){
- if (!isIdAttr)
- normTarget.append(' ');
- origPos++;
- }
- if (origPos == res.length() && res.length() != 0) {
- return normTarget.toString();
- }
- while(origPos < res.length()) {
- // append non-whitespace characters
- while (origPos < res.length() && !isWhiteSpace(res.charAt(origPos))) {
- if (res.charAt(origPos) == '&' && origPos+3 < res.length() && res.charAt(origPos+1)=='#') {
- // translate remaining WS char refs in order to prevent them from being "eaten"
- int endCharRef = res.indexOf(';', origPos);
- if (endCharRef > 0 && endCharRef < origPos + 10) {
- String toTranslate = res.substring(origPos+2,endCharRef);
- int codePoint = -1;
- if (toTranslate.indexOf('x') >=0) {
- // Hex digits
- String charRef = toTranslate.substring(1);
- if (charRef.length() != 0)
- codePoint = Integer.parseInt(charRef, 16);
- } else { //Decimal digits
- String charRef = toTranslate;
- if (charRef.length() != 0)
- codePoint = Integer.parseInt(charRef,10);
- }
- if (codePoint >= 0) {
- normTarget.append(PlatformDependentUtils.codepointToChars(codePoint));
- origPos = endCharRef+1;
- } else {
- normTarget.append(res.charAt(origPos));
- origPos++;
- }
- }
- } else {
- normTarget.append(res.charAt(origPos));
- origPos++;
- }
- }
- // skip whitespaces
- while (origPos < res.length() && isWhiteSpace(res.charAt(origPos))) {
- normTarget.append(' ');
- origPos++;
- }
- // append a single whitespace if not at end
-// if (origPos < res.length())
-// normTarget.append(' ');
- }
- return normTarget.toString();
- }
-
- /**
- * Implementation of F&O normalize-string function - remove whitespace at beginning and end + reduce whitespace in the middle to one
- * @param res String to be normalized
- * @return the normalized string
- */
- public static String normalizeString (String res) {
- StringBuffer normTarget = new StringBuffer(res.length());
- int origPos = 0;
- // eat all whitespace at the beginning
- while (origPos < res.length() && isWhiteSpace(res.charAt(origPos))){
- origPos++;
- }
- while(origPos < res.length()) {
- // append non-whitespace characters
- while (origPos < res.length() && !isWhiteSpace(res.charAt(origPos))) {
- normTarget.append(res.charAt(origPos));
- origPos++;
- }
- // skip whitespaces
- while (origPos < res.length() && isWhiteSpace(res.charAt(origPos))) {
- origPos++;
- }
- // append a single whitespace if not at end
- if (origPos < res.length())
- normTarget.append(' ');
- }
- return normTarget.toString();
- }
-
- public static boolean isWhiteSpace(char cToCheck) {
- if (cToCheck == ' '|| cToCheck == '\r' || cToCheck == '\n' || cToCheck == '\t') {
- return true;
- }
- return false;
- }
-
-
- public final static boolean isLetter (char ch) {
- if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
- return true;
- return false;
- }
-
- public static boolean isLowerCase(String text){
- for (int i=0; i < text.length(); i++){
- int c = text.charAt(i);
- if (!isLowerCaseLetter(c)){
- return false;
- }
- }
- return true;
- }
-
- public static boolean isUpperCase(String text){
- for (int i=0; i < text.length(); i++){
- int c = text.charAt(i);
- if (!isUpperCaseLetter(c)){
- return false;
- }
- }
- return true;
- }
-
- public static boolean isLowerCaseLetter(int chr) {
- if ((chr <= 122 && 97 <= chr) || DiacriticsUtils.isLowerCaseDiacritics(chr))
- return true;
- return false;
- }
-
-
- public static boolean isUpperCaseLetter(int chr) {
- if ((chr <= 90 && 65 <= chr) || DiacriticsUtils.isUpperCaseDiacritics(chr))
- return true;
- return false;
- }
-
- public static boolean sameCase(String text, String text2){
-
- for (int i=0; i < text.length(); i++){
- int c = text.charAt(i);
- int c2 = text2.charAt(i);
- if (!((isUpperCaseLetter(c)) && (isUpperCaseLetter(c2)) || (c <= 122 && 97 <= c) && (c2 <= 122 && 97 <= c2))){
- return false;
- }
- }
-
- return true;
- }
-
-
- private static String hex(int c) {
- return Integer.toHexString(c);
- }
-
- public static String stripLeadingWhitespace(String val) {
- int wsPos = 0;
- while (wsPos < val.length() && isWhiteSpace(val.charAt(wsPos))) {
- wsPos++;
- }
- if (wsPos < val.length())
- return val.substring(wsPos);
- return val;
- }
-
- /** For character encoding in URL/URI/IRI */
-
- public static String getEncodedCharacter(char c) {
- StringBuffer result = new StringBuffer();
- if (c < 128) {
- result.append("%");
- result.append(hex(c));
- } else if (c > 127 && c < 2048) {
- result.append("%");
- result.append(hex((c >> 6) | 0xC0));
-
- result.append("%");
- result.append(hex((c & 0x3F) | 0x80));
- } else if (c > 2047 && c < 65536) {
- result.append("%");
- result.append(hex((c >> 12) | 0xE0));
-
- result.append("%");
- result.append(hex(((c >> 6) & 0x3F) | 0x80));
-
- result.append("%");
- result.append(hex((c & 0x3F) | 0x80));
- } else if (c > 65535) {
- result.append("%");
- result.append(hex((c >> 18) | 0xF0));
-
- result.append("%");
- result.append(hex(((c >> 12) & 0x3F) | 0x80));
-
- result.append("%");
- result.append(hex(((c >> 6) & 0x3F) | 0x80));
-
- result.append("%");
- result.append(hex((c & 0x3F) | 0x80));
- }
-
- return result.toString().toUpperCase();
- }
-
- /**
- * This method is for helping to retain the order of comparators and compareTypes
- * @param i1
- * @param i2
- * @return the order relationship: 0 equals, -1 if i1<i2, -1 if i1>i2
- */
- public static int compareComparator(int i1, int i2){
- if(i1 == i2){
- return 0;
- }else if (i1 < i2){
- return -1;
- }else{
- return 1;
- }
- }
-
- /**
- * Get the cartesian product of values
- * @param combinations Helper Vector, usually empty at top-level invocation
- * @param cur Helper Vector, usually empty at top-level invocation
- * @param vectors Items that should be combined
- * @param len Length of items to look at
- * @return the certesian product of vectors with length of len
- */
- public static Vector getCombinations(Vector combinations, Vector cur, Vector vectors, int len) {
- if (len == vectors.size()){
- Vector newVector = new Vector();
- for (int i=0; i < cur.size(); i++){
- newVector.addElement(cur.elementAt(i));
- }
-
- combinations.addElement(newVector);
- }
- else{
- Vector vector = (Vector)vectors.elementAt(len);
- if (vector.size() > 0)
- for (int i=0; i < vector.size(); i++){
- cur.addElement(vector.elementAt(i));
- len = len+1;
- getCombinations(combinations, cur, vectors, len);
- len = len -1;
- cur.removeElement(vector.elementAt(i));
- } else {
- len = len+1;
- getCombinations(combinations, cur, vectors, len);
- len = len -1;
- }
-
- }
- return combinations;
- }
-
- /**
- * Add the contents of one vector to the second - needed for CLDC
- * @param from
- * @param to
- * @return the content of the contents of both vectors: first the content of to, then from
- */
- // add elements of vector to another vector
- public static Vector addToVector(Vector from, Vector to){
-
- for (int i=0; i < from.size(); i++){
- to.addElement(from.elementAt(i));
- }
-
- return to;
- }
- /**
- * Add the contents of an array to a Vector - needed for CLDC
- * @param from
- * @param to
- * @return the content of the contents of both vectors: first the content of to, then from
- */
- public static Vector addArrayToVector(Object[] from, Vector to){
- if (from != null)
- for (int i=0; i < from.length; i++){
- to.addElement(from[i]);
- }
-
- return to;
- }
-
- public static Object [] dumpVectorToArray(Vector vec) {
- Object [] ret = new Object[vec.size()];
- for (int i=0;i<ret.length;i++) {
- ret[i] = vec.elementAt(i);
- }
- return ret;
- }
-
-
-
- /** for testing purposes */
- /*public static void main(String[] args){
- String test = "this";
- String[] delimiters = {",", "(", ")", ";", ".", "!","?", "{", "}","\"", "[", "]", "|", "#", "%", "&", "/", " "};
- String[] result = split(test,delimiters);
-
- for (int j=0; j < result.length; j++){
- System.out.println(result[j]);
- }
-
- }*/
-}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pm_...@us...> - 2012-03-12 07:31:55
|
Revision: 4534
http://mxquery.svn.sourceforge.net/mxquery/?rev=4534&view=rev
Author: pm_fischer
Date: 2012-03-12 07:31:44 +0000 (Mon, 12 Mar 2012)
Log Message:
-----------
- push duplicate elimination of projection paths into
PreparedStatementImpl
Modified Paths:
--------------
trunk/MXQuery/midp_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java
trunk/MXQuery/src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java
Modified: trunk/MXQuery/midp_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java
===================================================================
--- trunk/MXQuery/midp_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java 2012-03-12 06:39:25 UTC (rev 4533)
+++ trunk/MXQuery/midp_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java 2012-03-12 07:31:44 UTC (rev 4534)
@@ -19,6 +19,7 @@
import java.util.Enumeration;
import ch.ethz.mxquery.util.Hashtable;
import ch.ethz.mxquery.util.ObjectObjectPair;
+import ch.ethz.mxquery.util.Set;
import java.util.Vector;
@@ -28,6 +29,8 @@
import ch.ethz.mxquery.exceptions.StaticException;
import ch.ethz.mxquery.iterators.TokenIterator;
import ch.ethz.mxquery.datamodel.QName;
+import ch.ethz.mxquery.datamodel.XQName;
+import ch.ethz.mxquery.model.AbstractStep;
import ch.ethz.mxquery.model.XDMIterator;
import ch.ethz.mxquery.model.Window;
import ch.ethz.mxquery.model.VariableHolder;
@@ -176,12 +179,66 @@
public Hashtable getProjectionPaths() throws StaticException {
//Preliminary implementation, producing just a single doc
+ // Eliminate duplicate paths
+ Set distPaths = new Set();
+
ObjectObjectPair paths = iter.getProjectionPaths();
+ Set returned = (Set) paths.getFirst();
+ Set used = (Set) paths.getSecond();
+
+ Set distReturned = new Set();
+ Enumeration en = returned.elements();
+
+ while (en.hasMoreElements()) {
+ Vector curPath = (Vector) en.nextElement();
+ String curPathSum = translateProjectionPath(curPath)+" #";
+ if (!distPaths.contains(curPathSum)) {
+ distPaths.add(curPathSum);
+ distReturned.add(curPath);
+ }
+ }
+
+ Set distUsed = new Set();
+
+ en = used.elements();
+ while (en.hasMoreElements()) {
+ Vector curPath = (Vector) en.nextElement();
+ String curPathSum = translateProjectionPath(curPath);
+ if (!distPaths.contains(curPathSum)) {
+ distPaths.add(curPathSum);
+ distUsed.add(curPath);
+ }
+ }
+
+
Hashtable ht = new Hashtable();
- ht.put("DOC", paths);
+ ht.put("DOC", new ObjectObjectPair(distReturned, distUsed));
return ht;
}
+ private String translateProjectionPath(Vector curPath) throws StaticException {
+ StringBuffer pathString = new StringBuffer();
+ for (int i=0;i<curPath.size();i++) {
+ AbstractStep as = (AbstractStep)curPath.elementAt(i);
+ if (as == AbstractStep.ROOT_STEP)
+ pathString.append("/");
+ else if (as == AbstractStep.KEEP_SUBTREE)
+ pathString.append(" #");
+ else
+ {
+ pathString.append(as.getDirectionString(true));
+ XQName xq = as.getNodeTest().getXQName();
+ if (xq != null)
+ // TODO: What about namespace URIs?
+ pathString.append(xq.toString());
+ else throw new StaticException(ErrorCodes.A0002_EC_NOT_SUPPORTED,"Unsupported node test for projection - please report",QueryLocation.OUTSIDE_QUERY_LOC);
+ if (i<curPath.size()-2 || ( (AbstractStep)curPath.elementAt(curPath.size()-1) != AbstractStep.KEEP_SUBTREE && i<curPath.size()-1) )
+ pathString.append("/");
+ }
+ }
+ return pathString.toString();
+ };
+
public void setProjectionInformation(QName varname,
ObjectObjectPair paths) throws StaticException {
VariableHolder vh = ctx.getVariable(varname);
Modified: trunk/MXQuery/src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java 2012-03-12 06:39:25 UTC (rev 4533)
+++ trunk/MXQuery/src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java 2012-03-12 07:31:44 UTC (rev 4534)
@@ -18,6 +18,7 @@
import ch.ethz.mxquery.util.Hashtable;
import ch.ethz.mxquery.util.ObjectObjectPair;
+import ch.ethz.mxquery.util.Set;
import java.util.Vector;
@@ -32,6 +33,7 @@
import ch.ethz.mxquery.exceptions.MXQueryException;
import ch.ethz.mxquery.exceptions.QueryLocation;
import ch.ethz.mxquery.exceptions.StaticException;
+import ch.ethz.mxquery.model.AbstractStep;
import ch.ethz.mxquery.model.VariableHolder;
import ch.ethz.mxquery.model.XDMIterator;
import ch.ethz.mxquery.query.PreparedStatement;
@@ -185,16 +187,70 @@
public Hashtable getProjectionPaths() throws StaticException {
//Preliminary implementation, producing just a single doc
+ // Eliminate duplicate paths
+ Set distPaths = new Set();
+
ObjectObjectPair paths = iter.getProjectionPaths();
+ Set returned = (Set) paths.getFirst();
+ Set used = (Set) paths.getSecond();
+
+ Set distReturned = new Set();
+ Enumeration en = returned.elements();
+
+ while (en.hasMoreElements()) {
+ Vector curPath = (Vector) en.nextElement();
+ String curPathSum = translateProjectionPath(curPath)+" #";
+ if (!distPaths.contains(curPathSum)) {
+ distPaths.add(curPathSum);
+ distReturned.add(curPath);
+ }
+ }
+
+ Set distUsed = new Set();
+
+ en = used.elements();
+ while (en.hasMoreElements()) {
+ Vector curPath = (Vector) en.nextElement();
+ String curPathSum = translateProjectionPath(curPath);
+ if (!distPaths.contains(curPathSum)) {
+ distPaths.add(curPathSum);
+ distUsed.add(curPath);
+ }
+ }
+
+
Hashtable ht = new Hashtable();
- ht.put("DOC", paths);
+ ht.put("DOC", new ObjectObjectPair(distReturned, distUsed));
return ht;
}
+ private String translateProjectionPath(Vector curPath) throws StaticException {
+ StringBuffer pathString = new StringBuffer();
+ for (int i=0;i<curPath.size();i++) {
+ AbstractStep as = (AbstractStep)curPath.elementAt(i);
+ if (as == AbstractStep.ROOT_STEP)
+ pathString.append("/");
+ else if (as == AbstractStep.KEEP_SUBTREE)
+ pathString.append(" #");
+ else
+ {
+ pathString.append(as.getDirectionString(true));
+ XQName xq = as.getNodeTest().getXQName();
+ if (xq != null)
+ // TODO: What about namespace URIs?
+ pathString.append(xq.toString());
+ else throw new StaticException(ErrorCodes.A0002_EC_NOT_SUPPORTED,"Unsupported node test for projection - please report",QueryLocation.OUTSIDE_QUERY_LOC);
+ if (i<curPath.size()-2 || ( (AbstractStep)curPath.elementAt(curPath.size()-1) != AbstractStep.KEEP_SUBTREE && i<curPath.size()-1) )
+ pathString.append("/");
+ }
+ }
+ return pathString.toString();
+ };
+
public void setProjectionInformation(QName varname,
ObjectObjectPair paths) throws StaticException {
VariableHolder vh = ctx.getVariable(varname);
vh.setProjectionPaths(paths);
}
-
+
}
Modified: trunk/MXQuery/xqib_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java
===================================================================
--- trunk/MXQuery/xqib_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java 2012-03-12 06:39:25 UTC (rev 4533)
+++ trunk/MXQuery/xqib_src/ch/ethz/mxquery/query/impl/PreparedStatementImpl.java 2012-03-12 07:31:44 UTC (rev 4534)
@@ -16,7 +16,9 @@
import ch.ethz.mxquery.util.Hashtable;
import ch.ethz.mxquery.util.ObjectObjectPair;
+import ch.ethz.mxquery.util.Set;
+import java.util.Enumeration;
import java.util.Vector;
import com.google.gwt.dom.client.Document;
@@ -33,6 +35,7 @@
import ch.ethz.mxquery.exceptions.MXQueryException;
import ch.ethz.mxquery.exceptions.QueryLocation;
import ch.ethz.mxquery.exceptions.StaticException;
+import ch.ethz.mxquery.model.AbstractStep;
import ch.ethz.mxquery.model.VariableHolder;
import ch.ethz.mxquery.model.XDMIterator;
import ch.ethz.mxquery.query.PreparedStatement;
@@ -180,12 +183,66 @@
}
public Hashtable getProjectionPaths() throws StaticException {
//Preliminary implementation, producing just a single doc
+ // Eliminate duplicate paths
+ Set distPaths = new Set();
+
ObjectObjectPair paths = iter.getProjectionPaths();
+ Set returned = (Set) paths.getFirst();
+ Set used = (Set) paths.getSecond();
+
+ Set distReturned = new Set();
+ Enumeration en = returned.elements();
+
+ while (en.hasMoreElements()) {
+ Vector curPath = (Vector) en.nextElement();
+ String curPathSum = translateProjectionPath(curPath)+" #";
+ if (!distPaths.contains(curPathSum)) {
+ distPaths.add(curPathSum);
+ distReturned.add(curPath);
+ }
+ }
+
+ Set distUsed = new Set();
+
+ en = used.elements();
+ while (en.hasMoreElements()) {
+ Vector curPath = (Vector) en.nextElement();
+ String curPathSum = translateProjectionPath(curPath);
+ if (!distPaths.contains(curPathSum)) {
+ distPaths.add(curPathSum);
+ distUsed.add(curPath);
+ }
+ }
+
+
Hashtable ht = new Hashtable();
- ht.put("DOC", paths);
+ ht.put("DOC", new ObjectObjectPair(distReturned, distUsed));
return ht;
- }
+ }
+ private String translateProjectionPath(Vector curPath) throws StaticException {
+ StringBuffer pathString = new StringBuffer();
+ for (int i=0;i<curPath.size();i++) {
+ AbstractStep as = (AbstractStep)curPath.elementAt(i);
+ if (as == AbstractStep.ROOT_STEP)
+ pathString.append("/");
+ else if (as == AbstractStep.KEEP_SUBTREE)
+ pathString.append(" #");
+ else
+ {
+ pathString.append(as.getDirectionString(true));
+ XQName xq = as.getNodeTest().getXQName();
+ if (xq != null)
+ // TODO: What about namespace URIs?
+ pathString.append(xq.toString());
+ else throw new StaticException(ErrorCodes.A0002_EC_NOT_SUPPORTED,"Unsupported node test for projection - please report",QueryLocation.OUTSIDE_QUERY_LOC);
+ if (i<curPath.size()-2 || ( (AbstractStep)curPath.elementAt(curPath.size()-1) != AbstractStep.KEEP_SUBTREE && i<curPath.size()-1) )
+ pathString.append("/");
+ }
+ }
+ return pathString.toString();
+ };
+
public void setProjectionInformation(QName varname,
ObjectObjectPair paths) throws StaticException {
VariableHolder vh = ctx.getVariable(varname);
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <pm_...@us...> - 2012-03-12 08:47:57
|
Revision: 4535
http://mxquery.svn.sourceforge.net/mxquery/?rev=4535&view=rev
Author: pm_fischer
Date: 2012-03-12 08:47:44 +0000 (Mon, 12 Mar 2012)
Log Message:
-----------
- more dataflow analysis for node id support
- switch node id generation to "on-demand" (as output by data flow
analysis)
- some performance optimizations on TokenBuffer and StaX parser wrapper
Modified Paths:
--------------
trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/Doc.java
trunk/MXQuery/src/ch/ethz/mxquery/contextConfig/Context.java
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java
trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java
trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java
trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Parse.java
trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Soap_call.java
trunk/MXQuery/src/ch/ethz/mxquery/iterators/ValidateIterator.java
trunk/MXQuery/src/ch/ethz/mxquery/iterators/scripting/WSFunction.java
trunk/MXQuery/src/ch/ethz/mxquery/sms/MMimpl/TokenBufferStore.java
trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/NonValidatingStaxAdapter.java
trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/XDMImportAdapter.java
trunk/MXQuery/xqib_src/ch/ethz/mxquery/functions/fn/Doc.java
Modified: trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/Doc.java
===================================================================
--- trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/Doc.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/android/src/ch/ethz/mxquery/functions/fn/Doc.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -52,6 +52,7 @@
private final int OPERATION_UNPARSED_LINES=3;
private boolean inValidateExpression = false;
private int operation = OPERATION_DOC;
+ private int requiredOptions = 0;
private String docURI = null;
private Reader rd = null; // keep around to close
@@ -139,10 +140,12 @@
// else
// cur = XDMInputFactory.createXMLInput(context, uri, true, context.getInputValidationMode(), loc);
((XMLSource)cur).setURI(uri);
+ cur = cur.require(requiredOptions);
break;
case OPERATION_TIDY:
cur = XDMInputFactory.createTidyInput(context, rd, loc);
((XMLSource)cur).setURI(uri);
+ cur = cur.require(requiredOptions);
break;
case OPERATION_UNPARSED:
StringBuffer sb = new StringBuffer();
@@ -201,6 +204,7 @@
copy.operation = operation;
copy.setConstModePreserve(this.constModePreserve);
copy.setSubIters(subIters);
+ copy.requiredOptions = requiredOptions;
return copy;
}
@@ -258,4 +262,10 @@
else
return null;
}
+
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
+
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/contextConfig/Context.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/contextConfig/Context.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/contextConfig/Context.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -186,7 +186,7 @@
public static final int NONVALIDATED_INPUT_MODE_DOM = 3;
public static final int NONVALIDATED_INPUT_MODE_SAX_TIDY = 4;
public static final int NONVALIDATED_INPUT_MODE_STAX_PROJECTION = 5;
-
+ //public static final int NONVALIDATED_INPUT_MODE_STAX_DUMMY = 6;
public static final int NO_VALIDATION = 0;
public static final int IGNORE_DTD = 1;
@@ -496,8 +496,10 @@
holder.setIter(st.getIterator(this));
}
}
- else
- holder.setIter(iter);
+ else {
+ iter = iter.require(holder.getRequiredOptions());
+ holder.setIter(iter);
+ }
}
/*
Modified: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/expathhttp/HttpIO.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -57,6 +57,7 @@
import ch.ethz.mxquery.iterators.SequenceTypeIterator;
import ch.ethz.mxquery.iterators.TokenIterator;
import ch.ethz.mxquery.model.CurrentBasedIterator;
+import ch.ethz.mxquery.model.DataflowAnalysis;
import ch.ethz.mxquery.model.Iterator;
import ch.ethz.mxquery.model.Wildcard;
import ch.ethz.mxquery.model.XDMIterator;
@@ -97,9 +98,10 @@
public final static QName EHC004_DYNAMIC_SRC_ATTR_INCOMPATIBLE = new QName(exPathErrorNS,"err","HC004");
public final static QName EHC005_DYNAMIC_INVALID_REQUEST_ELEM = new QName(exPathErrorNS,"err","HC005");
public final static QName EHC006_DYNAMIC_TIMEOUT = new QName(exPathErrorNS,"err","HC006");
- private boolean generateNodeIds = true;
+ private boolean generateNodeIds = false;
private static int nodeIdCount = 0;
Identifier last_identifier;
+ private int requiredOptions = 0;
private final static String uri = "http://www.mxquery.org/nodeconstruction";
static int docs = 0;
@@ -136,6 +138,7 @@
HttpIO copy = new HttpIO();
copy.setContext(context, true);
copy.setSubIters(subIters);
+ copy.requiredOptions = requiredOptions;
return copy;
}
@@ -157,6 +160,9 @@
private void init() throws MXQueryException {
+ if ((requiredOptions & DataflowAnalysis.NODEID_ORDER) != 0)
+ generateNodeIds = true;
+
Context childContext = new Context(context);
subIters[0].setResettable(true);
@@ -551,13 +557,16 @@
|| contentType.equalsIgnoreCase("application/xml")
|| contentType.equalsIgnoreCase("text/xml-external-parsed-entity")
|| contentType.equalsIgnoreCase("application/xml-external-parsed-entity")
- || contentType.indexOf("+xml") >= 0)
+ || contentType.indexOf("+xml") >= 0) {
resIts[resIts.length - 1] = XDMInputFactory.createXMLInput(
context, new StringReader(result.toString()), false,
context.getInputValidationMode(), loc);
+ resIts[resIts.length - 1].require(requiredOptions);
+ }
else if (contentType.indexOf("html") >= 0) {
resIts[resIts.length - 1] = XDMInputFactory.createTidyInput(
- context, new StringReader(result.toString()), loc);
+ context, new StringReader(result.toString()), loc);
+ resIts[resIts.length - 1].require(requiredOptions);
} else if (contentType.startsWith("text/") || contentType.equalsIgnoreCase("application/xml-dtd") || contentType.equalsIgnoreCase("application/json")) {
resIts[resIts.length - 1] = new TokenIterator(context,
new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(3), result
@@ -826,8 +835,11 @@
context.addNamespace(httpNS, httpURI);
return super.staticInit();
}
-
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/extensionsModules/zorbaRest/HttpIO.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -53,6 +53,7 @@
import ch.ethz.mxquery.functions.fn.EncodeForURI;
import ch.ethz.mxquery.iterators.TokenIterator;
import ch.ethz.mxquery.model.CurrentBasedIterator;
+import ch.ethz.mxquery.model.DataflowAnalysis;
import ch.ethz.mxquery.model.Iterator;
import ch.ethz.mxquery.model.TokenSequenceIterator;
import ch.ethz.mxquery.model.XDMIterator;
@@ -79,6 +80,7 @@
private boolean generateNodeIds = true;
private static int nodeIdCount = 0;
Identifier last_identifier;
+ private int requiredOptions = 0;
private final static String uri = "http://www.mxquery.org/nodeconstruction";
static int docs = 0;
@@ -127,6 +129,7 @@
if (request_type == REQUEST_TYPE_DELETE)
copy.setOperation("delete");
copy.tidy = tidy;
+ copy.requiredOptions = requiredOptions;
return copy;
}
@@ -147,6 +150,10 @@
XDMIterator[] resIts;
private void init() throws MXQueryException {
+
+ if ((requiredOptions & DataflowAnalysis.NODEID_ORDER) != 0)
+ generateNodeIds = true;
+
String url = getStringValue(subIters[0]);
if (request_type != REQUEST_TYPE_GET && url.indexOf('?') >= 0) {
throw new DynamicException(
@@ -563,13 +570,18 @@
if (contentType.equalsIgnoreCase("text/xml")
|| contentType.equalsIgnoreCase("application/xml")
|| contentType.indexOf("+xml") >= 0)
- if (tidy)
+ if (tidy) {
resIts[resIts.length - 4] = XDMInputFactory.createTidyInput(
context, new StringReader(result.toString()), loc);
- else
+ resIts[resIts.length - 4].require(requiredOptions);
+
+ }
+ else {
resIts[resIts.length - 4] = XDMInputFactory.createXMLInput(
context, new StringReader(result.toString()), false,
context.getInputValidationMode(), loc);
+ resIts[resIts.length - 4].require(requiredOptions);
+ }
else if (contentType.indexOf("html") >= 0 && tidy) {
resIts[resIts.length - 4] = XDMInputFactory.createTidyInput(
context, new StringReader(result.toString()), loc);
@@ -729,5 +741,9 @@
return docId;
}
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Doc.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -55,6 +55,7 @@
private final int OPERATION_UNPARSED_LINES=3;
private boolean inValidateExpression = false;
private int operation = OPERATION_DOC;
+ private int requiredOptions = 0;
private String docURI = null;
private Reader rd = null; // keep around to close
@@ -135,9 +136,11 @@
else
cur = XDMInputFactory.createXMLInput(context, uri, true, context.getInputValidationMode(), loc);
((XMLSource)cur).setURI(uri);
+ cur = cur.require(requiredOptions);
break;
case OPERATION_TIDY:
cur = XDMInputFactory.createTidyInput(context, rd, loc);
+ cur = cur.require(requiredOptions);
((XMLSource)cur).setURI(uri);
break;
case OPERATION_UNPARSED:
@@ -195,6 +198,7 @@
copy.setContext(context, true);
copy.setInValidateExpression(inValidateExpression);
copy.operation = operation;
+ copy.requiredOptions = requiredOptions;
copy.setConstModePreserve(this.constModePreserve);
copy.setSubIters(subIters);
return copy;
@@ -263,5 +267,9 @@
return new ObjectObjectPair(returned, new Set());
}
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Parse.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Parse.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Parse.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -33,13 +33,16 @@
public class Parse extends CurrentBasedIterator implements RequestTypeMulti{
private boolean useTidy;
+ private int requiredOptions = 0;
+
protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack)
throws MXQueryException {
Parse ret = new Parse();
ret.setSubIters(subIters);
ret.setContext(context, false);
ret.useTidy = useTidy;
+ ret.requiredOptions = requiredOptions;
return ret;
}
@@ -62,6 +65,7 @@
current = XDMInputFactory.createXMLInput(context, new StringReader(add),false,context.getInputValidationMode(),loc);
else
current = XDMInputFactory.createTidyInput(context, new StringReader(add), loc);
+ current = current.require(requiredOptions);
return;
}
public TypeInfo getStaticType() {
@@ -83,5 +87,10 @@
public void setReturnType(int type) throws MXQueryException {
}
+
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Soap_call.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Soap_call.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/functions/fn/Soap_call.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -36,6 +36,7 @@
import ch.ethz.mxquery.xdmio.XMLSource;
public class Soap_call extends CurrentBasedIterator {
+ private int requiredOptions = 0;
public TokenInterface next() throws MXQueryException{
if (called == 0) {
init();
@@ -103,6 +104,7 @@
}
XMLSource xmlIt = XDMInputFactory.createXMLInput(context, new StringReader(soapResult), false, context.getInputValidationMode(), loc);
xmlIt.setURI(location);
+ xmlIt = (XMLSource)xmlIt.require(requiredOptions);
current = new NodeIterator(context, xmlIt,loc);
//currentToken = new TextToken(null, soapResult);
@@ -112,9 +114,16 @@
}
protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack) throws MXQueryException {
- XDMIterator copy = new Soap_call();
+ Soap_call copy = new Soap_call();
copy.setContext(context, true);
copy.setSubIters(subIters);
+ copy.requiredOptions = requiredOptions;
return copy;
}
+
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
+
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/iterators/ValidateIterator.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/iterators/ValidateIterator.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/iterators/ValidateIterator.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -1,123 +1,129 @@
-/* Copyright 2006 - 2009 ETH Zurich
- *
- * Licensed 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.
- */
-
-package ch.ethz.mxquery.iterators;
-
-import java.io.Reader;
-import java.util.Vector;
-
-import ch.ethz.mxquery.contextConfig.Context;
-import ch.ethz.mxquery.datamodel.types.Type;
-import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
-import ch.ethz.mxquery.exceptions.DynamicException;
-import ch.ethz.mxquery.exceptions.ErrorCodes;
-import ch.ethz.mxquery.exceptions.MXQueryException;
-import ch.ethz.mxquery.exceptions.QueryLocation;
-import ch.ethz.mxquery.exceptions.TypeException;
-import ch.ethz.mxquery.model.CurrentBasedIterator;
-import ch.ethz.mxquery.model.XDMIterator;
-import ch.ethz.mxquery.util.StringReader;
-import ch.ethz.mxquery.xdmio.XDMInputFactory;
-import ch.ethz.mxquery.xdmio.XDMSerializer;
-
-public class ValidateIterator extends CurrentBasedIterator {
-
- private int mode;
-
-
- private class DetectDocIterator extends CurrentBasedIterator{
-
- public DetectDocIterator(Context ctx, XDMIterator it, QueryLocation loc) {
- super(ctx,new XDMIterator[]{it},loc);
- }
-
- private boolean isDoc = false;
- private int numRootNodes = 0;
-
- protected XDMIterator copy(Context context, XDMIterator[] subIters,
- Vector nestedPredCtxStack) throws MXQueryException {
- return new DetectDocIterator(context, subIters[0],loc);
- }
-
- public TokenInterface next() throws MXQueryException {
- if (called == 0) {
- called++;
- current = subIters[0];
- TokenInterface tok = getNext();
- if (tok.getEventType() == Type.START_DOCUMENT)
- isDoc = true;
- if (tok.getEventType() == Type.START_TAG)
- numRootNodes++;
- return tok;
- }
- TokenInterface t1 = getNext();
- if ((depth == 1 || isDoc && depth ==2)&&t1.getEventType() == Type.START_TAG) {
- numRootNodes++;
- }
- if (numRootNodes > 1 || (isDoc && depth==1 && t1.getEventType() == Type.START_DOCUMENT))
- if (isDoc && depth >1)
- throw new DynamicException(ErrorCodes.E0061_DYNAMIC_VALIDATE_MORE_THAN_ONE_ELEMENT, "Attempting to validate a document containing more than one root element. Offending element name: "+t1.getName(), loc);
- else
- throw new TypeException(ErrorCodes.E0030_TYPE_VALIDATE_MORE_THAN_ONE_ELEMENT, "Attempting to validate more than one element/document.", loc);
-
- return t1;
- }
-
- protected void resetImpl() throws MXQueryException {
- super.resetImpl();
- isDoc = false;
- numRootNodes = 0;
- }
-
- public boolean isDoc() {
- return isDoc;
- }
-
- }
-
- public ValidateIterator(int mode, Context ctx, XDMIterator[] subIters, QueryLocation loc) {
- super(ctx, subIters, loc);
- this.mode = mode;
- }
-
- protected void init() throws MXQueryException {
- XDMSerializer ip = new XDMSerializer();
- DetectDocIterator docDetect = new DetectDocIterator(context, subIters[0], loc);
- String strResult = ip.eventsToXML(docDetect);
- Reader reader = new StringReader(strResult);
- current = XDMInputFactory.createXMLInput(context, reader, docDetect.isDoc(), mode, loc);
- }
-
- protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack) throws MXQueryException {
- return new ValidateIterator(this.mode, this.context, subIters, loc);
- }
-
- public TokenInterface next() throws MXQueryException {
- if (called == 0) {
- init();
- called++;
- }
- TokenInterface tok = current.next();
- return tok;
- }
- public boolean isExprParameter(int valueToCheck, boolean recursive) {
- if (valueToCheck == EXPR_PARAM_XDMGEN)
- return true;
- else
- return super.isExprParameter(valueToCheck, recursive);
- }
-
-
-}
+/* Copyright 2006 - 2009 ETH Zurich
+ *
+ * Licensed 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.
+ */
+
+package ch.ethz.mxquery.iterators;
+
+import java.io.Reader;
+import java.util.Vector;
+
+import ch.ethz.mxquery.contextConfig.Context;
+import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
+import ch.ethz.mxquery.exceptions.DynamicException;
+import ch.ethz.mxquery.exceptions.ErrorCodes;
+import ch.ethz.mxquery.exceptions.MXQueryException;
+import ch.ethz.mxquery.exceptions.QueryLocation;
+import ch.ethz.mxquery.exceptions.TypeException;
+import ch.ethz.mxquery.model.CurrentBasedIterator;
+import ch.ethz.mxquery.model.XDMIterator;
+import ch.ethz.mxquery.util.StringReader;
+import ch.ethz.mxquery.xdmio.XDMInputFactory;
+import ch.ethz.mxquery.xdmio.XDMSerializer;
+
+public class ValidateIterator extends CurrentBasedIterator {
+
+ private int mode;
+ private int requiredOptions = 0;
+
+ private class DetectDocIterator extends CurrentBasedIterator{
+
+ public DetectDocIterator(Context ctx, XDMIterator it, QueryLocation loc) {
+ super(ctx,new XDMIterator[]{it},loc);
+ }
+
+ private boolean isDoc = false;
+ private int numRootNodes = 0;
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters,
+ Vector nestedPredCtxStack) throws MXQueryException {
+ return new DetectDocIterator(context, subIters[0],loc);
+ }
+
+ public TokenInterface next() throws MXQueryException {
+ if (called == 0) {
+ called++;
+ current = subIters[0];
+ TokenInterface tok = getNext();
+ if (tok.getEventType() == Type.START_DOCUMENT)
+ isDoc = true;
+ if (tok.getEventType() == Type.START_TAG)
+ numRootNodes++;
+ return tok;
+ }
+ TokenInterface t1 = getNext();
+ if ((depth == 1 || isDoc && depth ==2)&&t1.getEventType() == Type.START_TAG) {
+ numRootNodes++;
+ }
+ if (numRootNodes > 1 || (isDoc && depth==1 && t1.getEventType() == Type.START_DOCUMENT))
+ if (isDoc && depth >1)
+ throw new DynamicException(ErrorCodes.E0061_DYNAMIC_VALIDATE_MORE_THAN_ONE_ELEMENT, "Attempting to validate a document containing more than one root element. Offending element name: "+t1.getName(), loc);
+ else
+ throw new TypeException(ErrorCodes.E0030_TYPE_VALIDATE_MORE_THAN_ONE_ELEMENT, "Attempting to validate more than one element/document.", loc);
+
+ return t1;
+ }
+
+ protected void resetImpl() throws MXQueryException {
+ super.resetImpl();
+ isDoc = false;
+ numRootNodes = 0;
+ }
+
+ public boolean isDoc() {
+ return isDoc;
+ }
+
+ }
+
+ public ValidateIterator(int mode, Context ctx, XDMIterator[] subIters, QueryLocation loc) {
+ super(ctx, subIters, loc);
+ this.mode = mode;
+ }
+
+ protected void init() throws MXQueryException {
+ XDMSerializer ip = new XDMSerializer();
+ DetectDocIterator docDetect = new DetectDocIterator(context, subIters[0], loc);
+ String strResult = ip.eventsToXML(docDetect);
+ Reader reader = new StringReader(strResult);
+ current = XDMInputFactory.createXMLInput(context, reader, docDetect.isDoc(), mode, loc);
+ current = current.require(requiredOptions);
+ }
+
+ protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack) throws MXQueryException {
+ ValidateIterator val = new ValidateIterator(this.mode, this.context, subIters, loc);
+ val.requiredOptions = requiredOptions;
+ return val;
+ }
+
+ public TokenInterface next() throws MXQueryException {
+ if (called == 0) {
+ init();
+ called++;
+ }
+ TokenInterface tok = current.next();
+ return tok;
+ }
+ public boolean isExprParameter(int valueToCheck, boolean recursive) {
+ if (valueToCheck == EXPR_PARAM_XDMGEN)
+ return true;
+ else
+ return super.isExprParameter(valueToCheck, recursive);
+ }
+
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
+}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/iterators/scripting/WSFunction.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/iterators/scripting/WSFunction.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/iterators/scripting/WSFunction.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -64,6 +64,7 @@
private String[] paramTypes;
private QName returnName;
private String returnType;
+ private int requiredOptions;
public WSFunction(Context ctx, QueryLocation loc, QName name, String style,String soapAction, String namespace, Hashtable declaredNSs,
String encoding, String location, String[] paramNames,
@@ -238,7 +239,8 @@
soapResult = startTag+childElement+endTag;
}
XMLSource xmlIt = XDMInputFactory.createXMLInput(context, new StringReader(soapResult), false, context.getInputValidationMode(), loc);
- xmlIt.setURI(location);
+ xmlIt.setURI(location);
+ xmlIt = (XMLSource)xmlIt.require(requiredOptions);
if (this.returnType == null || this.returnType.equals("")){//the return 'part' is an element
TypeInfo stepInfo = new TypeInfo(Type.START_TAG,Type.OCCURRENCE_IND_EXACTLY_ONE,this.returnName);
@@ -319,9 +321,17 @@
}
protected XDMIterator copy(Context context, XDMIterator[] subIters, Vector nestedPredCtxStack) throws MXQueryException {
- XDMIterator copy = new WSFunction(context, loc, name.copy(), style, soapAction, namespace, declaredNSs, encoding, location, paramNames, Iterator.copyStrings(paramTypes), returnName, returnType);
+ WSFunction copy = new WSFunction(context, loc, name.copy(), style, soapAction, namespace, declaredNSs, encoding, location, paramNames, Iterator.copyStrings(paramTypes), returnName, returnType);
copy.setContext(context, true);
copy.setSubIters(subIters);
+ copy.requiredOptions = requiredOptions;
return copy;
}
+
+ public XDMIterator require(int requiredOptions) throws MXQueryException {
+ this.requiredOptions = requiredOptions;
+ return super.require(requiredOptions);
+ }
+
+
}
Modified: trunk/MXQuery/src/ch/ethz/mxquery/sms/MMimpl/TokenBufferStore.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/sms/MMimpl/TokenBufferStore.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/sms/MMimpl/TokenBufferStore.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -26,6 +26,7 @@
import ch.ethz.mxquery.datamodel.MXQueryNumber;
import ch.ethz.mxquery.datamodel.Source;
import ch.ethz.mxquery.datamodel.types.Type;
+import ch.ethz.mxquery.datamodel.types.TypeDictionary;
import ch.ethz.mxquery.datamodel.xdm.NamedToken;
import ch.ethz.mxquery.datamodel.xdm.TextToken;
import ch.ethz.mxquery.datamodel.xdm.Token;
@@ -41,7 +42,7 @@
*/
public class TokenBufferStore extends FIFOStore {
- private int initialCapacity = 50;
+ private int initialCapacity = 250;
//private int initialCapacity = 1000;
@@ -90,8 +91,8 @@
public boolean isScoring;
private int scoreCapacity = nodeIndexCapacity;
+ private TypeDictionary td = Context.getDictionary();
-
//protected static int descendantCounter = 0;
protected static int nodeIdCount = 0;
@@ -308,7 +309,7 @@
break;
}
- if ( Type.isAtomicType(type, Context.getDictionary()) || type == Type.UNTYPED || type == Type.ITEM || type == Type.FUNCTION_ITEM) {
+ if ( Type.isAtomicType(type, td) || type == Type.UNTYPED || type == Type.ITEM || type == Type.FUNCTION_ITEM) {
if (level == 0) {
indexNewNode();
Modified: trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/NonValidatingStaxAdapter.java
===================================================================
--- trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/NonValidatingStaxAdapter.java 2012-03-12 07:31:44 UTC (rev 4534)
+++ trunk/MXQuery/src/ch/ethz/mxquery/xdmio/xmlAdapters/NonValidatingStaxAdapter.java 2012-03-12 08:47:44 UTC (rev 4535)
@@ -1,232 +1,240 @@
-/* Copyright 2006 - 2009 ETH Zurich
- *
- * Licensed 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.
- */
-
-package ch.ethz.mxquery.xdmio.xmlAdapters;
-
-import java.util.LinkedList;
-import java.util.Vector;
-
-import javax.xml.stream.XMLStreamConstants;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamReader;
-
-import ch.ethz.mxquery.contextConfig.Context;
-import ch.ethz.mxquery.datamodel.QName;
-import ch.ethz.mxquery.datamodel.XQName;
-import ch.ethz.mxquery.datamodel.types.Type;
-import ch.ethz.mxquery.datamodel.xdm.CommentToken;
-import ch.ethz.mxquery.datamodel.xdm.ElementToken;
-import ch.ethz.mxquery.datamodel.xdm.NamedToken;
-import ch.ethz.mxquery.datamodel.xdm.ProcessingInstrToken;
-import ch.ethz.mxquery.datamodel.xdm.TextToken;
-import ch.ethz.mxquery.datamodel.xdm.Token;
-import ch.ethz.mxquery.datamodel.xdm.TokenInterface;
-import ch.ethz.mxquery.exceptions.MXQueryException;
-import ch.ethz.mxquery.exceptions.QueryLocation;
-import ch.ethz.mxquery.model.XDMIterator;
-import ch.ethz.mxquery.util.Utils;
-
-public class NonValidatingStaxAdapter extends XDMImportAdapter {
- private XMLStreamReader reader;
-
- private LinkedList tokensList;
-
- public NonValidatingStaxAdapter(Context ctx, QueryLocation loc, XMLStreamReader reader) {
- super(ctx, loc);
- this.reader = reader;
- this.tokensList = new LinkedList();
- }
-
- private TokenInterface getNext() {
- TokenInterface tok = Token.END_SEQUENCE_TOKEN;
- if (endOfSeq)
- return tok;
- try {
- int event = reader.getEventType();
- switch (event) {
- case XMLStreamConstants.ATTRIBUTE:
- break;
- case XMLStreamConstants.DTD:
- break;
- case XMLStreamConstants.CDATA:
- case XMLStreamConstants.CHARACTERS:
- case XMLStreamConstants.SPACE:
- {
- StringBuffer mergedText = new StringBuffer();
- while (event == XMLStreamConstants.CDATA || event == XMLStreamConstants.SPACE || event == XMLStreamConstants.CHARACTERS) {
- mergedText.append(reader.getText());
- reader.next();
- event = reader.getEventType();
- }
- return new TextToken(Type.TEXT_NODE_UNTYPED_ATOMIC, createNextTokenId(Type.TEXT_NODE_UNTYPED_ATOMIC, null), mergedText.toString(),curNsScope);
- }
- case XMLStreamConstants.COMMENT:
- tok = new CommentToken(createNextTokenId(Type.COMMENT, null), reader.getText(),curNsScope);
- break;
- case XMLStreamConstants.END_DOCUMENT:
- tok = new Token(Type.END_DOCUMENT,null,curN...
[truncated message content] |