From 5f29c3b769fcdb2532d4948aa1c649d4330304b9 Mon Sep 17 00:00:00 2001 From: jsdelfino Date: Tue, 11 Dec 2012 03:55:19 +0000 Subject: Use Jansson to read/write JSON instead of Mozilla SpiderMonkey. git-svn-id: http://svn.us.apache.org/repos/asf/tuscany@1419986 13f79535-47bb-0310-9956-ffa450edef68 --- sca-cpp/trunk/modules/js/Makefile.am | 11 - sca-cpp/trunk/modules/js/eval.hpp | 365 ------------------ sca-cpp/trunk/modules/js/js-shell.cpp | 55 --- sca-cpp/trunk/modules/js/js-test.cpp | 53 --- sca-cpp/trunk/modules/json/Makefile.am | 2 +- sca-cpp/trunk/modules/json/json-test.cpp | 414 ++++++++++++--------- sca-cpp/trunk/modules/json/json-test.hpp | 35 ++ sca-cpp/trunk/modules/json/json.hpp | 347 +++++++++++++---- sca-cpp/trunk/modules/scheme/json-value.cpp | 11 +- sca-cpp/trunk/modules/scheme/value-json.cpp | 5 +- sca-cpp/trunk/patches/jansson-2.4.patch | 11 + sca-cpp/trunk/unmaintained/README | 3 + sca-cpp/trunk/unmaintained/modules/js/Makefile.am | 31 ++ sca-cpp/trunk/unmaintained/modules/js/configure.ac | 63 ++++ sca-cpp/trunk/unmaintained/modules/js/eval.hpp | 407 ++++++++++++++++++++ sca-cpp/trunk/unmaintained/modules/js/js-shell.cpp | 55 +++ sca-cpp/trunk/unmaintained/modules/js/js-test.cpp | 75 ++++ .../trunk/unmaintained/modules/js/macos-install | 47 +++ .../trunk/unmaintained/modules/js/ubuntu-install | 48 +++ .../trunk/unmaintained/modules/json/Makefile.am | 29 ++ .../trunk/unmaintained/modules/json/json-test.cpp | 337 +++++++++++++++++ sca-cpp/trunk/unmaintained/modules/json/json.hpp | 197 ++++++++++ 22 files changed, 1859 insertions(+), 742 deletions(-) delete mode 100644 sca-cpp/trunk/modules/js/eval.hpp delete mode 100644 sca-cpp/trunk/modules/js/js-shell.cpp delete mode 100644 sca-cpp/trunk/modules/js/js-test.cpp create mode 100644 sca-cpp/trunk/modules/json/json-test.hpp create mode 100644 sca-cpp/trunk/patches/jansson-2.4.patch create mode 100644 sca-cpp/trunk/unmaintained/README create mode 100644 sca-cpp/trunk/unmaintained/modules/js/Makefile.am create mode 100644 sca-cpp/trunk/unmaintained/modules/js/configure.ac create mode 100644 sca-cpp/trunk/unmaintained/modules/js/eval.hpp create mode 100644 sca-cpp/trunk/unmaintained/modules/js/js-shell.cpp create mode 100644 sca-cpp/trunk/unmaintained/modules/js/js-test.cpp create mode 100755 sca-cpp/trunk/unmaintained/modules/js/macos-install create mode 100755 sca-cpp/trunk/unmaintained/modules/js/ubuntu-install create mode 100644 sca-cpp/trunk/unmaintained/modules/json/Makefile.am create mode 100644 sca-cpp/trunk/unmaintained/modules/json/json-test.cpp create mode 100644 sca-cpp/trunk/unmaintained/modules/json/json.hpp (limited to 'sca-cpp') diff --git a/sca-cpp/trunk/modules/js/Makefile.am b/sca-cpp/trunk/modules/js/Makefile.am index 38627678a1..2d1efea1dd 100644 --- a/sca-cpp/trunk/modules/js/Makefile.am +++ b/sca-cpp/trunk/modules/js/Makefile.am @@ -15,8 +15,6 @@ # specific language governing permissions and limitations # under the License. -incl_HEADERS = *.hpp -incldir = $(prefix)/include/modules/js jsfiles = htdocs/util.js htdocs/elemutil.js htdocs/xmlutil.js htdocs/atomutil.js htdocs/jsonutil.js htdocs/scdl.js htdocs/ui.js htdocs/component.js @@ -43,14 +41,5 @@ moddir = $(prefix)/modules/js nobase_dist_mod_DATA = ${minified} EXTRA_DIST = ${jsfiles} htdocs/ui.css -js_test_SOURCES = js-test.cpp -js_test_LDFLAGS = -lmozjs - -js_shell_SOURCES = js-shell.cpp -js_shell_LDFLAGS = -lmozjs - -noinst_PROGRAMS = js-test -mod_PROGRAMS = js-shell dist_noinst_SCRIPTS = util-test -TESTS = js-test util-test diff --git a/sca-cpp/trunk/modules/js/eval.hpp b/sca-cpp/trunk/modules/js/eval.hpp deleted file mode 100644 index f8f4cbe598..0000000000 --- a/sca-cpp/trunk/modules/js/eval.hpp +++ /dev/null @@ -1,365 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* $Rev$ $Date$ */ - -#ifndef tuscany_js_hpp -#define tuscany_js_hpp - -/** - * Javascript evaluation functions. - */ - -#define XP_UNIX -#ifdef WANT_MAINTAINER_WARNINGS -#pragma GCC diagnostic ignored "-Wunused-parameter" -#pragma GCC diagnostic ignored "-Wsign-compare" -#pragma GCC diagnostic ignored "-Wredundant-decls" -#endif -#include -#ifdef WANT_MAINTAINER_WARNINGS -#pragma GCC diagnostic warning "-Wunused-parameter" -#pragma GCC diagnostic warning "-Wsign-compare" -#pragma GCC diagnostic warning "-Wredundant-decls" -#endif -#include "string.hpp" -#include "list.hpp" -#include "value.hpp" -#include "element.hpp" -#include "monad.hpp" -#include "parallel.hpp" - -namespace tuscany { -namespace js { - -/** - * Report Javascript errors. - */ -void reportError(unused ::JSContext *cx, const char *message, JSErrorReport *report) { - cfailure << (const char*)(report->filename? report->filename : "") << ":" - << (int)report->lineno << ":" << message << endl; -} - -/** - * Encapsulates a JavaScript runtime. Shared by multiple threads in - * a process. - */ -class JSRuntime { -public: - JSRuntime() { - // Create JS runtime - debug("js::jsruntime"); - rt = JS_NewRuntime(1L * 512L * 1024L); - if(rt == NULL) - cleanup(); - } - - operator ::JSRuntime*() const { - return rt; - } - - ~JSRuntime() { - debug("js::~jsruntime"); - } - -private: - bool cleanup() { - if(rt != NULL) { - JS_DestroyRuntime(rt); - rt = NULL; - } - JS_ShutDown(); - return true; - } - - ::JSRuntime* rt; -} jsRuntime; - -JSClass jsGlobalClass = { "global", JSCLASS_GLOBAL_FLAGS, - JS_PropertyStub, JS_PropertyStub, - JS_PropertyStub, JS_StrictPropertyStub, - JS_EnumerateStub, JS_ResolveStub, - JS_ConvertStub, JS_FinalizeStub, - JSCLASS_NO_OPTIONAL_MEMBERS }; - -/** - * Represents a JavaScript context. Maintains one context per thread. - */ -#ifdef WANT_THREADS -perthread_ptr jsContext; -#else -::JSContext* jsContext = NULL; -#endif - -class JSContext { -public: - JSContext() { - // Create JS context if necessary - debug("js::jscontext"); - if (jsContext != NULL) { - cx = jsContext; - JS_BeginRequest(cx); - return; - } - debug("js::jsnewcontext"); - cx = JS_NewContext(jsRuntime, 8192); - if(cx == NULL) - return; - JS_BeginRequest(cx); - - JS_SetOptions(cx, JSOPTION_VAROBJFIX | JSOPTION_JIT | JSOPTION_METHODJIT); - JS_SetVersion(cx, JSVERSION_LATEST); - JS_SetErrorReporter(cx, reportError); - //JS_SetGCZeal(cx, 2); - - // Create global JS object - global = JS_NewCompartmentAndGlobalObject(cx, &jsGlobalClass, NULL); - if(global == NULL) { - cleanup(); - return; - } - - // Populate global object with the standard globals, like Object and Array - if(!JS_InitStandardClasses(cx, global)) { - cleanup(); - return; - } - jsContext = cx; - } - - ~JSContext() { - debug("js::~jscontext"); - cleanup(); - } - - operator ::JSContext*() const { - return cx; - } - - JSObject* getGlobal() const { - return global; - } - -private: - bool cleanup() { - if(cx != NULL) { - JS_MaybeGC(cx); - JS_EndRequest(cx); - if (cx != jsContext) { - debug("js::jsdestroycontext"); - JS_DestroyContext(cx); - } - cx = NULL; - } - return true; - } - - ::JSContext* cx; - JSObject* global; -}; - -/** - * Returns true if a list represents a JS array. - */ -const bool isJSArray(const list& l) { - if(isNil(l)) - return true; - const value v = car(l); - if (isSymbol(v)) - return false; - if(isList(v)) { - if(!isNil((list)v) && isSymbol(car(v))) - return false; - } - return true; -} - -/** - * Converts JS properties to values. - */ -const list jsPropertiesToValues(const list& propertiesSoFar, JSObject* o, JSObject* i, const js::JSContext& cx) { - - const value jsValToValue(const jsval& jsv, const js::JSContext& cx); - - jsid id; - if(!JS_NextProperty(cx, i, &id)) - return propertiesSoFar; - jsval idv; - JS_IdToValue(cx, id, &idv); - if (idv == JSVAL_VOID) - return propertiesSoFar; - - jsval jsv; - if(!JS_GetPropertyById(cx, o, id, &jsv)) - return propertiesSoFar; - const value val = jsValToValue(jsv, cx); - - if(JSVAL_IS_STRING(idv)) { - char* cname = JS_EncodeString(cx, JSVAL_TO_STRING(idv)); - const string name = cname; - JS_free(cx, cname); - if (isNil(val) && !isList(val)) - return jsPropertiesToValues(cons (mklist (element, c_str(name), val), propertiesSoFar), o, i, cx); - //return jsPropertiesToValues(propertiesSoFar, o, i, cx); - if (substr(name, 0, 1) == atsign) - return jsPropertiesToValues(cons(mklist(attribute, c_str(substr(name, 1)), val), propertiesSoFar), o, i, cx); - if (isList(val) && !isJSArray(val)) - return jsPropertiesToValues(cons(cons(element, cons(c_str(name), list(val))), propertiesSoFar), o, i, cx); - return jsPropertiesToValues(cons (mklist (element, c_str(name), val), propertiesSoFar), o, i, cx); - } - return jsPropertiesToValues(cons(val, propertiesSoFar), o, i, cx); -} - -/** - * Converts a JS val to a value. - */ -const value jsValToValue(const jsval& jsv, const js::JSContext& cx) { - switch(JS_TypeOfValue(cx, jsv)) { - case JSTYPE_STRING: { - char* cvalue = JS_EncodeString(cx, JSVAL_TO_STRING(jsv)); - const string svalue = string(cvalue); - JS_free(cx, cvalue); - return value(svalue); - } - case JSTYPE_BOOLEAN: { - return value((bool)JSVAL_TO_BOOLEAN(jsv)); - } - case JSTYPE_NUMBER: { - jsdouble jsd; - JS_ValueToNumber(cx, jsv, &jsd); - return value((double)jsd); - } - case JSTYPE_OBJECT: { - JSObject* o = JSVAL_TO_OBJECT(jsv); - if (o == NULL) - return value(); - JSObject* i = JS_NewPropertyIterator(cx, o); - if(i == NULL) - return value(list ()); - const value pv = jsPropertiesToValues(list (), o, i, cx); - return pv; - } - default: { - return value(); - } - } -} - -/** - * Converts a list of values to JS array elements. - */ -JSObject* valuesToJSElements(JSObject* a, const list& l, int i, const js::JSContext& cx) { - const jsval valueToJSVal(const value& val, const js::JSContext& cx); - if (isNil(l)) - return a; - jsval pv = valueToJSVal(car(l), cx); - JS_SetElement(cx, a, i, &pv); - return valuesToJSElements(a, cdr(l), ++i, cx); -} - -/** - * Converts a value to a JS val. - */ -const jsval valueToJSVal(const value& val, const js::JSContext& cx) { - JSObject* valuesToJSProperties(JSObject* o, const list& l, const js::JSContext& cx); - - switch(type(val)) { - case value::String: { - return STRING_TO_JSVAL(JS_NewStringCopyZ(cx, c_str((string)val))); - } - case value::Symbol: { - return STRING_TO_JSVAL(JS_NewStringCopyZ(cx, c_str((string)val))); - } - case value::Bool: { - return BOOLEAN_TO_JSVAL((bool)val); - } - case value::Number: { - jsval jsv; - if (!JS_NewNumberValue(cx, (jsdouble)val, &jsv)) - return DOUBLE_TO_JSVAL(0); - return jsv; - } - case value::List: { - if (isJSArray(val)) - return OBJECT_TO_JSVAL(valuesToJSElements(JS_NewArrayObject(cx, 0, NULL), val, 0, cx)); - return OBJECT_TO_JSVAL(valuesToJSProperties(JS_NewObject(cx, NULL, NULL, NULL), val, cx)); - } - case value::Nil: { - return JSVAL_NULL; - } - default: { - return JSVAL_VOID; - } - } -} - -/** - * Converts a list of values to JS properties. - */ -JSObject* valuesToJSProperties(JSObject* o, const list& l, const js::JSContext& cx) { - if (isNil(l)) - return o; - - // Write an attribute - const value token(car(l)); - - if (isTaggedList(token, attribute)) { - jsval pv = valueToJSVal(attributeValue(token), cx); - JS_SetProperty(cx, o, c_str(atsign + string(attributeName(token))), &pv); - - } else if (isTaggedList(token, element)) { - - // Write the value of an element - if (elementHasValue(token)) { - jsval pv = valueToJSVal(elementValue(token), cx); - JS_SetProperty(cx, o, c_str(string(elementName(token))), &pv); - - } else { - - // Write a parent element - JSObject* child = JS_NewObject(cx, NULL, NULL, NULL); - jsval pv = OBJECT_TO_JSVAL(child); - JS_SetProperty(cx, o, c_str(string(elementName(token))), &pv); - - // Write its children - valuesToJSProperties(child, elementChildren(token), cx); - } - } - - // Go on - return valuesToJSProperties(o, cdr(l), cx); -} - -/** - * Evaluate a script provided as a string. - */ -const failable evalScript(const string& s) { - js::JSContext cx; - jsval rval; - JSBool rc = JS_EvaluateScript(cx, cx.getGlobal(), c_str(s), (uintN)length(s), "eval.js", 1, &rval); - if (rc != JS_TRUE) { - return mkfailure("Couldn't evaluate Javascript script."); - } - return jsValToValue(rval, cx); -} - -} -} - -#endif /* tuscany_js_hpp */ diff --git a/sca-cpp/trunk/modules/js/js-shell.cpp b/sca-cpp/trunk/modules/js/js-shell.cpp deleted file mode 100644 index ee0fa89b31..0000000000 --- a/sca-cpp/trunk/modules/js/js-shell.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* $Rev$ $Date$ */ - -/** - * Evaluate a JavaScript script. - */ - -#include -#include "stream.hpp" -#include "fstream.hpp" -#include "string.hpp" -#include "eval.hpp" - -namespace tuscany { -namespace js { - -bool eval() { - ostringstream os; - for(;;) { - int c = cin.get(); - if (c == -1) - break; - os << (char)c; - } - failable v = evalScript(str(os)); - assert(hasContent(v)); - cout << v; - return true; -} - -} -} - -int main() { - tuscany::js::eval(); - return 0; -} diff --git a/sca-cpp/trunk/modules/js/js-test.cpp b/sca-cpp/trunk/modules/js/js-test.cpp deleted file mode 100644 index a7e5597610..0000000000 --- a/sca-cpp/trunk/modules/js/js-test.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/* $Rev$ $Date$ */ - -/** - * Test JavaScript evaluation functions. - */ - -#include -#include "stream.hpp" -#include "string.hpp" -#include "eval.hpp" - -namespace tuscany { -namespace js { - -bool testJSEval() { - failable v = evalScript("(function testJSON(n){ return JSON.parse(JSON.stringify(n)) })(5)"); - assert(hasContent(v)); - assert(content(v) == value(5)); - return true; -} - -} -} - -int main() { - tuscany::gc_scoped_pool p; - tuscany::cout << "Testing..." << tuscany::endl; - - tuscany::js::testJSEval(); - - tuscany::cout << "OK" << tuscany::endl; - - return 0; -} diff --git a/sca-cpp/trunk/modules/json/Makefile.am b/sca-cpp/trunk/modules/json/Makefile.am index 7b5b3878db..6de3f66339 100644 --- a/sca-cpp/trunk/modules/json/Makefile.am +++ b/sca-cpp/trunk/modules/json/Makefile.am @@ -19,7 +19,7 @@ incl_HEADERS = *.hpp incldir = $(prefix)/include/modules/json json_test_SOURCES = json-test.cpp -json_test_LDFLAGS = -lmozjs +json_test_LDFLAGS = -ljansson noinst_PROGRAMS = json-test TESTS = json-test diff --git a/sca-cpp/trunk/modules/json/json-test.cpp b/sca-cpp/trunk/modules/json/json-test.cpp index 945b6c072c..ab159f95a6 100644 --- a/sca-cpp/trunk/modules/json/json-test.cpp +++ b/sca-cpp/trunk/modules/json/json-test.cpp @@ -28,6 +28,7 @@ #include "string.hpp" #include "json.hpp" #include "perf.hpp" +#include "json-test.hpp" namespace tuscany { namespace json { @@ -37,47 +38,59 @@ ostream* jsonWriter(const string& s, ostream* os) { return os; } -const string jscustomer("{\n" - " \"customer\": {\n" - " \"@name\": \"jdoe\",\n" - " \"address\": {\n" - " \"@city\": \"san francisco\",\n" - " \"@state\": \"ca\"\n" - " },\n" - " \"account\": {\n" - " \"id\": \"1234\",\n" - " \"@balance\": 1000\n" - " }\n" - " }\n" +const string testCustomer("{" + "\"customer\":{" + "\"@name\":\"jdoe\"," + "\"address\":{" + "\"@city\":\"san francisco\"," + "\"@state\":\"ca\"" + "}," + "\"account\":{" + "\"id\":\"1234\"," + "\"@balance\":1000" + "}" + "}" "}"); -const string jsphones("{\n" - " \"phones\": [\n" - " \"408-1234\",\n" - " \"650-1234\"\n" - " ],\n" - " \"lastName\": \"test\\u0009tab\",\n" - " \"@firstName\": \"test1\"\n" +const string testCustomer2("{" + "\"customer\":{" + "\"@name\":\"jdoe\"," + "\"account\":{" + "\"id\":\"1234\"," + "\"@balance\":1000" + "}," + "\"address\":{" + "\"@city\":\"san francisco\"," + "\"@state\":\"ca\"" + "}" + "}" "}"); -const string jsecho("{\n" - " \"ns1:echoString\": {\n" - " \"@xmlns:ns1\": \"http://ws.apache.org/axis2/services/echo\",\n" - " \"text\": \"Hello World!\"\n" - " }\n" +const string testPhones("{" + "\"phones\":[" + "\"408-1234\"," + "\"650-1234\"" + "]," + "\"lastName\":\"test\\ttab\"," + "\"@firstName\":\"test1\"" "}"); -const string jsarray("{\n" - " \"fruit\": [\n" - " \"Apple\",\n" - " \"Orange\"\n" - " ]\n" +const string testEcho("{" + "\"ns1:echoString\":{" + "\"@xmlns:ns1\":\"http://ws.apache.org/axis2/services/echo\"," + "\"text\":\"Hello World!\"" + "}" "}"); -bool testJSON() { - gc_scoped_pool pool; - const js::JSContext cx; +const string testArray("{" + "\"fruit\":[" + "\"Apple\"," + "\"Orange\"" + "]" + "}"); +const bool testJSON() { + const gc_scoped_pool pool; { const list ad = mklist(mklist(attribute, "city", string("san francisco")), mklist(attribute, "state", string("ca"))); const list ac = mklist(mklist(element, "id", string("1234")), mklist(attribute, "balance", 1000)); @@ -85,161 +98,192 @@ bool testJSON() { const list c = mklist(cons(element, cons("customer", cr))); ostringstream os; - writeJSON(jsonWriter, &os, c, cx); - assert(str(os) == jscustomer); + writeElements(jsonWriter, &os, c); + assert(str(os) == testCustomer); } { const list phones = mklist (string("408-1234"), string("650-1234")); const list l = mklist (mklist (element, "phones", phones), mklist (element, "lastName", string("test\ttab")), mklist (attribute, "firstName", string("test1"))); ostringstream os; - writeJSON(jsonWriter, &os, l, cx); - assert(str(os) == jsphones); + writeElements(jsonWriter, &os, l); + assert(str(os) == testPhones); istringstream is(str(os)); const list il = streamList(is); - const list r = content(readJSON(il, cx)); + const list r = content(readElements(il)); assert(r == l); ostringstream wos; - write(content(writeJSON(r, cx)), wos); + write(content(writeElements(r)), wos); assert(str(wos) == str(os)); } { - const list l = mklist(list() + "ns1:echoString" + (list() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (list() + "text" + string("Hello World!"))); + const list l = mklist(nilListValue + "ns1:echoString" + (nilListValue + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (nilListValue + "text" + string("Hello World!"))); ostringstream wos; - write(content(writeJSON(valuesToElements(l), cx)), wos); - assert(str(wos) == jsecho); + write(content(writeElements(valuesToElements(l))), wos); + assert(str(wos) == testEcho); istringstream is(str(wos)); const list il = streamList(is); - const list r = elementsToValues(content(readJSON(il, cx))); + const list r = elementsToValues(content(readElements(il))); assert(r == l); } { - const list l = mklist((list() + "fruit" + string("Apple")), (list() + "fruit" + string("Orange"))); + const list l = mklist((nilListValue + "fruit" + string("Apple")), (nilListValue + "fruit" + string("Orange"))); ostringstream wos; - write(content(writeJSON(valuesToElements(l), cx)), wos); - assert(str(wos) == jsarray); + write(content(writeElements(valuesToElements(l))), wos); + assert(str(wos) == testArray); istringstream is(str(wos)); const list il = streamList(is); - const list r = elementsToValues(content(readJSON(il, cx))); - const list l2 = mklist(list() + "fruit" + (list() + string("Apple") + string("Orange"))); + const list r = elementsToValues(content(readElements(il))); + const list l2 = mklist(nilListValue + "fruit" + (nilListValue + string("Apple") + string("Orange"))); assert(r == l2); } return true; } -const string jsitem("{\n" - " \"id\": 3,\n" - " \"result\": [\n" - " {\n" - " \"price\": \"$2.99\",\n" - " \"name\": \"Apple\"\n" - " },\n" - " {\n" - " \"price\": \"$3.55\",\n" - " \"name\": \"Orange\"\n" - " },\n" - " {\n" - " \"price\": \"$1.55\",\n" - " \"name\": \"Pear\"\n" - " }\n" - " ]\n" +const string testItem("{" + "\"id\":3," + "\"result\":[" + "{" + "\"price\":\"$2.99\"," + "\"name\":\"Apple\"" + "}," + "{" + "\"price\":\"$3.55\"," + "\"name\":\"Orange\"" + "}," + "{" + "\"price\":\"$1.55\"," + "\"name\":\"Pear\"" + "}" + "]" + "}"); + +const string testResult("{" + "\"id\":1," + "\"result\":[" + "\"Service.get\"," + "\"Service.getTotal\"" + "]" "}"); -const string jsresult("{\n" - " \"id\": 1,\n" - " \"result\": [\n" - " \"Service.get\",\n" - " \"Service.getTotal\"\n" - " ]\n" +const string testFeed("{" + "\"id\":1," + "\"result\":[" + "\"Sample Feed\"," + "\"123456789\"," + "[" + "\"Item\"," + "\"111\"," + "{" + "\"name\":\"Apple\"," + "\"currencyCode\":\"USD\"," + "\"currencySymbol\":\"$\"," + "\"price\":2.99" + "}" + "]," + "[" + "\"Item\"," + "\"222\"," + "{" + "\"name\":\"Orange\"," + "\"currencyCode\":\"USD\"," + "\"currencySymbol\":\"$\"," + "\"price\":3.55" + "}" + "]," + "[" + "\"Item\"," + "\"333\"," + "{" + "\"name\":\"Pear\"," + "\"currencyCode\":\"USD\"," + "\"currencySymbol\":\"$\"," + "\"price\":1.55" + "}" + "]" + "]" "}"); -const string jsfeed("{\n" - " \"id\": 1,\n" - " \"result\": [\n" - " \"Sample Feed\",\n" - " \"123456789\",\n" - " [\n" - " \"Item\",\n" - " \"111\",\n" - " {\n" - " \"name\": \"Apple\",\n" - " \"currencyCode\": \"USD\",\n" - " \"currencySymbol\": \"$\",\n" - " \"price\": 2.99\n" - " }\n" - " ],\n" - " [\n" - " \"Item\",\n" - " \"222\",\n" - " {\n" - " \"name\": \"Orange\",\n" - " \"currencyCode\": \"USD\",\n" - " \"currencySymbol\": \"$\",\n" - " \"price\": 3.55\n" - " }\n" - " ],\n" - " [\n" - " \"Item\",\n" - " \"333\",\n" - " {\n" - " \"name\": \"Pear\",\n" - " \"currencyCode\": \"USD\",\n" - " \"currencySymbol\": \"$\",\n" - " \"price\": 1.55\n" - " }\n" - " ]\n" - " ]\n" +const string testFeed2("{" + "\"id\":1," + "\"result\":[" + "\"Sample Feed\"," + "\"123456789\"," + "[" + "\"Item\"," + "\"111\"," + "{" + "\"name\":\"Apple\"," + "\"price\":2.99," + "\"currencyCode\":\"USD\"," + "\"currencySymbol\":\"$\"" + "}" + "]," + "[" + "\"Item\"," + "\"222\"," + "{" + "\"name\":\"Orange\"," + "\"price\":3.55," + "\"currencyCode\":\"USD\"," + "\"currencySymbol\":\"$\"" + "}" + "]," + "[" + "\"Item\"," + "\"333\"," + "{" + "\"name\":\"Pear\"," + "\"price\":1.55," + "\"currencyCode\":\"USD\"," + "\"currencySymbol\":\"$\"" + "}" + "]" + "]" "}"); -const string jsechoreq("{\n" - " \"id\": 1,\n" - " \"method\": \"echo\",\n" - " \"params\": [\n" - " {\n" - " \"ns1:echoString\": {\n" - " \"@xmlns:ns1\": \"http://ws.apache.org/axis2/services/echo\",\n" - " \"text\": \"Hello World!\"\n" - " }\n" - " }\n" - " ]\n" +const string testEchoreq("{" + "\"id\":1," + "\"method\":\"echo\"," + "\"params\":[" + "{" + "\"ns1:echoString\":{" + "\"@xmlns:ns1\":\"http://ws.apache.org/axis2/services/echo\"," + "\"text\":\"Hello World!\"" + "}" + "}" + "]" "}"); -const string jsechores("{\n" - " \"id\": 1,\n" - " \"result\": {\n" - " \"ns1:echoString\": {\n" - " \"@xmlns:ns1\": \"http://ws.apache.org/axis2/c/samples\",\n" - " \"text\": \"Hello World!\"\n" - " }\n" - " }\n" +const string testEchores("{" + "\"id\":1," + "\"result\":{" + "\"ns1:echoString\":{" + "\"@xmlns:ns1\":\"http://ws.apache.org/axis2/c/samples\"," + "\"text\":\"Hello World!\"" + "}" + "}" "}"); -bool testJSONRPC() { - gc_scoped_pool pool; - js::JSContext cx; +const bool testJSONRPC() { + const gc_scoped_pool pool; { - const string lm("{\"id\": 1, \"method\": \"test\", \"params\": []}"); - const list e = content(readJSON(mklist(lm), cx)); + const string lm("{\"id\":1,\"method\":\"test\",\"params\":[]}"); + const list e = content(readElements(mklist(lm))); const list v = elementsToValues(e); assert(assoc("id", v) == mklist("id", 1)); assert(assoc("method", v) == mklist("method", string("test"))); - assert(assoc("params", v) == mklist("params", list())); + assert(assoc("params", v) == mklist("params", nilListValue)); } { - const string i2 = "{\"id\": 3,\"result\": {\"0\": {\"price\": \"$2.99\",\"name\": \"Apple\"},\"1\": {\"price\": \"$3.55\",\"name\": \"Orange\"},\"2\": {\"price\": \"$1.55\",\"name\": \"Pear\"}}}"; - const list e = content(readJSON(mklist(jsitem), cx)); - const list e2 = content(readJSON(mklist(i2), cx)); - assert(e == e2); - } - { - const list e = content(readJSON(mklist(jsitem), cx)); + const list e = content(readElements(mklist(testItem))); ostringstream os; - write(content(writeJSON(e, cx)), os); - assert(str(os) == jsitem); + write(content(writeElements(e)), os); + assert(str(os) == testItem); const list v = elementsToValues(e); const list r = valuesToElements(v); assert(r == e); @@ -248,87 +292,101 @@ bool testJSONRPC() { const list r = mklist(mklist("id", 1), mklist("result", mklist(string("Service.get"), string("Service.getTotal")))); const list e = valuesToElements(r); ostringstream os; - write(content(writeJSON(e, cx)), os); - assert(str(os) == jsresult); + write(content(writeElements(e)), os); + assert(str(os) == testResult); } { - const list r = content(readJSON(mklist(jsfeed), cx)); + const list r = content(readElements(mklist(testFeed))); const list v = elementsToValues(r); const list e = valuesToElements(v); ostringstream os; - write(content(writeJSON(e, cx)), os); - assert(str(os) == jsfeed); + write(content(writeElements(e)), os); +#ifndef __clang__ + assert(str(os) == testFeed2); +#endif } { - const list arg = mklist(list() + "ns1:echoString" + (list() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (list() + "text" + string("Hello World!"))); - const failable > r = jsonRequest(1, "echo", mklist(arg), cx); + const list arg = mklist(nilListValue + "ns1:echoString" + (nilListValue + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (nilListValue + "text" + string("Hello World!"))); + const failable > r = jsonRequest(1, "echo", mklist(arg)); ostringstream os; write(content(r), os); - assert(str(os) == jsechoreq); + assert(str(os) == testEchoreq); istringstream is(str(os)); const list il = streamList(is); - const list ir = elementsToValues(content(readJSON(il, cx))); + const list ir = elementsToValues(content(readElements(il))); assert(car(cadr(caddr(ir))) == arg); } { - const list res = mklist(list() + "ns1:echoString" + (list() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/c/samples")) + (list() + "text" + string("Hello World!"))); - const failable > r = jsonResult(1, res, cx); + const list res = mklist(nilListValue + "ns1:echoString" + (nilListValue + "@xmlns:ns1" + string("http://ws.apache.org/axis2/c/samples")) + (nilListValue + "text" + string("Hello World!"))); + const failable > r = jsonResult(1, res); ostringstream os; write(content(r), os); - assert(str(os) == jsechores); + assert(str(os) == testEchores); istringstream is(str(os)); const list il = streamList(is); - const list ir = elementsToValues(content(readJSON(il, cx))); + const list ir = elementsToValues(content(readElements(il))); assert(cdr(cadr(ir)) == res); } return true; } -struct testReadWrite { - testReadWrite() { - } - const bool operator()() const { - gc_scoped_pool pool; - js::JSContext cx; +const bool readWrite() { + const gc_scoped_pool pool; - const list ad = mklist(mklist(attribute, "city", string("san francisco")), mklist(attribute, "state", string("ca"))); - const list ac = mklist(mklist(element, "id", string("1234")), mklist(attribute, "balance", 1000)); - const list cr = mklist(mklist (attribute, "name", string("jdoe")), cons(element, cons("address", ad)), cons(element, cons("account", ac))); - const list c = mklist(cons(element, cons("customer", cr))); + istringstream is(testCustomer); + const list il = streamList(is); + const list r = elementsToValues(content(readElements(il))); - ostringstream os; - writeJSON(jsonWriter, &os, c, cx); - assert(str(os) == jscustomer); - - istringstream is(jscustomer); - const list il = streamList(is); - const list r = content(readJSON(il, cx)); - assert(r == c); - return true; - } -}; + ostringstream os; + writeElements(jsonWriter, &os, valuesToElements(r)); + //assert(str(os) == testCustomer2); + return true; +} -bool testJSONPerf() { - gc_scoped_pool pool; +const bool testReadWritePerf() { + const gc_scoped_pool pool; - const lambda rwl = lambda(testReadWrite()); + const blambda rwl = blambda(readWrite); cout << "JSON read + write test " << time(rwl, 5, 200) << " ms" << endl; return true; } +const bool readWriteBigDoc() { + const gc_scoped_pool pool; + + istringstream is(testBigDoc); + const list il = streamList(is); + const list r = elementsToValues(content(readElements(il))); + + ostringstream os; + writeElements(jsonWriter, &os, valuesToElements(r)); + //assert(str(os) == testBigDoc2); + return true; +} + +const bool testReadWriteBigDocPerf() { + const gc_scoped_pool pool; + + const blambda rwl = blambda(readWriteBigDoc); + cout << "JSON big doc read + write test " << time(rwl, 5, 200) << " ms" << endl; + + return true; +} + } } int main() { - tuscany::gc_scoped_pool p; + const tuscany::gc_scoped_pool p; tuscany::cout << "Testing..." << tuscany::endl; tuscany::json::testJSON(); tuscany::json::testJSONRPC(); - tuscany::json::testJSONPerf(); + tuscany::json::testReadWritePerf(); + tuscany::json::testReadWriteBigDocPerf(); tuscany::cout << "OK" << tuscany::endl; diff --git a/sca-cpp/trunk/modules/json/json-test.hpp b/sca-cpp/trunk/modules/json/json-test.hpp new file mode 100644 index 0000000000..a6ce7b1636 --- /dev/null +++ b/sca-cpp/trunk/modules/json/json-test.hpp @@ -0,0 +1,35 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* $Rev$ $Date$ */ + +/** + * Test JSON doc. + */ + +namespace tuscany { +namespace json { + +const string testBigDoc = "{\"feed\":{\"title\":\"Search Results\",\"id\":\"search\",\"entry\":[{\"title\":\"An empty app template\",\"id\":\"new\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"An empty test app\",\"id\":\"test\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Check my public social data\",\"id\":\"me360\",\"author\":\"admin@example.com\",\"updated\":\"Apr 28, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"nearme\",\"id\":\"nearme\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"nearme2\",\"id\":\"nearme2\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Our photos of an event\",\"id\":\"ourphotos\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"My online store\",\"id\":\"shoppingcart\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Slice\",\"id\":\"slice\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test animation components\",\"id\":\"testanimation\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test database components\",\"id\":\"testdb\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test event components\",\"id\":\"testevents\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test logic components\",\"id\":\"testlogic\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test search components\",\"id\":\"testsearch\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test social components\",\"id\":\"testsocial\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test text processing components\",\"id\":\"testtext\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test URL components\",\"id\":\"testurl\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test values and lists\",\"id\":\"testvalues\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test widgets\",\"id\":\"testwidgets\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test more widgets\",\"id\":\"testwidgets2\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test HTML generator components\",\"id\":\"testwidgets3\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"jsdtest\",\"id\":\"jsdtest\",\"author\":\"jsdelfino\",\"updated\":\"Jul 27, 2012\",\"content\":{\"stats\":{\"description\":\"Test app\"}}},{\"title\":\"SMS send service\",\"id\":\"twsms\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"boao\",\"id\":\"boao\",\"author\":\"jsdelfino\",\"updated\":\"2012-10-12T12:06:59+00:00\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"An empty test app\",\"id\":\"test\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"An empty app template\",\"id\":\"new\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"nearme\",\"id\":\"nearme\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"nearme2\",\"id\":\"nearme2\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Our photos of an event\",\"id\":\"ourphotos\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"My online store\",\"id\":\"shoppingcart\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Slice\",\"id\":\"slice\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test animation components\",\"id\":\"testanimation\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test database components\",\"id\":\"testdb\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test event components\",\"id\":\"testevents\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test social components\",\"id\":\"testsocial\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test logic components\",\"id\":\"testlogic\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test search components\",\"id\":\"testsearch\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test text processing components\",\"id\":\"testtext\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test URL components\",\"id\":\"testurl\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test values and lists\",\"id\":\"testvalues\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test widgets\",\"id\":\"testwidgets\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test more widgets\",\"id\":\"testwidgets2\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Test HTML generator components\",\"id\":\"testwidgets3\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"test9\",\"id\":\"test9\",\"author\":\"jsdelfino\",\"updated\":\"2012-09-25T06:17:18+00:00\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"SMS send service\",\"id\":\"twsms\",\"author\":\"admin@example.com\",\"updated\":\"Jan 01, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}},{\"title\":\"Check my public social data\",\"id\":\"me360\",\"author\":\"admin@example.com\",\"updated\":\"Apr 28, 2012\",\"content\":{\"stats\":{\"description\":\"Sample app\"}}}]}}"; + +const string testBigDoc2 = "{\"feed\":{\"title\":\"Search Results\",\"id\":\"search\",\"entry\":[{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"An empty app template\",\"id\":\"new\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"An empty test app\",\"id\":\"test\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Check my public social data\",\"id\":\"me360\",\"updated\":\"Apr 28, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"nearme\",\"id\":\"nearme\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"nearme2\",\"id\":\"nearme2\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Our photos of an event\",\"id\":\"ourphotos\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"My online store\",\"id\":\"shoppingcart\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Slice\",\"id\":\"slice\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test animation components\",\"id\":\"testanimation\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test database components\",\"id\":\"testdb\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test event components\",\"id\":\"testevents\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test logic components\",\"id\":\"testlogic\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test search components\",\"id\":\"testsearch\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test social components\",\"id\":\"testsocial\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test text processing components\",\"id\":\"testtext\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test URL components\",\"id\":\"testurl\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test values and lists\",\"id\":\"testvalues\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test widgets\",\"id\":\"testwidgets\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test more widgets\",\"id\":\"testwidgets2\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test HTML generator components\",\"id\":\"testwidgets3\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Test app\"}},\"title\":\"jsdtest\",\"id\":\"jsdtest\",\"updated\":\"Jul 27, 2012\",\"author\":\"jsdelfino\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"SMS send service\",\"id\":\"twsms\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"boao\",\"id\":\"boao\",\"updated\":\"2012-10-12T12:06:59+00:00\",\"author\":\"jsdelfino\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"An empty test app\",\"id\":\"test\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"An empty app template\",\"id\":\"new\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"nearme\",\"id\":\"nearme\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"nearme2\",\"id\":\"nearme2\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Our photos of an event\",\"id\":\"ourphotos\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"My online store\",\"id\":\"shoppingcart\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Slice\",\"id\":\"slice\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test animation components\",\"id\":\"testanimation\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test database components\",\"id\":\"testdb\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test event components\",\"id\":\"testevents\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test social components\",\"id\":\"testsocial\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test logic components\",\"id\":\"testlogic\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test search components\",\"id\":\"testsearch\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test HTTP components\",\"id\":\"testhttp\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test text processing components\",\"id\":\"testtext\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test URL components\",\"id\":\"testurl\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test values and lists\",\"id\":\"testvalues\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test widgets\",\"id\":\"testwidgets\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test more widgets\",\"id\":\"testwidgets2\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Test HTML generator components\",\"id\":\"testwidgets3\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"test9\",\"id\":\"test9\",\"updated\":\"2012-09-25T06:17:18+00:00\",\"author\":\"jsdelfino\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"SMS send service\",\"id\":\"twsms\",\"updated\":\"Jan 01, 2012\",\"author\":\"admin@example.com\"},{\"content\":{\"stats\":{\"description\":\"Sample app\"}},\"title\":\"Check my public social data\",\"id\":\"me360\",\"updated\":\"Apr 28, 2012\",\"author\":\"admin@example.com\"}]}}"; + +} +} + diff --git a/sca-cpp/trunk/modules/json/json.hpp b/sca-cpp/trunk/modules/json/json.hpp index 85579c1b28..b3545476a1 100644 --- a/sca-cpp/trunk/modules/json/json.hpp +++ b/sca-cpp/trunk/modules/json/json.hpp @@ -31,50 +31,243 @@ #include "value.hpp" #include "element.hpp" #include "monad.hpp" -#include "../js/eval.hpp" +#include "jansson.h" namespace tuscany { namespace json { /** - * Return true if a list of strings contains a JSON document. + * Customize JSON memory allocation functions. */ -const bool isJSON(const list& ls) { - if (isNil(ls)) - return false; - const string s = substr(car(ls), 0, 1); - return s == "[" || s == "{"; +inline void* jsonAlloc(size_t size) { + return gc_pool_malloc(size); } +inline void jsonFree(void *ptr) { + return gc_pool_free(ptr); +} + +class JSONAllocFuncs { +public: + inline JSONAllocFuncs() { + json_set_alloc_funcs(jsonAlloc, jsonFree); + } +} jsonAllocFuncs; + /** - * Consumes JSON strings and populates a JS object. + * Returns true if a list represents a JS array. */ -failable consume(JSONParser* parser, const list& ilist, const js::JSContext& cx) { - if (isNil(ilist)) +inline const bool isJSArray(const list& l) { + if(isNil(l)) return true; - JSString* jstr = JS_NewStringCopyZ(cx, c_str(car(ilist))); - if(!JS_ConsumeJSONText(cx, parser, JS_GetStringCharsZ(cx, jstr), (uint32)JS_GetStringLength(jstr))) - return mkfailure("JS_ConsumeJSONText failed"); - return consume(parser, cdr(ilist), cx); + const value v = car(l); + if (isSymbol(v)) + return false; + if(isList(v)) { + if(!isNil((list)v) && isSymbol(car(v))) + return false; + } + return true; } /** - * Convert a list of strings representing a JSON document to a list of values. + * Converts a JS array to values. */ -const failable > readJSON(const list& ilist, const js::JSContext& cx) { - jsval val; - JSONParser* parser = JS_BeginJSONParse(cx, &val); - if(parser == NULL) - return mkfailure >("JS_BeginJSONParse failed"); +inline const list jsArrayToValues(const list& listSoFar, json_t* const a, const int i) { + const value jsValToValue(json_t* const jsv); + + if (i < 0) + return listSoFar; + json_t* const jsv = json_array_get(a, i); + const value val = jsValToValue(jsv); + return jsArrayToValues(cons(val, listSoFar), a, i - 1); +} - const failable consumed = consume(parser, ilist, cx); +/** + * Converts JS properties to values. + */ +inline const list jsPropertiesToValues(const list& propertiesSoFar, json_t* const o, void* i) { + const value jsValToValue(json_t* const jsv); - if(!JS_FinishJSONParse(cx, parser, JSVAL_NULL)) - return mkfailure >("JS_FinishJSONParse failed"); - if(!hasContent(consumed)) - return mkfailure >(consumed); + if (i == NULL) + return reverse(propertiesSoFar); + const char* const name = json_object_iter_key(i); + json_t* const jsv = json_object_iter_value(i); + const value val = jsValToValue(jsv); + if (isNil(val) && !isList(val)) + return jsPropertiesToValues(cons (mklist (element, c_str(name), val), propertiesSoFar), o, json_object_iter_next(o, i)); + if (substr(name, 0, 1) == atsign) + return jsPropertiesToValues(cons(mklist(attribute, c_str(substr(name, 1)), val), propertiesSoFar), o, json_object_iter_next(o, i)); + if (isList(val) && !isJSArray(val)) + return jsPropertiesToValues(cons(cons(element, cons(c_str(name), list(val))), propertiesSoFar), o, json_object_iter_next(o, i)); + return jsPropertiesToValues(cons (mklist (element, c_str(name), val), propertiesSoFar), o, json_object_iter_next(o, i)); +} + +/** + * Converts a JS val to a value. + */ +const value jsValToValue(json_t* const jsv) { + switch(json_typeof(jsv)) { + case json_type::JSON_STRING: { + const string svalue = string(json_string_value(jsv)); + return value(svalue); + } + case json_type::JSON_TRUE: { + return value((bool)true); + } + case json_type::JSON_FALSE: { + return value((bool)false); + } + case json_type::JSON_REAL: { + return value((double)json_real_value(jsv)); + } + case json_type::JSON_INTEGER: { + return value((double)json_integer_value(jsv)); + } + case json_type::JSON_NULL: { + return nilValue; + } + case json_type::JSON_ARRAY: { + const int i = (int)json_array_size(jsv) - 1; + const value v = jsArrayToValues(list (), jsv, i); + return v; + } + case json_type::JSON_OBJECT: { + void* const i = json_object_iter(jsv); + const value v = jsPropertiesToValues(list (), jsv, i); + return v; + } + default: { + return nilValue; + } + } +} - return list(js::jsValToValue(val, cx)); +/** + * Converts a list of values to JS array elements. + */ +inline json_t* const valuesToJSElements(json_t* const a, const list& l) { + json_t* const valueToJSVal(const value& val); + if (isNil(l)) + return a; + json_t* const v = valueToJSVal(car(l)); + json_array_append(a, v); + return valuesToJSElements(a, cdr(l)); +} + +/** + * Converts a value to a JS val. + */ +inline json_t* const valueToJSVal(const value& val) { + json_t* const valuesToJSProperties(json_t* const o, const list& l); + + switch(type(val)) { + case value::String: { + return json_string(c_str((string)val)); + } + case value::Symbol: { + return json_string(c_str((string)val)); + } + case value::Bool: { + return json_boolean((bool)val); + } + case value::Number: { + const double d = (double)val; + if (((double)((json_int_t)d)) == d) + return json_integer((json_int_t)d); + else + return json_real(d); + } + case value::List: { + if (isJSArray(val)) { + json_t* const a = json_array(); + return valuesToJSElements(a, val); + } + json_t* const c = json_object(); + return valuesToJSProperties(c, val); + } + case value::Nil: { + return json_null(); + } + default: { + return json_null(); + } + } +} + +/** + * Converts a list of values to JS properties. + */ +inline json_t* const valuesToJSProperties(json_t* const o, const list& l) { + if (isNil(l)) + return o; + + // Write an attribute + const value token(car(l)); + + if (isTaggedList(token, attribute)) { + json_t* const v = valueToJSVal(attributeValue(token)); + json_object_set(o, c_str(atsign + string(attributeName(token))), v); + + } else if (isTaggedList(token, element)) { + + // Write the value of an element + if (elementHasValue(token)) { + json_t* const v = valueToJSVal(elementValue(token)); + json_object_set(o, c_str(string(elementName(token))), v); + + } else { + + // Write a parent element + json_t* const c = json_object(); + json_object_set(o, c_str(string(elementName(token))), c); + + // Write its children + valuesToJSProperties(c, elementChildren(token)); + } + } + + // Go on + return valuesToJSProperties(o, cdr(l)); +} + +/** + * Return true if a list of strings contains a JSON document. + */ +inline const bool isJSON(const list& ls) { + if (isNil(ls)) + return false; + const string s = substr(car(ls), 0, 1); + return s == "[" || s == "{"; +} + + /** + * Convert a list of strings representing a JSON document to a list of elements. + */ +inline const failable > readElements(const list& ilist) { + ostringstream os; + write(ilist, os); + json_error_t e; + json_t* const val = json_loads(c_str(str(os)), 0, &e); + if(val == NULL) + return mkfailure >(string("json_loads failed: ") + string(e.text)); + return list(jsValToValue(val)); +} + +/** + * Convert a list of strings representing a JSON document to a value + */ +inline const failable readValue(const list& ilist) { + ostringstream os; + write(ilist, os); + json_error_t e; + json_t* const jv = json_loads(c_str(str(os)), JSON_DECODE_ANY, &e); + if(jv == NULL) + return mkfailure(string("json_loads failed: ") + string(e.text)); + const value val = jsValToValue(jv); + if (!isList(val)) + return val; + return (value)elementsToValues(val); } /** @@ -82,47 +275,68 @@ const failable > readJSON(const list& ilist, const js::JSCon */ template class WriteContext { public: - WriteContext(const lambda& reduce, const R& accum, const js::JSContext& cx) : cx(cx), reduce(reduce), accum(accum) { + inline WriteContext(const lambda& reduce, const R& accum) : reduce(reduce), accum(accum) { } - const js::JSContext& cx; - const lambda reduce; - R accum; + + const lambda reduce; + gc_mutable_ref accum; }; /** - * Called by JS_Stringify to write JSON out. + * Called by dump_callback to write JSON out. */ -template JSBool writeCallback(const jschar *buf, uint32 len, void *data) { - WriteContext& wcx = *(static_cast*> (data)); - JSString* jstr = JS_NewUCStringCopyN(wcx.cx, buf, len); - char* cstr = JS_EncodeString(wcx.cx, jstr); - const string str(cstr, JS_GetStringLength(jstr)); - JS_free(wcx.cx, cstr); +template inline int writeCallback(const char *buf, size_t len, void *data) { + WriteContext& wcx = *(WriteContext*)data; + const string str(buf, len); wcx.accum = wcx.reduce(str, wcx.accum); - return JS_TRUE; + return 0; } /** - * Convert a list of values to a JSON document. + * Convert a value to a JSON document. */ -template const failable writeJSON(const lambda& reduce, const R& initial, const list& l, const js::JSContext& cx) { - jsval val; - if (js::isJSArray(l)) - val = OBJECT_TO_JSVAL(valuesToJSElements(JS_NewArrayObject(cx, 0, NULL), l, 0, cx)); - else - val = OBJECT_TO_JSVAL(valuesToJSProperties(JS_NewObject(cx, NULL, NULL, NULL), l, cx)); +template inline const failable writeValue(const lambda& reduce, const R& initial, const list& l) { + json_t* const val = valueToJSVal(l); + WriteContext wcx(reduce, initial); + if (json_dump_callback(val, writeCallback, &wcx, JSON_COMPACT | JSON_ENSURE_ASCII | JSON_PRESERVE_ORDER | JSON_ENCODE_ANY) == -1) + return mkfailure("json_dump_callback failed"); + return (R)wcx.accum; +} - WriteContext wcx(reduce, initial, cx); - if (!JS_Stringify(cx, &val, NULL, INT_TO_JSVAL(1), writeCallback, &wcx)) - return mkfailure("JS_Stringify failed"); - return wcx.accum; +/** + * Convert a list of elements to a JSON document. + */ +template inline const failable writeElements(const lambda& reduce, const R& initial, const list& l) { + json_t* const val = isJSArray(l)? valuesToJSElements(::json_array(), l) : valuesToJSProperties(::json_object(), l); + + WriteContext wcx(reduce, initial); + if (json_dump_callback(val, writeCallback, &wcx, JSON_COMPACT | JSON_ENSURE_ASCII | JSON_PRESERVE_ORDER | JSON_ENCODE_ANY) == -1) + return mkfailure("json_dump_callback failed"); + return (R)wcx.accum; } /** - * Convert a list of values to a list of strings representing a JSON document. + * Convert a list of elements to a list of strings representing a JSON document. */ -const failable > writeJSON(const list& l, const js::JSContext& cx) { - const failable > ls = writeJSON>(rcons, list(), valuesToElements(elementsToValues(l)), cx); +inline const failable > writeElements(const list& l) { + const failable > ls = writeElements>(rcons, list(), valuesToElements(elementsToValues(l))); + if (!hasContent(ls)) + return ls; + return reverse(list(content(ls))); +} + +/** + * Convert a value to a list of strings representing a JSON document. + */ +inline const failable > writeValue(const value& v) { + if (!isList(v)) { + const failable > ls = writeValue>(rcons, list(), v); + if (!hasContent(ls)) + return ls; + return reverse(list(content(ls))); + } + + const failable > ls = writeElements>(rcons, list(), valuesToElements(elementsToValues(valuesToElements(v)))); if (!hasContent(ls)) return ls; return reverse(list(content(ls))); @@ -131,44 +345,37 @@ const failable > writeJSON(const list& l, const js::JSContex /** * Convert a list of function + params to a JSON-RPC request. */ -const failable > jsonRequest(const value& id, const value& func, const value& params, js::JSContext& cx) { +inline const failable > jsonRequest(const value& id, const value& func, const value& params) { const list r = mklist(mklist("id", id), mklist("method", string(func)), mklist("params", params)); - return writeJSON(valuesToElements(r), cx); + return writeElements(valuesToElements(r)); } /** * Convert a value to a JSON-RPC result. */ -const failable > jsonResult(const value& id, const value& val, js::JSContext& cx) { - return writeJSON(valuesToElements(mklist(mklist("id", id), mklist("result", val))), cx); +inline const failable > jsonResult(const value& id, const value& val) { + return writeElements(valuesToElements(mklist(mklist("id", id), mklist("result", val)))); } /** * Convert a JSON-RPC result to a value. */ -const failable jsonResultValue(const list& s, js::JSContext& cx) { - const failable > jsres = json::readJSON(s, cx); +inline const failable jsonResultValue(const list& s) { + const failable jsres = json::readValue(s); if (!hasContent(jsres)) return mkfailure(jsres); - const list rval(cadr(elementsToValues(content(jsres)))); + const list rval(cadr(content(jsres))); const value val = cadr(rval); - if (isList(val) && !js::isJSArray(val)) + if (isList(val) && !isJSArray(val)) return value(mklist(val)); return val; } -/** - * Convert a JSON payload to a list of values. - */ -const list jsonValues(const list& e) { - return elementsToValues(e); -} - /** * Return a portable function name from a JSON-RPC function name. * Strip the ".", "system." and "Service." prefixes added by some JSON-RPC clients. */ -const string funcName(const string& f) { +inline const string funcName(const string& f) { if (length(f) > 1 && find(f, ".", 0) == 0) return c_str(f) + 1; if (length(f) > 7 && find(f, "system.", 0) == 0) @@ -182,9 +389,9 @@ const string funcName(const string& f) { * Returns a list of param values other than the id and method args from a list * of key value pairs. */ -const list queryParams(const list >& a) { +inline const list queryParams(const list >& a) { if (isNil(a)) - return list(); + return nilListValue; const list p = car(a); if (car(p) == value("id") || car(p) == value("method")) return queryParams(cdr(a)); diff --git a/sca-cpp/trunk/modules/scheme/json-value.cpp b/sca-cpp/trunk/modules/scheme/json-value.cpp index 4bdf8bd37f..b5c1c25302 100644 --- a/sca-cpp/trunk/modules/scheme/json-value.cpp +++ b/sca-cpp/trunk/modules/scheme/json-value.cpp @@ -32,14 +32,13 @@ namespace tuscany { namespace scheme { -int jsonValue() { - const js::JSContext cx; - const failable > lv = json::readJSON(streamList(cin), cx); - if (!hasContent(lv)) { - cerr << reason(lv) << " : " << rcode(lv); +const int jsonValue() { + const failable v = json::readValue(streamList(cin)); + if (!hasContent(v)) { + cerr << reason(v) << " : " << rcode(v); return 1; } - cout << writeValue(content(lv)); + write(content(writeValue(content(v))), cout); return 0; } diff --git a/sca-cpp/trunk/modules/scheme/value-json.cpp b/sca-cpp/trunk/modules/scheme/value-json.cpp index a8c875fcc8..732b73d2e3 100644 --- a/sca-cpp/trunk/modules/scheme/value-json.cpp +++ b/sca-cpp/trunk/modules/scheme/value-json.cpp @@ -32,9 +32,8 @@ namespace tuscany { namespace scheme { -int valueJSON() { - const js::JSContext cx; - failable > s = json::writeJSON(readValue(cin), cx); +const int valueJSON() { + const failable > s = json::writeValue(content(readValue(cin))); if (!hasContent(s)) { cerr << reason(s) << " : " << rcode(s); return 1; diff --git a/sca-cpp/trunk/patches/jansson-2.4.patch b/sca-cpp/trunk/patches/jansson-2.4.patch new file mode 100644 index 0000000000..006d69d8c3 --- /dev/null +++ b/sca-cpp/trunk/patches/jansson-2.4.patch @@ -0,0 +1,11 @@ +--- src/strconv.c ++++ src/strconv.c +@@ -79,7 +79,7 @@ + char *start, *end; + size_t length; + +- ret = snprintf(buffer, size, "%.17g", value); ++ ret = snprintf(buffer, size, "%g", value); + if(ret < 0) + return -1; + diff --git a/sca-cpp/trunk/unmaintained/README b/sca-cpp/trunk/unmaintained/README new file mode 100644 index 0000000000..22c0f8bfc2 --- /dev/null +++ b/sca-cpp/trunk/unmaintained/README @@ -0,0 +1,3 @@ +Apache Tuscany SCA Unmaintained Modules +======================================= + diff --git a/sca-cpp/trunk/unmaintained/modules/js/Makefile.am b/sca-cpp/trunk/unmaintained/modules/js/Makefile.am new file mode 100644 index 0000000000..96fddb0a40 --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/js/Makefile.am @@ -0,0 +1,31 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + + +incl_HEADERS = *.hpp +incldir = $(prefix)/include/modules/js + +moddir = $(prefix)/modules/js + +js_test_SOURCES = js-test.cpp +js_test_LDFLAGS = -ljansson + +js_shell_SOURCES = js-shell.cpp +js_shell_LDFLAGS = -ljansson + +mod_PROGRAMS = js-shell + diff --git a/sca-cpp/trunk/unmaintained/modules/js/configure.ac b/sca-cpp/trunk/unmaintained/modules/js/configure.ac new file mode 100644 index 0000000000..6d46dd90d4 --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/js/configure.ac @@ -0,0 +1,63 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Enable Javascript support. +AC_MSG_CHECKING([whether to enable Javascript support]) +AC_ARG_ENABLE(js, [AS_HELP_STRING([--enable-js], [enable Javascript support [default=no]])], +[ case "${enableval}" in + no) + AC_MSG_RESULT(no) + ;; + *) + AC_MSG_RESULT(yes) + want_js=true + ;; + esac ], +[ + AC_MSG_RESULT(no) +]) +if test "${want_js}" = "true"; then + + # Configure path to libmozjs includes and lib. + AC_MSG_CHECKING([for js-include]) + AC_ARG_WITH([js-include], [AC_HELP_STRING([--with-js-include=PATH], [path to installed SpiderMonkey include dir + [default=/usr/include]])], [ + JS_INCLUDE="${withval}" + AC_MSG_RESULT("${withval}") + ], [ + JS_INCLUDE="/usr/include" + AC_MSG_RESULT(/usr/include) + ]) + AC_MSG_CHECKING([for js-lib]) + AC_ARG_WITH([js-lib], [AC_HELP_STRING([--with-js-lib=PATH], [path to installed SpiderMonkey lib dir [default=/usr/lib]])], [ + JS_LIB="${withval}" + AC_MSG_RESULT("${withval}") + ], [ + JS_LIB="/usr/lib" + AC_MSG_RESULT(/usr/lib) + ]) + AC_SUBST(JS_INCLUDE) + AC_SUBST(JS_LIB) + LIBS="-L${JS_LIB} ${defaultlibs}" + AC_CHECK_LIB([mozjs], [JS_NewContext], [], [AC_MSG_ERROR([couldn't find a suitable libmozjs, use --with-js-lib=PATH])]) + AM_CONDITIONAL([WANT_JS], true) + AC_DEFINE([WANT_JS], 1, [enable Javascript support]) + +else + AM_CONDITIONAL([WANT_JS], false) +fi + diff --git a/sca-cpp/trunk/unmaintained/modules/js/eval.hpp b/sca-cpp/trunk/unmaintained/modules/js/eval.hpp new file mode 100644 index 0000000000..47957e8cdd --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/js/eval.hpp @@ -0,0 +1,407 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* $Rev$ $Date$ */ + +#ifndef tuscany_js_hpp +#define tuscany_js_hpp + +/** + * Javascript evaluation functions. + */ + +#define XP_UNIX +#ifdef WANT_MAINTAINER_WARNINGS +#pragma GCC diagnostic ignored "-Wunused-parameter" +#pragma GCC diagnostic ignored "-Wsign-compare" +#pragma GCC diagnostic ignored "-Wredundant-decls" +#endif +#include "jsapi.h" +#ifdef WANT_MAINTAINER_WARNINGS +#pragma GCC diagnostic warning "-Wunused-parameter" +#pragma GCC diagnostic warning "-Wsign-compare" +#pragma GCC diagnostic warning "-Wredundant-decls" +#endif +#include "string.hpp" +#include "list.hpp" +#include "value.hpp" +#include "element.hpp" +#include "monad.hpp" +#include "parallel.hpp" + +namespace tuscany { +namespace js { + +/** + * Report Javascript errors. + */ +void reportError(unused ::JSContext *cx, const char *message, JSErrorReport *report) { + cfailure << (const char*)(report->filename? report->filename : "") << ":" + << (int)report->lineno << ":" << message << endl; +} + +/** + * Encapsulates a JavaScript runtime. Shared by multiple threads in + * a process. + */ +class JSRuntime { +public: + JSRuntime() { + // Create JS runtime + debug("js::jsruntime"); + pthread_mutex_init(&mutex, NULL); +#ifdef WANT_THREADS + rt = JS_NewRuntime(32L * 1024L * 1024L); +#else + rt = JS_NewRuntime(8L * 1024L * 1024L); +#endif + if(rt == NULL) + cleanup(); + } + + operator ::JSRuntime*() const { + return rt; + } + + ~JSRuntime() { + debug("js::~jsruntime"); + } + + bool lock() { + //pthread_mutex_lock(&mutex); + return true; + } + + bool unlock() { + //pthread_mutex_unlock(&mutex); + return true; + } + +private: + bool cleanup() { + if(rt != NULL) { + JS_DestroyRuntime(rt); + rt = NULL; + } + JS_ShutDown(); + return true; + } + + pthread_mutex_t mutex; + ::JSRuntime* rt; +} jsRuntime; + +JSClass jsGlobalClass = { "global", JSCLASS_GLOBAL_FLAGS, + JS_PropertyStub, JS_PropertyStub, + JS_PropertyStub, JS_StrictPropertyStub, + JS_EnumerateStub, JS_ResolveStub, + JS_ConvertStub, JS_FinalizeStub, + JSCLASS_NO_OPTIONAL_MEMBERS }; + +/** + * Represents a JavaScript context. Maintains one context per thread. + */ +#ifdef WANT_THREADS +perthread_ptr jsContext; +#else +::JSContext* jsContext = NULL; +#endif + +class JSContext { +public: + JSContext() { + debug("js::jscontext"); + jsRuntime.lock(); + + // Create JS context if necessary + if (jsContext != NULL) { + cx = jsContext; + debug(cx, "js::jscontext::beginRequest::cx"); + JS_SetContextThread(cx); + JS_BeginRequest(cx); + return; + } + + debug("js::jscontext::newcontext"); + cx = JS_NewContext(jsRuntime, 8192); + if(cx == NULL) { + jsRuntime.unlock(); + return; + } + debug(cx, "js::jscontext::beginRequest::cx"); + JS_SetContextThread(cx); + JS_BeginRequest(cx); + + JS_SetOptions(cx, JSOPTION_VAROBJFIX /*| JSOPTION_JIT | JSOPTION_METHODJIT*/); + JS_SetVersion(cx, JSVERSION_LATEST); + JS_SetErrorReporter(cx, reportError); + JS_SetGCZeal(cx, 0); + + // Create global JS object + global = JS_NewCompartmentAndGlobalObject(cx, &jsGlobalClass, NULL); + if(global == NULL) { + JS_DestroyContext(cx); + cleanup(); + return; + } + JS_SetGlobalObject(cx, global); + + // Populate global object with the standard globals, like Object and Array + if(!JS_InitStandardClasses(cx, global)) { + JS_DestroyContext(cx); + cleanup(); + return; + } + + jsContext = cx; + } + + ~JSContext() { + debug("js::~jscontext"); + cleanup(); + } + + operator ::JSContext*() const { + return cx; + } + + JSObject* getGlobal() const { + return global; + } + +private: + bool cleanup() { + if(cx != NULL) { + if (cx != jsContext) { + debug(cx, "js::jscontext::endrequest::cx"); + JS_EndRequest(cx); + JS_ClearContextThread(cx); + debug(cx, "js::jscontext::destroycontext::cx"); + JS_DestroyContext(cx); + jsContext = NULL; + } else { + //debug(cx, "js::jscontext::maybegc::cx"); + //JS_MaybeGC(cx); + debug(cx, "js::jscontext::endrequest::cx"); + JS_EndRequest(cx); + JS_ClearContextThread(cx); + } + cx = NULL; + } + jsRuntime.unlock(); + return true; + } + + ::JSContext* cx; + JSObject* global; +}; + +/** + * Returns true if a list represents a JS array. + */ +const bool isJSArray(const list& l) { + if(isNil(l)) + return true; + const value v = car(l); + if (isSymbol(v)) + return false; + if(isList(v)) { + if(!isNil((list)v) && isSymbol(car(v))) + return false; + } + return true; +} + +/** + * Converts JS properties to values. + */ +const list jsPropertiesToValues(const list& propertiesSoFar, JSObject* o, JSObject* i, const js::JSContext& cx) { + + const value jsValToValue(const jsval& jsv, const js::JSContext& cx); + + jsid id; + if(!JS_NextProperty(cx, i, &id)) + return propertiesSoFar; + jsval idv; + JS_IdToValue(cx, id, &idv); + if (idv == JSVAL_VOID) + return propertiesSoFar; + + jsval jsv; + if(!JS_GetPropertyById(cx, o, id, &jsv)) + return propertiesSoFar; + const value val = jsValToValue(jsv, cx); + + if(JSVAL_IS_STRING(idv)) { + char* cname = JS_EncodeString(cx, JSVAL_TO_STRING(idv)); + const string name = cname; + JS_free(cx, cname); + if (isNil(val) && !isList(val)) + return jsPropertiesToValues(cons (mklist (element, c_str(name), val), propertiesSoFar), o, i, cx); + //return jsPropertiesToValues(propertiesSoFar, o, i, cx); + if (substr(name, 0, 1) == atsign) + return jsPropertiesToValues(cons(mklist(attribute, c_str(substr(name, 1)), val), propertiesSoFar), o, i, cx); + if (isList(val) && !isJSArray(val)) + return jsPropertiesToValues(cons(cons(element, cons(c_str(name), list(val))), propertiesSoFar), o, i, cx); + return jsPropertiesToValues(cons (mklist (element, c_str(name), val), propertiesSoFar), o, i, cx); + } + return jsPropertiesToValues(cons(val, propertiesSoFar), o, i, cx); +} + +/** + * Converts a JS val to a value. + */ +const value jsValToValue(const jsval& jsv, const js::JSContext& cx) { + switch(JS_TypeOfValue(cx, jsv)) { + case JSTYPE_STRING: { + char* cvalue = JS_EncodeString(cx, JSVAL_TO_STRING(jsv)); + const string svalue = string(cvalue); + JS_free(cx, cvalue); + return value(svalue); + } + case JSTYPE_BOOLEAN: { + return value((bool)JSVAL_TO_BOOLEAN(jsv)); + } + case JSTYPE_NUMBER: { + double jsd; + JS_ValueToNumber(cx, jsv, &jsd); + return value((double)jsd); + } + case JSTYPE_OBJECT: { + JSObject* o = JSVAL_TO_OBJECT(jsv); + if (o == NULL) + return value(); + JSObject* i = JS_NewPropertyIterator(cx, o); + if(i == NULL) + return value(list ()); + const value pv = jsPropertiesToValues(list (), o, i, cx); + return pv; + } + default: { + return value(); + } + } +} + +/** + * Converts a list of values to JS array elements. + */ +JSObject* valuesToJSElements(JSObject* a, const list& l, int i, const js::JSContext& cx) { + const jsval valueToJSVal(const value& val, const js::JSContext& cx); + if (isNil(l)) + return a; + jsval pv = valueToJSVal(car(l), cx); + JS_SetElement(cx, a, i, &pv); + return valuesToJSElements(a, cdr(l), ++i, cx); +} + +/** + * Converts a value to a JS val. + */ +const jsval valueToJSVal(const value& val, const js::JSContext& cx) { + JSObject* valuesToJSProperties(JSObject* o, const list& l, const js::JSContext& cx); + + switch(type(val)) { + case value::String: { + return STRING_TO_JSVAL(JS_NewStringCopyZ(cx, c_str((string)val))); + } + case value::Symbol: { + return STRING_TO_JSVAL(JS_NewStringCopyZ(cx, c_str((string)val))); + } + case value::Bool: { + return BOOLEAN_TO_JSVAL((bool)val); + } + case value::Number: { + jsval jsv = DOUBLE_TO_JSVAL((double)val); + return jsv; + } + case value::List: { + if (isJSArray(val)) { + JSObject* array = JS_NewArrayObject(cx, 0, NULL); + //debug(array, "js::valueToJSVal::new::array"); + return OBJECT_TO_JSVAL(valuesToJSElements(array, val, 0, cx)); + } + JSObject* child = JS_NewObject(cx, NULL, NULL, NULL); + //debug(child, "js::valueToJSVal::new::child"); + return OBJECT_TO_JSVAL(valuesToJSProperties(child, val, cx)); + } + case value::Nil: { + return JSVAL_NULL; + } + default: { + return JSVAL_VOID; + } + } +} + +/** + * Converts a list of values to JS properties. + */ +JSObject* valuesToJSProperties(JSObject* o, const list& l, const js::JSContext& cx) { + if (isNil(l)) + return o; + + // Write an attribute + const value token(car(l)); + + if (isTaggedList(token, attribute)) { + jsval pv = valueToJSVal(attributeValue(token), cx); + JS_SetProperty(cx, o, c_str(atsign + string(attributeName(token))), &pv); + + } else if (isTaggedList(token, element)) { + + // Write the value of an element + if (elementHasValue(token)) { + jsval pv = valueToJSVal(elementValue(token), cx); + JS_SetProperty(cx, o, c_str(string(elementName(token))), &pv); + + } else { + + // Write a parent element + JSObject* child = JS_NewObject(cx, NULL, NULL, NULL); + //debug(child, "js::valuesToJSProperties::new::child"); + jsval pv = OBJECT_TO_JSVAL(child); + JS_SetProperty(cx, o, c_str(string(elementName(token))), &pv); + + // Write its children + valuesToJSProperties(child, elementChildren(token), cx); + } + } + + // Go on + return valuesToJSProperties(o, cdr(l), cx); +} + +/** + * Evaluate a script provided as a string. + */ +const failable evalScript(const string& s) { + js::JSContext cx; + jsval rval; + JSBool rc = JS_EvaluateScript(cx, cx.getGlobal(), c_str(s), (unsigned int)length(s), "eval.js", 1, &rval); + if (rc != JS_TRUE) { + return mkfailure("Couldn't evaluate Javascript script."); + } + return jsValToValue(rval, cx); +} + +} +} + +#endif /* tuscany_js_hpp */ diff --git a/sca-cpp/trunk/unmaintained/modules/js/js-shell.cpp b/sca-cpp/trunk/unmaintained/modules/js/js-shell.cpp new file mode 100644 index 0000000000..ee0fa89b31 --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/js/js-shell.cpp @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* $Rev$ $Date$ */ + +/** + * Evaluate a JavaScript script. + */ + +#include +#include "stream.hpp" +#include "fstream.hpp" +#include "string.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace js { + +bool eval() { + ostringstream os; + for(;;) { + int c = cin.get(); + if (c == -1) + break; + os << (char)c; + } + failable v = evalScript(str(os)); + assert(hasContent(v)); + cout << v; + return true; +} + +} +} + +int main() { + tuscany::js::eval(); + return 0; +} diff --git a/sca-cpp/trunk/unmaintained/modules/js/js-test.cpp b/sca-cpp/trunk/unmaintained/modules/js/js-test.cpp new file mode 100644 index 0000000000..1940ce706c --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/js/js-test.cpp @@ -0,0 +1,75 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* $Rev$ $Date$ */ + +/** + * Test JavaScript evaluation functions. + */ + +#include +#include "stream.hpp" +#include "string.hpp" +#include "parallel.hpp" +#include "perf.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace js { + +bool testEval() { + gc_scoped_pool pool; + failable v = evalScript("(function testJSON(n){ return JSON.parse(JSON.stringify(n)) })(5)"); + assert(hasContent(v)); + assert(content(v) == value(5)); + return true; +} + +struct evalLoop { + evalLoop() { + } + const bool operator()() const { + failable v = evalScript("(function testJSON(n){ return JSON.parse(JSON.stringify(n)) })(5)"); + assert(hasContent(v)); + assert(content(v) == value(5)); + return true; + } +}; + +const bool testEvalPerf() { + gc_scoped_pool pool; + const lambda el = evalLoop(); + cout << "JS eval test " << time(el, 5, 5) << " ms" << endl; + return true; +} + +} +} + +int main() { + tuscany::gc_scoped_pool p; + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::js::testEval(); + tuscany::js::testEvalPerf(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sca-cpp/trunk/unmaintained/modules/js/macos-install b/sca-cpp/trunk/unmaintained/modules/js/macos-install new file mode 100755 index 0000000000..615b52f61b --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/js/macos-install @@ -0,0 +1,47 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Build Mozilla Portable Runtime +curl -OL http://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.8/src/nspr-4.8.8.tar.gz +tar xzf nspr-4.8.8.tar.gz +cd nspr-4.8.8/mozilla/nsprpub +./configure --prefix=$build/nspr-4.8.8-bin --enable-64bit +make +make install +install_name_tool -id $build/nspr-4.8.8-bin/lib/libnspr4.dylib $build/nspr-4.8.8-bin/lib/libnspr4.dylib +install_name_tool -id $build/nspr-4.8.8-bin/lib/libplc4.dylib $build/nspr-4.8.8-bin/lib/libplc4.dylib +install_name_tool -id $build/nspr-4.8.8-bin/lib/libplds4.dylib $build/nspr-4.8.8-bin/lib/libplds4.dylib +install_name_tool -change @executable_path/libnspr4.dylib $build/nspr-4.8.8-bin/lib/libnspr4.dylib $build/nspr-4.8.8-bin/lib/libplc4.dylib +install_name_tool -change @executable_path/libnspr4.dylib $build/nspr-4.8.8-bin/lib/libnspr4.dylib $build/nspr-4.8.8-bin/lib/libplds4.dylib +if [ "$?" != "0" ]; then + exit $? +fi +cd $build + +# Build SpiderMonkey +curl -OL http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz +tar xzf js185-1.0.0.tar.gz +cd js-1.8.5/js/src +./configure --prefix=$build/js-1.8.5-bin --enable-threadsafe --with-system-nspr --with-nspr-prefix=$build/nspr-4.8.8-bin +make +make install +ln -s $build/js-1.8.5-bin/lib/libmozjs185.dylib $build/js-1.8.5-bin/lib/libmozjs.dylib +if [ "$?" != "0" ]; then + exit $? +fi +cd $build + diff --git a/sca-cpp/trunk/unmaintained/modules/js/ubuntu-install b/sca-cpp/trunk/unmaintained/modules/js/ubuntu-install new file mode 100755 index 0000000000..9b46c16348 --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/js/ubuntu-install @@ -0,0 +1,48 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# Build Mozilla Portable Runtime +curl -OL http://ftp.mozilla.org/pub/mozilla.org/nspr/releases/v4.8.8/src/nspr-4.8.8.tar.gz +tar xzf nspr-4.8.8.tar.gz +cd nspr-4.8.8/mozilla/nsprpub +./configure --prefix=$build/nspr-4.8.8-bin --enable-64bit +make +make install +if [ "$?" != "0" ]; then + exit $? +fi +cd $build + +# Build SpiderMonkey +sudo apt-get -y install zip unzip +if [ "$?" != "0" ]; then + exit $? +fi +curl -OL http://ftp.mozilla.org/pub/mozilla.org/js/js185-1.0.0.tar.gz +tar xzf js185-1.0.0.tar.gz +cd js-1.8.5/js/src +export LD_RUN_PATH=$build/nspr-4.8.8-bin/lib +./configure --prefix=$build/js-1.8.5-bin --enable-threadsafe --with-system-nspr --with-nspr-prefix=$build/nspr-4.8.8-bin +make +make install +unset LD_RUN_PATH +ln -s $build/js-1.8.5-bin/lib/libmozjs185.so $build/js-1.8.5-bin/lib/libmozjs.so +if [ "$?" != "0" ]; then + exit $? +fi +cd $build + diff --git a/sca-cpp/trunk/unmaintained/modules/json/Makefile.am b/sca-cpp/trunk/unmaintained/modules/json/Makefile.am new file mode 100644 index 0000000000..70352f047b --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/json/Makefile.am @@ -0,0 +1,29 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +if WANT_JS + +incl_HEADERS = *.hpp +incldir = $(prefix)/include/modules/json + +json_test_SOURCES = json-test.cpp +json_test_LDFLAGS = -lmozjs + +noinst_PROGRAMS = json-test +TESTS = json-test + +endif diff --git a/sca-cpp/trunk/unmaintained/modules/json/json-test.cpp b/sca-cpp/trunk/unmaintained/modules/json/json-test.cpp new file mode 100644 index 0000000000..23cd32682c --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/json/json-test.cpp @@ -0,0 +1,337 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* $Rev$ $Date$ */ + +/** + * Test JSON data conversion functions. + */ + +#include +#include "stream.hpp" +#include "string.hpp" +#include "json.hpp" +#include "parallel.hpp" +#include "perf.hpp" + +namespace tuscany { +namespace json { + +ostream* jsonWriter(const string& s, ostream* os) { + (*os) << s; + return os; +} + +const string jscustomer("{\n" + " \"customer\": {\n" + " \"@name\": \"jdoe\",\n" + " \"address\": {\n" + " \"@city\": \"san francisco\",\n" + " \"@state\": \"ca\"\n" + " },\n" + " \"account\": {\n" + " \"id\": \"1234\",\n" + " \"@balance\": 1000\n" + " }\n" + " }\n" + "}"); + +const string jsphones("{\n" + " \"phones\": [\n" + " \"408-1234\",\n" + " \"650-1234\"\n" + " ],\n" + " \"lastName\": \"test\\u0009tab\",\n" + " \"@firstName\": \"test1\"\n" + "}"); + +const string jsecho("{\n" + " \"ns1:echoString\": {\n" + " \"@xmlns:ns1\": \"http://ws.apache.org/axis2/services/echo\",\n" + " \"text\": \"Hello World!\"\n" + " }\n" + "}"); + +const string jsarray("{\n" + " \"fruit\": [\n" + " \"Apple\",\n" + " \"Orange\"\n" + " ]\n" + "}"); + +bool testJSON() { + gc_scoped_pool pool; + const js::JSContext cx; + + { + const list ad = mklist(mklist(attribute, "city", string("san francisco")), mklist(attribute, "state", string("ca"))); + const list ac = mklist(mklist(element, "id", string("1234")), mklist(attribute, "balance", 1000)); + const list cr = mklist(mklist (attribute, "name", string("jdoe")), cons(element, cons("address", ad)), cons(element, cons("account", ac))); + const list c = mklist(cons(element, cons("customer", cr))); + + ostringstream os; + writeJSON(jsonWriter, &os, c, cx); + assert(str(os) == jscustomer); + } + { + const list phones = mklist (string("408-1234"), string("650-1234")); + const list l = mklist (mklist (element, "phones", phones), mklist (element, "lastName", string("test\ttab")), mklist (attribute, "firstName", string("test1"))); + + ostringstream os; + writeJSON(jsonWriter, &os, l, cx); + assert(str(os) == jsphones); + + istringstream is(str(os)); + const list il = streamList(is); + const list r = content(readJSON(il, cx)); + assert(r == l); + + ostringstream wos; + write(content(writeJSON(r, cx)), wos); + assert(str(wos) == str(os)); + } + { + const list l = mklist(list() + "ns1:echoString" + (list() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (list() + "text" + string("Hello World!"))); + ostringstream wos; + write(content(writeJSON(valuesToElements(l), cx)), wos); + assert(str(wos) == jsecho); + + istringstream is(str(wos)); + const list il = streamList(is); + const list r = elementsToValues(content(readJSON(il, cx))); + assert(r == l); + } + { + const list l = mklist((list() + "fruit" + string("Apple")), (list() + "fruit" + string("Orange"))); + ostringstream wos; + write(content(writeJSON(valuesToElements(l), cx)), wos); + assert(str(wos) == jsarray); + + istringstream is(str(wos)); + const list il = streamList(is); + const list r = elementsToValues(content(readJSON(il, cx))); + const list l2 = mklist(list() + "fruit" + (list() + string("Apple") + string("Orange"))); + assert(r == l2); + } + return true; +} + +const string jsitem("{\n" + " \"id\": 3,\n" + " \"result\": [\n" + " {\n" + " \"price\": \"$2.99\",\n" + " \"name\": \"Apple\"\n" + " },\n" + " {\n" + " \"price\": \"$3.55\",\n" + " \"name\": \"Orange\"\n" + " },\n" + " {\n" + " \"price\": \"$1.55\",\n" + " \"name\": \"Pear\"\n" + " }\n" + " ]\n" + "}"); + +const string jsresult("{\n" + " \"id\": 1,\n" + " \"result\": [\n" + " \"Service.get\",\n" + " \"Service.getTotal\"\n" + " ]\n" + "}"); + +const string jsfeed("{\n" + " \"id\": 1,\n" + " \"result\": [\n" + " \"Sample Feed\",\n" + " \"123456789\",\n" + " [\n" + " \"Item\",\n" + " \"111\",\n" + " {\n" + " \"name\": \"Apple\",\n" + " \"currencyCode\": \"USD\",\n" + " \"currencySymbol\": \"$\",\n" + " \"price\": 2.99\n" + " }\n" + " ],\n" + " [\n" + " \"Item\",\n" + " \"222\",\n" + " {\n" + " \"name\": \"Orange\",\n" + " \"currencyCode\": \"USD\",\n" + " \"currencySymbol\": \"$\",\n" + " \"price\": 3.55\n" + " }\n" + " ],\n" + " [\n" + " \"Item\",\n" + " \"333\",\n" + " {\n" + " \"name\": \"Pear\",\n" + " \"currencyCode\": \"USD\",\n" + " \"currencySymbol\": \"$\",\n" + " \"price\": 1.55\n" + " }\n" + " ]\n" + " ]\n" + "}"); + +const string jsechoreq("{\n" + " \"id\": 1,\n" + " \"method\": \"echo\",\n" + " \"params\": [\n" + " {\n" + " \"ns1:echoString\": {\n" + " \"@xmlns:ns1\": \"http://ws.apache.org/axis2/services/echo\",\n" + " \"text\": \"Hello World!\"\n" + " }\n" + " }\n" + " ]\n" + "}"); + +const string jsechores("{\n" + " \"id\": 1,\n" + " \"result\": {\n" + " \"ns1:echoString\": {\n" + " \"@xmlns:ns1\": \"http://ws.apache.org/axis2/c/samples\",\n" + " \"text\": \"Hello World!\"\n" + " }\n" + " }\n" + "}"); + +bool testJSONRPC() { + gc_scoped_pool pool; + js::JSContext cx; + { + const string lm("{\"id\": 1, \"method\": \"test\", \"params\": []}"); + const list e = content(readJSON(mklist(lm), cx)); + const list v = elementsToValues(e); + assert(assoc("id", v) == mklist("id", 1)); + assert(assoc("method", v) == mklist("method", string("test"))); + assert(assoc("params", v) == mklist("params", list())); + } + { + const string i2 = "{\"id\": 3,\"result\": {\"0\": {\"price\": \"$2.99\",\"name\": \"Apple\"},\"1\": {\"price\": \"$3.55\",\"name\": \"Orange\"},\"2\": {\"price\": \"$1.55\",\"name\": \"Pear\"}}}"; + const list e = content(readJSON(mklist(jsitem), cx)); + const list e2 = content(readJSON(mklist(i2), cx)); + assert(e == e2); + } + { + const list e = content(readJSON(mklist(jsitem), cx)); + ostringstream os; + write(content(writeJSON(e, cx)), os); + assert(str(os) == jsitem); + const list v = elementsToValues(e); + const list r = valuesToElements(v); + assert(r == e); + } + { + const list r = mklist(mklist("id", 1), mklist("result", mklist(string("Service.get"), string("Service.getTotal")))); + const list e = valuesToElements(r); + ostringstream os; + write(content(writeJSON(e, cx)), os); + assert(str(os) == jsresult); + } + { + const list r = content(readJSON(mklist(jsfeed), cx)); + const list v = elementsToValues(r); + const list e = valuesToElements(v); + ostringstream os; + write(content(writeJSON(e, cx)), os); + assert(str(os) == jsfeed); + } + { + const list arg = mklist(list() + "ns1:echoString" + (list() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (list() + "text" + string("Hello World!"))); + const failable > r = jsonRequest(1, "echo", mklist(arg), cx); + ostringstream os; + write(content(r), os); + assert(str(os) == jsechoreq); + + istringstream is(str(os)); + const list il = streamList(is); + const list ir = elementsToValues(content(readJSON(il, cx))); + assert(car(cadr(caddr(ir))) == arg); + } + { + const list res = mklist(list() + "ns1:echoString" + (list() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/c/samples")) + (list() + "text" + string("Hello World!"))); + const failable > r = jsonResult(1, res, cx); + ostringstream os; + write(content(r), os); + assert(str(os) == jsechores); + + istringstream is(str(os)); + const list il = streamList(is); + const list ir = elementsToValues(content(readJSON(il, cx))); + assert(cdr(cadr(ir)) == res); + } + return true; +} + +struct testReadWrite { + testReadWrite() { + } + const bool operator()() const { + gc_scoped_pool pool; + js::JSContext cx; + + const list ad = mklist(mklist(attribute, "city", string("san francisco")), mklist(attribute, "state", string("ca"))); + const list ac = mklist(mklist(element, "id", string("1234")), mklist(attribute, "balance", 1000)); + const list cr = mklist(mklist (attribute, "name", string("jdoe")), cons(element, cons("address", ad)), cons(element, cons("account", ac))); + const list c = mklist(cons(element, cons("customer", cr))); + + ostringstream os; + writeJSON(jsonWriter, &os, c, cx); + assert(str(os) == jscustomer); + + istringstream is(jscustomer); + const list il = streamList(is); + const list r = content(readJSON(il, cx)); + assert(r == c); + return true; + } +}; + +bool testJSONPerf() { + gc_scoped_pool pool; + + const lambda rwl = lambda(testReadWrite()); + cout << "JSON read + write test " << time(rwl, 5, 200) << " ms" << endl; + + return true; +} + +} +} + +int main() { + tuscany::gc_scoped_pool p; + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::json::testJSON(); + tuscany::json::testJSONRPC(); + tuscany::json::testJSONPerf(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sca-cpp/trunk/unmaintained/modules/json/json.hpp b/sca-cpp/trunk/unmaintained/modules/json/json.hpp new file mode 100644 index 0000000000..85579c1b28 --- /dev/null +++ b/sca-cpp/trunk/unmaintained/modules/json/json.hpp @@ -0,0 +1,197 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/* $Rev$ $Date$ */ + +#ifndef tuscany_json_hpp +#define tuscany_json_hpp + +/** + * JSON data conversion functions. + */ + +#include "string.hpp" +#include "list.hpp" +#include "value.hpp" +#include "element.hpp" +#include "monad.hpp" +#include "../js/eval.hpp" + +namespace tuscany { +namespace json { + +/** + * Return true if a list of strings contains a JSON document. + */ +const bool isJSON(const list& ls) { + if (isNil(ls)) + return false; + const string s = substr(car(ls), 0, 1); + return s == "[" || s == "{"; +} + +/** + * Consumes JSON strings and populates a JS object. + */ +failable consume(JSONParser* parser, const list& ilist, const js::JSContext& cx) { + if (isNil(ilist)) + return true; + JSString* jstr = JS_NewStringCopyZ(cx, c_str(car(ilist))); + if(!JS_ConsumeJSONText(cx, parser, JS_GetStringCharsZ(cx, jstr), (uint32)JS_GetStringLength(jstr))) + return mkfailure("JS_ConsumeJSONText failed"); + return consume(parser, cdr(ilist), cx); +} + +/** + * Convert a list of strings representing a JSON document to a list of values. + */ +const failable > readJSON(const list& ilist, const js::JSContext& cx) { + jsval val; + JSONParser* parser = JS_BeginJSONParse(cx, &val); + if(parser == NULL) + return mkfailure >("JS_BeginJSONParse failed"); + + const failable consumed = consume(parser, ilist, cx); + + if(!JS_FinishJSONParse(cx, parser, JSVAL_NULL)) + return mkfailure >("JS_FinishJSONParse failed"); + if(!hasContent(consumed)) + return mkfailure >(consumed); + + return list(js::jsValToValue(val, cx)); +} + +/** + * Context passed to the JSON write callback function. + */ +template class WriteContext { +public: + WriteContext(const lambda& reduce, const R& accum, const js::JSContext& cx) : cx(cx), reduce(reduce), accum(accum) { + } + const js::JSContext& cx; + const lambda reduce; + R accum; +}; + +/** + * Called by JS_Stringify to write JSON out. + */ +template JSBool writeCallback(const jschar *buf, uint32 len, void *data) { + WriteContext& wcx = *(static_cast*> (data)); + JSString* jstr = JS_NewUCStringCopyN(wcx.cx, buf, len); + char* cstr = JS_EncodeString(wcx.cx, jstr); + const string str(cstr, JS_GetStringLength(jstr)); + JS_free(wcx.cx, cstr); + wcx.accum = wcx.reduce(str, wcx.accum); + return JS_TRUE; +} + +/** + * Convert a list of values to a JSON document. + */ +template const failable writeJSON(const lambda& reduce, const R& initial, const list& l, const js::JSContext& cx) { + jsval val; + if (js::isJSArray(l)) + val = OBJECT_TO_JSVAL(valuesToJSElements(JS_NewArrayObject(cx, 0, NULL), l, 0, cx)); + else + val = OBJECT_TO_JSVAL(valuesToJSProperties(JS_NewObject(cx, NULL, NULL, NULL), l, cx)); + + WriteContext wcx(reduce, initial, cx); + if (!JS_Stringify(cx, &val, NULL, INT_TO_JSVAL(1), writeCallback, &wcx)) + return mkfailure("JS_Stringify failed"); + return wcx.accum; +} + +/** + * Convert a list of values to a list of strings representing a JSON document. + */ +const failable > writeJSON(const list& l, const js::JSContext& cx) { + const failable > ls = writeJSON>(rcons, list(), valuesToElements(elementsToValues(l)), cx); + if (!hasContent(ls)) + return ls; + return reverse(list(content(ls))); +} + +/** + * Convert a list of function + params to a JSON-RPC request. + */ +const failable > jsonRequest(const value& id, const value& func, const value& params, js::JSContext& cx) { + const list r = mklist(mklist("id", id), mklist("method", string(func)), mklist("params", params)); + return writeJSON(valuesToElements(r), cx); +} + +/** + * Convert a value to a JSON-RPC result. + */ +const failable > jsonResult(const value& id, const value& val, js::JSContext& cx) { + return writeJSON(valuesToElements(mklist(mklist("id", id), mklist("result", val))), cx); +} + +/** + * Convert a JSON-RPC result to a value. + */ +const failable jsonResultValue(const list& s, js::JSContext& cx) { + const failable > jsres = json::readJSON(s, cx); + if (!hasContent(jsres)) + return mkfailure(jsres); + const list rval(cadr(elementsToValues(content(jsres)))); + const value val = cadr(rval); + if (isList(val) && !js::isJSArray(val)) + return value(mklist(val)); + return val; +} + +/** + * Convert a JSON payload to a list of values. + */ +const list jsonValues(const list& e) { + return elementsToValues(e); +} + +/** + * Return a portable function name from a JSON-RPC function name. + * Strip the ".", "system." and "Service." prefixes added by some JSON-RPC clients. + */ +const string funcName(const string& f) { + if (length(f) > 1 && find(f, ".", 0) == 0) + return c_str(f) + 1; + if (length(f) > 7 && find(f, "system.", 0) == 0) + return c_str(f) + 7; + if (length(f) > 8 && find(f, "Service.", 0) == 0) + return c_str(f) + 8; + return f; +} + +/** + * Returns a list of param values other than the id and method args from a list + * of key value pairs. + */ +const list queryParams(const list >& a) { + if (isNil(a)) + return list(); + const list p = car(a); + if (car(p) == value("id") || car(p) == value("method")) + return queryParams(cdr(a)); + return cons(cadr(p), queryParams(cdr(a))); +} + +} +} + +#endif /* tuscany_json_hpp */ -- cgit v1.2.3