diff options
Diffstat (limited to '')
209 files changed, 22631 insertions, 0 deletions
diff --git a/sandbox/sebastien/cpp/apr-2/modules/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/Makefile.am new file mode 100644 index 0000000000..a0fa000791 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/Makefile.am @@ -0,0 +1,19 @@ +# 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. + +SUBDIRS = scheme atom rss js json scdl http server python java openid oauth wsgi + diff --git a/sandbox/sebastien/cpp/apr-2/modules/atom/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/atom/Makefile.am new file mode 100644 index 0000000000..9a628ca969 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/atom/Makefile.am @@ -0,0 +1,25 @@ +# 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/atom + +atom_test_SOURCES = atom-test.cpp +atom_test_LDFLAGS = -lxml2 + +noinst_PROGRAMS = atom-test +TESTS = atom-test diff --git a/sandbox/sebastien/cpp/apr-2/modules/atom/atom-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/atom/atom-test.cpp new file mode 100644 index 0000000000..4acc720816 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/atom/atom-test.cpp @@ -0,0 +1,212 @@ +/* + * 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 ATOM data conversion functions. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "atom.hpp" + +namespace tuscany { +namespace atom { + +ostream* writer(const string& s, ostream* os) { + (*os) << s; + return os; +} + +string itemEntry("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" + "<title type=\"text\">item</title>" + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</id>" + "<content type=\"application/xml\">" + "<item>" + "<name>Apple</name><price>$2.99</price>" + "</item>" + "</content>" + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b\"/>" + "</entry>\n"); + +string itemTextEntry("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" + "<title type=\"text\">item</title>" + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</id>" + "<content type=\"text\">Apple</content>" + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b\"/>" + "</entry>\n"); + +string incompleteEntry("<entry xmlns=\"http://www.w3.org/2005/Atom\">" + "<title>item</title><content type=\"text/xml\">" + "<Item xmlns=\"http://services/\">" + "<name xmlns=\"\">Orange</name>" + "<price xmlns=\"\">3.55</price>" + "</Item>" + "</content>" + "</entry>"); + +string completedEntry("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" + "<title type=\"text\">item</title>" + "<id></id>" + "<content type=\"application/xml\">" + "<Item xmlns=\"http://services/\">" + "<name xmlns=\"\">Orange</name>" + "<price xmlns=\"\">3.55</price>" + "</Item>" + "</content><link href=\"\"/>" + "</entry>\n"); + +bool testEntry() { + { + const list<value> i = list<value>() + element + value("item") + + value(list<value>() + element + value("name") + value(string("Apple"))) + + value(list<value>() + element + value("price") + value(string("$2.99"))); + const list<value> a = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + ostringstream os; + writeATOMEntry<ostream*>(writer, &os, a); + assert(str(os) == itemEntry); + } + { + const list<value> a = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), string("Apple")); + ostringstream os; + writeATOMEntry<ostream*>(writer, &os, a); + assert(str(os) == itemTextEntry); + } + { + const list<value> a = content(readATOMEntry(mklist(itemEntry))); + ostringstream os; + writeATOMEntry<ostream*>(writer, &os, a); + assert(str(os) == itemEntry); + } + { + const list<value> a = content(readATOMEntry(mklist(itemTextEntry))); + ostringstream os; + writeATOMEntry<ostream*>(writer, &os, a); + assert(str(os) == itemTextEntry); + } + { + const list<value> a = content(readATOMEntry(mklist(incompleteEntry))); + ostringstream os; + writeATOMEntry<ostream*>(writer, &os, a); + assert(str(os) == completedEntry); + } + return true; +} + +string emptyFeed("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<feed xmlns=\"http://www.w3.org/2005/Atom\">" + "<title type=\"text\">Feed</title>" + "<id>1234</id>" + "</feed>\n"); + +string itemFeed("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<feed xmlns=\"http://www.w3.org/2005/Atom\">" + "<title type=\"text\">Feed</title>" + "<id>1234</id>" + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" + "<title type=\"text\">item</title>" + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</id>" + "<content type=\"application/xml\">" + "<item>" + "<name>Apple</name><price>$2.99</price>" + "</item>" + "</content>" + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b\"/>" + "</entry>" + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" + "<title type=\"text\">item</title>" + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c</id>" + "<content type=\"application/xml\">" + "<item>" + "<name>Orange</name><price>$3.55</price>" + "</item>" + "</content>" + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c\"/>" + "</entry>" + "</feed>\n"); + +bool testFeed() { + { + ostringstream os; + writeATOMFeed<ostream*>(writer, &os, mklist<value>("Feed", "1234")); + assert(str(os) == emptyFeed); + } + { + const list<value> a = content(readATOMFeed(mklist(emptyFeed))); + ostringstream os; + writeATOMFeed<ostream*>(writer, &os, a); + assert(str(os) == emptyFeed); + } + { + const list<value> i = list<value>() + + (list<value>() + "item" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b" + + (list<value>() + element + "item" + + (list<value>() + element + "name" + "Apple") + + (list<value>() + element + "price" + "$2.99"))) + + (list<value>() + "item" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c" + + (list<value>() + element + "item" + + (list<value>() + element + "name" + "Orange") + + (list<value>() + element + "price" + "$3.55"))); + const list<value> a = cons<value>("Feed", cons<value>("1234", i)); + ostringstream os; + writeATOMFeed<ostream*>(writer, &os, a); + assert(str(os) == itemFeed); + } + { + const list<value> i = list<value>() + + (list<value>() + "item" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b" + + valueToElement(list<value>() + "item" + + (list<value>() + "name" + "Apple") + + (list<value>() + "price" + "$2.99"))) + + (list<value>() + "item" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c" + + valueToElement(list<value>() + "item" + + (list<value>() + "name" + "Orange") + + (list<value>() + "price" + "$3.55"))); + const list<value> a = cons<value>("Feed", cons<value>("1234", i)); + ostringstream os; + writeATOMFeed<ostream*>(writer, &os, a); + assert(str(os) == itemFeed); + } + { + const list<value> a = content(readATOMFeed(mklist(itemFeed))); + ostringstream os; + writeATOMFeed<ostream*>(writer, &os, a); + assert(str(os) == itemFeed); + } + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::atom::testEntry(); + tuscany::atom::testFeed(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/atom/atom.hpp b/sandbox/sebastien/cpp/apr-2/modules/atom/atom.hpp new file mode 100644 index 0000000000..253be9bdd6 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/atom/atom.hpp @@ -0,0 +1,203 @@ +/* + * 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_atom_hpp +#define tuscany_atom_hpp + +/** + * ATOM data conversion functions. + */ + +#include "string.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "xml.hpp" + +namespace tuscany { +namespace atom { + +/** + * Convert a list of elements to a list of values representing an ATOM entry. + */ +const list<value> entryElementsToValues(const list<value>& e) { + const list<value> lt = filter<value>(selector(mklist<value>(element, "title")), e); + const value t = isNil(lt)? value(emptyString) : elementValue(car(lt)); + const list<value> li = filter<value>(selector(mklist<value>(element, "id")), e); + const value i = isNil(li)? value(emptyString) : elementValue(car(li)); + const list<value> lc = filter<value>(selector(mklist<value>(element, "content")), e); + return mklist<value>(t, i, elementValue(car(lc))); +} + +/** + * Convert a list of elements to a list of values representing ATOM entries. + */ +const list<value> entriesElementsToValues(const list<value>& e) { + if (isNil(e)) + return e; + return cons<value>(entryElementsToValues(car(e)), entriesElementsToValues(cdr(e))); +} + +/** + * Return true if a list of strings contains an ATOM feed. + */ +const bool isATOMFeed(const list<string>& ls) { + if (!isXML(ls)) + return false; + return contains(car(ls), "<feed") && contains(car(ls), "=\"http://www.w3.org/2005/Atom\""); +} + +/** + * Convert a list of strings to a list of values representing an ATOM entry. + */ +const failable<list<value> > readATOMEntry(const list<string>& ilist) { + const list<value> e = readXML(ilist); + if (isNil(e)) + return mkfailure<list<value> >("Empty entry"); + return entryElementsToValues(car(e)); +} + +/** + * Convert a list of values representing an ATOM entry to a value. + */ +const value entryValue(const list<value>& e) { + const list<value> v = elementsToValues(mklist<value>(caddr(e))); + return cons(car(e), mklist<value>(cadr(e), isList(car(v))? (value)cdr<value>(car(v)) : car(v))); +} + +/** + * Convert a list of strings to a list of values representing an ATOM feed. + */ +const failable<list<value> > readATOMFeed(const list<string>& ilist) { + const list<value> f = readXML(ilist); + if (isNil(f)) + return mkfailure<list<value> >("Empty feed"); + const list<value> t = filter<value>(selector(mklist<value>(element, "title")), car(f)); + const list<value> i = filter<value>(selector(mklist<value>(element, "id")), car(f)); + const list<value> e = filter<value>(selector(mklist<value>(element, "entry")), car(f)); + if (isNil(e)) + return mklist<value>(elementValue(car(t)), elementValue(car(i))); + return cons<value>(elementValue(car(t)), cons(elementValue(car(i)), entriesElementsToValues(e))); +} + +/** + * Convert an ATOM feed containing elements to an ATOM feed containing values. + */ +const list<value> feedValuesLoop(const list<value> e) { + if (isNil(e)) + return e; + return cons<value>(entryValue(car(e)), feedValuesLoop(cdr(e))); +} + +const list<value> feedValues(const list<value>& e) { + return cons(car<value>(e), cons<value>(cadr<value>(e), feedValuesLoop(cddr<value>(e)))); +} + +/** + * Convert a list of values representing an ATOM entry to a list of elements. + * The first two values in the list are the entry title and id. + */ +const list<value> entryElement(const list<value>& l) { + return list<value>() + + element + "entry" + (list<value>() + attribute + "xmlns" + "http://www.w3.org/2005/Atom") + + (list<value>() + element + "title" + (list<value>() + attribute + "type" + "text") + car(l)) + + (list<value>() + element + "id" + cadr(l)) + + (list<value>() + element + "content" + + (list<value>() + attribute + "type" + (isList(caddr(l))? "application/xml" : "text")) + caddr(l)) + + (list<value>() + element + "link" + (list<value>() + attribute + "href" + cadr(l))); +} + +/** + * Convert a list of values representing ATOM entries to a list of elements. + */ +const list<value> entriesElements(const list<value>& l) { + if (isNil(l)) + return l; + return cons<value>(entryElement(car(l)), entriesElements(cdr(l))); +} + +/** + * Convert a list of values representing an ATOM entry to an ATOM entry. + * The first two values in the list are the entry id and title. + */ +template<typename R> const failable<R> writeATOMEntry(const lambda<R(const string&, const R)>& reduce, const R& initial, const list<value>& l) { + return writeXML<R>(reduce, initial, mklist<value>(entryElement(l))); +} + +const failable<list<string> > writeATOMEntry(const list<value>& l) { + const failable<list<string> > ls = writeATOMEntry<list<string> >(rcons<string>, list<string>(), l); + if (!hasContent(ls)) + return ls; + return reverse(list<string>(content(ls))); +} + +/** + * Convert a list of values representing an ATOM feed to an ATOM feed. + * The first two values in the list are the feed id and title. + */ +template<typename R> const failable<R> writeATOMFeed(const lambda<R(const string&, const R)>& reduce, const R& initial, const list<value>& l) { + const list<value> f = list<value>() + + element + "feed" + (list<value>() + attribute + "xmlns" + "http://www.w3.org/2005/Atom") + + (list<value>() + element + "title" + (list<value>() + attribute + "type" + "text") + car(l)) + + (list<value>() + element + "id" + cadr(l)); + if (isNil(cddr(l))) + return writeXML<R>(reduce, initial, mklist<value>(f)); + const list<value> fe = append(f, entriesElements(cddr(l))); + return writeXML<R>(reduce, initial, mklist<value>(fe)); +} + +/** + * Convert a list of values representing an ATOM feed to a list of strings. + * The first two values in the list are the feed id and title. + */ +const failable<list<string> > writeATOMFeed(const list<value>& l) { + const failable<list<string> > ls = writeATOMFeed<list<string>>(rcons<string>, list<string>(), l); + if (!hasContent(ls)) + return ls; + return reverse(list<string>(content(ls))); +} + +/** + * Convert an ATOM entry containing a value to an ATOM entry containing an item element. + */ +const list<value> entryValuesToElements(const list<value> val) { + if (isList(caddr(val))) + return cons(car(val), cons(cadr(val), valuesToElements(mklist<value>(cons<value>("item", (list<value>)caddr(val)))))); + return cons(car(val), cons(cadr(val), valuesToElements(mklist<value>(mklist<value>("item", caddr(val)))))); +} + +/** + * Convert an ATOM feed containing values to an ATOM feed containing elements. + */ +const list<value> feedValuesToElementsLoop(const list<value> val) { + if (isNil(val)) + return val; + return cons<value>(entryValuesToElements(car(val)), feedValuesToElementsLoop(cdr(val))); +} + +const list<value> feedValuesToElements(const list<value>& val) { + return cons(car<value>(val), cons<value>(cadr<value>(val), feedValuesToElementsLoop(cddr<value>(val)))); +} + +} +} + +#endif /* tuscany_atom_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/http/Makefile.am new file mode 100644 index 0000000000..a47b83fbf0 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/Makefile.am @@ -0,0 +1,65 @@ +# 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. + +INCLUDES = -I${HTTPD_INCLUDE} + +incl_HEADERS = *.hpp +incldir = $(prefix)/include/modules/http + +dist_mod_SCRIPTS = httpd-conf httpd-addr httpd-start httpd-stop httpd-restart ssl-ca-conf ssl-cert-conf ssl-cert-find httpd-ssl-conf basic-auth-conf cert-auth-conf form-auth-conf open-auth-conf passwd-auth-conf group-auth-conf proxy-conf proxy-ssl-conf proxy-member-conf proxy-ssl-member-conf vhost-conf vhost-ssl-conf tunnel-ssl-conf httpd-worker-conf httpd-event-conf +moddir=$(prefix)/modules/http + +curl_test_SOURCES = curl-test.cpp +curl_test_LDFLAGS = -lxml2 -lcurl -lmozjs + +curl_get_SOURCES = curl-get.cpp +curl_get_LDFLAGS = -lxml2 -lcurl -lmozjs + +curl_connect_SOURCES = curl-connect.cpp +curl_connect_LDFLAGS = -lxml2 -lcurl -lmozjs + +mod_LTLIBRARIES = libmod_tuscany_ssltunnel.la libmod_tuscany_openauth.la +noinst_DATA = libmod_tuscany_ssltunnel.so libmod_tuscany_openauth.so + +libmod_tuscany_ssltunnel_la_SOURCES = mod-ssltunnel.cpp +libmod_tuscany_ssltunnel_la_LDFLAGS = -lxml2 -lcurl -lmozjs +libmod_tuscany_ssltunnel.so: + ln -s .libs/libmod_tuscany_ssltunnel.so + +libmod_tuscany_openauth_la_SOURCES = mod-openauth.cpp +libmod_tuscany_openauth_la_LDFLAGS = -lxml2 -lcurl -lmozjs +libmod_tuscany_openauth.so: + ln -s .libs/libmod_tuscany_openauth.so + +mod_DATA = httpd.prefix httpd-apachectl.prefix httpd-modules.prefix curl.prefix +nobase_dist_mod_DATA = conf/* + +EXTRA_DIST = htdocs/index.html htdocs/login/index.html htdocs/logout/index.html + +httpd.prefix: $(top_builddir)/config.status + echo ${HTTPD_PREFIX} >httpd.prefix +httpd-apachectl.prefix: $(top_builddir)/config.status + echo ${HTTPD_APACHECTL_PREFIX} >httpd-apachectl.prefix +httpd-modules.prefix: $(top_builddir)/config.status + echo ${HTTPD_MODULES_PREFIX} >httpd-modules.prefix +curl.prefix: $(top_builddir)/config.status + echo ${CURL_PREFIX} >curl.prefix + +dist_noinst_SCRIPTS = httpd-test http-test proxy-test +noinst_PROGRAMS = curl-test curl-get curl-connect +TESTS = httpd-test http-test proxy-test + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/basic-auth-conf b/sandbox/sebastien/cpp/apr-2/modules/http/basic-auth-conf new file mode 100755 index 0000000000..c3018e1174 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/basic-auth-conf @@ -0,0 +1,41 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD basic authentication configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +# Generate basic authentication configuration +cat >>$root/conf/auth.conf <<EOF +# Generated by: basic-auth-conf $* +# Require clients to present a userid + password for HTTP +# basic authentication +<Location /> +AuthType Basic +AuthName "$host" +AuthBasicProvider file +Require valid-user +</Location> + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/cert-auth-conf b/sandbox/sebastien/cpp/apr-2/modules/http/cert-auth-conf new file mode 100755 index 0000000000..c6720c7ae4 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/cert-auth-conf @@ -0,0 +1,52 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD certificate-based authentication configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +# Generate authentication configuration +cat >>$root/conf/auth.conf <<EOF +# Generated by: cert-auth-conf $* +# Require clients to present a valid client certificate +SSLVerifyClient require +SSLVerifyDepth 1 + +<Location /> +AuthType Basic +AuthName "$host" +AuthBasicProvider file +Require valid-user +</Location> + +EOF + +# Create password file and certificate-based users +cat >>$root/conf/httpd.passwd <<EOF +/C=US/ST=CA/L=San Francisco/O=$host/OU=server/CN=$host:\$1\$OXLyS...\$Owx8s2/m9/gfkcRVXzgoE/ +/C=US/ST=CA/L=San Francisco/O=$host/OU=proxy/CN=$host:\$1\$OXLyS...\$Owx8s2/m9/gfkcRVXzgoE/ +/C=US/ST=CA/L=San Francisco/O=$host/OU=tunnel/CN=$host:\$1\$OXLyS...\$Owx8s2/m9/gfkcRVXzgoE/ +/C=US/ST=CA/L=San Francisco/O=localhost/OU=server/CN=localhost:\$1\$OXLyS...\$Owx8s2/m9/gfkcRVXzgoE/ +/C=US/ST=CA/L=San Francisco/O=localhost/OU=tunnel/CN=localhost:\$1\$OXLyS...\$Owx8s2/m9/gfkcRVXzgoE/ +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/conf/mime.types b/sandbox/sebastien/cpp/apr-2/modules/http/conf/mime.types new file mode 100644 index 0000000000..4279f51bca --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/conf/mime.types @@ -0,0 +1,607 @@ +# 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. + +# This file controls what Internet media types are sent to the client for +# given file extension(s). Sending the correct media type to the client +# is important so they know how to handle the content of the file. +# Extra types can either be added here or by using an AddType directive +# in your config files. For more information about Internet media types, +# please read RFC 2045, 2046, 2047, 2048, and 2077. The Internet media type +# registry is at <http://www.iana.org/assignments/media-types/>. + +# MIME type Extensions +application/activemessage +application/andrew-inset ez +application/applefile +application/atom+xml atom +application/atomicmail +application/batch-smtp +application/beep+xml +application/cals-1840 +application/cnrp+xml +application/commonground +application/cpl+xml +application/cybercash +application/dca-rft +application/dec-dx +application/dvcs +application/edi-consent +application/edifact +application/edi-x12 +application/eshop +application/font-tdpfr +application/http +application/hyperstudio +application/iges +application/index +application/index.cmd +application/index.obj +application/index.response +application/index.vnd +application/iotp +application/ipp +application/isup +application/mac-binhex40 hqx +application/mac-compactpro cpt +application/macwriteii +application/marc +application/mathematica +application/mathml+xml mathml +application/msword doc +application/news-message-id +application/news-transmission +application/ocsp-request +application/ocsp-response +application/octet-stream bin dms lha lzh exe class so dll dmg +application/oda oda +application/ogg ogg +application/parityfec +application/pdf pdf +application/pgp-encrypted +application/pgp-keys +application/pgp-signature +application/pkcs10 +application/pkcs7-mime +application/pkcs7-signature +application/pkix-cert +application/pkix-crl +application/pkixcmp +application/postscript ai eps ps +application/prs.alvestrand.titrax-sheet +application/prs.cww +application/prs.nprend +application/prs.plucker +application/qsig +application/rdf+xml rdf +application/reginfo+xml +application/remote-printing +application/riscos +application/rtf +application/sdp +application/set-payment +application/set-payment-initiation +application/set-registration +application/set-registration-initiation +application/sgml +application/sgml-open-catalog +application/sieve +application/slate +application/smil smi smil +application/srgs gram +application/srgs+xml grxml +application/timestamp-query +application/timestamp-reply +application/tve-trigger +application/vemmi +application/vnd.3gpp.pic-bw-large +application/vnd.3gpp.pic-bw-small +application/vnd.3gpp.pic-bw-var +application/vnd.3gpp.sms +application/vnd.3m.post-it-notes +application/vnd.accpac.simply.aso +application/vnd.accpac.simply.imp +application/vnd.acucobol +application/vnd.acucorp +application/vnd.adobe.xfdf +application/vnd.aether.imp +application/vnd.amiga.ami +application/vnd.anser-web-certificate-issue-initiation +application/vnd.anser-web-funds-transfer-initiation +application/vnd.audiograph +application/vnd.blueice.multipass +application/vnd.bmi +application/vnd.businessobjects +application/vnd.canon-cpdl +application/vnd.canon-lips +application/vnd.cinderella +application/vnd.claymore +application/vnd.commerce-battelle +application/vnd.commonspace +application/vnd.contact.cmsg +application/vnd.cosmocaller +application/vnd.criticaltools.wbs+xml +application/vnd.ctc-posml +application/vnd.cups-postscript +application/vnd.cups-raster +application/vnd.cups-raw +application/vnd.curl +application/vnd.cybank +application/vnd.data-vision.rdz +application/vnd.dna +application/vnd.dpgraph +application/vnd.dreamfactory +application/vnd.dxr +application/vnd.ecdis-update +application/vnd.ecowin.chart +application/vnd.ecowin.filerequest +application/vnd.ecowin.fileupdate +application/vnd.ecowin.series +application/vnd.ecowin.seriesrequest +application/vnd.ecowin.seriesupdate +application/vnd.enliven +application/vnd.epson.esf +application/vnd.epson.msf +application/vnd.epson.quickanime +application/vnd.epson.salt +application/vnd.epson.ssf +application/vnd.ericsson.quickcall +application/vnd.eudora.data +application/vnd.fdf +application/vnd.ffsns +application/vnd.fints +application/vnd.flographit +application/vnd.framemaker +application/vnd.fsc.weblaunch +application/vnd.fujitsu.oasys +application/vnd.fujitsu.oasys2 +application/vnd.fujitsu.oasys3 +application/vnd.fujitsu.oasysgp +application/vnd.fujitsu.oasysprs +application/vnd.fujixerox.ddd +application/vnd.fujixerox.docuworks +application/vnd.fujixerox.docuworks.binder +application/vnd.fut-misnet +application/vnd.grafeq +application/vnd.groove-account +application/vnd.groove-help +application/vnd.groove-identity-message +application/vnd.groove-injector +application/vnd.groove-tool-message +application/vnd.groove-tool-template +application/vnd.groove-vcard +application/vnd.hbci +application/vnd.hhe.lesson-player +application/vnd.hp-hpgl +application/vnd.hp-hpid +application/vnd.hp-hps +application/vnd.hp-pcl +application/vnd.hp-pclxl +application/vnd.httphone +application/vnd.hzn-3d-crossword +application/vnd.ibm.afplinedata +application/vnd.ibm.electronic-media +application/vnd.ibm.minipay +application/vnd.ibm.modcap +application/vnd.ibm.rights-management +application/vnd.ibm.secure-container +application/vnd.informix-visionary +application/vnd.intercon.formnet +application/vnd.intertrust.digibox +application/vnd.intertrust.nncp +application/vnd.intu.qbo +application/vnd.intu.qfx +application/vnd.irepository.package+xml +application/vnd.is-xpr +application/vnd.japannet-directory-service +application/vnd.japannet-jpnstore-wakeup +application/vnd.japannet-payment-wakeup +application/vnd.japannet-registration +application/vnd.japannet-registration-wakeup +application/vnd.japannet-setstore-wakeup +application/vnd.japannet-verification +application/vnd.japannet-verification-wakeup +application/vnd.jisp +application/vnd.kde.karbon +application/vnd.kde.kchart +application/vnd.kde.kformula +application/vnd.kde.kivio +application/vnd.kde.kontour +application/vnd.kde.kpresenter +application/vnd.kde.kspread +application/vnd.kde.kword +application/vnd.kenameaapp +application/vnd.koan +application/vnd.liberty-request+xml +application/vnd.llamagraphics.life-balance.desktop +application/vnd.llamagraphics.life-balance.exchange+xml +application/vnd.lotus-1-2-3 +application/vnd.lotus-approach +application/vnd.lotus-freelance +application/vnd.lotus-notes +application/vnd.lotus-organizer +application/vnd.lotus-screencam +application/vnd.lotus-wordpro +application/vnd.mcd +application/vnd.mediastation.cdkey +application/vnd.meridian-slingshot +application/vnd.micrografx.flo +application/vnd.micrografx.igx +application/vnd.mif mif +application/vnd.minisoft-hp3000-save +application/vnd.mitsubishi.misty-guard.trustweb +application/vnd.mobius.daf +application/vnd.mobius.dis +application/vnd.mobius.mbk +application/vnd.mobius.mqy +application/vnd.mobius.msl +application/vnd.mobius.plc +application/vnd.mobius.txf +application/vnd.mophun.application +application/vnd.mophun.certificate +application/vnd.motorola.flexsuite +application/vnd.motorola.flexsuite.adsi +application/vnd.motorola.flexsuite.fis +application/vnd.motorola.flexsuite.gotap +application/vnd.motorola.flexsuite.kmr +application/vnd.motorola.flexsuite.ttc +application/vnd.motorola.flexsuite.wem +application/vnd.mozilla.xul+xml xul +application/vnd.ms-artgalry +application/vnd.ms-asf +application/vnd.ms-excel xls +application/vnd.ms-lrm +application/vnd.ms-powerpoint ppt +application/vnd.ms-project +application/vnd.ms-tnef +application/vnd.ms-works +application/vnd.ms-wpl +application/vnd.mseq +application/vnd.msign +application/vnd.music-niff +application/vnd.musician +application/vnd.netfpx +application/vnd.noblenet-directory +application/vnd.noblenet-sealer +application/vnd.noblenet-web +application/vnd.novadigm.edm +application/vnd.novadigm.edx +application/vnd.novadigm.ext +application/vnd.obn +application/vnd.osa.netdeploy +application/vnd.palm +application/vnd.pg.format +application/vnd.pg.osasli +application/vnd.powerbuilder6 +application/vnd.powerbuilder6-s +application/vnd.powerbuilder7 +application/vnd.powerbuilder7-s +application/vnd.powerbuilder75 +application/vnd.powerbuilder75-s +application/vnd.previewsystems.box +application/vnd.publishare-delta-tree +application/vnd.pvi.ptid1 +application/vnd.pwg-multiplexed +application/vnd.pwg-xhtml-print+xml +application/vnd.quark.quarkxpress +application/vnd.rapid +application/vnd.s3sms +application/vnd.sealed.net +application/vnd.seemail +application/vnd.shana.informed.formdata +application/vnd.shana.informed.formtemplate +application/vnd.shana.informed.interchange +application/vnd.shana.informed.package +application/vnd.smaf +application/vnd.sss-cod +application/vnd.sss-dtf +application/vnd.sss-ntf +application/vnd.street-stream +application/vnd.svd +application/vnd.swiftview-ics +application/vnd.triscape.mxs +application/vnd.trueapp +application/vnd.truedoc +application/vnd.ufdl +application/vnd.uplanet.alert +application/vnd.uplanet.alert-wbxml +application/vnd.uplanet.bearer-choice +application/vnd.uplanet.bearer-choice-wbxml +application/vnd.uplanet.cacheop +application/vnd.uplanet.cacheop-wbxml +application/vnd.uplanet.channel +application/vnd.uplanet.channel-wbxml +application/vnd.uplanet.list +application/vnd.uplanet.list-wbxml +application/vnd.uplanet.listcmd +application/vnd.uplanet.listcmd-wbxml +application/vnd.uplanet.signal +application/vnd.vcx +application/vnd.vectorworks +application/vnd.vidsoft.vidconference +application/vnd.visio +application/vnd.visionary +application/vnd.vividence.scriptfile +application/vnd.vsf +application/vnd.wap.sic +application/vnd.wap.slc +application/vnd.wap.wbxml wbxml +application/vnd.wap.wmlc wmlc +application/vnd.wap.wmlscriptc wmlsc +application/vnd.webturbo +application/vnd.wrq-hp3000-labelled +application/vnd.wt.stf +application/vnd.wv.csp+wbxml +application/vnd.xara +application/vnd.xfdl +application/vnd.yamaha.hv-dic +application/vnd.yamaha.hv-script +application/vnd.yamaha.hv-voice +application/vnd.yellowriver-custom-menu +application/voicexml+xml vxml +application/watcherinfo+xml +application/whoispp-query +application/whoispp-response +application/wita +application/wordperfect5.1 +application/x-bcpio bcpio +application/x-cdlink vcd +application/x-chess-pgn pgn +application/x-compress +application/x-cpio cpio +application/x-csh csh +application/x-director dcr dir dxr +application/x-dvi dvi +application/x-futuresplash spl +application/x-gtar gtar +application/x-gzip +application/x-hdf hdf +application/x-javascript js +application/x-koan skp skd skt skm +application/x-latex latex +application/x-netcdf nc cdf +application/x-sh sh +application/x-shar shar +application/x-shockwave-flash swf +application/x-stuffit sit +application/x-sv4cpio sv4cpio +application/x-sv4crc sv4crc +application/x-tar tar +application/x-tcl tcl +application/x-tex tex +application/x-texinfo texinfo texi +application/x-troff t tr roff +application/x-troff-man man +application/x-troff-me me +application/x-troff-ms ms +application/x-ustar ustar +application/x-wais-source src +application/x400-bp +application/xhtml+xml xhtml xht +application/xslt+xml xslt +application/xml xml xsl +application/xml-dtd dtd +application/xml-external-parsed-entity +application/zip zip +audio/32kadpcm +audio/amr +audio/amr-wb +audio/basic au snd +audio/cn +audio/dat12 +audio/dsr-es201108 +audio/dvi4 +audio/evrc +audio/evrc0 +audio/g722 +audio/g.722.1 +audio/g723 +audio/g726-16 +audio/g726-24 +audio/g726-32 +audio/g726-40 +audio/g728 +audio/g729 +audio/g729D +audio/g729E +audio/gsm +audio/gsm-efr +audio/l8 +audio/l16 +audio/l20 +audio/l24 +audio/lpc +audio/midi mid midi kar +audio/mpa +audio/mpa-robust +audio/mp4a-latm +audio/mpeg mpga mp2 mp3 +audio/parityfec +audio/pcma +audio/pcmu +audio/prs.sid +audio/qcelp +audio/red +audio/smv +audio/smv0 +audio/telephone-event +audio/tone +audio/vdvi +audio/vnd.3gpp.iufp +audio/vnd.cisco.nse +audio/vnd.cns.anp1 +audio/vnd.cns.inf1 +audio/vnd.digital-winds +audio/vnd.everad.plj +audio/vnd.lucent.voice +audio/vnd.nortel.vbk +audio/vnd.nuera.ecelp4800 +audio/vnd.nuera.ecelp7470 +audio/vnd.nuera.ecelp9600 +audio/vnd.octel.sbc +audio/vnd.qcelp +audio/vnd.rhetorex.32kadpcm +audio/vnd.vmx.cvsd +audio/x-aiff aif aiff aifc +audio/x-alaw-basic +audio/x-mpegurl m3u +audio/x-pn-realaudio ram ra +audio/x-pn-realaudio-plugin +application/vnd.rn-realmedia rm +audio/x-wav wav +chemical/x-pdb pdb +chemical/x-xyz xyz +image/bmp bmp +image/cgm cgm +image/g3fax +image/gif gif +image/ief ief +image/jpeg jpeg jpg jpe +image/naplps +image/png png +image/prs.btif +image/prs.pti +image/svg+xml svg +image/t38 +image/tiff tiff tif +image/tiff-fx +image/vnd.cns.inf2 +image/vnd.djvu djvu djv +image/vnd.dwg +image/vnd.dxf +image/vnd.fastbidsheet +image/vnd.fpx +image/vnd.fst +image/vnd.fujixerox.edmics-mmr +image/vnd.fujixerox.edmics-rlc +image/vnd.globalgraphics.pgb +image/vnd.mix +image/vnd.ms-modi +image/vnd.net-fpx +image/vnd.svf +image/vnd.wap.wbmp wbmp +image/vnd.xiff +image/x-cmu-raster ras +image/x-icon ico +image/x-portable-anymap pnm +image/x-portable-bitmap pbm +image/x-portable-graymap pgm +image/x-portable-pixmap ppm +image/x-rgb rgb +image/x-xbitmap xbm +image/x-xpixmap xpm +image/x-xwindowdump xwd +message/delivery-status +message/disposition-notification +message/external-body +message/http +message/news +message/partial +message/rfc822 +message/s-http +message/sip +message/sipfrag +model/iges igs iges +model/mesh msh mesh silo +model/vnd.dwf +model/vnd.flatland.3dml +model/vnd.gdl +model/vnd.gs-gdl +model/vnd.gtw +model/vnd.mts +model/vnd.parasolid.transmit.binary +model/vnd.parasolid.transmit.text +model/vnd.vtu +model/vrml wrl vrml +multipart/alternative +multipart/appledouble +multipart/byteranges +multipart/digest +multipart/encrypted +multipart/form-data +multipart/header-set +multipart/mixed +multipart/parallel +multipart/related +multipart/report +multipart/signed +multipart/voice-message +text/calendar ics ifb +text/css css +text/directory +text/enriched +text/html html htm +text/parityfec +text/plain asc txt +text/prs.lines.tag +text/rfc822-headers +text/richtext rtx +text/rtf rtf +text/sgml sgml sgm +text/t140 +text/tab-separated-values tsv +text/uri-list +text/vnd.abc +text/vnd.curl +text/vnd.dmclientscript +text/vnd.fly +text/vnd.fmi.flexstor +text/vnd.in3d.3dml +text/vnd.in3d.spot +text/vnd.iptc.nitf +text/vnd.iptc.newsml +text/vnd.latex-z +text/vnd.motorola.reflex +text/vnd.ms-mediapackage +text/vnd.net2phone.commcenter.command +text/vnd.sun.j2me.app-descriptor +text/vnd.wap.si +text/vnd.wap.sl +text/vnd.wap.wml wml +text/vnd.wap.wmlscript wmls +text/x-setext etx +text/xml +text/xml-external-parsed-entity +video/bmpeg +video/bt656 +video/celb +video/dv +video/h261 +video/h263 +video/h263-1998 +video/h263-2000 +video/jpeg +video/mp1s +video/mp2p +video/mp2t +video/mp4v-es +video/mpv +video/mpeg mpeg mpg mpe +video/nv +video/parityfec +video/pointer +video/quicktime qt mov +video/smpte292m +video/vnd.fvt +video/vnd.motorola.video +video/vnd.motorola.videop +video/vnd.mpegurl mxu m4u +video/vnd.nokia.interleaved-multimedia +video/vnd.objectvideo +video/vnd.vivo +video/x-msvideo avi +video/x-sgi-movie movie +x-conference/x-cooltalk ice diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/curl-connect.cpp b/sandbox/sebastien/cpp/apr-2/modules/http/curl-connect.cpp new file mode 100644 index 0000000000..432ccc2000 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/curl-connect.cpp @@ -0,0 +1,98 @@ +/* + * 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$ */ + +/** + * HTTP connect command line test tool. + */ + +#include <assert.h> +#include <stdio.h> +#include "stream.hpp" +#include "string.hpp" +#include "perf.hpp" +#include "http.hpp" + +namespace tuscany { +namespace http { + +const bool testConnect(const string& url, const string& ca = "", const string& cert = "", const string& key = "") { + gc_scoped_pool p; + + CURLSession cs(ca, cert, key); + const failable<bool> crc = connect(url, cs); + assert(hasContent(crc)); + + apr_pollset_t* pollset; + apr_status_t cprc = apr_pollset_create(&pollset, 2, pool(p), 0); + assert(cprc == APR_SUCCESS); + apr_socket_t* csock = sock(0, p); + const apr_pollfd_t* cpollfd = pollfd(csock, APR_POLLIN | APR_POLLERR | APR_POLLNVAL | APR_POLLHUP, p); + apr_pollset_add(pollset, cpollfd); + apr_socket_t* tsock = sock(cs); + const apr_pollfd_t* tpollfd = pollfd(tsock, APR_POLLIN | APR_POLLERR | APR_POLLNVAL | APR_POLLHUP, p); + apr_pollset_add(pollset, tpollfd); + + const apr_pollfd_t* pollfds; + apr_int32_t pollcount; + for(;;) { + apr_status_t pollrc = apr_pollset_poll(pollset, -1, &pollcount, &pollfds); + assert(pollrc == APR_SUCCESS); + + for (; pollcount > 0; pollcount--, pollfds++) { + if (pollfds->rtnevents & APR_POLLIN) { + char data[8192]; + if (pollfds->desc.s == csock) { + const size_t rl = ::read(0, data, sizeof(data)); + if (rl == (size_t)-1) + return false; + if (rl > 0) { + const failable<bool> src = http::send(data, rl, cs); + assert(hasContent(src)); + } + } + else { + const failable<size_t> frl = http::recv(data, sizeof(data), cs); + assert(hasContent(frl)); + const size_t rl = content(frl); + if (rl == 0) + return true; + const size_t wl = ::write(0, data, rl); + assert(wl == rl); + } + continue; + } + assert(!(pollfds->rtnevents & (APR_POLLERR | APR_POLLHUP | APR_POLLNVAL))); + } + } + return true; +} + +} +} + +int main(unused const int argc, const char** argv) { + if (argc > 2) + tuscany::http::testConnect(tuscany::string(argv[1]), tuscany::string(argv[2]), tuscany::string(argv[3]), tuscany::string(argv[4])); + else + tuscany::http::testConnect(tuscany::string(argv[1])); + return 0; +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/curl-get.cpp b/sandbox/sebastien/cpp/apr-2/modules/http/curl-get.cpp new file mode 100644 index 0000000000..762423bebb --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/curl-get.cpp @@ -0,0 +1,53 @@ +/* + * 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$ */ + +/** + * HTTP GET command line test tool. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "perf.hpp" +#include "http.hpp" + +namespace tuscany { +namespace http { + +const bool testGet(const string& url, const string& ca = "", const string& cert = "", const string& key = "") { + CURLSession ch(ca, cert, key); + const failable<value> val = get(url, ch); + assert(hasContent(val)); + cout << content(val) << endl; + return true; +} + +} +} + +int main(unused const int argc, const char** argv) { + if (argc > 2) + tuscany::http::testGet(tuscany::string(argv[1]), tuscany::string(argv[2]), tuscany::string(argv[3]), tuscany::string(argv[4])); + else + tuscany::http::testGet(tuscany::string(argv[1])); + return 0; +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/curl-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/http/curl-test.cpp new file mode 100644 index 0000000000..a7b8fd90b6 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/curl-test.cpp @@ -0,0 +1,91 @@ +/* + * 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 HTTP client functions. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "perf.hpp" +#include "http.hpp" + +namespace tuscany { +namespace http { + +string testURI = "http://localhost:8090"; + +ostream* curlWriter(const string& s, ostream* os) { + (*os) << s; + return os; +} + +const bool testGet() { + CURLSession ch("", "", ""); + { + ostringstream os; + const failable<list<ostream*> > r = get<ostream*>(curlWriter, &os, testURI, ch); + assert(hasContent(r)); + assert(contains(str(os), "HTTP/1.1 200 OK")); + assert(contains(str(os), "It works")); + } + { + const failable<value> r = getcontent(testURI, ch); + assert(hasContent(r)); + assert(contains(car(reverse(list<value>(content(r)))), "It works")); + } + return true; +} + +struct getLoop { + CURLSession& ch; + getLoop(CURLSession& ch) : ch(ch) { + } + const bool operator()() const { + const failable<value> r = getcontent(testURI, ch); + assert(hasContent(r)); + assert(contains(car(reverse(list<value>(content(r)))), "It works")); + return true; + } +}; + +const bool testGetPerf() { + CURLSession ch("", "", ""); + lambda<bool()> gl = getLoop(ch); + cout << "Static GET test " << time(gl, 5, 200) << " ms" << endl; + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + tuscany::http::testURI = tuscany::string("http://") + tuscany::http::hostname() + ":8090"; + + tuscany::http::testGet(); + tuscany::http::testGetPerf(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/form-auth-conf b/sandbox/sebastien/cpp/apr-2/modules/http/form-auth-conf new file mode 100755 index 0000000000..a9077116da --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/form-auth-conf @@ -0,0 +1,54 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD form authentication configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +# Generate form authentication configuration +cat >>$root/conf/auth.conf <<EOF +# Generated by: form-auth-conf $* +# Require clients to present a userid + password through form-based +# authentication +<Location /> +AuthType Form +AuthName "$host" +AuthFormProvider file +AuthFormLoginRequiredLocation /login +AuthFormLogoutLocation / +Session On +SessionCookieName TuscanyFormAuth path=/;secure=TRUE +#SessionCryptoPassphrase secret +Require valid-user +</Location> + +<Location /login/dologin> +SetHandler form-login-handler +</Location> + +<Location /logout/dologout> +SetHandler form-logout-handler +</Location> + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/group-auth-conf b/sandbox/sebastien/cpp/apr-2/modules/http/group-auth-conf new file mode 100755 index 0000000000..dc8dad8641 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/group-auth-conf @@ -0,0 +1,44 @@ +#!/bin/sh + +# 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. + +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` +user=$2 +group="members" + +# Add user to group +cat $root/conf/httpd.groups | awk " BEGIN { found = 0 } /$group: / { printf \"%s %s\n\", \$0, \"$user\"; found = 1 } !/$group: / { printf \"%s\n\", \$0 } END { if (found == 0) printf \"%s: %s\n\", \"$group\", \"$user\" } " >$root/conf/.httpd.groups.tmp 2>/dev/null +cp $root/conf/.httpd.groups.tmp $root/conf/httpd.groups +rm $root/conf/.httpd.groups.tmp + +# Generate HTTPD group authorization configuration +conf=`cat $root/conf/auth.conf | grep "Generated by: group-auth-conf"` +if [ "$conf" = "" ]; then + cat >>$root/conf/auth.conf <<EOF +# Generated by: group-auth-conf $1 +# Allow group member access to root location +<Location /> +AuthGroupFile "$root/conf/httpd.groups" +Require group members +</Location> + +EOF +fi + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/index.html b/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/index.html new file mode 100644 index 0000000000..1bfb3e30c2 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/index.html @@ -0,0 +1,21 @@ +<!-- + 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. +--> + +<html><body><h1>It works!</h1></body></html> + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/login/index.html b/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/login/index.html new file mode 100644 index 0000000000..3f312e4ca4 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/login/index.html @@ -0,0 +1,40 @@ +<!-- + 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. +--> + +<html><body><h1>Sign in</h1> + +<script type="text/javascript"> +function submitFormSignin() { + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.formSignin.httpd_location.value = '/'; + document.formSignin.submit(); +} +</script> + +<form name="formSignin" method="POST" action="/login/dologin"> +<table border="0"> +<tr><td>Username:</td><td><input type="text" name="httpd_username" value=""/></td></tr> +<tr><td>Password:</td><td><input type="password" name="httpd_password" value=""/></td></tr> +<tr><td><input type="button" onclick="submitFormSignin()" value="Sign in"/></td><td></td></tr> +</table> +<input type="hidden" name="httpd_location" value="/"/> +</form> + +</body> +</html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/logout/index.html b/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/logout/index.html new file mode 100644 index 0000000000..1ac6e39a1c --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/htdocs/logout/index.html @@ -0,0 +1,33 @@ +<!-- + 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. +--> + +<html><body> +<h1>Sign out</h1> + +<form name="signout" action="/login" method="GET"> +<script type="text/javascript"> +function submitSignout() { + document.cookie = 'TuscanyFormAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.signout.submit(); + return true; +} +</script> +<input type="button" onclick="submitSignout()" value="Sign out"/> +</form> +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/http-test b/sandbox/sebastien/cpp/apr-2/modules/http/http-test new file mode 100755 index 0000000000..0db47fe189 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/http-test @@ -0,0 +1,32 @@ +#!/bin/sh + +# 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. + +# Setup +./httpd-conf tmp localhost 8090 htdocs +./httpd-start tmp +sleep 2 + +# Test +./curl-test +rc=$? + +# Cleanup +./httpd-stop tmp +sleep 2 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/http.hpp b/sandbox/sebastien/cpp/apr-2/modules/http/http.hpp new file mode 100644 index 0000000000..95b904435d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/http.hpp @@ -0,0 +1,663 @@ +/* + * 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_http_hpp +#define tuscany_http_hpp + +/** + * CURL HTTP client functions. + */ + +#include <unistd.h> +#include <curl/curl.h> +#include <curl/types.h> +#include <curl/easy.h> +#include <apr_network_io.h> +#include <apr_portable.h> +#include <apr_poll.h> + +#include "string.hpp" +#include "gc.hpp" +#include "list.hpp" +#include "value.hpp" +#include "element.hpp" +#include "monad.hpp" +#include "parallel.hpp" +#include "../atom/atom.hpp" +#include "../rss/rss.hpp" +#include "../json/json.hpp" + +namespace tuscany { +namespace http { + +/** + * CURL library runtime, one per process. + */ +class CURLRuntime { +public: + CURLRuntime() { + curl_global_init(CURL_GLOBAL_ALL); + } +} curlRuntime; + +/** + * Represents a CURL session handle. + */ +class CURLSession { +public: + CURLSession() : h(NULL), p(NULL), sock(NULL), wpollset(NULL), wpollfd(NULL), rpollset(NULL), rpollfd(NULL), owner(false), ca(""), cert(""), key("") { + } + + CURLSession(const string& ca, const string& cert, const string& key) : h(curl_easy_init()), p(gc_pool(mkpool())), sock(NULL), wpollset(NULL), wpollfd(NULL), rpollset(NULL), rpollfd(NULL), owner(true), ca(ca), cert(cert), key(key) { + } + + CURLSession(const CURLSession& c) : h(c.h), p(c.p), sock(c.sock), wpollset(c.wpollset), wpollfd(c.wpollfd), rpollset(c.rpollset), rpollfd(c.rpollfd), owner(false), ca(c.ca), cert(c.cert), key(c.key) { + } + + ~CURLSession() { + if (!owner) + return; + if (h == NULL) + return; + curl_easy_cleanup(h); + destroy(p); + } + +private: + CURL* h; + gc_pool p; + apr_socket_t* sock; + apr_pollset_t* wpollset; + apr_pollfd_t* wpollfd; + apr_pollset_t* rpollset; + apr_pollfd_t* rpollfd; + bool owner; + + friend CURL* handle(const CURLSession& cs); + friend apr_socket_t* sock(const CURLSession& cs); + friend const failable<bool> connect(const string& url, CURLSession& cs); + friend const failable<bool> send(const char* c, const size_t l, const CURLSession& cs); + friend const failable<size_t> recv(char* c, const size_t l, const CURLSession& cs); + +public: + string ca; + string cert; + string key; +}; + +/** + * Returns the CURL handle used by a CURL session. + */ +CURL* handle(const CURLSession& cs) { + return cs.h; +} + +/** + * Return an apr_socket_t for the socket used by a CURL session. + */ +apr_socket_t* sock(const CURLSession& cs) { + return cs.sock; +} + +/** + * Convert a socket fd to an apr_socket_t. + */ +apr_socket_t* sock(const int sd, const gc_pool& p) { + int fd = sd; + apr_socket_t* s = NULL; + apr_os_sock_put(&s, &fd, pool(p)); + return s; +} + +/** + * Convert a CURL return code to an error string. + */ +const string curlreason(CURLcode rc) { + return curl_easy_strerror(rc); +} + +/** + * Convert an APR status to an error string. + */ +const string apreason(apr_status_t rc) { + char buf[256]; + return apr_strerror(rc, buf, sizeof(buf)); +} + +/** + * Setup a CURL session + */ +const failable<CURL*> setup(const string& url, const CURLSession& cs) { + + // Init CURL session + CURL* ch = handle(cs); + curl_easy_reset(ch); + curl_easy_setopt(ch, CURLOPT_USERAGENT, "libcurl/1.0"); + + // Setup protocol options + curl_easy_setopt(ch, CURLOPT_TCP_NODELAY, true); + curl_easy_setopt(ch, CURLOPT_FOLLOWLOCATION, true); + curl_easy_setopt(ch, CURLOPT_POSTREDIR, CURL_REDIR_POST_ALL); + + // Setup SSL options + if (cs.ca != "") { + debug(cs.ca, "http::setup::ca"); + curl_easy_setopt(ch, CURLOPT_CAINFO, c_str(cs.ca)); + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, true); + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYHOST, 2); + } else + curl_easy_setopt(ch, CURLOPT_SSL_VERIFYPEER, false); + if (cs.cert != "") { + debug(cs.cert, "http::setup::cert"); + curl_easy_setopt(ch, CURLOPT_SSLCERT, c_str(cs.cert)); + curl_easy_setopt(ch, CURLOPT_SSLCERTTYPE, "PEM"); + } + if (cs.key != "") { + debug(cs.key, "http::setup::key"); + curl_easy_setopt(ch, CURLOPT_SSLKEY, c_str(cs.key)); + curl_easy_setopt(ch, CURLOPT_SSLKEYTYPE, "PEM"); + } + + // Set target URL + curl_easy_setopt(ch, CURLOPT_URL, c_str(url)); + + return ch; +} + +/** + * Context passed to the read callback function. + */ +class CURLReadContext { +public: + CURLReadContext(const list<string>& ilist) : ilist(ilist) { + } + list<string> ilist; +}; + +/** + * Called by CURL to read data to send. + */ +size_t readCallback(void *ptr, size_t size, size_t nmemb, void *data) { + CURLReadContext& rcx = *static_cast<CURLReadContext*>(data); + if (isNil(rcx.ilist)) + return 0; + const list<string> f(fragment(rcx.ilist, size * nmemb)); + const string s = car(f); + rcx.ilist = cdr(f); + memcpy(ptr, c_str(s), length(s)); + return length(s); +} + +/** + * Context passed to CURL write callback function. + */ +template<typename R> class CURLWriteContext { +public: + CURLWriteContext(const lambda<R(const string&, const R)>& reduce, const R& accum) : reduce(reduce), accum(accum) { + } + const lambda<R(const string&, const R)> reduce; + R accum; +}; + +/** + * Called by CURL to write received data. + */ +template<typename R> size_t writeCallback(void *ptr, size_t size, size_t nmemb, void *data) { + CURLWriteContext<R>& wcx = *(static_cast<CURLWriteContext<R>*> (data)); + const size_t realsize = size * nmemb; + wcx.accum = wcx.reduce(string((const char*)ptr, realsize), wcx.accum); + return realsize; +} + +/** + * Apply an HTTP verb to a list containing a list of headers and a list of content, and + * a reduce function used to process the response. + */ +curl_slist* headers(curl_slist* cl, const list<string>& h) { + if (isNil(h)) + return cl; + return headers(curl_slist_append(cl, c_str(string(car(h)))), cdr(h)); +} + +template<typename R> const failable<list<R> > apply(const list<list<string> >& hdr, const lambda<R(const string&, const R)>& reduce, const R& initial, const string& url, const string& verb, const CURLSession& cs) { + debug(url, "http::apply::url"); + debug(verb, "http::apply::verb"); + + // Setup the CURL session + const failable<CURL*> fch = setup(url, cs); + if (!hasContent(fch)) + return mkfailure<list<R>>(reason(fch)); + CURL* ch = content(fch); + + // Set the request headers + curl_slist* hl = headers(NULL, car(hdr)); + if (hl != NULL) + curl_easy_setopt(ch, CURLOPT_HTTPHEADER, hl); + + // Convert request body to a string + // TODO use HTTP chunking instead + ostringstream os; + write(cadr(hdr), os); + const string s = str(os); + const size_t sz = length(s); + + // Setup the read, write header and write data callbacks + CURLReadContext rcx(mklist(s)); + curl_easy_setopt(ch, CURLOPT_READFUNCTION, (size_t (*)(void*, size_t, size_t, void*))readCallback); + curl_easy_setopt(ch, CURLOPT_READDATA, &rcx); + CURLWriteContext<R> hcx(reduce, initial); + curl_easy_setopt(ch, CURLOPT_HEADERFUNCTION, (size_t (*)(void*, size_t, size_t, void*))(writeCallback<R>)); + curl_easy_setopt(ch, CURLOPT_HEADERDATA, &hcx); + CURLWriteContext<R> wcx(reduce, initial); + curl_easy_setopt(ch, CURLOPT_WRITEFUNCTION, (size_t (*)(void*, size_t, size_t, void*))(writeCallback<R>)); + curl_easy_setopt(ch, CURLOPT_WRITEDATA, &wcx); + + // Apply the HTTP verb + if (verb == "POST") { + curl_easy_setopt(ch, CURLOPT_POST, true); + curl_easy_setopt(ch, CURLOPT_POSTFIELDSIZE, sz); + } else if (verb == "PUT") { + curl_easy_setopt(ch, CURLOPT_UPLOAD, true); + curl_easy_setopt(ch, CURLOPT_INFILESIZE, sz); + } else if (verb == "DELETE") + curl_easy_setopt(ch, CURLOPT_CUSTOMREQUEST, "DELETE"); + const CURLcode rc = curl_easy_perform(ch); + + // Free the headers + if (hl != NULL) + curl_slist_free_all(hl); + + // Return the HTTP return code or content + if (rc) + return mkfailure<list<R> >(string(curl_easy_strerror(rc))); + long httprc; + curl_easy_getinfo (ch, CURLINFO_RESPONSE_CODE, &httprc); + if (httprc != 200 && httprc != 201) { + ostringstream es; + es << "HTTP code " << httprc; + return mkfailure<list<R> >(str(es)); + } + return mklist<R>(hcx.accum, wcx.accum); +} + +/** + * Evaluate an expression remotely, at the given URL. + */ +const failable<value> evalExpr(const value& expr, const string& url, const CURLSession& cs) { + debug(url, "http::evalExpr::url"); + debug(expr, "http::evalExpr::input"); + + // Convert expression to a JSON-RPC request + js::JSContext cx; + const failable<list<string> > jsreq = json::jsonRequest(1, car<value>(expr), cdr<value>(expr), cx); + if (!hasContent(jsreq)) + return mkfailure<value>(reason(jsreq)); + + // POST it to the URL + const list<string> h = mklist<string>("Content-Type: application/json-rpc"); + const failable<list<list<string> > > res = apply<list<string> >(mklist<list<string> >(h, content(jsreq)), rcons<string>, list<string>(), url, "POST", cs); + if (!hasContent(res)) + return mkfailure<value>(reason(res)); + + // Parse and return JSON-RPC result + const failable<value> rval = json::jsonResultValue(cadr<list<string> >(content(res)), cx); + debug(rval, "http::evalExpr::result"); + if (!hasContent(rval)) + return mkfailure<value>(reason(rval)); + return content(rval); +} + +/** + * Find and return a header. + */ +const failable<string> header(const char* prefix, const list<string>& h) { + if (isNil(h)) + return mkfailure<string>(string("Couldn't find header: ") + prefix); + const string s = car(h); + if (find(s, prefix) != 0) + return header(prefix, cdr(h)); + const string l(substr(s, length(prefix))); + return substr(l, 0, find_first_of(l, "\r\n")); +} + +/** + * Find and return a location header. + */ +const failable<string> location(const list<string>& h) { + return header("Location: ", h); +} + +/** + * Convert a location to an entry id. + */ +const failable<value> entryId(const failable<string> l) { + if (!hasContent(l)) + return mkfailure<value>(reason(l)); + const string ls(content(l)); + return value(mklist<value>(string(substr(ls, find_last(ls, '/') + 1)))); +} + +/** + * Find and return a content-type header. + */ +const failable<string> contentType(const list<string>& h) { + return header("Content-Type: ", h); +} + +/** + * HTTP GET, return the resource at the given URL. + */ +template<typename R> const failable<list<R> > get(const lambda<R(const string&, const R)>& reduce, const R& initial, const string& url, const CURLSession& cs) { + debug(url, "http::get::url"); + const list<list<string> > req = mklist(list<string>(), list<string>()); + return apply(req, reduce, initial, url, "GET", cs); +} + +/** + * HTTP GET, return a list of values representing the resource at the given URL. + */ +const failable<value> getcontent(const string& url, const CURLSession& cs) { + debug(url, "http::get::url"); + + // Get the contents of the resource at the given URL + const failable<list<list<string> > > res = get<list<string>>(rcons<string>, list<string>(), url, cs); + if (!hasContent(res)) + return mkfailure<value>(reason(res)); + const list<string> ls(reverse(cadr(content(res)))); + + // Return the content as a list of values + const value val(mkvalues(ls)); + debug(val, "http::get::result"); + return val; +} + +/** + * HTTP GET, return a list of values representing the resource at the given URL. + */ +const failable<value> get(const string& url, const CURLSession& cs) { + debug(url, "http::get::url"); + + // Get the contents of the resource at the given URL + const failable<list<list<string> > > res = get<list<string> >(rcons<string>, list<string>(), url, cs); + if (!hasContent(res)) + return mkfailure<value>(reason(res)); + const string ct(content(contentType(car(content(res))))); + debug(ct, "http::get::contentType"); + + const list<string> ls(reverse(cadr(content(res)))); + debug(ls, "http::get::content"); + + if (contains(ct, "application/atom+xml;type=entry")) { + // Read an ATOM entry + const value val(atom::entryValue(content(atom::readATOMEntry(ls)))); + debug(val, "http::get::result"); + return val; + } + if (contains(ct, "application/atom+xml;type=feed") || atom::isATOMFeed(ls)) { + // Read an ATOM feed + const value val(atom::feedValues(content(atom::readATOMFeed(ls)))); + debug(val, "http::get::result"); + return val; + } + if (contains(ct, "application/rss+xml") || rss::isRSSFeed(ls)) { + // Read an RSS feed + const value val(rss::feedValues(content(rss::readRSSFeed(ls)))); + debug(val, "http::get::result"); + return val; + } + if (contains(ct, "text/javascript") || contains(ct, "application/json") || json::isJSON(ls)) { + // Read a JSON document + js::JSContext cx; + const value val(json::jsonValues(content(json::readJSON(ls, cx)))); + debug(val, "http::get::result"); + return val; + } + if (contains(ct, "text/xml") || contains(ct, "application/xml") || isXML(ls)) { + // Read an XML document + const value val(elementsToValues(readXML(ls))); + debug(val, "http::get::result"); + return val; + } + + // Return the content type and a content list + const value val(mklist<value>(ct, mkvalues(ls))); + debug(val, "http::get::result"); + return val; +} + +/** + * HTTP POST. + */ +const failable<value> post(const value& val, const string& url, const CURLSession& cs) { + + // Convert value to an ATOM entry + const failable<list<string> > entry = atom::writeATOMEntry(atom::entryValuesToElements(val)); + if (!hasContent(entry)) + return mkfailure<value>(reason(entry)); + debug(url, "http::post::url"); + debug(content(entry), "http::post::input"); + + // POST it to the URL + const list<string> h = mklist<string>("Content-Type: application/atom+xml"); + const list<list<string> > req = mklist<list<string> >(h, content(entry)); + const failable<list<list<string> > > res = apply<list<string>>(req, rcons<string>, list<string>(), url, "POST", cs); + if (!hasContent(res)) + return mkfailure<value>(reason(res)); + + // Return the new entry id from the HTTP location header + const failable<value> eid(entryId(location(car(content(res))))); + debug(eid, "http::post::result"); + return eid; +} + +/** + * HTTP PUT. + */ +const failable<value> put(const value& val, const string& url, const CURLSession& cs) { + + // Convert value to an ATOM entry + const failable<list<string> > entry = atom::writeATOMEntry(atom::entryValuesToElements(val)); + if (!hasContent(entry)) + return mkfailure<value>(reason(entry)); + debug(url, "http::put::url"); + debug(content(entry), "http::put::input"); + + // PUT it to the URL + const list<string> h = mklist<string>("Content-Type: application/atom+xml"); + const list<list<string> > req = mklist<list<string> >(h, content(entry)); + const failable<list<list<string> > > res = apply<list<string> >(req, rcons<string>, list<string>(), url, "PUT", cs); + if (!hasContent(res)) + return mkfailure<value>(reason(res)); + + debug(true, "http::put::result"); + return value(true); +} + +/** + * HTTP DELETE. + */ +const failable<value, string> del(const string& url, const CURLSession& cs) { + debug(url, "http::delete::url"); + + const list<list<string> > req = mklist(list<string>(), list<string>()); + const failable<list<list<string> > > res = apply<list<string> >(req, rcons<string>, list<string>(), url, "DELETE", cs); + if (!hasContent(res)) + return mkfailure<value>(reason(res)); + + debug(true, "http::delete::result"); + return value(true); +} + +/** + * Returns the current host name. + */ +const string hostname() { + char h[256]; + if (gethostname(h, 256) == -1) + return "localhost"; + return h; +} + +/** + * Create an APR pollfd for a socket. + */ +apr_pollfd_t* pollfd(apr_socket_t* s, const int e, const gc_pool& p) { + apr_pollfd_t* pfd = gc_new<apr_pollfd_t>(p); + pfd->p = pool(p); + pfd->desc_type = APR_POLL_SOCKET; + pfd->reqevents = (apr_int16_t)e; + pfd->rtnevents = (apr_int16_t)e; + pfd->desc.s = s; + pfd->client_data = NULL; + return pfd; +} + +/** + * Connect to a URL. + */ +const failable<bool> connect(const string& url, CURLSession& cs) { + debug(url, "http::connect::url"); + + // Setup the CURL session + const failable<CURL*> fch = setup(url, cs); + if (!hasContent(fch)) + return mkfailure<bool>(reason(fch)); + CURL* ch = content(fch); + + // Connect + curl_easy_setopt(ch, CURLOPT_CONNECT_ONLY, true); + const CURLcode rc = curl_easy_perform(ch); + if (rc) + return mkfailure<bool>(string(curl_easy_strerror(rc))); + + // Convert the connected socket to an apr_socket_t + int sd; + const CURLcode grc = curl_easy_getinfo(ch, CURLINFO_LASTSOCKET, &sd); + if (grc) + return mkfailure<bool>(string(curl_easy_strerror(grc))); + cs.sock = sock(sd, cs.p); + + // Create pollsets and pollfds which can be used to poll the socket + apr_status_t rpcrc = apr_pollset_create(&cs.rpollset, 1, pool(cs.p), 0); + if (rpcrc != APR_SUCCESS) + return mkfailure<bool>(apreason(rpcrc)); + cs.rpollfd = pollfd(cs.sock, APR_POLLIN, cs.p); + apr_pollset_add(cs.rpollset, cs.rpollfd); + apr_status_t wpcrc = apr_pollset_create(&cs.wpollset, 1, pool(cs.p), 0); + if (wpcrc != APR_SUCCESS) + return mkfailure<bool>(apreason(wpcrc)); + cs.wpollfd = pollfd(cs.sock, APR_POLLOUT, cs.p); + apr_pollset_add(cs.wpollset, cs.wpollfd); + + return true; +} + +/** + * Send an array of chars. + */ +const failable<bool> send(const char* c, const size_t l, const CURLSession& cs) { + + // Send the data + size_t wl = 0; + const CURLcode rc = curl_easy_send(cs.h, c, (size_t)l, &wl); + if (rc == CURLE_OK && wl == (size_t)l) + return true; + if (rc != CURLE_AGAIN) + return mkfailure<bool>(curlreason(rc)); + + // If the socket was not ready, wait for it to become ready + const apr_pollfd_t* pollfds; + apr_int32_t pollcount; + apr_status_t pollrc = apr_pollset_poll(cs.wpollset, -1, &pollcount, &pollfds); + if (pollrc != APR_SUCCESS) + return mkfailure<bool>(apreason(pollrc)); + + // Send what's left + return send(c + wl, l - wl, cs); +} + +/** + * Receive an array of chars. + */ +const failable<size_t> recv(char* c, const size_t l, const CURLSession& cs) { + + // Receive data + size_t rl; + const CURLcode rc = curl_easy_recv(cs.h, c, (size_t)l, &rl); + if (rc == CURLE_OK) + return (size_t)rl; + if (rc == 1) + return 0; + if (rc != CURLE_AGAIN) + return mkfailure<size_t>(curlreason(rc)); + + // If the socket was not ready, wait for it to become ready + const apr_pollfd_t* pollfds; + apr_int32_t pollcount; + apr_status_t pollrc = apr_pollset_poll(cs.rpollset, -1, &pollcount, &pollfds); + if (pollrc != APR_SUCCESS) + return mkfailure<size_t>(apreason(pollrc)); + + // Receive again + return recv(c, l, cs); +} + +/** + * HTTP client proxy function. + */ +struct proxy { + proxy(const string& uri, const string& ca, const string& cert, const string& key, const gc_pool& p) : p(p), uri(uri), ca(ca), cert(cert), key(key), cs(*(new (gc_new<CURLSession>(p)) CURLSession(ca, cert, key))) { + } + + const value operator()(const list<value>& args) const { + const value fun = car(args); + if (fun == "get") { + const failable<value> val = get(uri + path(cadr(args)), cs); + return content(val); + } + if (fun == "post") { + const failable<value> val = post(caddr(args), uri + path(cadr(args)), cs); + return content(val); + } + if (fun == "put") { + const failable<value> val = put(caddr(args), uri + path(cadr(args)), cs); + return content(val); + } + if (fun == "delete") { + const failable<value> val = del(uri + path(cadr(args)), cs); + return content(val); + } + const failable<value> val = evalExpr(args, uri, cs); + return content(val); + } + + const gc_pool p; + const string uri; + const string ca; + const string cert; + const string key; + const CURLSession& cs; +}; + +} +} + +#endif /* tuscany_http_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-addr b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-addr new file mode 100755 index 0000000000..62fc775ea7 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-addr @@ -0,0 +1,54 @@ +#!/bin/sh + +# 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. + +# Parse a string in the form ip-addr:local-port/public-port +addr=`echo $2 | awk -F "/" '{ print $1 }'` +ip=`echo $addr | awk -F ":" '{ print $1 }'` +port=`echo $addr | awk -F ":" '{ print $2 }'` +if [ "$port" = "" ]; then + port=$ip + ip="" + listen=$port + vhost="*:$port" +else + listen="$ip:$port" + vhost="$ip:$port" +fi +pport=`echo $2 | awk -F "/" '{ print $2 }'` +if [ "$pport" = "" ]; then + pport=$port +fi + +# Return the requested part +if [ "$1" = "ip" ]; then + echo $ip +fi +if [ "$1" = "port" ]; then + echo $port +fi +if [ "$1" = "pport" ]; then + echo $pport +fi +if [ "$1" = "listen" ]; then + echo $listen +fi +if [ "$1" = "vhost" ]; then + echo $vhost +fi +return 0 diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-conf b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-conf new file mode 100755 index 0000000000..37fa2e4051 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-conf @@ -0,0 +1,255 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +jsprefix=`readlink -f $here/../js` + +host=$2 +port=`$here/httpd-addr port $3` +pport=`$here/httpd-addr pport $3` +listen=`$here/httpd-addr listen $3` +vhost=`$here/httpd-addr vhost $3` + +mkdir -p $4 +htdocs=`readlink -f $4` + +user=`id -un` +group=`id -gn` + +modules_prefix=`cat $here/httpd-modules.prefix` + +mkdir -p $root +mkdir -p $root/logs +mkdir -p $root/conf +cat >$root/conf/httpd.conf <<EOF +# Generated by: httpd-conf $* +# Apache HTTPD server configuration + +# Main server name +ServerName http://$host:$pport +PidFile $root/logs/httpd.pid + +# Load configured MPM +Include conf/mpm.conf + +# Load required modules +Include conf/modules.conf + +# Basic security precautions +User $user +Group $group +ServerSignature Off +ServerTokens Prod +Timeout 45 +LimitRequestBody 1048576 +HostNameLookups Off + +# Log HTTP requests +# [timestamp] [access] remote-host remote-ident remote-user "request-line" +# status response-size "referrer" "user-agent" "user-track" local-IP +# virtual-host response-time bytes-received bytes-sent +LogLevel info +ErrorLog $root/logs/error_log +LogFormat "[%{%a %b %d %H:%M:%S %Y}t] [access] %h %l %u \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" \"%{cookie}n\" %A %V %D %I %O" combined +CustomLog $root/logs/access_log combined +CookieTracking on +CookieName TuscanyVisitorId + +# Configure Mime types +TypesConfig $here/conf/mime.types + +# Set default document root +DocumentRoot $htdocs +DirectoryIndex index.html + +# Protect server files +<Directory /> +Options None +AllowOverride None +Require all denied +</Directory> + +# Configure authentication +Include conf/auth.conf + +# Allow access to public locations +<Location /login> +AuthType None +Require all granted +</Location> +<Location /logout> +AuthType None +Require all granted +</Location> +<Location /public> +AuthType None +Require all granted +</Location> +<Location /favicon.ico> +AuthType None +Require all granted +</Location> + +# Listen on HTTP port +Listen $listen + +# Setup HTTP virtual host +<VirtualHost $vhost> +ServerName http://$host:$pport + +RewriteEngine on +RewriteCond %{HTTP_HOST} !^$host [NC] +RewriteRule .* http://$host:$pport%{REQUEST_URI} [R,L] + +Include conf/svhost.conf + +# Allow access to document root +<Directory "$htdocs"> +Options FollowSymLinks +AuthType None +Require all granted +</Directory> + +# Allow access to root location +<Location /> +Options FollowSymLinks +AuthType None +Require all granted +</Location> + +</VirtualHost> + +EOF + +# Run with the prefork MPM +cat >$root/conf/mpm.conf <<EOF +# Generated by: httpd-conf $* +LoadModule mpm_prefork_module ${modules_prefix}/modules/mod_mpm_prefork.so + +EOF + +# Generate modules list +cat >$root/conf/modules.conf <<EOF +# Generated by: httpd-conf $* +# Load a minimal set of modules, the load order is important +# (e.g. load mod_headers before mod_rewrite, so its hooks execute +# after mod_rewrite's hooks) +LoadModule alias_module ${modules_prefix}/modules/mod_alias.so +LoadModule authn_file_module ${modules_prefix}/modules/mod_authn_file.so +LoadModule authn_core_module ${modules_prefix}/modules/mod_authn_core.so +LoadModule authz_host_module ${modules_prefix}/modules/mod_authz_host.so +LoadModule authz_groupfile_module ${modules_prefix}/modules/mod_authz_groupfile.so +LoadModule authz_user_module ${modules_prefix}/modules/mod_authz_user.so +LoadModule authz_core_module ${modules_prefix}/modules/mod_authz_core.so +LoadModule auth_basic_module ${modules_prefix}/modules/mod_auth_basic.so +LoadModule auth_digest_module ${modules_prefix}/modules/mod_auth_digest.so +LoadModule auth_form_module ${modules_prefix}/modules/mod_auth_form.so +LoadModule request_module ${modules_prefix}/modules/mod_request.so +LoadModule deflate_module ${modules_prefix}/modules/mod_deflate.so +LoadModule filter_module ${modules_prefix}/modules/mod_filter.so +LoadModule proxy_module ${modules_prefix}/modules/mod_proxy.so +LoadModule proxy_connect_module ${modules_prefix}/modules/mod_proxy_connect.so +LoadModule proxy_http_module ${modules_prefix}/modules/mod_proxy_http.so +LoadModule proxy_balancer_module ${modules_prefix}/modules/mod_proxy_balancer.so +LoadModule lbmethod_byrequests_module ${modules_prefix}/modules/mod_lbmethod_byrequests.so +LoadModule headers_module ${modules_prefix}/modules/mod_headers.so +LoadModule ssl_module ${modules_prefix}/modules/mod_ssl.so +LoadModule socache_shmcb_module ${modules_prefix}/modules/mod_socache_shmcb.so +LoadModule rewrite_module ${modules_prefix}/modules/mod_rewrite.so +LoadModule mime_module ${modules_prefix}/modules/mod_mime.so +LoadModule status_module ${modules_prefix}/modules/mod_status.so +LoadModule asis_module ${modules_prefix}/modules/mod_asis.so +LoadModule negotiation_module ${modules_prefix}/modules/mod_negotiation.so +LoadModule dir_module ${modules_prefix}/modules/mod_dir.so +LoadModule setenvif_module ${modules_prefix}/modules/mod_setenvif.so +<IfModule !log_config_module> +LoadModule log_config_module ${modules_prefix}/modules/mod_log_config.so +</IfModule> +LoadModule logio_module ${modules_prefix}/modules/mod_logio.so +LoadModule usertrack_module ${modules_prefix}/modules/mod_usertrack.so +LoadModule vhost_alias_module ${modules_prefix}/modules/mod_vhost_alias.so +LoadModule cgi_module ${modules_prefix}/modules/mod_cgi.so +LoadModule unixd_module ${modules_prefix}/modules/mod_unixd.so +LoadModule session_module ${modules_prefix}/modules/mod_session.so +#LoadModule session_crypto_module ${modules_prefix}/modules/mod_session_crypto.so +LoadModule session_cookie_module ${modules_prefix}/modules/mod_session_cookie.so +LoadModule slotmem_shm_module ${modules_prefix}/modules/mod_slotmem_shm.so +LoadModule ratelimit_module ${modules_prefix}/modules/mod_ratelimit.so +LoadModule reqtimeout_module ${modules_prefix}/modules/mod_reqtimeout.so + +LoadModule mod_tuscany_ssltunnel $here/libmod_tuscany_ssltunnel.so +LoadModule mod_tuscany_openauth $here/libmod_tuscany_openauth.so + +EOF + +# Generate auth configuration +cat >$root/conf/auth.conf <<EOF +# Generated by: httpd-conf $* +# Authentication configuration + +# Allow authorized access to document root +<Directory "$htdocs"> +Options FollowSymLinks +Require all granted +</Directory> + +# Allow authorized access to root location +<Location /> +Options FollowSymLinks +AuthUserFile "$root/conf/httpd.passwd" +Require all granted +</Location> + +EOF + +# Create password and group files +cat >$root/conf/httpd.passwd <<EOF +# Generated by: httpd-conf $* +EOF + +cat >$root/conf/httpd.groups <<EOF +# Generated by: httpd-conf $* +EOF + +# Generate vhost configuration +cat >$root/conf/vhost.conf <<EOF +# Generated by: httpd-conf $* +# Virtual host configuration +UseCanonicalName Off + +EOF + +cat >$root/conf/svhost.conf <<EOF +# Generated by: httpd-conf $* +# Static virtual host configuration +Include conf/vhost.conf + +EOF + +cat >$root/conf/dvhost.conf <<EOF +# Generated by: httpd-conf $* +# Mass dynamic virtual host configuration +Include conf/vhost.conf + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-event-conf b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-event-conf new file mode 100755 index 0000000000..58923d9dd9 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-event-conf @@ -0,0 +1,35 @@ +#!/bin/sh + +# 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. + +# Configure HTTPD to run with the event MPM +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +modules_prefix=`cat $here/httpd-modules.prefix` + +mkdir -p $root +mkdir -p $root/conf +cat >$root/conf/mpm.conf <<EOF +# Generated by: httpd-event-conf $* +# Use HTTPD event MPM +LoadModule mpm_event_module ${modules_prefix}/modules/mod_mpm_event.so + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-restart b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-restart new file mode 100755 index 0000000000..3e3b687f98 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-restart @@ -0,0 +1,25 @@ +#!/bin/sh + +# 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. + +# Restart httpd server +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` + +apachectl=`cat $here/httpd-apachectl.prefix` +$apachectl -k graceful -d $root -f $root/conf/httpd.conf diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-ssl-conf b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-ssl-conf new file mode 100755 index 0000000000..5882a18cb4 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-ssl-conf @@ -0,0 +1,163 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD SSL configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` +gport=`echo $conf | awk '{ print $7 }'` +port=`$here/httpd-addr port $gport` +pport=`$here/httpd-addr pport $gport` + +sslpport=`$here/httpd-addr pport $2` +sslport=`$here/httpd-addr listen $2` +sslvhost=`$here/httpd-addr vhost $2` + +htdocs=`echo $conf | awk '{ print $8 }'` +mkdir -p $htdocs +htdocs=`readlink -f $htdocs` + +# Extract organization name from our CA certificate +org=`openssl x509 -noout -subject -nameopt multiline -in $root/cert/ca.crt | grep organizationName | awk -F "= " '{ print $2 }'` + +# Generate HTTPD configuration +cat >>$root/conf/httpd.conf <<EOF +# Generated by: httpd-ssl-conf $* + +# Configure SSL support +AddType application/x-x509-ca-cert .crt +AddType application/x-pkcs7-crl .crl +SSLPassPhraseDialog builtin +SSLSessionCache "shmcb:$root/logs/ssl_scache(512000)" +SSLSessionCacheTimeout 300 +Mutex "file:$root/logs" ssl-cache +SSLRandomSeed startup builtin +SSLRandomSeed connect builtin + +# Listen on HTTPS port +Listen $sslport + +# HTTPS virtual host +<VirtualHost $sslvhost> +ServerName https://$host:$sslpport + +Include conf/svhost-ssl.conf + +# Allow the server admin to view the server status +<Location /server-status> +SetHandler server-status +HostnameLookups on +Require user admin +</Location> + +</VirtualHost> + +EOF + +# Generate HTTP vhost configuration +cat >>$root/conf/svhost.conf <<EOF +# Generated by: httpd-ssl-conf $* +# Redirect HTTP traffic to HTTPS +<Location /> +RewriteEngine on +RewriteCond %{SERVER_PORT} ^$port$ [OR] +RewriteCond %{SERVER_PORT} ^$pport$ +RewriteRule .* https://$host:$sslpport%{REQUEST_URI} [R,L] +</Location> + +EOF + +cat >>$root/conf/dvhost.conf <<EOF +# Generated by: httpd-ssl-conf $* +# Redirect HTTP traffic to HTTPS +<Location /> +RewriteEngine on +RewriteCond %{SERVER_PORT} ^$port$ [OR] +RewriteCond %{SERVER_PORT} ^$pport$ +RewriteRule .* https://%{SERVER_NAME}:$sslpport%{REQUEST_URI} [R,L] +</Location> + +EOF + +# Generate HTTPS vhost configuration +cat >$root/conf/vhost-ssl.conf <<EOF +# Generated by: httpd-ssl-conf $* +# Virtual host configuration +UseCanonicalName Off + +# Enable SSL +SSLEngine on +SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL +BrowserMatch ".*MSIE.*" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0 +SSLOptions +StrictRequire +OptRenegotiate +FakeBasicAuth + +# Require clients to use SSL and authenticate +<Location /> +SSLRequireSSL +SSLRequire %{SSL_CIPHER_USEKEYSIZE} >= 128 +</Location> + +# Log SSL requests +# [timestamp] [sslaccess] remote-host remote-ident remote-user SSL-protocol +# SSL-cipher "request-line" status response-size "referrer" "user-agent" +# "SSL-client-I-DN" "SSL-client-S-DN" "user-track" local-IP virtual-host +# response-time bytes-received bytes-sent +LogFormat "[%{%a %b %d %H:%M:%S %Y}t] [sslaccess] %h %l %u %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" \"%{SSL_CLIENT_I_DN}x\" \"%{SSL_CLIENT_S_DN}x\" \"%{cookie}n\" %A %V %D %I %O" sslcombined +CustomLog $root/logs/ssl_access_log sslcombined + +EOF + +proxycert="server" +if [ "$proxyconf" != "" ]; then + proxycert="proxy" +fi + +cat >$root/conf/svhost-ssl.conf <<EOF +# Generated by: httpd-ssl-conf $* +# Static virtual host configuration +Include conf/vhost-ssl.conf + +# Declare SSL certificates used in this virtual host +SSLCACertificateFile "$root/cert/ca.crt" +SSLCertificateChainFile "$root/cert/ca.crt" +SSLCertificateFile "$root/cert/server.crt" +SSLCertificateKeyFile "$root/cert/server.key" + +EOF + +cat >$root/conf/dvhost-ssl.conf <<EOF +# Mass dynamic virtual host configuration +# Generated by: httpd-ssl-conf $* +Include conf/vhost-ssl.conf + +# Declare wildcard SSL certificates used in this virtual host +SSLCACertificateFile "$root/cert/ca.crt" +SSLCertificateChainFile "$root/cert/ca.crt" +SSLCertificateFile "$root/cert/vhost.crt" +SSLCertificateKeyFile "$root/cert/vhost.key" + +# Declare proxy SSL client certificates +SSLProxyCACertificateFile "$root/cert/ca.crt" +SSLProxyMachineCertificateFile "$root/cert/$proxycert.pem" + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-start b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-start new file mode 100755 index 0000000000..5c006d1b54 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-start @@ -0,0 +1,25 @@ +#!/bin/sh + +# 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. + +# Start httpd server +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` + +apachectl=`cat $here/httpd-apachectl.prefix` +$apachectl -E $root/logs/error_log -k start -d $root -f $root/conf/httpd.conf diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-stop b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-stop new file mode 100755 index 0000000000..09ac5d035f --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-stop @@ -0,0 +1,25 @@ +#!/bin/sh + +# 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. + +# Stop httpd server +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` + +apachectl=`cat $here/httpd-apachectl.prefix` +$apachectl -k graceful-stop -d $root -f $root/conf/httpd.conf diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-test b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-test new file mode 100755 index 0000000000..a3b9145871 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-test @@ -0,0 +1,40 @@ +#!/bin/sh + +# 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. + +echo "Testing..." +here=`readlink -f $0`; here=`dirname $here` +curl_prefix=`cat $here/../http/curl.prefix` + +# Setup +./httpd-conf tmp localhost 8090 htdocs +./httpd-start tmp +sleep 2 + +# Test HTTP GET +$curl_prefix/bin/curl http://localhost:8090/index.html 2>/dev/null >tmp/index.html +diff tmp/index.html htdocs/index.html +rc=$? + +# Cleanup +./httpd-stop tmp +sleep 2 +if [ "$rc" = "0" ]; then + echo "OK" +fi +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd-worker-conf b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-worker-conf new file mode 100755 index 0000000000..bb6bca4562 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd-worker-conf @@ -0,0 +1,35 @@ +#!/bin/sh + +# 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. + +# Configure HTTPD to run with the worker MPM +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +modules_prefix=`cat $here/httpd-modules.prefix` + +mkdir -p $root +mkdir -p $root/conf +cat >$root/conf/mpm.conf <<EOF +# Generated by: httpd-worker-conf $* +# Use HTTPD worker MPM +LoadModule mpm_worker_module ${modules_prefix}/modules/mod_mpm_worker.so + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/httpd.hpp b/sandbox/sebastien/cpp/apr-2/modules/http/httpd.hpp new file mode 100644 index 0000000000..78d292dc89 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/httpd.hpp @@ -0,0 +1,689 @@ +/* + * 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_httpd_hpp +#define tuscany_httpd_hpp + +/** + * HTTPD module implementation functions. + */ + +#include <apr_strings.h> +#include <apr_fnmatch.h> +#include <apr_lib.h> +#define APR_WANT_STRFUNC +#include <apr_want.h> +#include <apr_base64.h> + +#include <httpd.h> +// Hack to workaround compile error with HTTPD 2.3.8 +#define new new_ +#include <http_config.h> +#undef new +#include <http_core.h> +#include <http_connection.h> +#include <http_request.h> +#include <http_protocol.h> +// Hack to workaround compile error with HTTPD 2.3.8 +#define aplog_module_index aplog_module_index = 0 +#include <http_log.h> +#undef aplog_module_index +#undef APLOG_MODULE_INDEX +#define APLOG_MODULE_INDEX (aplog_module_index ? *aplog_module_index : APLOG_NO_MODULE) +#include <http_main.h> +#include <util_script.h> +#include <util_md5.h> +#include <http_config.h> +#include <http_log.h> +#include <ap_mpm.h> +#include <mod_core.h> +#include <ap_provider.h> +#include <mod_auth.h> + +#include "string.hpp" +#include "stream.hpp" +#include "sstream.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" + + +namespace tuscany { +namespace httpd { + +/** + * Returns a server-scoped module configuration. + */ +template<typename C> void* makeServerConf(apr_pool_t* p, server_rec* s) { + return new (gc_new<C>(p)) C(p, s); +} + +template<typename C> const C& serverConf(const request_rec* r, const module* mod) { + return *(C*)ap_get_module_config(r->server->module_config, mod); +} + +template<typename C> C& serverConf(const server_rec* s, const module* mod) { + return *(C*)ap_get_module_config(s->module_config, mod); +} + +template<typename C> C& serverConf(const cmd_parms* cmd, const module* mod) { + return *(C*)ap_get_module_config(cmd->server->module_config, mod); +} + +/** + * Returns a directory-scoped module configuration. + */ +template<typename C> void* makeDirConf(apr_pool_t *p, char* d) { + return new (gc_new<C>(p)) C(p, d); +} + +template<typename C> const C& dirConf(const request_rec* r, const module* mod) { + return *(C*)ap_get_module_config(r->per_dir_config, mod); +} + +template<typename C> C& dirConf(const void* c) { + return *(C*)c; +} + +/** + * Return the name of a server. + */ +const string serverName(const server_rec* s, const string& def = "localhost") { + ostringstream n; + n << (s->server_scheme != NULL? s->server_scheme : "http") << "://" + << (s->server_hostname != NULL? s->server_hostname : def) << ":" + << (s->port != 0? s->port : 80) + << (s->path != NULL? string(s->path, s->pathlen) : ""); + return str(n); +} + +/** + * Determine the name of a server from an HTTP request. + */ +const string serverName(request_rec* r, const string& def = "localhost") { + ostringstream n; + const char* hn = ap_get_server_name(r); + n << (r->server->server_scheme != NULL? r->server->server_scheme : "http") << "://" + << (hn != NULL? hn : (r->server->server_hostname != NULL? r->server->server_hostname : def)) << ":" + << (r->server->port != 0? r->server->port : 80) + << (r->server->path != NULL? string(r->server->path, r->server->pathlen) : ""); + return str(n); +} + +/** + * Return the host name for a server. + */ +const string hostName(const server_rec* s, const string& def = "localhost") { + return s->server_hostname != NULL? s->server_hostname : def; +} + +/** + * Return the host name from an HTTP request. + */ +const string hostName(request_rec* r, const string& def = "localhost") { + const char* hn = ap_get_server_name(r); + return hn != NULL? hn : (r->server->server_hostname != NULL? r->server->server_hostname : def); +} + +/** + * Return the first subdomain name in a host name. + */ +const string subdomain(const string& host) { + return substr(host, 0, find(host, '.')); +} + +/** + * Return true if a request is targeting a virtual host. + */ +const bool isVirtualHostRequest(const server_rec* s, request_rec* r) { + return hostName(r) != hostName(s); +} + +/** + * Return true if a URI is absolute. + */ +const bool isAbsolute(const string& uri) { + return contains(uri, "://"); +} + +/** + * Return the protocol scheme for a server. + */ +const string scheme(const server_rec* s, const string& def = "http") { + return s->server_scheme != NULL? s->server_scheme : def; +} + +/** + * Return the protocol scheme from an HTTP request. + */ +const string scheme(request_rec* r, const string& def = "http") { + return r->server->server_scheme != NULL? r->server->server_scheme : def; +} + +/** + * Return the content type of a request. + */ +const string contentType(const request_rec* r) { + const char* ct = apr_table_get(r->headers_in, "Content-Type"); + if (ct == NULL) + return ""; + return ct; +} + +/** + * Return the remaining part of a uri after the given path (aka the path info.) + */ +const list<value> pathInfo(const list<value>& uri, const list<value>& path) { + if (isNil(path)) + return uri; + return pathInfo(cdr(uri), cdr(path)); +} + +/** + * Convert a URI and a path to an absolute URL. + */ +const string url(const string& uri, const list<value>& p, request_rec* r) { + const string u = uri + path(p); + return ap_construct_url(r->pool, c_str(u), r); +} + +/** + * Convert a URI to an absolute URL. + */ +const string url(const string& uri, request_rec* r) { + return ap_construct_url(r->pool, c_str(uri), r); +} + +/** + * Escape a URI. + */ +const char escape_c2x[] = "0123456789ABCDEF"; +const string escape(const string& uri) { + debug(uri, "httpd::escape::uri"); + char* copy = (char*)apr_palloc(gc_current_pool(), 3 * length(uri) + 3); + const unsigned char* s = (const unsigned char *)c_str(uri); + unsigned char* d = (unsigned char*)copy; + unsigned c; + while ((c = *s)) { + if (apr_isalnum(c) || c == '_') + *d++ = (unsigned char)c; + else if (c == ' ') + *d++ = '+'; + else { + *d++ = '%'; + *d++ = escape_c2x[c >> 4]; + *d++ = escape_c2x[c & 0xf]; + } + ++s; + } + *d = '\0'; + debug(copy, "httpd::escape::result"); + return copy; +} + +/** + * Unescape a URI. + */ +const string unescape(const string& uri) { + debug(uri, "httpd::unescape::uri"); + char* b = const_cast<char*>(c_str(string(c_str(uri)))); + ap_unescape_url(b); + debug(b, "httpd::unescape::result"); + return b; +} + +/** + * Returns a list of key value pairs from the args in a query string. + */ +const list<value> queryArg(const string& s) { + debug(s, "httpd::queryArg::string"); + const list<string> t = tokenize("=", s); + if (isNil(cdr(t))) + return mklist<value>(c_str(car(t)), ""); + return mklist<value>(c_str(car(t)), cadr(t)); +} + +const string fixupQueryArgs(const string& a) { + const list<string> t = tokenize("?", a); + if (isNil(t) || isNil(cdr(t))) + return a; + return join("&", t); +} + +const list<list<value> > queryArgs(const string& a) { + return map<string, list<value>>(queryArg, tokenize("&", fixupQueryArgs(a))); +} + +/** + * Returns a list of key value pairs from the args in an HTTP request. + */ +const list<list<value> > queryArgs(const request_rec* r) { + if (r->args == NULL) + return list<list<value> >(); + return queryArgs(r->args); +} + +/** + * Converts a list of key value pairs to a query string. + */ +ostringstream& queryString(const list<list<value> > args, ostringstream& os) { + if (isNil(args)) + return os; + debug(car(args), "httpd::queryString::arg"); + os << car(car(args)) << "=" << c_str(cadr(car(args))); + if (!isNil(cdr(args))) + os << "&"; + return queryString(cdr(args), os); +} + +const string queryString(const list<list<value> > args) { + ostringstream os; + return str(queryString(args, os)); +} + +/** + * Converts the args received in a POST to a list of key value pairs. + */ +const list<list<value> > postArgs(const list<value>& a) { + if (isNil(a)) + return list<list<value> >(); + const list<value> l = car(a); + return cons(l, postArgs(cdr(a))); +} + +/** + * Setup the HTTP read policy. + */ +const int setupReadPolicy(request_rec* r) { + const int rc = ap_setup_client_block(r, REQUEST_CHUNKED_DECHUNK); + if(rc != OK) + return rc; + ap_should_client_block(r); + if(r->read_chunked == true && r->remaining == 0) + r->chunked = true; + //apr_table_setn(r->headers_out, "Connection", "close"); + return OK; +} + +/** + * Read the content of a POST or PUT. + */ +const list<string> read(request_rec* r) { + char b[1024]; + const size_t n = ap_get_client_block(r, b, sizeof(b)); + if (n <= 0) + return list<string>(); + return cons(string(b, n), read(r)); +} + +/** + * Write an HTTP result. + */ +const failable<int> writeResult(const failable<list<string> >& ls, const string& ct, request_rec* r) { + if (!hasContent(ls)) + return mkfailure<int>(reason(ls)); + ostringstream os; + write(content(ls), os); + const string ob(str(os)); + debug(ob, "httpd::writeResult"); + + // Make sure browsers come back and check for updated dynamic content + apr_table_setn(r->headers_out, "Expires", "Tue, 01 Jan 1980 00:00:00 GMT"); + + // Compute and return an Etag for the returned content + const string etag(ap_md5(r->pool, (const unsigned char*)c_str(ob))); + + // Check for an If-None-Match header and just return a 304 not-modified status + // if the Etag matches the Etag presented by the client, to save bandwith + const char* match = apr_table_get(r->headers_in, "If-None-Match"); + apr_table_setn(r->headers_out, "ETag", apr_pstrdup(r->pool, c_str(etag))); + if (match != NULL && etag == match) { + + r->status = HTTP_NOT_MODIFIED; + return OK; + } + ap_set_content_type(r, apr_pstrdup(r->pool, c_str(ct))); + ap_rputs(c_str(ob), r); + return OK; +} + +/** + * Report a request execution status. + */ +const int reportStatus(const failable<int>& rc) { + debug(rc, "httpd::reportStatus::rc"); + if (!hasContent(rc)) + return HTTP_INTERNAL_SERVER_ERROR; + return content(rc); +} + +/** + * Construct a redirect URI. + */ +const string redirectURI(const string& file, const string& pi) { + return file + pi; +} + +const string redirectURI(const string& file, const string& pi, const string& args) { + return file + pi + "?" + args; +} + +/** + * Convert a value to an HTTPD request struc + */ +request_rec* request(const value& v) { + return (request_rec*)(long)(double)v; +} + +/** + * Convert an HTTPD request struct to a value + */ +const value requestValue(request_rec* r) { + return value((double)(long)r); +} + +/** + * Update request filters in an HTTPD redirect request. + * Similar to httpd/modules/http/http_request.c::update_r_in_filters. + */ +const bool redirectFilters(ap_filter_t* f, request_rec* from, request_rec* to) { + if (f == NULL) + return true; + if (f->r == from) + f->r = to; + return redirectFilters(f->next, from, to); +} + +/** + * Create an HTTPD internal redirect request. + * Similar to httpd/modules/http/http_request.c::internal_internal_redirect. + */ +extern "C" { + AP_DECLARE(ap_conf_vector_t*) ap_create_request_config(apr_pool_t *p); +} + +const failable<request_rec*, int> internalRedirectRequest(const string& nr_uri, request_rec* r) { + if (ap_is_recursion_limit_exceeded(r)) + return mkfailure<request_rec*, int>(HTTP_INTERNAL_SERVER_ERROR); + + // Create a new request + request_rec* nr = (request_rec*)apr_pcalloc(r->pool, sizeof(request_rec)); + nr->connection = r->connection; + nr->server = r->server; + nr->pool = r->pool; + nr->method = r->method; + nr->method_number = r->method_number; + nr->allowed_methods = ap_make_method_list(nr->pool, 2); + ap_parse_uri(nr, apr_pstrdup(nr->pool, c_str(nr_uri))); + nr->filename = apr_pstrdup(nr->pool, c_str(string("/redirected:") + nr_uri)); + nr->request_config = ap_create_request_config(r->pool); + nr->per_dir_config = r->server->lookup_defaults; + nr->prev = r; + r->next = nr; + + // Run create request hook + ap_run_create_request(nr); + + // Inherit protocol info from the original request + nr->the_request = r->the_request; + nr->allowed = r->allowed; + nr->status = r->status; + nr->assbackwards = r->assbackwards; + nr->header_only = r->header_only; + nr->protocol = r->protocol; + nr->proto_num = r->proto_num; + nr->hostname = r->hostname; + nr->request_time = r->request_time; + nr->main = r->main; + nr->headers_in = r->headers_in; + nr->headers_out = apr_table_make(r->pool, 12); + nr->err_headers_out = r->err_headers_out; + nr->subprocess_env = r->subprocess_env; + nr->notes = apr_table_make(r->pool, 5); + nr->allowed_methods = ap_make_method_list(nr->pool, 2); + nr->htaccess = r->htaccess; + nr->no_cache = r->no_cache; + nr->expecting_100 = r->expecting_100; + nr->no_local_copy = r->no_local_copy; + nr->read_length = r->read_length; + nr->vlist_validator = r->vlist_validator; + nr->user = r->user; + + // Setup input and output filters + nr->proto_output_filters = r->proto_output_filters; + nr->proto_input_filters = r->proto_input_filters; + nr->output_filters = nr->proto_output_filters; + nr->input_filters = nr->proto_input_filters; + if (nr->main) + ap_add_output_filter_handle(ap_subreq_core_filter_handle, NULL, nr, nr->connection); + redirectFilters(nr->input_filters, r, nr); + redirectFilters(nr->output_filters, r, nr); + const int rrc = ap_run_post_read_request(nr); + if (rrc != OK && rrc != DECLINED) + return mkfailure<request_rec*, int>(rrc); + + return nr; +} + +/** + * Process an HTTPD internal redirect request. + * Similar to httpd/modules/http/http_request.c::ap_internal_redirect. + */ +extern "C" { + AP_DECLARE(int) ap_invoke_handler(request_rec *r); +} + +const int internalRedirect(request_rec* nr) { + int status = ap_run_quick_handler(nr, 0); + if (status == DECLINED) { + status = ap_process_request_internal(nr); + if (status == OK) + status = ap_invoke_handler(nr); + } + if (status != OK) { + nr->status = status; + return OK; + } + ap_finalize_request_protocol(nr); + return OK; +} + +/** + * Create and process an HTTPD internal redirect request. + */ +const int internalRedirect(const string& uri, request_rec* r) { + debug(uri, "httpd::internalRedirect"); + const failable<request_rec*, int> nr = httpd::internalRedirectRequest(uri, r); + if (!hasContent(nr)) + return reason(nr); + return httpd::internalRedirect(content(nr)); +} + +/** + * Create an HTTPD sub request. + * Similar to httpd/server/request.c::make_sub_request + */ +const failable<request_rec*, int> internalSubRequest(const string& nr_uri, request_rec* r) { + if (ap_is_recursion_limit_exceeded(r)) + return mkfailure<request_rec*, int>(HTTP_INTERNAL_SERVER_ERROR); + + // Create a new sub pool + apr_pool_t *nrp; + apr_pool_create(&nrp, r->pool); + apr_pool_tag(nrp, "subrequest"); + + // Create a new POST request + request_rec* nr = (request_rec*)apr_pcalloc(nrp, sizeof(request_rec)); + nr->connection = r->connection; + nr->server = r->server; + nr->pool = nrp; + nr->method = "POST"; + nr->method_number = M_POST; + nr->allowed_methods = ap_make_method_list(nr->pool, 2); + ap_parse_uri(nr, apr_pstrdup(nr->pool, c_str(nr_uri))); + nr->filename = apr_pstrdup(nr->pool, c_str(string("/subreq:") + nr_uri)); + nr->request_config = ap_create_request_config(r->pool); + nr->per_dir_config = r->server->lookup_defaults; + + // Inherit some of the protocol info from the parent request + nr->the_request = r->the_request; + nr->hostname = r->hostname; + nr->request_time = r->request_time; + nr->allowed = r->allowed; + nr->status = HTTP_OK; + nr->assbackwards = r->assbackwards; + nr->header_only = r->header_only; + nr->protocol = const_cast<char*>("INCLUDED"); + nr->hostname = r->hostname; + nr->request_time = r->request_time; + nr->main = r; + nr->headers_in = apr_table_make(r->pool, 12); + nr->headers_out = apr_table_make(r->pool, 12); + nr->err_headers_out = apr_table_make(nr->pool, 5); + nr->subprocess_env = r->subprocess_env; + nr->subprocess_env = apr_table_copy(nr->pool, r->subprocess_env); + nr->notes = apr_table_make(r->pool, 5); + nr->htaccess = r->htaccess; + nr->no_cache = r->no_cache; + nr->expecting_100 = r->expecting_100; + nr->no_local_copy = r->no_local_copy; + nr->read_length = 0; + nr->vlist_validator = r->vlist_validator; + nr->user = r->user; + + // Setup input and output filters + nr->proto_output_filters = r->proto_output_filters; + nr->proto_input_filters = r->proto_input_filters; + nr->output_filters = nr->proto_output_filters; + nr->input_filters = nr->proto_input_filters; + ap_add_output_filter_handle(ap_subreq_core_filter_handle, NULL, nr, nr->connection); + + // Run create request hook + ap_run_create_request(nr); + nr->used_path_info = AP_REQ_DEFAULT_PATH_INFO; + + return nr; +} + +/** + * Return an HTTP external redirect request. + */ +const int externalRedirect(const string& uri, request_rec* r) { + debug(uri, "httpd::externalRedirect"); + r->status = HTTP_MOVED_TEMPORARILY; + apr_table_setn(r->headers_out, "Location", apr_pstrdup(r->pool, c_str(uri))); + r->filename = apr_pstrdup(r->pool, c_str(string("/redirect:/") + uri)); + return HTTP_MOVED_TEMPORARILY; +} + +/** + * Put a value in the process user data. + */ +const bool putUserData(const string& k, const void* v, const server_rec* s) { + apr_pool_userdata_set((const void *)v, c_str(k), apr_pool_cleanup_null, s->process->pool); + return true; +} + +/** + * Return a user data value. + */ +const void* userData(const string& k, const server_rec* s) { + void* v = NULL; + apr_pool_userdata_get(&v, c_str(k), s->process->pool); + return v; +} + +#ifdef WANT_MAINTAINER_MODE + +/** + * Debug log. + */ + +/** + * Log an optional value. + */ +const char* debugOptional(const char* s) { + if (s == NULL) + return ""; + return s; +} + +/** + * Log a header + */ +int debugHeader(unused void* r, const char* key, const char* value) { + cdebug << " header key: " << key << ", value: " << value << endl; + return 1; +} + +/** + * Log an environment variable + */ +int debugEnv(unused void* r, const char* key, const char* value) { + cdebug << " var key: " << key << ", value: " << value << endl; + return 1; +} + +/** + * Log a note. + */ +int debugNote(unused void* r, const char* key, const char* value) { + cdebug << " note key: " << key << ", value: " << value << endl; + return 1; +} + +/** + * Log a request. + */ +const bool debugRequest(request_rec* r, const string& msg) { + cdebug << msg << ":" << endl; + cdebug << " unparsed uri: " << debugOptional(r->unparsed_uri) << endl; + cdebug << " uri: " << debugOptional(r->uri) << endl; + cdebug << " path info: " << debugOptional(r->path_info) << endl; + cdebug << " filename: " << debugOptional(r->filename) << endl; + cdebug << " uri tokens: " << pathTokens(r->uri) << endl; + cdebug << " args: " << debugOptional(r->args) << endl; + cdebug << " server: " << debugOptional(r->server->server_hostname) << endl; + cdebug << " protocol: " << debugOptional(r->protocol) << endl; + cdebug << " method: " << debugOptional(r->method) << endl; + cdebug << " method number: " << r->method_number << endl; + cdebug << " content type: " << contentType(r) << endl; + cdebug << " content encoding: " << debugOptional(r->content_encoding) << endl; + apr_table_do(debugHeader, r, r->headers_in, NULL); + cdebug << " user: " << debugOptional(r->user) << endl; + cdebug << " auth type: " << debugOptional(r->ap_auth_type) << endl; + apr_table_do(debugEnv, r, r->subprocess_env, NULL); + apr_table_do(debugNote, r, r->notes, NULL); + return true; +} + +#define httpdDebugRequest(r, msg) httpd::debugRequest(r, msg) + +#else + +#define httpdDebugRequest(r, msg) + +#endif + +} +} + +#endif /* tuscany_httpd_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/mod-openauth.cpp b/sandbox/sebastien/cpp/apr-2/modules/http/mod-openauth.cpp new file mode 100644 index 0000000000..b43624f08d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/mod-openauth.cpp @@ -0,0 +1,325 @@ +/* + * 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$ */ + +/** + * HTTPD module for Tuscany Open authentication. + * + * This module allows multiple authentication mechanisms to co-exist in a + * single Web site: + * - OAuth1 using Tuscany's mod-tuscany-oauth1 + * - OAuth2 using Tuscany's mod-tuscany-oauth2 + * - OpenID using mod_auth_openid + * - Form-based using HTTPD's mod_auth_form + * - SSL certificate using SSLFakeBasicAuth and mod_auth_basic + */ + +#include <sys/stat.h> + +#include "string.hpp" +#include "stream.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "httpd.hpp" +#include "http.hpp" +#include "openauth.hpp" + +extern "C" { +extern module AP_MODULE_DECLARE_DATA mod_tuscany_openauth; +} + +namespace tuscany { +namespace openauth { + +/** + * Server configuration. + */ +class ServerConf { +public: + ServerConf(apr_pool_t* p, server_rec* s) : p(p), server(s) { + } + + const gc_pool p; + server_rec* server; +}; + +/** + * Directory configuration. + */ +class DirConf { +public: + DirConf(apr_pool_t* p, char* d) : p(p), dir(d), enabled(false), login("") { + } + + const gc_pool p; + const char* dir; + bool enabled; + string login; +}; + +/** + * Return the user info from a form auth session cookie. + */ +const failable<value> userInfo(const value& sid, const string& realm) { + const list<list<value>> info = httpd::queryArgs(sid); + debug(info, "modopenauth::userInfo::info"); + const list<value> user = assoc<value>(realm + "-user", info); + if (isNil(user)) + return mkfailure<value>("Couldn't retrieve user id"); + const list<value> pw = assoc<value>(realm + "-pw", info); + if (isNil(pw)) + return mkfailure<value>("Couldn't retrieve password"); + return value(mklist<value>(mklist<value>("realm", realm), mklist<value>("id", cadr(user)), mklist<value>("password", cadr(pw)))); +} + +/** + * Return the user info from a basic auth header. + */ +const failable<value> userInfo(const char* header, const string& realm, request_rec* r) { + debug(header, "modopenauth::userInfo::header"); + if (strcasecmp(ap_getword(r->pool, &header, ' '), "Basic")) + return mkfailure<value>("Wrong authentication scheme"); + + while (apr_isspace(*header)) + header++; + char *decoded_line = (char*)apr_palloc(r->pool, apr_base64_decode_len(header) + 1); + int length = apr_base64_decode(decoded_line, header); + decoded_line[length] = '\0'; + + const string user(ap_getword_nulls(r->pool, const_cast<const char**>(&decoded_line), ':')); + const string pw(decoded_line); + + return value(mklist<value>(mklist<value>("realm", realm), mklist<value>("id", user), mklist<value>("password", pw))); +} + +/** + * Handle an authenticated request. + */ +const failable<int> authenticated(const list<list<value> >& info, request_rec* r) { + debug(info, "modopenauth::authenticated::info"); + + // Store user info in the request + const list<value> realm = assoc<value>("realm", info); + if (isNil(realm) || isNil(cdr(realm))) + return mkfailure<int>("Couldn't retrieve realm"); + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "REALM"), apr_pstrdup(r->pool, c_str(cadr(realm)))); + + const list<value> id = assoc<value>("id", info); + if (isNil(id) || isNil(cdr(id))) + return mkfailure<int>("Couldn't retrieve user id"); + r->user = apr_pstrdup(r->pool, c_str(cadr(id))); + + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "NICKNAME"), apr_pstrdup(r->pool, c_str(cadr(id)))); + return OK; +} + +/** + * Run the authnz hooks to try to authenticate a request. + */ +const failable<int> checkAuthnz(const string& user, const string& pw, request_rec* r) { + const authn_provider* provider = (const authn_provider*)ap_lookup_provider(AUTHN_PROVIDER_GROUP, AUTHN_DEFAULT_PROVIDER, AUTHN_PROVIDER_VERSION); + if (!provider || !provider->check_password) + return mkfailure<int>("No Authn provider configured"); + apr_table_setn(r->notes, AUTHN_PROVIDER_NAME_NOTE, AUTHN_DEFAULT_PROVIDER); + const authn_status auth_result = provider->check_password(r, c_str(user), c_str(pw)); + apr_table_unset(r->notes, AUTHN_PROVIDER_NAME_NOTE); + if (auth_result != AUTH_GRANTED) + return mkfailure<int>("Authentication failure for: " + user); + return OK; +} + +/** + * Check user authentication. + */ +static int checkAuthn(request_rec *r) { + // Decline if we're not enabled or AuthType is not set to Open + const DirConf& dc = httpd::dirConf<DirConf>(r, &mod_tuscany_openauth); + if (!dc.enabled) + return DECLINED; + const char* atype = ap_auth_type(r); + if (atype == NULL || strcasecmp(atype, "Open")) + return DECLINED; + + gc_scoped_pool pool(r->pool); + httpdDebugRequest(r, "modopenauth::checkAuthn::input"); + + // Get session id from the request + const maybe<string> sid = sessionID(r); + if (hasContent(sid)) { + // Decline if the session id was not created by this module + const string stype = substr(content(sid), 0, 7); + if (stype == "OAuth2_" || stype == "OAuth1_" || stype == "OpenID_") + return DECLINED; + + // Retrieve the auth realm + const char* aname = ap_auth_name(r); + if (aname == NULL) + return httpd::reportStatus(mkfailure<int>("Missing AuthName")); + + // Extract user info from the session id + const failable<value> info = userInfo(content(sid), aname); + if (hasContent(info)) { + + // Try to authenticate the request + const value cinfo = content(info); + const failable<int> authz = checkAuthnz(cadr(assoc<value>("id", cinfo)), cadr(assoc<value>("password", cinfo)), r); + if (!hasContent(authz)) { + + // Authentication failed, redirect to login page + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(login(dc.login, r)); + } + + // Successfully authenticated, store the user info in the request + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(authenticated(cinfo, r)); + } + } + + // Get basic auth header from the request + const char* header = apr_table_get(r->headers_in, (PROXYREQ_PROXY == r->proxyreq) ? "Proxy-Authorization" : "Authorization"); + if (header != NULL) { + + // Retrieve the auth realm + const char* aname = ap_auth_name(r); + if (aname == NULL) + return httpd::reportStatus(mkfailure<int>("Missing AuthName")); + + // Extract user info from the session id + const failable<value> info = userInfo(header, aname, r); + if (hasContent(info)) { + + // Try to authenticate the request + const value cinfo = content(info); + const failable<int> authz = checkAuthnz(cadr(assoc<value>("id", cinfo)), cadr(assoc<value>("password", cinfo)), r); + if (!hasContent(authz)) { + + // Authentication failed, redirect to login page + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(login(dc.login, r)); + } + + // Successfully authenticated, store the user info in the request + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(authenticated(cinfo, r)); + } + } + + // Get the request args + const list<list<value> > args = httpd::queryArgs(r); + + // Decline if the request is for another authentication provider + if (!isNil(assoc<value>("openid_identifier", args))) + return DECLINED; + if (!isNil(assoc<value>("mod_oauth1_step", args))) + return DECLINED; + if (!isNil(assoc<value>("mod_oauth2_step", args))) + return DECLINED; + + // Redirect to the login page + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(login(dc.login, r)); +} + +/** + * Process the module configuration. + */ +int postConfigMerge(ServerConf& mainsc, server_rec* s) { + if (s == NULL) + return OK; + debug(httpd::serverName(s), "modopenauth::postConfigMerge::serverName"); + + return postConfigMerge(mainsc, s->next); +} + +int postConfig(apr_pool_t* p, unused apr_pool_t* plog, unused apr_pool_t* ptemp, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_openauth); + debug(httpd::serverName(s), "modopenauth::postConfig::serverName"); + + // Merge server configurations + return postConfigMerge(sc, s); +} + +/** + * Child process initialization. + */ +void childInit(apr_pool_t* p, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf* psc = (ServerConf*)ap_get_module_config(s->module_config, &mod_tuscany_openauth); + if(psc == NULL) { + cfailure << "[Tuscany] Due to one or more errors mod_tuscany_openauth loading failed. Causing apache to stop loading." << endl; + exit(APEXIT_CHILDFATAL); + } + ServerConf& sc = *psc; + + // Merge the updated configuration into the virtual hosts + postConfigMerge(sc, s->next); +} + +/** + * Configuration commands. + */ +const char* confEnabled(cmd_parms *cmd, void *c, const int arg) { + gc_scoped_pool pool(cmd->pool); + DirConf& dc = httpd::dirConf<DirConf>(c); + dc.enabled = (bool)arg; + return NULL; +} +const char* confLogin(cmd_parms *cmd, void *c, const char* arg) { + gc_scoped_pool pool(cmd->pool); + DirConf& dc = httpd::dirConf<DirConf>(c); + dc.login = arg; + return NULL; +} + +/** + * HTTP server module declaration. + */ +const command_rec commands[] = { + AP_INIT_FLAG("AuthOpenAuth", (const char*(*)())confEnabled, NULL, OR_AUTHCFG, "Tuscany Open Auth authentication On | Off"), + AP_INIT_TAKE1("AuthOpenAuthLoginPage", (const char*(*)())confLogin, NULL, OR_AUTHCFG, "Tuscany Open Auth login page"), + {NULL, NULL, NULL, 0, NO_ARGS, NULL} +}; + +void registerHooks(unused apr_pool_t *p) { + ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_check_authn(checkAuthn, NULL, NULL, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_CONF); +} + +} +} + +extern "C" { + +module AP_MODULE_DECLARE_DATA mod_tuscany_openauth = { + STANDARD20_MODULE_STUFF, + // dir config and merger + tuscany::httpd::makeDirConf<tuscany::openauth::DirConf>, NULL, + // server config and merger + tuscany::httpd::makeServerConf<tuscany::openauth::ServerConf>, NULL, + // commands and hooks + tuscany::openauth::commands, tuscany::openauth::registerHooks +}; + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/mod-ssltunnel.cpp b/sandbox/sebastien/cpp/apr-2/modules/http/mod-ssltunnel.cpp new file mode 100644 index 0000000000..d2c53b462e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/mod-ssltunnel.cpp @@ -0,0 +1,361 @@ +/* + * 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$ */ + +/** + * HTTPD module used to tunnel traffic over an HTTPS connection. + */ + +#include <sys/stat.h> + +#include "string.hpp" +#include "stream.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "httpd.hpp" +#include "http.hpp" + +extern "C" { +extern module AP_MODULE_DECLARE_DATA mod_tuscany_ssltunnel; +} + +namespace tuscany { +namespace httpd { +namespace modssltunnel { + +/** + * Server configuration. + */ +class ServerConf { +public: + ServerConf(apr_pool_t* p, server_rec* s) : p(p), server(s) { + } + + const gc_pool p; + server_rec* server; + string pass; + string host; + string path; + string ca; + string cert; + string key; +}; + +extern "C" { +extern module AP_DECLARE_DATA core_module; +} + +/** + * Process the module configuration. + */ +int M_SSLTUNNEL; +int postConfigMerge(ServerConf& mainsc, apr_pool_t* p, server_rec* s) { + if (s == NULL) + return OK; + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_ssltunnel); + debug(httpd::serverName(s), "modwiring::postConfigMerge::serverName"); + + // Merge configuration from main server + if (length(sc.ca) == 0 && length(mainsc.ca) !=0) + sc.ca = mainsc.ca; + if (length(sc.cert) == 0 && length(mainsc.cert) !=0) + sc.cert = mainsc.cert; + if (length(sc.key) == 0 && length(mainsc.key) !=0) + sc.key = mainsc.key; + + // Parse the configured TunnelPass URI + if (length(sc.pass) != 0) { + apr_uri_t uri; + apr_status_t prc = apr_uri_parse(p, c_str(sc.pass), &uri); + if (prc != APR_SUCCESS) { + mkfailure<int>("Couldn't parse TunnelPass: " + sc.pass + ", " + http::apreason(prc)); + return prc; + } + sc.host = uri.hostname; + sc.path = uri.path; + } + return postConfigMerge(mainsc, p, s->next); +} + +int postConfig(apr_pool_t* p, unused apr_pool_t* plog, unused apr_pool_t* ptemp, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_ssltunnel); + debug(httpd::serverName(s), "modwiring::postConfig::serverName"); + + // Register the SSLTUNNEL method + M_SSLTUNNEL = ap_method_register(p, "SSLTUNNEL"); + + // Merge and process server configurations + return postConfigMerge(sc, p, s); +} + +/** + * Close a connection. + */ +const int close(conn_rec* conn, apr_socket_t* csock) { + debug("modssltunnel::close"); + apr_socket_close(csock); + conn->aborted = 1; + return OK; +} + +/** + * Abort a connection. + */ +const int abort(conn_rec* conn, apr_socket_t* csock, const string& reason) { + debug("modssltunnel::abort"); + apr_socket_close(csock); + conn->aborted = 1; + return httpd::reportStatus(mkfailure<int>(reason)); +} + +/** + * Tunnel traffic from a client connection to a target URL. + */ +int tunnel(conn_rec* conn, const string& ca, const string& cert, const string& key, const string& url, const string& preamble, const gc_pool& p, unused ap_filter_t* ifilter, ap_filter_t* ofilter) { + + // Create input/output bucket brigades + apr_bucket_brigade* ib = apr_brigade_create(pool(p), conn->bucket_alloc); + apr_bucket_brigade* ob = apr_brigade_create(pool(p), conn->bucket_alloc); + + // Get client connection socket + apr_socket_t* csock = (apr_socket_t*)ap_get_module_config(conn->conn_config, &core_module); + + // Open connection to target + http::CURLSession cs(ca, cert, key); + const failable<bool> crc = http::connect(url, cs); + if (!hasContent(crc)) + return abort(conn, csock, reason(crc)); + apr_socket_t* tsock = http::sock(cs); + + // Send preamble + if (length(preamble) != 0) { + debug(preamble, "modssltunnel::tunnel::sendPreambleToTarget"); + const failable<bool> src = http::send(c_str(preamble), length(preamble), cs); + if (!hasContent(src)) + return abort(conn, csock, string("Couldn't send to target: ") + reason(src)); + } + + // Create a pollset for the client and target sockets + apr_pollset_t* pollset; + apr_status_t cprc = apr_pollset_create(&pollset, 2, pool(p), 0); + if (cprc != APR_SUCCESS) + return abort(conn, csock, http::apreason(cprc)); + const apr_pollfd_t* cpollfd = http::pollfd(csock, APR_POLLIN, p); + apr_pollset_add(pollset, cpollfd); + const apr_pollfd_t* tpollfd = http::pollfd(tsock, APR_POLLIN, p); + apr_pollset_add(pollset, tpollfd); + + // Relay traffic in both directions until end of stream + const apr_pollfd_t* pollfds = cpollfd; + apr_int32_t pollcount = 1; + for(;;) { + for (; pollcount > 0; pollcount--, pollfds++) { + if (pollfds->rtnevents & APR_POLLIN) { + if (pollfds->desc.s == csock) { + + // Receive buckets from client + const apr_status_t getrc = ap_get_brigade(conn->input_filters, ib, AP_MODE_READBYTES, APR_BLOCK_READ, HUGE_STRING_LEN); + if (getrc != APR_SUCCESS) + return abort(conn, csock, string("Couldn't receive from client")); + + for (apr_bucket* bucket = APR_BRIGADE_FIRST(ib); bucket != APR_BRIGADE_SENTINEL(ib); bucket = APR_BUCKET_NEXT(bucket)) { + if (APR_BUCKET_IS_FLUSH(bucket)) + continue; + + // Client connection closed + if (APR_BUCKET_IS_EOS(bucket)) + return close(conn, csock); + + const char *data; + apr_size_t rl; + apr_bucket_read(bucket, &data, &rl, APR_BLOCK_READ); + if (rl > 0) { + debug(string(data, rl), "modssltunnel::tunnel::sendToTarget"); + + // Send to target + const failable<bool> src = http::send(data, rl, cs); + if (!hasContent(src)) + return abort(conn, csock, string("Couldn't send to target: ") + reason(src)); + } + } + apr_brigade_cleanup(ib); + } else { + + // Receive from target + char data[8192]; + const failable<size_t> frl = http::recv(data, sizeof(data), cs); + if (!hasContent(frl)) + return abort(conn, csock, string("Couldn't receive from target") + reason(frl)); + const size_t rl = content(frl); + + // Target connection closed + if (rl == 0) + return close(conn, csock); + + // Send bucket to client + debug(string(data, rl), "modssltunnel::tunnel::sendToClient"); + APR_BRIGADE_INSERT_TAIL(ob, apr_bucket_transient_create(data, rl, conn->bucket_alloc)); + APR_BRIGADE_INSERT_TAIL(ob, apr_bucket_flush_create(conn->bucket_alloc)); + if (ap_pass_brigade(ofilter, ob) != APR_SUCCESS) + return abort(conn, csock, "Couldn't send data bucket to client"); + apr_brigade_cleanup(ob); + } + } + + // Error + if (pollfds->rtnevents & (APR_POLLERR | APR_POLLHUP | APR_POLLNVAL)) { + if (pollfds->desc.s == csock) + return abort(conn, csock, "Couldn't receive from client"); + else + return abort(conn, csock, "Couldn't receive from target"); + } + } + + // Poll the client and target sockets + debug("modssltunnel::tunnel::poll"); + apr_status_t pollrc = apr_pollset_poll(pollset, -1, &pollcount, &pollfds); + if (pollrc != APR_SUCCESS) + return abort(conn, csock, "Couldn't poll sockets"); + debug(pollcount, "modssltunnel::tunnel::pollfds"); + } + + // Close client connection + return close(conn, csock); +} + +/** + * Return the first connection filter in a list of filters. + */ +ap_filter_t* connectionFilter(ap_filter_t* f) { + if (f == NULL) + return f; + if (f->frec->ftype < AP_FTYPE_CONNECTION) + return connectionFilter(f->next); + return f; +} + +/** + * Process a client connection and relay it to a tunnel. + */ +int processConnection(conn_rec *conn) { + // Only allow configured virtual hosts + if (!conn->base_server->is_virtual) + return DECLINED; + if (ap_get_module_config(conn->base_server->module_config, &mod_tuscany_ssltunnel) == NULL) + return DECLINED; + + gc_scoped_pool(conn->pool); + const ServerConf& sc = httpd::serverConf<ServerConf>(conn->base_server, &mod_tuscany_ssltunnel); + if (length(sc.pass) == 0) + return DECLINED; + debug(sc.pass, "modssltunnel::processConnection::pass"); + + // Run the tunnel + const string preamble = string("SSLTUNNEL ") + sc.path + string(" HTTP/1.1\r\nHost: ") + sc.host + string("\r\n\r\n"); + debug(preamble, "modssltunnel::processConnection::preamble"); + return tunnel(conn, sc.ca, sc.cert, sc.key, sc.pass, preamble, gc_pool(conn->pool), connectionFilter(conn->input_filters), connectionFilter(conn->output_filters)); +} + +/** + * Tunnel a SSLTUNNEL request to a target host/port. + */ +int handler(request_rec* r) { + if (r->method_number != M_SSLTUNNEL) + return DECLINED; + + // Only allow HTTPS + if (strcmp(r->server->server_scheme, "https")) + return DECLINED; + + // Build the target URL + debug(r->uri, "modssltunnel::handler::uri"); + const list<value> path(pathValues(r->uri)); + const string url = string(cadr(path)) + ":" + caddr(path); + debug(url, "modssltunnel::handler::target"); + + // Run the tunnel + return tunnel(r->connection, "", "", "", url, "", gc_pool(r->pool), connectionFilter(r->proto_input_filters), connectionFilter(r->proto_output_filters)); +} + +/** + * Configuration commands. + */ +const char* confTunnelPass(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_ssltunnel); + sc.pass = arg; + return NULL; +} +const char* confCAFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_ssltunnel); + sc.ca = arg; + return NULL; +} +const char* confCertFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_ssltunnel); + sc.cert = arg; + return NULL; +} +const char* confCertKeyFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_ssltunnel); + sc.key = arg; + return NULL; +} + +/** + * HTTP server module declaration. + */ +const command_rec commands[] = { + AP_INIT_TAKE1("TunnelPass", (const char*(*)())confTunnelPass, NULL, RSRC_CONF, "Tunnel server name"), + AP_INIT_TAKE1("TunnelSSLCACertificateFile", (const char*(*)())confCAFile, NULL, RSRC_CONF, "Tunnel SSL CA certificate file"), + AP_INIT_TAKE1("TunnelSSLCertificateFile", (const char*(*)())confCertFile, NULL, RSRC_CONF, "Tunnel SSL certificate file"), + AP_INIT_TAKE1("TunnelSSLCertificateKeyFile", (const char*(*)())confCertKeyFile, NULL, RSRC_CONF, "Tunnel SSL certificate key file"), + {NULL, NULL, NULL, 0, NO_ARGS, NULL} +}; + +void registerHooks(unused apr_pool_t *p) { + ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_process_connection(processConnection, NULL, NULL, APR_HOOK_MIDDLE); +} + +} +} +} + +extern "C" { + +module AP_MODULE_DECLARE_DATA mod_tuscany_ssltunnel = { + STANDARD20_MODULE_STUFF, + // dir config and merger + NULL, NULL, + // server config and merger + tuscany::httpd::makeServerConf<tuscany::httpd::modssltunnel::ServerConf>, NULL, + // commands and hooks + tuscany::httpd::modssltunnel::commands, tuscany::httpd::modssltunnel::registerHooks +}; + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/open-auth-conf b/sandbox/sebastien/cpp/apr-2/modules/http/open-auth-conf new file mode 100755 index 0000000000..2bd5bc3504 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/open-auth-conf @@ -0,0 +1,55 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD form authentication configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +# Generate form authentication configuration +cat >>$root/conf/auth.conf <<EOF +# Generated by: open-auth-conf $* +# Enable Tuscany open authentication +<Location /> +AuthType Open +AuthName "$host" +AuthOpenAuth On +AuthOpenAuthLoginPage /login +Require valid-user +</Location> + +# Use HTTPD form-based authentication +<Location /login/dologin> +AuthType Form +AuthName "$host" +AuthFormProvider file +AuthFormLoginRequiredLocation /login +AuthFormLogoutLocation / +Session On +SessionCookieName TuscanyOpenAuth path=/;secure=TRUE +#SessionCryptoPassphrase secret +Require valid-user +SetHandler form-login-handler +</Location> + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/openauth.hpp b/sandbox/sebastien/cpp/apr-2/modules/http/openauth.hpp new file mode 100644 index 0000000000..ff69a9732f --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/openauth.hpp @@ -0,0 +1,98 @@ +/* + * 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_openauth_hpp +#define tuscany_openauth_hpp + +/** + * Tuscany Open auth support utility functions. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "../json/json.hpp" +#include "../http/httpd.hpp" +#include "../http/http.hpp" + +namespace tuscany { +namespace openauth { + +/** + * Return the session id from a request. + */ +const char* cookieName(const char* cs) { + if (*cs != ' ') + return cs; + return cookieName(cs + 1); +} +const maybe<string> sessionID(const list<string> c) { + if (isNil(c)) + return maybe<string>(); + const string cn = cookieName(c_str(car(c))); + const size_t i = find(cn, "="); + if (i < length(cn)) { + const list<string> kv = mklist<string>(substr(cn, 0, i), substr(cn, i+1)); + if (!isNil(kv) && !isNil(cdr(kv))) { + if (car(kv) == "TuscanyOpenAuth") + return cadr(kv); + } + } + return sessionID(cdr(c)); +} + +const maybe<string> sessionID(const request_rec* r) { + const char* c = apr_table_get(r->headers_in, "Cookie"); + debug(c, "openauth::sessionid::cookies"); + if (c == NULL) + return maybe<string>(); + return sessionID(tokenize(";", c)); +} + +/** + * Convert a session id to a cookie string. + */ +const string cookie(const string& sid) { + const time_t t = time(NULL) + 86400; + char exp[32]; + strftime(exp, 32, "%a, %d-%b-%Y %H:%M:%S GMT", gmtime(&t)); + const string c = string("TuscanyOpenAuth=") + sid + string(";path=/;expires=" + string(exp)) + ";secure=TRUE"; + debug(c, "openauth::cookie"); + return c; +} + +/** + * Redirect to the configured login page. + */ +const failable<int> login(const string& page, request_rec* r) { + const list<list<value> > largs = mklist<list<value> >(mklist<value>("openauth_referrer", httpd::escape(httpd::url(r->uri, r)))); + const string loc = httpd::url(page, r) + string("?") + httpd::queryString(largs); + debug(loc, "openauth::login::uri"); + return httpd::externalRedirect(loc, r); +} + +} +} + +#endif /* tuscany_openauth_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/passwd-auth-conf b/sandbox/sebastien/cpp/apr-2/modules/http/passwd-auth-conf new file mode 100755 index 0000000000..89a3f19e4b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/passwd-auth-conf @@ -0,0 +1,31 @@ +#!/bin/sh + +# 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. + +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` +user=$2 +pass=$3 + +httpd_prefix=`cat $here/httpd.prefix` + +# Create password file +touch $root/conf/httpd.passwd +$httpd_prefix/bin/htpasswd -b $root/conf/httpd.passwd $user $pass 2>/dev/null + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/proxy-conf b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-conf new file mode 100755 index 0000000000..e9abe8435f --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-conf @@ -0,0 +1,41 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD proxy balancer configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +cat >>$root/conf/vhost.conf <<EOF +# Generated by: proxy-conf $* +# Enable HTTP reverse proxy +ProxyRequests Off +ProxyPreserveHost On +ProxyStatus On + +# Enable load balancing +ProxyPass / balancer://cluster/ + +<Proxy balancer://cluster> +Require all granted +ProxySet lbmethod=byrequests +</Proxy> + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/proxy-member-conf b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-member-conf new file mode 100755 index 0000000000..ef9cb35e8a --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-member-conf @@ -0,0 +1,35 @@ +#!/bin/sh + +# 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. + +# Add a proxy balancer member +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +host=$2 +port=`$here/httpd-addr port $3` + +cat >>$root/conf/vhost.conf <<EOF +# Generated by: proxy-member-conf $* +# Add proxy balancer member +BalancerMember balancer://cluster http://$host:$port +ProxyPassReverse / http://$host:$port/ + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/proxy-ssl-conf b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-ssl-conf new file mode 100755 index 0000000000..f5e2bfc4a4 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-ssl-conf @@ -0,0 +1,72 @@ +#!/bin/sh + +# 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. + +# Generate a minimal HTTPD proxy balancer configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +cat >>$root/conf/vhost-ssl.conf <<EOF +# Generated by: proxy-ssl-conf $* +# Enable HTTPS reverse proxy +ProxyRequests Off +ProxyPreserveHost On +ProxyStatus On +SSLProxyEngine on +SSLProxyCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL + +# Verify server certificates +SSLProxyVerify require +SSLProxyVerifyDepth 1 + +# Enable load balancing +ProxyPass /balancer-manager ! +ProxyPass / balancer://sslcluster/ + +<Proxy balancer://sslcluster> +Require all granted +ProxySet lbmethod=byrequests +</Proxy> + +# Enable balancer manager +<Location /balancer-manager> +SetHandler balancer-manager +HostnameLookups on +Require user admin +</Location> + +EOF + +cat >>$root/conf/svhost-ssl.conf <<EOF +# Generated by: proxy-ssl-conf $* +# Declare proxy SSL client certificates +SSLProxyCACertificateFile "$root/cert/ca.crt" +SSLProxyMachineCertificateFile "$root/cert/proxy.pem" + +EOF + +cat >>$root/conf/dvhost-ssl.conf <<EOF +# Generated by: proxy-ssl-conf $* + +# Declare proxy SSL client certificates +SSLProxyCACertificateFile "$root/cert/ca.crt" +SSLProxyMachineCertificateFile "$root/cert/proxy.pem" + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/proxy-ssl-member-conf b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-ssl-member-conf new file mode 100755 index 0000000000..b6bf055ad8 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-ssl-member-conf @@ -0,0 +1,43 @@ +#!/bin/sh + +# 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. + +# Add a proxy balancer member +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +host=$2 +sslport=`$here/httpd-addr port $3` + +cat >>$root/conf/svhost-ssl.conf <<EOF +# Generated by: proxy-ssl-member-conf $* +# Add proxy balancer member +BalancerMember balancer://sslcluster https://$host:$sslport +ProxyPassReverse / https://$host:$sslport/ + +EOF + +cat >>$root/conf/dvhost-ssl.conf <<EOF +# Generated by: proxy-ssl-member-conf $* +# Add proxy balancer member +BalancerMember balancer://sslcluster https://$host:$sslport +ProxyPassReverse / https://$host:$sslport/ + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/proxy-test b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-test new file mode 100755 index 0000000000..b6c9a6a0d9 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/proxy-test @@ -0,0 +1,37 @@ +#!/bin/sh + +# 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. + +# Setup +./httpd-conf tmp localhost 8091/8090 htdocs +./httpd-start tmp +./httpd-conf tmp/proxy localhost 8090 tmp/proxy/htdocs +./proxy-conf tmp/proxy +./proxy-member-conf tmp/proxy localhost 8091 +./httpd-start tmp/proxy +sleep 2 + +# Test +./curl-test +rc=$? + +# Cleanup +./httpd-stop tmp/proxy +./httpd-stop tmp +sleep 2 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/ssl-ca-conf b/sandbox/sebastien/cpp/apr-2/modules/http/ssl-ca-conf new file mode 100755 index 0000000000..e7b9f96ee2 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/ssl-ca-conf @@ -0,0 +1,96 @@ +#!/bin/sh + +# 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. + +# Generate a test certification authority certificate +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +host=$2 + +# Don't override existing certificate +if [ -f $root/cert/ca.crt ]; then + return 0 +fi + +# Generate openssl configuration +mkdir -p $root/cert +umask 0007 +cat >$root/cert/openssl-ca.conf <<EOF +[ req ] +default_bits = 1024 +encrypt_key = no +prompt = no +distinguished_name = req_distinguished_name +x509_extensions = v3_ca + +[ req_distinguished_name ] +C = US +ST = CA +L = San Francisco +O = $host +OU = authority +CN = $host +emailAddress = admin@$host + +[ v3_ca ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer:always +basicConstraints = CA:true + +[ca] +default_ca = ca_default + +[ca_default] +certificate = $root/cert/ca.crt +private_key = $root/cert/ca.key +serial = $root/cert/ca-serial +database = $root/cert/ca-database +new_certs_dir = $root/cert +default_md = sha1 +email_in_dn = no +default_days = 365 +default_crl_days = 30 +policy = policy_any +copy_extensions = none + +[ policy_any ] +countryName = supplied +stateOrProvinceName = optional +localityName = optional +organizationName = optional +organizationalUnitName = optional +commonName = supplied +emailAddress = optional + +EOF + +rm -rf $root/cert/*.crt $root/cert/*.pem $root/cert/hash +rm -f $root/cert/ca-database +echo 1000 > $root/cert/ca-serial +touch $root/cert/ca-database + +# Generate the certification authority certificate +openssl req -new -x509 -config $root/cert/openssl-ca.conf -out $root/cert/ca.crt -keyout $root/cert/ca.key + +# Add to the hash directory and rehash +mkdir -p $root/cert/hash +cp $root/cert/ca.crt $root/cert/hash +c_rehash $root/cert/hash + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/ssl-cert-conf b/sandbox/sebastien/cpp/apr-2/modules/http/ssl-cert-conf new file mode 100755 index 0000000000..57c4522535 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/ssl-cert-conf @@ -0,0 +1,76 @@ +#!/bin/sh + +# 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. + +# Generate a test certificate +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +host=$2 +if [ "$3" != "" ]; then + certname=$3 +else + certname="server" +fi + +# Don't regenerate the certificate if it already exists +if [ -f $root/cert/$certname.crt ]; then + return 0 +fi + +# Generate openssl configuration +mkdir -p $root/cert +umask 0007 +cat >$root/cert/openssl-cert-$certname.conf <<EOF +[ req ] +default_bits = 1024 +encrypt_key = no +prompt = no +distinguished_name = req_distinguished_name + +[ req_distinguished_name ] +C = US +ST = CA +L = San Francisco +O = $host +OU = $certname +CN = $host +emailAddress = admin@$host +EOF + +# Generate a certificate request +openssl req -new -config $root/cert/openssl-cert-$certname.conf -out $root/cert/$certname-req.crt -keyout $root/cert/$certname.key + +# Generate a certificate, signed with our test certification authority certificate +openssl ca -batch -config $root/cert/openssl-ca.conf -out $root/cert/$certname.crt -infiles $root/cert/$certname-req.crt + +# Export it to PKCS12 format, that's the format Web browsers want to import +openssl pkcs12 -export -passout pass: -out $root/cert/$certname.p12 -inkey $root/cert/$certname.key -in $root/cert/$certname.crt -certfile $root/cert/ca.crt + +# Convert the certificate to PEM format and concatenate the key to it, for use +# by mod_proxy +openssl x509 -in $root/cert/$certname.crt -out $root/cert/$certname.pem +cat $root/cert/$certname.key >> $root/cert/$certname.pem + +# Add to the hash directory and rehash +mkdir -p $root/cert/hash +cp $root/cert/$certname.crt $root/cert/hash +cp $root/cert/$certname.pem $root/cert/hash +c_rehash $root/cert/hash + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/ssl-cert-find b/sandbox/sebastien/cpp/apr-2/modules/http/ssl-cert-find new file mode 100755 index 0000000000..b5aefb8e38 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/ssl-cert-find @@ -0,0 +1,26 @@ +#!/bin/sh + +# 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. + +# List certificate files, useful to distribute them to another host +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` + +cd $root +find -regex '.*\.\(\(crt\)\|\(pem\)\|\(p12\)\|\(key\)\|\(0\)\)' 2>/dev/null + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/tunnel-ssl-conf b/sandbox/sebastien/cpp/apr-2/modules/http/tunnel-ssl-conf new file mode 100755 index 0000000000..8cf4ada20a --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/tunnel-ssl-conf @@ -0,0 +1,55 @@ +#!/bin/sh + +# 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. + +# Generate an SSL tunnel configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +port=`$here/httpd-addr port $2` +sslhost=$3 +sslport=$4 +tport=$5 + +# Generate HTTPD configuration +cat >>$root/conf/httpd.conf <<EOF +# Generated by: tunnel-ssl-conf $* +# Tunnel TCP/IP traffic over HTTPS + +# Listen on local port +Listen 127.0.0.1:$port + +# Tunnel virtual host +<VirtualHost 127.0.0.1:$port> +ServerName http://localhost:$port + +TunnelPass https://$sslhost:$sslport/tunnel/localhost/$tport + +# Declare SSL certificates used in this virtual host +#TunnelSSLCACertificateFile "$root/cert/ca.crt" +TunnelSSLCertificateFile "$root/cert/tunnel.crt" +TunnelSSLCertificateKeyFile "$root/cert/tunnel.key" + +</VirtualHost> + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/vhost-conf b/sandbox/sebastien/cpp/apr-2/modules/http/vhost-conf new file mode 100755 index 0000000000..f45d448906 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/vhost-conf @@ -0,0 +1,65 @@ +#!/bin/sh + +# 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. + +# Generate mass dynamic virtual hosting configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` +addr=`echo $conf | awk '{ print $7 }'` +port=`$here/httpd-addr port $addr` +pport=`$here/httpd-addr pport $addr` +vhost=`$here/httpd-addr vhost $addr` + +htdocs=`echo $conf | awk '{ print $8 }'` +mkdir -p $htdocs +htdocs=`readlink -f $htdocs` + +cat >>$root/conf/httpd.conf <<EOF +# Generated by: vhost-conf $* +# Enable mass dynamic virtual hosting +NameVirtualHost $vhost + +<VirtualHost $vhost> +ServerName http://vhost.$host:$pport +ServerAlias *.$host +VirtualDocumentRoot $htdocs/domains/%1/ + +Include conf/dvhost.conf + +# Allow access to document root +<Directory "$htdocs"> +Options FollowSymLinks +AuthType None +Require all granted +</Directory> + +# Allow access to root location +<Location /> +Options FollowSymLinks +AuthType None +Require all granted +</Location> + +</VirtualHost> + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/http/vhost-ssl-conf b/sandbox/sebastien/cpp/apr-2/modules/http/vhost-ssl-conf new file mode 100755 index 0000000000..36b2a15412 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/http/vhost-ssl-conf @@ -0,0 +1,53 @@ +#!/bin/sh + +# 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. + +# Generate mass dynamic virtual hosting configuration +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +sslconf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-ssl-conf"` +ssladdr=`echo $sslconf | awk '{ print $6 }'` +sslport=`$here/httpd-addr port $ssladdr` +sslpport=`$here/httpd-addr pport $ssladdr` +sslvhost=`$here/httpd-addr vhost $ssladdr` + +htdocs=`echo $conf | awk '{ print $8 }'` +mkdir -p $htdocs +htdocs=`readlink -f $htdocs` + +cat >>$root/conf/httpd.conf <<EOF +# Generated by: vhost-ssl-conf $* +# Enable mass dynamic virtual hosting over HTTPS +SSLStrictSNIVHostCheck Off + +# HTTPS dynamic virtual host +NameVirtualHost $sslvhost +<VirtualHost $sslvhost> +ServerName https://vhost.$host:$sslpport +ServerAlias *.$host +VirtualDocumentRoot $htdocs/domains/%1/ + +Include conf/dvhost-ssl.conf + +</VirtualHost> + diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/java/Makefile.am new file mode 100644 index 0000000000..39b7ad550a --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/Makefile.am @@ -0,0 +1,69 @@ +# 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. + +JAVAROOT = $(top_builddir)/modules/java + +if WANT_JAVA + +INCLUDES = -I${JAVA_INCLUDE} + +incl_HEADERS = *.hpp +incldir = $(prefix)/include/modules/java + +dist_mod_SCRIPTS = java-conf +moddir = $(prefix)/modules/java + +prefix_DATA = java.prefix +prefixdir = $(prefix)/modules/java +java.prefix: $(top_builddir)/config.status + echo ${JAVA_PREFIX} >java.prefix + +EXTRA_DIST = domain-test.composite + +mod_LTLIBRARIES = libmod_tuscany_java.la +libmod_tuscany_java_la_SOURCES = mod-java.cpp +libmod_tuscany_java_la_LDFLAGS = -lxml2 -lcurl -lmozjs ${JAVA_LDFLAGS} +noinst_DATA = libmod_tuscany_java.so +libmod_tuscany_java.so: + ln -s .libs/libmod_tuscany_java.so + +jni_test_SOURCES = jni-test.cpp +jni_test_LDFLAGS = ${JAVA_LDFLAGS} + +java_test_SOURCES = java-test.cpp +java_test_LDFLAGS = ${JAVA_LDFLAGS} + +java_shell_SOURCES = java-shell.cpp +java_shell_LDFLAGS = ${JAVA_LDFLAGS} + +dist_mod_JAVA = org/apache/tuscany/*.java test/*.java +jardir = ${prefix}/modules/java +jarfile = libmod-tuscany-java-${PACKAGE_VERSION}.jar +jar_DATA = ${jarfile} +${jarfile}: ${dist_mod_JAVA} + ${JAR} cf $@ org/apache/tuscany/*.class + +CLEANFILES = *.stamp ${jarfile} org/apache/tuscany/*.class test/*.class + +client_test_SOURCES = client-test.cpp +client_test_LDFLAGS = -lxml2 -lcurl -lmozjs + +dist_noinst_SCRIPTS = server-test wiring-test +noinst_PROGRAMS = jni-test java-test java-shell client-test +TESTS = jni-test java-test server-test + +endif diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/client-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/java/client-test.cpp new file mode 100644 index 0000000000..d06c57721e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/client-test.cpp @@ -0,0 +1,39 @@ +/* + * 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 HTTP client functions. + */ + +#include "stream.hpp" +#include "string.hpp" +#include "../server/client-test.hpp" + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + tuscany::server::testURI = "http://localhost:8090/java"; + + tuscany::server::testServer(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/domain-test.composite b/sandbox/sebastien/cpp/apr-2/modules/java/domain-test.composite new file mode 100644 index 0000000000..190f2ff5bb --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/domain-test.composite @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * 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. +--> +<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912" + xmlns:t="http://tuscany.apache.org/xmlns/sca/1.1" + targetNamespace="http://domain/test" + name="domain-test"> + + <component name="java-test"> + <implementation.java class="test.ServerImpl"/> + <service name="test"> + <t:binding.http uri="java"/> + </service> + </component> + + <component name="client-test"> + <implementation.java class="test.ClientImpl"/> + <service name="client"> + <t:binding.http uri="client"/> + </service> + <reference name="ref" target="java-test"> + <t:binding.http/> + </reference> + </component> + +</composite> diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/driver.hpp b/sandbox/sebastien/cpp/apr-2/modules/java/driver.hpp new file mode 100644 index 0000000000..ddfc057940 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/driver.hpp @@ -0,0 +1,61 @@ +/* + * 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_java_driver_hpp +#define tuscany_java_driver_hpp + +/** + * Java evaluator main driver loop. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "monad.hpp" +#include "../scheme/driver.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace java { + +const value evalDriverLoop(const JavaRuntime& jr, const JavaClass jc, istream& in, ostream& out) { + scheme::promptForInput(scheme::evalInputPrompt, out); + value input = scheme::readValue(in); + if (isNil(input)) + return input; + const failable<value> output = evalClass(jr, input, jc); + scheme::announceOutput(scheme::evalOutputPrompt, out); + scheme::userPrint(content(output), out); + return evalDriverLoop(jr, jc, in, out); +} + +const bool evalDriverRun(const char* name, istream& in, ostream& out) { + scheme::setupDisplay(out); + JavaRuntime javaRuntime; + const failable<JavaClass> jc = readClass(javaRuntime, ".", name); + if (!hasContent(jc)) + return true; + evalDriverLoop(javaRuntime, content(jc), in, out); + return true; +} + +} +} +#endif /* tuscany_java_driver_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/eval.hpp b/sandbox/sebastien/cpp/apr-2/modules/java/eval.hpp new file mode 100644 index 0000000000..11e57cb08a --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/eval.hpp @@ -0,0 +1,562 @@ +/* + * 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_java_eval_hpp +#define tuscany_java_eval_hpp + +/** + * Java component implementation evaluation logic. + */ +#include <jni.h> + +#include "list.hpp" +#include "value.hpp" + +namespace tuscany { +namespace java { + +/** + * Handle differences between various JNI APIs. + */ +#ifdef JAVA_HARMONY_VM +#define JNI_VERSION JNI_VERSION_1_4 +#else +#define JNI_VERSION JNI_VERSION_1_6 +#endif + +/** + * Represent a Java VM runtime. + */ +jobject JNICALL nativeInvoke(JNIEnv *env, jobject self, jobject proxy, jobject method, jobjectArray args); +jobject JNICALL nativeUUID(JNIEnv *env); + +class JavaRuntime { +public: + JavaRuntime() { + + // Get existing JVM + jsize nvms = 0; + JNI_GetCreatedJavaVMs(&jvm, 1, &nvms); + if (nvms == 0) { + + // Create a new JVM + JavaVMInitArgs args; + args.version = JNI_VERSION; + args.ignoreUnrecognized = JNI_FALSE; + JavaVMOption options[3]; + args.options = options; + args.nOptions = 0; + + // Configure classpath + const char* envcp = getenv("CLASSPATH"); + const string cp = string("-Djava.class.path=") + (envcp == NULL? "." : envcp); + options[args.nOptions].optionString = const_cast<char*>(c_str(cp)); + options[args.nOptions++].extraInfo = NULL; + +#ifdef WANT_MAINTAINER_MODE + // Enable assertions + options[args.nOptions++].optionString = const_cast<char*>("-ea"); +#endif + + // Configure Java debugging + const char* jpdaopts = getenv("JPDA_OPTS"); + if (jpdaopts != NULL) { + options[args.nOptions].optionString = const_cast<char*>(jpdaopts); + options[args.nOptions++].extraInfo = NULL; + } else { + const char* jpdaaddr = getenv("JPDA_ADDRESS"); + if (jpdaaddr != NULL) { + const string jpda = string("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=") + jpdaaddr; + options[args.nOptions].optionString = const_cast<char*>(c_str(jpda)); + options[args.nOptions++].extraInfo = NULL; + } + } + + // Create the JVM +#ifdef JAVA_HARMONY_VM + JNI_CreateJavaVM(&jvm, &env, &args); +#else + JNI_CreateJavaVM(&jvm, (void**)&env, &args); +#endif + + } else { + + // Just point to existing JVM + jvm->GetEnv((void**)&env, JNI_VERSION); + } + + // Lookup System classes and methods + classClass = env->FindClass("java/lang/Class"); + methodClass = env->FindClass("java/lang/reflect/Method"); + objectClass = env->FindClass("java/lang/Object"); + doubleClass = env->FindClass("java/lang/Double"); + booleanClass = env->FindClass("java/lang/Boolean"); + stringClass = env->FindClass("java/lang/String"); + objectArrayClass = env->FindClass("[Ljava/lang/Object;"); + iterableClass = env->FindClass("java/lang/Iterable"); + classForName = env->GetStaticMethodID(classClass, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"); + doubleValueOf = env->GetStaticMethodID(doubleClass, "valueOf", "(D)Ljava/lang/Double;"); + doubleValue = env->GetMethodID(doubleClass, "doubleValue", "()D"); + booleanValueOf = env->GetStaticMethodID(booleanClass, "valueOf", "(Z)Ljava/lang/Boolean;"); + booleanValue = env->GetMethodID(booleanClass, "booleanValue", "()Z"); + declaredMethods = env->GetMethodID(classClass, "getDeclaredMethods", "()[Ljava/lang/reflect/Method;"); + methodName = env->GetMethodID(methodClass, "getName", "()Ljava/lang/String;"); + parameterTypes = env->GetMethodID(methodClass, "getParameterTypes", "()[Ljava/lang/Class;"); + + // Lookup Tuscany classes and methods + loaderClass = env->FindClass("org/apache/tuscany/ClassLoader"); + loaderValueOf = env->GetStaticMethodID(loaderClass, "valueOf", "(Ljava/lang/String;)Ljava/lang/ClassLoader;"); + loaderForName = env->GetStaticMethodID(loaderClass, "forName", "(Ljava/lang/String;ZLjava/lang/ClassLoader;)Ljava/lang/Class;"); + invokerClass = env->FindClass("org/apache/tuscany/InvocationHandler"); + invokerValueOf = env->GetStaticMethodID(invokerClass, "valueOf", "(Ljava/lang/Class;J)Ljava/lang/Object;"); + invokerStackTrace = env->GetStaticMethodID(invokerClass, "stackTrace", "(Ljava/lang/Throwable;)Ljava/lang/String;"); + invokerLambda = env->GetFieldID(invokerClass, "lambda", "J"); + iterableUtilClass = env->FindClass("org/apache/tuscany/IterableUtil"); + iterableValueOf = env->GetStaticMethodID(iterableUtilClass, "list", "([Ljava/lang/Object;)Ljava/lang/Iterable;"); + iterableIsNil = env->GetStaticMethodID(iterableUtilClass, "isNil", "(Ljava/lang/Object;)Z"); + iterableCar = env->GetStaticMethodID(iterableUtilClass, "car", "(Ljava/lang/Object;)Ljava/lang/Object;"); + iterableCdr = env->GetStaticMethodID(iterableUtilClass, "cdr", "(Ljava/lang/Object;)Ljava/lang/Iterable;"); + uuidClass = env->FindClass("org/apache/tuscany/UUIDUtil"); + + // Register our native invocation handler function + JNINativeMethod invokenm; + invokenm.name = const_cast<char*>("invoke"); + invokenm.signature = const_cast<char*>("(Ljava/lang/Object;Ljava/lang/reflect/Method;[Ljava/lang/Object;)Ljava/lang/Object;"); + invokenm.fnPtr = (void*)nativeInvoke; + env->RegisterNatives(invokerClass, &invokenm, 1); + + // Register our native UUID function + JNINativeMethod uuidnm; + uuidnm.name = const_cast<char*>("uuid"); + uuidnm.signature = const_cast<char*>("()Ljava/lang/String;"); + uuidnm.fnPtr = (void*)nativeUUID; + env->RegisterNatives(uuidClass, &uuidnm, 1); + } + + JavaVM* jvm; + JNIEnv* env; + + jclass classClass; + jclass methodClass; + jclass objectClass; + jclass doubleClass; + jclass booleanClass; + jclass stringClass; + jclass objectArrayClass; + jclass iterableClass; + jmethodID doubleValueOf; + jmethodID doubleValue; + jmethodID booleanValueOf; + jmethodID booleanValue; + jmethodID declaredMethods; + jmethodID methodName; + jmethodID parameterTypes; + jmethodID classForName; + jclass loaderClass; + jmethodID loaderValueOf; + jmethodID loaderForName; + jclass invokerClass; + jmethodID invokerValueOf; + jmethodID invokerStackTrace; + jfieldID invokerLambda; + jclass iterableUtilClass; + jmethodID iterableValueOf; + jmethodID iterableCar; + jmethodID iterableCdr; + jmethodID iterableIsNil; + jclass uuidClass; +}; + +/** + * Return the last exception that occurred in a JVM. + */ +string lastException(const JavaRuntime& jr) { + if (!jr.env->ExceptionCheck()) + return "No Exception"; + const jthrowable ex = jr.env->ExceptionOccurred(); + const jstring trace = (jstring)jr.env->CallStaticObjectMethod(jr.invokerClass, jr.invokerStackTrace, ex); + const char* c = jr.env->GetStringUTFChars(trace, NULL); + const string msg(c); + jr.env->ReleaseStringUTFChars(trace, c); + jr.env->ExceptionClear(); + return msg; +} + +/** + * Declare conversion functions. + */ +const jobject valueToJobject(const JavaRuntime& jr, const value& jtype, const value& v); +const value jobjectToValue(const JavaRuntime& jr, const jobject o); +const jobjectArray valuesToJarray(const JavaRuntime& jr, const list<value>& v); +const list<value> jarrayToValues(const JavaRuntime& jr, const jobjectArray o); +const list<value> jiterableToValues(const JavaRuntime& jr, const jobject o); + +/** + * Convert a Java class name to a JNI class name. + */ +const bool jniClassNameHelper(char* to, const char* from) { + if (*from == '\0') { + *to = '\0'; + return true; + } + *to = *from == '.'? '/' : *from; + return jniClassNameHelper(to + 1, from + 1); +} + +const string jniClassName(const string& from) { + char buf[length(from) + 1]; + jniClassNameHelper(buf, c_str(from)); + return string(buf); +} + +/** + * Create a new Java object representing a lambda expression. + */ +class javaLambda { +public: + javaLambda(const JavaRuntime& jr, const value& iface, const lambda<value(const list<value>&)>& func) : jr(jr), iface(iface), func(func) { + } + + const value operator()(const list<value>& expr) const { + if (isNil(expr)) + return func(expr); + const value& op(car(expr)); + if (op == "equals") + return value(cadr(expr) == this); + if (op == "hashCode") + return value((double)(long)this); + if (op == "toString") { + ostringstream os; + os << this; + return value(string("org.apache.tuscany.InvocationHandler@") + (c_str(str(os)) + 2)); + } + return func(expr); + } + + const JavaRuntime& jr; + const value iface; + const lambda<value(const list<value>&)> func; +}; + +/** + * Native implementation of the InvocationHandler.invoke Java method. + * Dispatches the call to the lambda function wrapped in the invocation handler. + */ +jobject JNICALL nativeInvoke(JNIEnv* env, jobject self, unused jobject proxy, jobject method, jobjectArray args) { + + // Retrieve the lambda function from the invocation handler + jclass clazz = env->GetObjectClass(self); + jfieldID f = env->GetFieldID(clazz, "lambda", "J"); + const javaLambda& jl = *(javaLambda*)(long)env->GetLongField(self, f); + + // Retrieve the function name + const jstring s = (jstring)env->CallObjectMethod(method, jl.jr.methodName); + const char* c = env->GetStringUTFChars(s, NULL); + const value func(c); + env->ReleaseStringUTFChars(s, c); + + // Build the expression to evaluate, either (func, args[0], args[1], args[2]...) + // or just args[0] for the special eval(...) function + const list<value> expr = func == "eval"? (list<value>)car<value>(jarrayToValues(jl.jr, args)) : cons<value>(func, jarrayToValues(jl.jr, args)); + debug(expr, "java::nativeInvoke::expr"); + + // Invoke the lambda function + value result = jl(expr); + debug(result, "java::nativeInvoke::result"); + + // Convert result to a jobject + return valueToJobject(jl.jr, value(), result); +} + +/** + * Native implementation of IterableUtil.uuid. We are providing a native implementation + * of this function as java.util.UUID seems to behave differently with different JDKs. + */ +jobject JNICALL nativeUUID(JNIEnv* env) { + const value uuid = mkuuid(); + return env->NewStringUTF(c_str(uuid)); +} + +/** + * Convert a lambda function to Java proxy. + */ +const jobject mkJavaLambda(const JavaRuntime& jr, unused const value& iface, const lambda<value(const list<value>&)>& l) { + const gc_ptr<javaLambda> jl = new (gc_new<javaLambda>()) javaLambda(jr, iface, l); + jclass jc = (jclass)(long)(double)iface; + const jobject obj = jr.env->CallStaticObjectMethod(jr.invokerClass, jr.invokerValueOf, jc, (long)(javaLambda*)jl); + return obj; +} + +/** + * Convert a list of values to a Java jobjectArray. + */ +const jobjectArray valuesToJarrayHelper(const JavaRuntime& jr, jobjectArray a, const list<value>& v, const int i) { + if (isNil(v)) + return a; + jr.env->SetObjectArrayElement(a, i, valueToJobject(jr, value(), car(v))); + return valuesToJarrayHelper(jr, a, cdr(v), i + 1); +} + +const jobjectArray valuesToJarray(const JavaRuntime& jr, const list<value>& v) { + jobjectArray a = jr.env->NewObjectArray((jsize)length(v), jr.objectClass, NULL); + return valuesToJarrayHelper(jr, a, v, 0); +} + +/** + * Convert a Java jobjectArray to a Java iterable. + */ +const jobject jarrayToJiterable(const JavaRuntime& jr, jobjectArray a) { + return jr.env->CallStaticObjectMethod(jr.iterableClass, jr.iterableValueOf, a); +} + +/** + * Convert a value to a Java jobject. + */ +const jobject valueToJobject(const JavaRuntime& jr, const value& jtype, const value& v) { + switch (type(v)) { + case value::List: + return jarrayToJiterable(jr, valuesToJarray(jr, v)); + case value::Lambda: + return mkJavaLambda(jr, jtype, v); + case value::Symbol: + return jr.env->NewStringUTF(c_str(string("'") + v)); + case value::String: + return jr.env->NewStringUTF(c_str(v)); + case value::Number: + return jr.env->CallStaticObjectMethod(jr.doubleClass, jr.doubleValueOf, (double)v); + case value::Bool: + return jr.env->CallStaticObjectMethod(jr.booleanClass, jr.booleanValueOf, (bool)v); + default: + return NULL; + } +} + +/** + * Convert a list of values to an array of jvalues. + */ +const jvalue* valuesToJvaluesHelper(const JavaRuntime& jr, jvalue* a, const list<value>& types, const list<value>& v) { + if (isNil(v)) + return a; + a->l = valueToJobject(jr, car(types), car(v)); + return valuesToJvaluesHelper(jr, a + 1, cdr(types), cdr(v)); +} + +const jvalue* valuesToJvalues(const JavaRuntime& jr, const list<value>& types, const list<value>& v) { + const size_t n = length(v); + jvalue* a = new (gc_anew<jvalue>(n)) jvalue[n]; + valuesToJvaluesHelper(jr, a, types, v); + return a; +} + +/** + * Convert a Java jobjectArray to a list of values. + */ +const list<value> jarrayToValuesHelper(const JavaRuntime& jr, jobjectArray a, const int i, const int size) { + if (i == size) + return list<value>(); + return cons(jobjectToValue(jr, jr.env->GetObjectArrayElement(a, i)), jarrayToValuesHelper(jr, a, i + 1, size)); +} + +const list<value> jarrayToValues(const JavaRuntime& jr, jobjectArray o) { + if (o == NULL) + return list<value>(); + return jarrayToValuesHelper(jr, o, 0, jr.env->GetArrayLength(o)); +} + +/** + * Convert a Java Iterable to a list of values. + */ +const list<value> jiterableToValuesHelper(const JavaRuntime& jr, jobject o) { + if ((bool)jr.env->CallStaticBooleanMethod(jr.iterableUtilClass, jr.iterableIsNil, o)) + return list<value>(); + jobject car = jr.env->CallStaticObjectMethod(jr.iterableUtilClass, jr.iterableCar, o); + jobject cdr = jr.env->CallStaticObjectMethod(jr.iterableUtilClass, jr.iterableCdr, o); + return cons(jobjectToValue(jr, car), jiterableToValuesHelper(jr, cdr)); +} + +const list<value> jiterableToValues(const JavaRuntime& jr, jobject o) { + if (o == NULL) + return list<value>(); + return jiterableToValuesHelper(jr, o); +} + +/** + * Lambda function used to represent a Java callable object. + */ +struct javaCallable { + const JavaRuntime& jr; + const jobject obj; + + javaCallable(const JavaRuntime& jr, const jobject obj) : jr(jr), obj(obj) { + } + + const value operator()(const list<value>& args) const { + jobjectArray jargs = valuesToJarray(jr, args); + jobject result = jargs; //CallObject(func, jargs); + return jobjectToValue(jr, result); + } +}; + +/** + * Convert a Java jobject to a value. + */ +const value jobjectToValue(const JavaRuntime& jr, const jobject o) { + if (o == NULL) + return value(); + const jclass clazz = jr.env->GetObjectClass(o); + if ((jr.env->IsSameObject(clazz, jr.stringClass))) { + const char* s = jr.env->GetStringUTFChars((jstring)o, NULL); + if (*s == '\'') { + const value v(s + 1); + jr.env->ReleaseStringUTFChars((jstring)o, s); + return v; + } + const value v = string(s); + jr.env->ReleaseStringUTFChars((jstring)o, s); + return v; + } + if (jr.env->IsSameObject(clazz, jr.booleanClass)) + return value((bool)jr.env->CallBooleanMethod(o, jr.booleanValue)); + if (jr.env->IsSameObject(clazz, jr.doubleClass)) + return value((double)jr.env->CallDoubleMethod(o, jr.doubleValue)); + if (jr.env->IsAssignableFrom(clazz, jr.iterableClass)) + return jiterableToValues(jr, o); + if (jr.env->IsAssignableFrom(clazz, jr.objectArrayClass)) + return jarrayToValues(jr, (jobjectArray)o); + return lambda<value(const list<value>&)>(javaCallable(jr, o)); +} + +/** + * Returns a balanced tree of the methods of a class. + */ +const value parameterTypeToValue(const jobject t) { + return value((double)(long)t); +} + +const list<value> parameterTypesToValues(const JavaRuntime& jr, const jobjectArray t, const int i) { + if (i == 0) + return list<value>(); + return cons<value>(parameterTypeToValue(jr.env->GetObjectArrayElement(t, i - 1)), parameterTypesToValues(jr, t, i - 1)); +} + +const value methodToValue(const JavaRuntime& jr, const jobject m) { + const jobject s = jr.env->CallObjectMethod(m, jr.methodName); + const char* c = jr.env->GetStringUTFChars((jstring)s, NULL); + const string& name = string(c); + jr.env->ReleaseStringUTFChars((jstring)s, c); + + const jmethodID mid = jr.env->FromReflectedMethod(m); + + const jobjectArray t = (jobjectArray)jr.env->CallObjectMethod(m, jr.parameterTypes); + const list<value> types = reverse(parameterTypesToValues(jr, t, jr.env->GetArrayLength(t))); + + return cons<value>(c_str(name), cons<value>((double)(long)mid, types)); +} + +const list<value> methodsToValues(const JavaRuntime& jr, const jobjectArray m, const int i) { + if (i == 0) + return list<value>(); + return cons<value>(methodToValue(jr, jr.env->GetObjectArrayElement(m, i - 1)), methodsToValues(jr, m, i - 1)); +} + +const list<value> methodsToValues(const JavaRuntime& jr, const jclass clazz) { + const jobjectArray m = (jobjectArray)jr.env->CallObjectMethod(clazz, jr.declaredMethods); + return methodsToValues(jr, m, jr.env->GetArrayLength(m)); +} + +/** + * Represents a Java Class. + */ +class JavaClass { +public: + JavaClass() : loader(NULL), clazz(NULL), obj(NULL) { + } + JavaClass(const jobject loader, const jclass clazz, const jobject obj, const list<value> m) : loader(loader), clazz(clazz), obj(obj), m(m) { + } + + const jobject loader; + const jclass clazz; + const jobject obj; + const list<value> m; +}; + +/** + * Read a class. + */ +const failable<JavaClass> readClass(const JavaRuntime& jr, const string& path, const string& name) { + + // Create a class loader from the given path + const jobject jpath = jr.env->NewStringUTF(c_str(path)); + jobject loader = jr.env->CallStaticObjectMethod(jr.loaderClass, jr.loaderValueOf, jpath); + + // Load the class + const jobject jname = jr.env->NewStringUTF(c_str(name)); + const jclass clazz = (jclass)jr.env->CallStaticObjectMethod(jr.loaderClass, jr.loaderForName, jname, JNI_TRUE, loader); + if (clazz == NULL) + return mkfailure<JavaClass>(string("Couldn't load class: ") + name + " : " + lastException(jr)); + + // Create an instance + const jmethodID constr = jr.env->GetMethodID(clazz, "<init>", "()V"); + if (constr == NULL) + return mkfailure<JavaClass>(string("Couldn't find constructor: ") + name + " : " + lastException(jr)); + const jobject obj = jr.env->NewObject(clazz, constr); + if (obj == NULL) + return mkfailure<JavaClass>(string("Couldn't construct object: ") + name + " : " + lastException(jr)); + + return JavaClass(loader, clazz, obj, methodsToValues(jr, clazz)); +} + +/** + * Evaluate an expression against a Java class. + */ +const failable<value> evalClass(const JavaRuntime& jr, const value& expr, const JavaClass jc) { + debug(expr, "java::evalClass::expr"); + + // Lookup the Java function named as the expression operand + const list<value> func = assoc<value>(car<value>(expr), jc.m); + if (isNil(func)) { + + // The start, stop, and restart functions are optional + const value fn = car<value>(expr); + if (fn == "start" || fn == "stop") + return value(lambda<value(const list<value>&)>()); + + return mkfailure<value>(string("Couldn't find function: ") + car<value>(expr) + " : " + lastException(jr)); + } + const jmethodID fid = (jmethodID)(long)(double)cadr(func); + + // Convert args to Java jvalues + const jvalue* args = valuesToJvalues(jr, cddr(func), cdr<value>(expr)); + + // Call the Java function + const jobject result = jr.env->CallObjectMethodA(jc.obj, fid, const_cast<jvalue*>(args)); + if (result == NULL) + return mkfailure<value>(string("Function call failed: ") + car<value>(expr) + " : " + lastException(jr)); + + // Convert Java result to a value + const value v = jobjectToValue(jr, result); + debug(v, "java::evalClass::result"); + return v; +} + +} +} +#endif /* tuscany_java_eval_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/java-conf b/sandbox/sebastien/cpp/apr-2/modules/java/java-conf new file mode 100755 index 0000000000..cf5faddb84 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/java-conf @@ -0,0 +1,31 @@ +#!/bin/sh + +# 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. + +# Generate a Java server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +cat >>$root/conf/modules.conf <<EOF +# Generated by: java-conf $* +# Support for Java SCA components +LoadModule mod_tuscany_eval $here/libmod_tuscany_java.so + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/java-shell.cpp b/sandbox/sebastien/cpp/apr-2/modules/java/java-shell.cpp new file mode 100644 index 0000000000..51df513990 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/java-shell.cpp @@ -0,0 +1,40 @@ +/* + * 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$ */ + +/** + * Java evaluator shell, used for interactive testing of Java classes. + */ + +#include <assert.h> +#include "gc.hpp" +#include "stream.hpp" +#include "string.hpp" +#include "driver.hpp" + +int main(const int argc, char** argv) { + tuscany::gc_scoped_pool pool; + if (argc != 2) { + tuscany::cerr << "Usage: java-shell <class name>" << tuscany::endl; + return 1; + } + tuscany::java::evalDriverRun(argv[1], tuscany::cin, tuscany::cout); + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/java-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/java/java-test.cpp new file mode 100644 index 0000000000..f811a4f58d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/java-test.cpp @@ -0,0 +1,138 @@ +/* + * 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 Java evaluator. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "driver.hpp" + +namespace tuscany { +namespace java { + +bool testEvalExpr() { + gc_scoped_pool pool; + JavaRuntime javaRuntime; + { + const failable<JavaClass> obj = readClass(javaRuntime, ".", "test.CalcImpl"); + assert(hasContent(obj)); + const value exp = mklist<value>("mult", 2, 3); + const failable<value> r = evalClass(javaRuntime, exp, content(obj)); + assert(hasContent(r)); + assert(content(r) == value(6)); + } + { + const failable<JavaClass> obj = readClass(javaRuntime, ".", "test.CalcImpl"); + assert(hasContent(obj)); + const value exp = mklist<value>("even", 2); + const failable<value> r = evalClass(javaRuntime, exp, content(obj)); + assert(hasContent(r)); + assert(content(r) == value(true)); + } + { + const failable<JavaClass> obj = readClass(javaRuntime, ".", "test.AdderImpl"); + assert(hasContent(obj)); + const value exp = mklist<value>("add", 2, 3); + const failable<value> r = evalClass(javaRuntime, exp, content(obj)); + assert(hasContent(r)); + assert(content(r) == value(5)); + } + { + const failable<JavaClass> obj = readClass(javaRuntime, ".", "test.CalcImpl"); + assert(hasContent(obj)); + const value exp = mklist<value>("square", mklist<value>(1, 2, 3)); + const failable<value> r = evalClass(javaRuntime, exp, content(obj)); + assert(hasContent(r)); + assert(content(r) == mklist<value>(1, 4, 9)); + } + return true; +} + +const value add(const list<value>& args) { + assert(car(args) == "add"); + const double x = cadr(args); + const double y = caddr(args); + return x + y; +} + +bool testEvalLambda() { + gc_scoped_pool pool; + JavaRuntime javaRuntime; + { + const failable<JavaClass> obj = readClass(javaRuntime, ".", "test.CalcImpl"); + assert(hasContent(obj)); + const value tcel = mklist<value>("add", 3, 4, lambda<value(const list<value>&)>(add)); + const failable<value> r = evalClass(javaRuntime, tcel, content(obj)); + assert(hasContent(r)); + assert(content(r) == value(7)); + } + { + const failable<JavaClass> obj = readClass(javaRuntime, ".", "test.CalcImpl"); + assert(hasContent(obj)); + const value tcel = mklist<value>("addEval", 3, 4, lambda<value(const list<value>&)>(add)); + const failable<value> r = evalClass(javaRuntime, tcel, content(obj)); + assert(hasContent(r)); + assert(content(r) == value(7)); + } + return true; +} + +bool testClassLoader() { + gc_scoped_pool pool; + JavaRuntime javaRuntime; + const failable<JavaClass> obj = readClass(javaRuntime, ".", "org.apache.tuscany.ClassLoader$Test"); + assert(hasContent(obj)); + const value exp = mklist<value>("testClassLoader"); + const failable<value> r = evalClass(javaRuntime, exp, content(obj)); + assert(hasContent(r)); + assert(content(r) == value(true)); + return true; +} + +bool testIterableUtil() { + gc_scoped_pool pool; + JavaRuntime javaRuntime; + const failable<JavaClass> obj = readClass(javaRuntime, ".", "org.apache.tuscany.IterableUtil$Test"); + assert(hasContent(obj)); + const value exp = mklist<value>("testList"); + const failable<value> r = evalClass(javaRuntime, exp, content(obj)); + assert(hasContent(r)); + assert(content(r) == value(true)); + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::java::testEvalExpr(); + tuscany::java::testEvalLambda(); + tuscany::java::testClassLoader(); + tuscany::java::testIterableUtil(); + + tuscany::cout << "OK" << tuscany::endl; + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/jni-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/java/jni-test.cpp new file mode 100644 index 0000000000..727af13dc6 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/jni-test.cpp @@ -0,0 +1,80 @@ +/* + * 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$ */ + +/** + * Basic JNI test. + */ + +#include <assert.h> +#include <jni.h> +#include "stream.hpp" +#include "string.hpp" +#include "fstream.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace java { + +#ifdef JAVA_HARMONY_VM +#define JNI_VERSION JNI_VERSION_1_4 +#else +#define JNI_VERSION JNI_VERSION_1_6 +#endif + +bool testJNI() { + gc_scoped_pool pool; + JavaVM* jvm; + JNIEnv* env; + + JavaVMInitArgs args; + args.version = JNI_VERSION; + args.ignoreUnrecognized = JNI_FALSE; + JavaVMOption options[3]; + args.options = options; + args.nOptions = 0; + const char* envcp = getenv("CLASSPATH"); + const string cp = string("-Djava.class.path=") + (envcp == NULL? "." : envcp); + options[args.nOptions].optionString = const_cast<char*>(c_str(cp)); + options[args.nOptions++].extraInfo = NULL; +#ifdef JAVA_HARMONY_VM + JNI_CreateJavaVM(&jvm, &env, &args); +#else + JNI_CreateJavaVM(&jvm, (void**)&env, &args); +#endif + + jclass classClass = env->FindClass("java/lang/Class"); + assert(classClass != NULL); + jclass loaderClass = env->FindClass("org/apache/tuscany/ClassLoader"); + assert(loaderClass != NULL); + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::java::testJNI(); + + tuscany::cout << "OK" << tuscany::endl; + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/mod-java.cpp b/sandbox/sebastien/cpp/apr-2/modules/java/mod-java.cpp new file mode 100644 index 0000000000..510f9574b0 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/mod-java.cpp @@ -0,0 +1,80 @@ +/* + * 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$ */ + +/** + * HTTPD module used to eval Java component implementations. + */ + +#include "string.hpp" +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "../server/mod-cpp.hpp" +#include "../server/mod-eval.hpp" +#include "mod-java.hpp" + +namespace tuscany { +namespace server { +namespace modeval { + +/** + * Apply a lifecycle start or restart event. + */ +struct javaLifecycle { + javaLifecycle(java::JavaRuntime& jr) : jr(jr) { + } + const value operator()(const list<value>& params) const { + const value func = car(params); + if (func == "javaRuntime") + return (gc_ptr<value>)(value*)(void*)&jr; + return lambda<value(const list<value>&)>(); + } + java::JavaRuntime& jr; +}; + +const value applyLifecycle(unused const list<value>& params) { + + // Create a Java runtime + java::JavaRuntime& jr = *(new (gc_new<java::JavaRuntime>()) java::JavaRuntime()); + + // Return the function to invoke on subsequent events + return failable<value>(lambda<value(const list<value>&)>(javaLifecycle(jr))); +} + +/** + * Evaluate a Java component implementation and convert it to an applicable + * lambda function. + */ +const failable<lambda<value(const list<value>&)> > evalImplementation(const string& path, const value& impl, const list<value>& px, const lambda<value(const list<value>&)>& lifecycle) { + const string itype(elementName(impl)); + if (contains(itype, ".java")) { + const void* p = (gc_ptr<value>)lifecycle(mklist<value>("javaRuntime")); + return modjava::evalImplementation(path, impl, px, *(java::JavaRuntime*)p); + } + if (contains(itype, ".cpp")) + return modcpp::evalImplementation(path, impl, px); + return mkfailure<lambda<value(const list<value>&)> >(string("Unsupported implementation type: ") + itype); +} + +} +} +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/mod-java.hpp b/sandbox/sebastien/cpp/apr-2/modules/java/mod-java.hpp new file mode 100644 index 0000000000..e7da06e930 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/mod-java.hpp @@ -0,0 +1,77 @@ +/* + * 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_modjava_hpp +#define tuscany_modjava_hpp + +/** + * Evaluation functions used by mod-eval to evaluate Java + * component implementations. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace server { +namespace modjava { + +/** + * Apply a Java component implementation function. + */ +struct applyImplementation { + java::JavaClass impl; + const list<value> px; + java::JavaRuntime& jr; + applyImplementation(const java::JavaClass& impl, const list<value>& px, java::JavaRuntime& jr) : impl(impl), px(px), jr(jr) { + } + const value operator()(const list<value>& params) const { + const value expr = append<value>(params, px); + debug(expr, "modeval::java::applyImplementation::input"); + const failable<value> res = java::evalClass(jr, expr, impl); + const value val = !hasContent(res)? mklist<value>(value(), reason(res)) : mklist<value>(content(res)); + debug(val, "modeval::java::applyImplementation::result"); + return val; + } +}; + +/** + * Evaluate a Java component implementation and convert it to an applicable + * lambda function. + */ +const failable<lambda<value(const list<value>&)> > evalImplementation(const string& path, const value& impl, const list<value>& px, java::JavaRuntime& jr) { + const string cn(attributeValue("class", impl)); + const failable<java::JavaClass> jc = java::readClass(jr, path, cn); + if (!hasContent(jc)) + return mkfailure<lambda<value(const list<value>&)> >(reason(jc)); + return lambda<value(const list<value>&)>(applyImplementation(content(jc), px, jr)); +} + +} +} +} + +#endif /* tuscany_modjava_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/ClassLoader.java b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/ClassLoader.java new file mode 100644 index 0000000000..ef7b2316fb --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/ClassLoader.java @@ -0,0 +1,76 @@ +/* + * 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. + */ + +package org.apache.tuscany; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; + +/** + * Class loader used to load SCA component implementation classes. + */ +class ClassLoader extends URLClassLoader { + + ClassLoader(final URL... urls) { + super(urls); + } + + /** + * Create a class loader for an SCA contribution path. + */ + static java.lang.ClassLoader valueOf(final String path) throws MalformedURLException { + return new ClassLoader(new File(path).toURI().toURL()); + } + + /** + * Load a class. + */ + static Class<?> forName(final String name, final boolean resolve, final java.lang.ClassLoader loader) throws ClassNotFoundException { + return Class.forName(name, resolve, loader); + } + + /** + * Test the class loader. + */ + static class Test { + Boolean testClassLoader() { + try { + final Class<?> clazz = ClassLoader.forName("test.CalcImpl", true, ClassLoader.valueOf(".")); + assert clazz != null; + } catch(final MalformedURLException e) { + throw new RuntimeException(e); + } catch(final ClassNotFoundException e) { + throw new RuntimeException(e); + } + return true; + } + } + + public static void main(final String[] args) { + System.out.println("Testing..."); + + Test.class.getClassLoader().setDefaultAssertionStatus(true); + new Test().testClassLoader(); + + System.out.println("OK"); + } + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/InvocationHandler.java b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/InvocationHandler.java new file mode 100644 index 0000000000..06466fe9fc --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/InvocationHandler.java @@ -0,0 +1,59 @@ +/* + * 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. + */ + +package org.apache.tuscany; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.lang.reflect.Proxy; + +/** + * Proxy Invocation handler used to represent SCA component references. + */ +class InvocationHandler implements java.lang.reflect.InvocationHandler { + final long lambda; + + InvocationHandler(final long lambda) { + this.lambda = lambda; + } + + /** + * Create a proxy for an interface and the lambda function representing + * an SCA component reference. + */ + static Object valueOf(final Class<?> iface, final long lambda) { + return Proxy.newProxyInstance(iface.getClassLoader(), new Class[]{iface}, new InvocationHandler(lambda)); + } + + /** + * Proxy invocation of a C++ function. + */ + public native Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable; + + /** + * Return the stack trace of an exception. + */ + static String stackTrace(final Throwable e) { + final StringWriter sw = new StringWriter(); + final PrintWriter pw = new PrintWriter(sw); + e.printStackTrace(pw); + return sw.toString(); + } +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/IterableUtil.java b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/IterableUtil.java new file mode 100644 index 0000000000..6d559f370a --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/IterableUtil.java @@ -0,0 +1,368 @@ +/* + * 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. + */ + +package org.apache.tuscany; + +import static java.util.Arrays.*; + +import java.util.AbstractList; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +/** + * Utility functions to help work efficiently with iterable lists, inspired from Lisp. + */ +public class IterableUtil { + + /** + * Convert an array or a variable list of arguments to an iterable list. + */ + public static <T> Iterable<T> list(final Object... a) { + return new ArrayIterable<T>(a, 0); + } + + /** + * Convert an iterable list to a java.util.Collection. + */ + @SuppressWarnings("unchecked") + public static <T> Collection<T> collection(final Object l) { + final Collection<T> c = new ArrayList<T>(); + for(final Object x : (Iterable<?>)l) + c.add((T)x); + return c; + } + + /** + * Construct a new list from an element and a list. + */ + public static <T> Iterable<T> cons(final Object car, final Iterable<?> cdr) { + return new PairIterable<T>(car, cdr); + } + + /** + * Return true if a list is nil (empty). + */ + public static boolean isNil(final Object l) { + if(l instanceof BasicIterable<?>) + return ((BasicIterable<?>)l).isNil(); + if(l instanceof Collection<?>) + return ((Collection<?>)l).isEmpty(); + return !((Iterable<?>)l).iterator().hasNext(); + } + + /** + * Return the car (first element) of a list. + */ + @SuppressWarnings("unchecked") + public static <T> T car(final Object l) { + if(l instanceof BasicIterable<?>) + return ((BasicIterable<T>)l).car(); + if(l instanceof List<?>) + return (T)((List<?>)l).get(0); + return (T)((Iterable<?>)l).iterator().next(); + } + + /** + * Return the cdr (rest after the first element) of a list. + */ + @SuppressWarnings("unchecked") + public static <T> Iterable<T> cdr(final Object l) { + if(l instanceof BasicIterable<?>) + return ((BasicIterable<T>)l).cdr(); + if(l instanceof List<?>) + return new ListIterable<T>((List<?>)l, 1); + if(l instanceof Collection<?>) + return new ArrayIterable<T>(((Collection<?>)l).toArray(), 1); + return new Iterable<T>() { + public Iterator<T> iterator() { + final Iterator<T> i = ((Iterable<T>)l).iterator(); + i.next(); + return i; + } + }; + } + + /** + * Return the car of the cdr of a list. + */ + @SuppressWarnings("unchecked") + public static <T> T cadr(final Object l) { + return (T)car(cdr(l)); + } + + /** + * Return the cdr of the cdr of a list. + */ + public static <T> Iterable<T> cddr(final Object l) { + return cdr(cdr(l)); + } + + /** + * Return the car of the cdr of the cdr of a list. + */ + @SuppressWarnings("unchecked") + public static <T> T caddr(final Object l) { + return (T)car(cddr(l)); + } + + /** + * Return the first pair matching a key from a list of key value pairs. + */ + public static <T> Iterable<T> assoc(final Object k, final Object l) { + if(isNil(l)) + return list(); + if(k.equals(car(car(l)))) + return car(l); + return assoc(k, cdr(l)); + } + + /** + * Internal base implementation class for iterable and immutable lists. + */ + static abstract class BasicIterable<T> extends AbstractList<T> { + abstract T car(); + + abstract Iterable<T> cdr(); + + abstract Boolean isNil(); + + @Override + public int size() { + return this.isNil()? 0 : 1 + ((List<T>)this.cdr()).size(); + } + + @Override + public T get(final int index) { + throw new UnsupportedOperationException(); + } + } + + /** + * Internal implementation of a list backed by an array. + */ + static class ArrayIterable<T> extends BasicIterable<T> { + final Object[] a; + final int start; + + ArrayIterable(final Object[] a, final int start) { + this.a = a; + this.start = start; + } + + @Override + Boolean isNil() { + return this.a.length - this.start == 0; + } + + @SuppressWarnings("unchecked") + @Override + T car() { + return (T)this.a[this.start]; + } + + @Override + BasicIterable<T> cdr() { + return new ArrayIterable<T>(this.a, this.start + 1); + } + + @Override + public Iterator<T> iterator() { + return new Iterator<T>() { + int i = ArrayIterable.this.start; + + public boolean hasNext() { + return this.i < ArrayIterable.this.a.length; + } + + @SuppressWarnings("unchecked") + public T next() { + return (T)ArrayIterable.this.a[this.i++]; + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + } + + /** + * Internal implementation of a list backed by a java.util.List. + */ + static class ListIterable<T> extends BasicIterable<T> { + final List<?> l; + final int start; + + ListIterable(final List<?> l, final int start) { + this.l = l; + this.start = start; + } + + @Override + Boolean isNil() { + return this.l.size() - this.start == 0; + } + + @SuppressWarnings("unchecked") + @Override + T car() { + return (T)this.l.get(this.start); + } + + @Override + BasicIterable<T> cdr() { + return new ListIterable<T>(this.l, this.start + 1); + } + + @Override + public Iterator<T> iterator() { + return new Iterator<T>() { + int i = ListIterable.this.start; + + public boolean hasNext() { + return this.i < ListIterable.this.l.size(); + } + + @SuppressWarnings("unchecked") + public T next() { + return (T)ListIterable.this.l.get(this.i++); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + } + + /** + * Internal implementation of a list backed by an element / iterable pair. + */ + static class PairIterable<T> extends BasicIterable<T> { + final Object car; + final Iterable<?> cdr; + + PairIterable(final Object car, final Iterable<?> cdr) { + this.car = car; + this.cdr = cdr; + } + + @Override + Boolean isNil() { + return false; + } + + @SuppressWarnings("unchecked") + @Override + T car() { + return (T)this.car; + } + + @SuppressWarnings("unchecked") + @Override + Iterable<T> cdr() { + return (Iterable<T>)this.cdr; + } + + @Override + public Iterator<T> iterator() { + return new Iterator<T>() { + boolean carIterator = true; + Iterator<?> cdrIterator = PairIterable.this.cdr.iterator(); + + public boolean hasNext() { + if(this.carIterator) + return true; + return this.cdrIterator.hasNext(); + } + + @SuppressWarnings("unchecked") + public T next() { + if(this.carIterator) { + this.carIterator = false; + return (T)PairIterable.this.car; + } + return (T)this.cdrIterator.next(); + } + + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + } + + /** + * Test the list functions. + */ + static class Test { + Boolean testList() { + final Iterable<Object> l = list(2, 3, 4); + assert car(l) == Integer.valueOf(2); + assert cadr(l) == Integer.valueOf(3); + assert caddr(l) == Integer.valueOf(4); + + final Iterable<Object> c = cons(0, cons(1, l)); + assert car(c) == Integer.valueOf(0); + assert cadr(c) == Integer.valueOf(1); + assert caddr(c) == Integer.valueOf(2); + assert c.toString().equals("[0, 1, 2, 3, 4]"); + + final Iterable<Object> cl = cons(0, cons(1, new ArrayList<Object>(asList(2, 3, 4)))); + assert car(cl) == Integer.valueOf(0); + assert cadr(cl) == Integer.valueOf(1); + assert caddr(cl) == Integer.valueOf(2); + assert cl.toString().equals("[0, 1, 2, 3, 4]"); + + final List<Object> jl = new ArrayList<Object>(collection(cl)); + assert jl.size() == 5; + assert jl.get(0) == Integer.valueOf(0); + assert jl.get(1) == Integer.valueOf(1); + assert jl.get(2) == Integer.valueOf(2); + + final Iterable<Object> n = list(); + assert isNil(n); + assert n.toString().equals("[]"); + + final Iterable<Object> cn = cons(0, n); + assert !isNil(cn); + assert isNil(cdr(cn)); + assert cn.toString().equals("[0]"); + + final Iterable<Object> al = new ArrayList<Object>(Arrays.asList(1, 2, 3)); + assert car(al) == Integer.valueOf(1); + assert cadr(al) == Integer.valueOf(2); + assert caddr(al) == Integer.valueOf(3); + return true; + } + } + + public static void main(final String[] args) { + System.out.println("Testing..."); + + Test.class.getClassLoader().setDefaultAssertionStatus(true); + new Test().testList(); + + System.out.println("OK"); + } + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/Service.java b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/Service.java new file mode 100644 index 0000000000..a00d5b1b53 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/Service.java @@ -0,0 +1,53 @@ +/* + * 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. + */ + +package org.apache.tuscany; + +/** + * Interface used to represent SCA component references providing both REST + * access to a resource and function application. + */ +public interface Service { + + /** + * Post a new item to a collection of items. + */ + Iterable<String> post(Iterable<String> collection, Iterable<?> item); + + /** + * Return an item. + */ + Iterable<?> get(Iterable<String> id); + + /** + * Update an item. + */ + boolean put(Iterable<String> id, Iterable<?> item); + + /** + * Delete an item. + */ + boolean delete(Iterable<String> id); + + /** + * Evaluate an expression. + */ + <T> T eval(Object... params); + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/UUIDUtil.java b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/UUIDUtil.java new file mode 100644 index 0000000000..60076c62ca --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/org/apache/tuscany/UUIDUtil.java @@ -0,0 +1,32 @@ +/* + * 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. + */ + +package org.apache.tuscany; + +/** + * A fast and portable UUID generator function. + */ +public class UUIDUtil { + + /** + * Return a UUID. + */ + public static native String uuid(); + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/server-test b/sandbox/sebastien/cpp/apr-2/modules/java/server-test new file mode 100755 index 0000000000..dba63a9525 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/server-test @@ -0,0 +1,41 @@ +#!/bin/sh + +# 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. + +# Setup +../http/httpd-conf tmp localhost 8090 ../server/htdocs +../server/server-conf tmp +./java-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite domain-test.composite +EOF + +export CLASSPATH="`pwd`/libmod-tuscany-java-1.0.jar:`pwd`" + +../http/httpd-start tmp +sleep 2 + +# Test +./client-test 2>/dev/null +rc=$? + +# Cleanup +../http/httpd-stop tmp +sleep 2 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/test/Adder.java b/sandbox/sebastien/cpp/apr-2/modules/java/test/Adder.java new file mode 100644 index 0000000000..7236548c41 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/test/Adder.java @@ -0,0 +1,26 @@ +/* + * 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. + */ + +package test; + +public interface Adder { + + Double add(Double x, Double y); + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/test/AdderImpl.java b/sandbox/sebastien/cpp/apr-2/modules/java/test/AdderImpl.java new file mode 100644 index 0000000000..e607012b78 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/test/AdderImpl.java @@ -0,0 +1,28 @@ +/* + * 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. + */ + +package test; + +public class AdderImpl { + + public Double add(Double x, Double y) { + return x + y; + } + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/test/CalcImpl.java b/sandbox/sebastien/cpp/apr-2/modules/java/test/CalcImpl.java new file mode 100644 index 0000000000..5bea01a43f --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/test/CalcImpl.java @@ -0,0 +1,52 @@ +/* + * 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. + */ + +package test; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.tuscany.Service; + +public class CalcImpl { + + public Double add(final Double x, final Double y, final Adder adder) { + return adder.add(x, y); + } + + public Double addEval(final Double x, final Double y, final Service adder) { + return adder.eval("add", x, y); + } + + public Double mult(final Double x, final Double y) { + return x * y; + } + + public Boolean even(final Double x) { + return (double)((int)(double)x / 2 * 2) == (double)x; + } + + public Iterable<Double> square(final Iterable<Double> l) { + final List<Double> r = new ArrayList<Double>(); + for(final Double x : l) + r.add(x * x); + return r; + } + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/test/Client.java b/sandbox/sebastien/cpp/apr-2/modules/java/test/Client.java new file mode 100644 index 0000000000..c3bd875fcc --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/test/Client.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package test; + +public interface Client { + + String echo(String x); + + Iterable<?> get(Iterable<String> id); + + Iterable<String> post(Iterable<String> collection, Iterable<?> item); + + Boolean put(Iterable<String> id, Iterable<?> item); + + Boolean delete(Iterable<String> id); + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/test/ClientImpl.java b/sandbox/sebastien/cpp/apr-2/modules/java/test/ClientImpl.java new file mode 100644 index 0000000000..ade2ba302e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/test/ClientImpl.java @@ -0,0 +1,44 @@ +/* + * 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. + */ + +package test; + +public class ClientImpl { + + public String echo(String x, Server server) { + return server.echo(x); + } + + public Iterable<?> get(Iterable<String> id, Server server) { + return server.get(id); + } + + public Iterable<String> post(Iterable<String> collection, Iterable<?> item, Server server) { + return server.post(collection, item); + } + + public Boolean put(Iterable<String> id, Iterable<?> item, Server server) { + return server.put(id, item); + } + + public Boolean delete(Iterable<String> id, Server server) { + return server.delete(id); + } + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/test/Server.java b/sandbox/sebastien/cpp/apr-2/modules/java/test/Server.java new file mode 100644 index 0000000000..3dfe3c84ef --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/test/Server.java @@ -0,0 +1,34 @@ +/* + * 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. + */ + +package test; + +public interface Server { + + String echo(String x); + + Iterable<?> get(Iterable<String> id); + + Iterable<String> post(Iterable<String> collection, Iterable<?> item); + + Boolean put(Iterable<String> id, Iterable<?> item); + + Boolean delete(Iterable<String> id); + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/test/ServerImpl.java b/sandbox/sebastien/cpp/apr-2/modules/java/test/ServerImpl.java new file mode 100644 index 0000000000..9de68fdb75 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/test/ServerImpl.java @@ -0,0 +1,51 @@ +/* + * 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. + */ + +package test; + +import static org.apache.tuscany.IterableUtil.*; + +public class ServerImpl { + + public String echo(final String x) { + return x; + } + + public Iterable<?> get(final Iterable<String> id) { + if (isNil(id)) + return list("Sample Feed", "123456789", + list("Item", "111", list(list("'name", "Apple"), list("'currencyCode", "USD"), list("'currencySymbol", "$"), list("'price", 2.99))), + list("Item", "222", list(list("'name", "Orange"), list("'currencyCode", "USD"), list("'currencySymbol", "$"), list("'price", 3.55))), + list("Item", "333", list(list("'name", "Pear"), list("'currencyCode", "USD"), list("'currencySymbol", "$"), list("'price", 1.55)))); + final Iterable<?> entry = list(list("'name", "Apple"), list("'currencyCode", "USD"), list("'currencySymbol", "$"), list("'price", 2.99)); + return list("Item", car(id), entry); + } + + public Iterable<String> post(final Iterable<String> collection, final Iterable<?> item) { + return list("123456789"); + } + + public Boolean put(final Iterable<String> id, final Iterable<?> item) { + return true; + } + + public Boolean delete(final Iterable<String> id) { + return true; + } +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/java/wiring-test b/sandbox/sebastien/cpp/apr-2/modules/java/wiring-test new file mode 100755 index 0000000000..fb2ad48efc --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/java/wiring-test @@ -0,0 +1,80 @@ +#!/bin/sh + +# 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. + +echo "Testing..." +here=`readlink -f $0`; here=`dirname $here` +curl_prefix=`cat $here/../http/curl.prefix` + +# Setup +../http/httpd-conf tmp localhost 8090 ../server/htdocs +../server/server-conf tmp +./java-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite domain-test.composite +EOF + +export CLASSPATH="`pwd`/libmod-tuscany-java-1.0.jar:`pwd`" + +../http/httpd-start tmp +sleep 2 + +# Test HTTP GET +$curl_prefix/bin/curl http://localhost:8090/index.html 2>/dev/null >tmp/index.html +diff tmp/index.html ../server/htdocs/index.html +rc=$? + +# Test ATOMPub +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ >tmp/feed.xml 2>/dev/null + diff tmp/feed.xml ../server/htdocs/test/feed.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 >tmp/entry.xml 2>/dev/null + diff tmp/entry.xml ../server/htdocs/test/entry.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ -X POST -H "Content-type: application/atom+xml" --data @../server/htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 -X PUT -H "Content-type: application/atom+xml" --data @../server/htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 -X DELETE 2>/dev/null + rc=$? +fi + +# Test JSON-RPC +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ -X POST -H "Content-type: application/json-rpc" --data @../server/htdocs/test/json-request.txt >tmp/json-result.txt 2>/dev/null + diff tmp/json-result.txt ../server/htdocs/test/json-result.txt + rc=$? +fi + +# Cleanup +../http/httpd-stop tmp +sleep 2 +if [ "$rc" = "0" ]; then + echo "OK" +fi +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/js/Makefile.am new file mode 100644 index 0000000000..8c88f32c0f --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/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. + +incl_HEADERS = *.hpp +incldir = $(prefix)/include/modules/js + +moddir = $(prefix)/modules/js +nobase_dist_mod_DATA = htdocs/*.js htdocs/*.css +EXTRA_DIST = htdocs/*.js htdocs/*.css + +js_test_SOURCES = js-test.cpp +js_test_LDFLAGS = -lmozjs + +noinst_PROGRAMS = js-test +TESTS = js-test diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/eval.hpp b/sandbox/sebastien/cpp/apr-2/modules/js/eval.hpp new file mode 100644 index 0000000000..b7c69a1a0c --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/eval.hpp @@ -0,0 +1,308 @@ +/* + * 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 +#include <jsapi.h> +#include "string.hpp" +#include "list.hpp" +#include "value.hpp" +#include "element.hpp" +#include "monad.hpp" + +namespace tuscany { +namespace js { + +/** + * Report Javascript errors. + */ +void reportError(unused ::JSContext *cx, const char *message, JSErrorReport *report) { +#ifdef WANT_MAINTAINER_MODE + cdebug << (const char*)(report->filename? report->filename : "<no filename>") << ":" + << (int)report->lineno << ":" << message << endl; +#endif +} + +/** + * Encapsulates a JavaScript runtime. Shared by multiple threads in + * a process. + */ +class JSRuntime { +public: + JSRuntime() { + // Create JS runtime + rt = JS_NewRuntime(8L * 1024L * 1024L); + if(rt == NULL) + cleanup(); + } + + operator ::JSRuntime*() const { + return rt; + } +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_PropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, JS_FinalizeStub, JSCLASS_NO_OPTIONAL_MEMBERS}; + +/** + * Represents a JavaScript context. Create one per thread. + */ +class JSContext { +public: + JSContext() { + // Create JS context + cx = JS_NewContext(jsRuntime, 8192); + if(cx == NULL) + return; + JS_SetOptions(cx, JSOPTION_VAROBJFIX); + JS_SetVersion(cx, JSVERSION_DEFAULT); + JS_SetErrorReporter(cx, reportError); + + // Create global JS object + global = JS_NewObject(cx, &jsGlobalClass, NULL, 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() { + cleanup(); + } + + operator ::JSContext*() const { + return cx; + } + + JSObject* getGlobal() const { + return global; + } + +private: + bool cleanup() { + if(cx != NULL) { + 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<value>& l) { + if(isNil(l)) + return true; + const value v = car(l); + if (isSymbol(v)) + return false; + if(isList(v)) { + if(!isNil((list<value>)v) && isSymbol(car<value>(v))) + return false; + } + return true; +} + +/** + * Converts JS properties to values. + */ +const list<value> jsPropertiesToValues(const list<value>& 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) || id == JSVAL_VOID) + return propertiesSoFar; + jsval jsv; + if(!JS_GetPropertyById(cx, o, id, &jsv)) + return propertiesSoFar; + const value val = jsValToValue(jsv, cx); + + jsval idv; + JS_IdToValue(cx, id, &idv); + if(JSVAL_IS_STRING(idv)) { + if (isNil(val) && !isList(val)) + return jsPropertiesToValues(propertiesSoFar, o, i, cx); + const string name = JS_GetStringBytes(JSVAL_TO_STRING(idv)); + if (substr(name, 0, 1) == atsign) + return jsPropertiesToValues(cons<value>(mklist<value>(attribute, c_str(substr(name, 1)), val), propertiesSoFar), o, i, cx); + if (isList(val) && !isJSArray(val)) + return jsPropertiesToValues(cons<value>(cons<value>(element, cons<value>(c_str(name), list<value>(val))), propertiesSoFar), o, i, cx); + return jsPropertiesToValues(cons<value> (mklist<value> (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: { + return value(string(JS_GetStringBytes(JSVAL_TO_STRING(jsv)))); + } + 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<value> ()); + const value pv = jsPropertiesToValues(list<value> (), o, i, cx); + return pv; + } + default: { + return value(); + } + } +} + +/** + * Converts a list of values to JS array elements. + */ +JSObject* valuesToJSElements(JSObject* a, const list<value>& 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<value>& 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: { + return DOUBLE_TO_JSVAL(JS_NewDouble(cx, (double)val)); + } + 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)); + } + default: { + return JSVAL_VOID; + } + } +} + +/** + * Converts a list of values to JS properties. + */ +JSObject* valuesToJSProperties(JSObject* o, const list<value>& 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<value> 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<value>("Couldn't evaluate Javascript script."); + } + return jsValToValue(rval, cx); +} + +} +} + +#endif /* tuscany_js_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/atomutil.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/atomutil.js new file mode 100644 index 0000000000..6b998dceda --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/atomutil.js @@ -0,0 +1,169 @@ +/* + * 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. + */ + +/** + * ATOM data conversion functions. + */ +var atom = new Object(); + +/** + * Convert a list of elements to a list of values representing an ATOM entry. + */ +atom.entryElementsToValues = function(e) { + var lt = filter(selector(mklist(element, "'title")), e); + var t = isNil(lt)? '' : elementValue(car(lt)); + var li = filter(selector(mklist(element, "'id")), e); + var i = isNil(li)? '' : elementValue(car(li)); + var lc = filter(selector(mklist(element, "'content")), e); + return mklist(t, i, elementValue(car(lc))); +}; + +/** + * Convert a list of elements to a list of values representing ATOM entries. + */ +atom.entriesElementsToValues = function(e) { + if (isNil(e)) + return e; + return cons(atom.entryElementsToValues(car(e)), atom.entriesElementsToValues(cdr(e))); +}; + +/** + * Convert a list of strings to a list of values representing an ATOM entry. + */ +atom.readATOMEntry = function(l) { + var e = readXML(l); + if (isNil(e)) + return mklist(); + return atom.entryElementsToValues(car(e)); +}; + +/** + * Convert a list of values representy an ATOM entry to a value. + */ +atom.entryValue = function(e) { + var v = elementsToValues(mklist(caddr(e))); + return cons(car(e), (cadr(e), cdr(car(v)))); +}; + +/** + * Return true if a list of strings represents an ATOM feed. + */ +atom.isATOMFeed = function(l) { + if (!isXML(l)) + return false; + return car(l).match('<feed') != null && car(l).match('="http://www.w3.org/2005/Atom"') != null; +}; + +/** + * Convert a DOM document to a list of values representing an ATOM feed. + */ +atom.readATOMFeedDocument = function(doc) { + var f = readXMLDocument(doc); + if (isNil(f)) + return mklist(); + var t = filter(selector(mklist(element, "'title")), car(f)); + var i = filter(selector(mklist(element, "'id")), car(f)); + var e = filter(selector(mklist(element, "'entry")), car(f)); + if (isNil(e)) + return mklist(elementValue(car(t)), elementValue(car(i))); + return cons(elementValue(car(t)), cons(elementValue(car(i)), atom.entriesElementsToValues(e))); +}; + +/** + * Convert a list of strings to a list of values representing an ATOM feed. + */ +atom.readATOMFeed = function(l) { + return atom.readAtomFeedDocument(parseXML(l)); +}; + +/** + * Convert an ATOM feed containing elements to an ATOM feed containing values. + */ +atom.feedValues = function(e) { + function feedValuesLoop(e) { + if (isNil(e)) + return e; + return cons(entryValue(car(e)), feedValuesLoop(cdr(e))); + } + + return cons(car(e), cons(cadr(e), feedValuesLoop(cddr(e)))); +}; + +/** + * Convert a list of values representy an ATOM entry to a list of elements. + */ +atom.entryElement = function(l) { + return mklist(element, "'entry", mklist(attribute, "'xmlns", "http://www.w3.org/2005/Atom"), + mklist(element, "'title", mklist(attribute, "'type", "text"), car(l)), + mklist(element, "'id", cadr(l)), + mklist(element, "'content", mklist(attribute, "'type", (isList(caddr(l))? "application/xml" : "text")), caddr(l)), + mklist(element, "'link", mklist(attribute, "'href", cadr(l)))); +}; + +/** + * Convert a list of values representing ATOM entries to a list of elements. + */ +atom.entriesElements = function(l) { + if (isNil(l)) + return l; + return cons(atom.entryElement(car(l)), atom.entriesElements(cdr(l))); +}; + +/** + * Convert a list of values representing an ATOM entry to an ATOM entry. + */ +atom.writeATOMEntry = function(l) { + return writeXML(mklist(atom.entryElement(l)), true); +}; + +/** + * Convert a list of values representing an ATOM feed to an ATOM feed. + */ +atom.writeATOMFeed = function(l) { + var f = mklist(element, "'feed", mklist(attribute, "'xmlns", "http://www.w3.org/2005/Atom"), + mklist(element, "'title", mklist(attribute, "'type", "text"), car(l)), + mklist(element, "'id", cadr(l))); + if (isNil(cddr(l))) + return writeXML(mklist(f), true); + var fe = append(f, atom.entriesElements(cddr(l))); + return writeXML(mklist(fe), true); +}; + +/** + * Convert an ATOM entry containing a value to an ATOM entry containing an item element. + */ +atom.entryValuesToElements = function(v) { + if (isList(caddr(v))) + return cons(car(v), cons(cadr(v), valuesToElements(mklist(cons("'item", caddr(v)))))); + return cons(car(v), cons(cadr(v), valuesToElements(mklist(mklist("'item", caddr(v)))))); +}; + +/** + * Convert an ATOM feed containing values to an ATOM feed containing elements. + */ +atom.feedValuesToElements = function(v) { + function feedValuesToElementsLoop(v) { + if (isNil(v)) + return v; + return cons(atom.entryValuesToElements(car(v)), feedValuesToElementsLoop(cdr(v))); + } + + return cons(car(v), cons(cadr(v), feedValuesToElementsLoop(cddr(v)))); +}; + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/component.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/component.js new file mode 100644 index 0000000000..9ce6aa86e5 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/component.js @@ -0,0 +1,561 @@ +/* + * 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. + * + * The JSON-RPC client code is based on Jan-Klaas' JavaScript + * o lait library (jsolait). + * + * $Id: jsonrpc.js,v 1.36.2.3 2006/03/08 15:09:37 mclark Exp $ + * + * Copyright (c) 2003-2004 Jan-Klaas Kollhof + * Copyright (c) 2005 Michael Clark, Metaparadigm Pte Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"). + */ + +/** + * Client component wiring API, supporting JSON and ATOM bindings. + */ + +/** + * Escape a character. + */ +var JSONClient = new Object(); + +JSONClient.escapeJSONChar = function(c) { + if(c == "\"" || c == "\\") return "\\" + c; + else if (c == "\b") return "\\b"; + else if (c == "\f") return "\\f"; + else if (c == "\n") return "\\n"; + else if (c == "\r") return "\\r"; + else if (c == "\t") return "\\t"; + var hex = c.charCodeAt(0).toString(16); + if(hex.length == 1) return "\\u000" + hex; + else if(hex.length == 2) return "\\u00" + hex; + else if(hex.length == 3) return "\\u0" + hex; + else return "\\u" + hex; +}; + +/** + * Encode a string into JSON format. + */ +JSONClient.escapeJSONString = function(s) { + /* The following should suffice but Safari's regex is broken + (doesn't support callback substitutions) + return "\"" + s.replace(/([^\u0020-\u007f]|[\\\"])/g, + JSONClient.escapeJSONChar) + "\""; + */ + + /* Rather inefficient way to do it */ + var parts = s.split(""); + for(var i = 0; i < parts.length; i++) { + var c = parts[i]; + if(c == '"' || + c == '\\' || + c.charCodeAt(0) < 32 || + c.charCodeAt(0) >= 128) + parts[i] = JSONClient.escapeJSONChar(parts[i]); + } + return "\"" + parts.join("") + "\""; +}; + +/** + * Marshall objects to JSON format. + */ +JSONClient.toJSON = function(o) { + if(o == null) { + return "null"; + } else if(o.constructor == String) { + return JSONClient.escapeJSONString(o); + } else if(o.constructor == Number) { + return o.toString(); + } else if(o.constructor == Boolean) { + return o.toString(); + } else if(o.constructor == Date) { + return '{javaClass: "java.util.Date", time: ' + o.valueOf() +'}'; + } else if(o.constructor == Array) { + var v = []; + for(var i = 0; i < o.length; i++) v.push(JSONClient.toJSON(o[i])); + return "[" + v.join(", ") + "]"; + } else { + var v = []; + for(attr in o) { + if(o[attr] == null) v.push("\"" + attr + "\": null"); + else if(typeof o[attr] == "function"); /* skip */ + else v.push(JSONClient.escapeJSONString(attr) + ": " + JSONClient.toJSON(o[attr])); + } + return "{" + v.join(", ") + "}"; + } +}; + +/** + * Construct an HTTPBindingClient. + */ +function HTTPBindingClient(cname, uri, objectID) { + this.uri = "/references/" + cname + "/" + uri; + this.objectID = objectID; + this.apply = this._createApplyMethod(); + + if (typeof DOMParser == "undefined") { + DOMParser = function () {} + + DOMParser.prototype.parseFromString = function (str, contentType) { + if (typeof ActiveXObject != "undefined") { + var d = new ActiveXObject("MSXML.DomDocument"); + d.loadXML(str); + return d; + } else if (typeof XMLHttpRequest != "undefined") { + var req = new XMLHttpRequest; + req.open("GET", "data:" + (contentType || "application/xml") + + ";charset=utf-8," + encodeURIComponent(str), false); + if (req.overrideMimeType) { + req.overrideMimeType(contentType); + } + req.send(null); + return req.responseXML; + } + } + } +} + +/** + * HTTPBindingClient.Exception. + */ +HTTPBindingClient.Exception = function(code, message, javaStack) { + this.code = code; + var name; + if(javaStack) { + this.javaStack = javaStack; + var m = javaStack.match(/^([^:]*)/); + if(m) name = m[0]; + } + if(name) this.name = name; + else this.name = "HTTPBindingClientException"; + this.message = message; +}; + +HTTPBindingClient.Exception.CODE_REMOTE_EXCEPTION = 490; +HTTPBindingClient.Exception.CODE_ERR_CLIENT = 550; +HTTPBindingClient.Exception.CODE_ERR_PARSE = 590; +HTTPBindingClient.Exception.CODE_ERR_NOMETHOD = 591; +HTTPBindingClient.Exception.CODE_ERR_UNMARSHALL = 592; +HTTPBindingClient.Exception.CODE_ERR_MARSHALL = 593; + +HTTPBindingClient.Exception.prototype = new Error(); +HTTPBindingClient.Exception.prototype.toString = function(code, msg) { + return this.name + ": " + this.message; +}; + +/** + * Default top level exception handler. + */ +HTTPBindingClient.default_ex_handler = function(e) { + alert(e); +}; + +/** + * Client settable variables + */ +HTTPBindingClient.toplevel_ex_handler = HTTPBindingClient.default_ex_handler; +HTTPBindingClient.profile_async = false; +HTTPBindingClient.max_req_active = 1; +HTTPBindingClient.requestId = 1; + +/** + * HTTPBindingClient implementation + */ +HTTPBindingClient.prototype._createApplyMethod = function() { + var fn = function() { + var args = []; + var callback = null; + var methodName = arguments[0]; + for(var i = 1; i < arguments.length; i++) args.push(arguments[i]); + + if(typeof args[args.length - 1] == "function") callback = args.pop(); + + var req = fn.client._makeRequest.call(fn.client, methodName, args, callback); + if(callback == null) { + return fn.client._sendRequest.call(fn.client, req); + } else { + HTTPBindingClient.async_requests.push(req); + HTTPBindingClient.kick_async(); + return req.requestId; + } + }; + fn.client = this; + return fn; +}; + +HTTPBindingClient._getCharsetFromHeaders = function(http) { + try { + var contentType = http.getResponseHeader("Content-type"); + var parts = contentType.split(/\s*;\s*/); + for(var i = 0; i < parts.length; i++) { + if(parts[i].substring(0, 8) == "charset=") + return parts[i].substring(8, parts[i].length); + } + } catch (e) {} + return "UTF-8"; +}; + +/** + * Async queue globals + */ +HTTPBindingClient.async_requests = []; +HTTPBindingClient.async_inflight = {}; +HTTPBindingClient.async_responses = []; +HTTPBindingClient.async_timeout = null; +HTTPBindingClient.num_req_active = 0; + +HTTPBindingClient._async_handler = function() { + HTTPBindingClient.async_timeout = null; + + while(HTTPBindingClient.async_responses.length > 0) { + var res = HTTPBindingClient.async_responses.shift(); + if(res.canceled) continue; + if(res.profile) res.profile.dispatch = new Date(); + try { + res.cb(res.result, res.ex, res.profile); + } catch(e) { + HTTPBindingClient.toplevel_ex_handler(e); + } + } + + while(HTTPBindingClient.async_requests.length > 0 && HTTPBindingClient.num_req_active < HTTPBindingClient.max_req_active) { + var req = HTTPBindingClient.async_requests.shift(); + if(req.canceled) continue; + req.client._sendRequest.call(req.client, req); + } +}; + +HTTPBindingClient.kick_async = function() { + if(HTTPBindingClient.async_timeout == null) + HTTPBindingClient.async_timeout = setTimeout(HTTPBindingClient._async_handler, 0); +}; + +HTTPBindingClient.cancelRequest = function(requestId) { + /* If it is in flight then mark it as canceled in the inflight map + and the XMLHttpRequest callback will discard the reply. */ + if(HTTPBindingClient.async_inflight[requestId]) { + HTTPBindingClient.async_inflight[requestId].canceled = true; + return true; + } + + /* If its not in flight yet then we can just mark it as canceled in + the the request queue and it will get discarded before being sent. */ + for(var i in HTTPBindingClient.async_requests) { + if(HTTPBindingClient.async_requests[i].requestId == requestId) { + HTTPBindingClient.async_requests[i].canceled = true; + return true; + } + } + + /* It may have returned from the network and be waiting for its callback + to be dispatched, so mark it as canceled in the response queue + and the response will get discarded before calling the callback. */ + for(var i in HTTPBindingClient.async_responses) { + if(HTTPBindingClient.async_responses[i].requestId == requestId) { + HTTPBindingClient.async_responses[i].canceled = true; + return true; + } + } + + return false; +}; + +HTTPBindingClient.prototype._makeRequest = function(methodName, args, cb) { + var req = {}; + req.client = this; + req.requestId = HTTPBindingClient.requestId++; + + var obj = {}; + obj.id = req.requestId; + if (this.objectID) + obj.method = ".obj#" + this.objectID + "." + methodName; + else + obj.method = methodName; + obj.params = args; + + if (cb) req.cb = cb; + if (HTTPBindingClient.profile_async) + req.profile = { "submit": new Date() }; + req.data = JSONClient.toJSON(obj); + + return req; +}; + +HTTPBindingClient.prototype._sendRequest = function(req) { + if(req.profile) req.profile.start = new Date(); + + /* Get free http object from the pool */ + var http = HTTPBindingClient.poolGetHTTPRequest(); + HTTPBindingClient.num_req_active++; + + /* Send the request */ + http.open("POST", this.uri, (req.cb != null)); + http.setRequestHeader("Content-type", "application/json-rpc"); + + /* Construct call back if we have one */ + if(req.cb) { + var self = this; + http.onreadystatechange = function() { + if(http.readyState == 4) { + http.onreadystatechange = function () {}; + var res = { "cb": req.cb, "result": null, "ex": null}; + if (req.profile) { + res.profile = req.profile; + res.profile.end = new Date(); + } + try { res.result = self._handleResponse(http); } + catch(e) { res.ex = e; } + if(!HTTPBindingClient.async_inflight[req.requestId].canceled) + HTTPBindingClient.async_responses.push(res); + delete HTTPBindingClient.async_inflight[req.requestId]; + HTTPBindingClient.kick_async(); + } + }; + } else { + http.onreadystatechange = function() {}; + } + + HTTPBindingClient.async_inflight[req.requestId] = req; + + try { + http.send(req.data); + } catch(e) { + HTTPBindingClient.poolReturnHTTPRequest(http); + HTTPBindingClient.num_req_active--; + throw new HTTPBindingClient.Exception(HTTPBindingClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + if(!req.cb) return this._handleResponse(http); +}; + +HTTPBindingClient.prototype._handleResponse = function(http) { + /* Get the charset */ + if(!this.charset) { + this.charset = HTTPBindingClient._getCharsetFromHeaders(http); + } + + /* Get request results */ + var status, statusText, data; + try { + status = http.status; + statusText = http.statusText; + data = http.responseText; + } catch(e) { + HTTPBindingClient.poolReturnHTTPRequest(http); + HTTPBindingClient.num_req_active--; + HTTPBindingClient.kick_async(); + throw new HTTPBindingClient.Exception(HTTPBindingClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + /* Return http object to the pool; */ + HTTPBindingClient.poolReturnHTTPRequest(http); + HTTPBindingClient.num_req_active--; + + /* Unmarshall the response */ + if(status != 200) { + throw new HTTPBindingClient.Exception(status, statusText); + } + var obj; + try { + eval("obj = " + data); + } catch(e) { + throw new HTTPBindingClient.Exception(550, "error parsing result"); + } + if(obj.error) + throw new HTTPBindingClient.Exception(obj.error.code, obj.error.msg, obj.error.trace); + var res = obj.result; + + /* Handle CallableProxy */ + if(res && res.objectID && res.JSONRPCType == "CallableReference") + return new HTTPBindingClient(this.uri, res.objectID); + + return res; +}; + + +/** + * XMLHttpRequest wrapper code + */ +HTTPBindingClient.http_spare = []; +HTTPBindingClient.http_max_spare = 8; + +HTTPBindingClient.poolGetHTTPRequest = function() { + if(HTTPBindingClient.http_spare.length > 0) { + return HTTPBindingClient.http_spare.pop(); + } + return HTTPBindingClient.getHTTPRequest(); +}; + +HTTPBindingClient.poolReturnHTTPRequest = function(http) { + if(HTTPBindingClient.http_spare.length >= HTTPBindingClient.http_max_spare) + delete http; + else + HTTPBindingClient.http_spare.push(http); +}; + +HTTPBindingClient.msxmlNames = [ "MSXML2.XMLHTTP.5.0", + "MSXML2.XMLHTTP.4.0", + "MSXML2.XMLHTTP.3.0", + "MSXML2.XMLHTTP", + "Microsoft.XMLHTTP" ]; + +HTTPBindingClient.getHTTPRequest = function() { + /* Mozilla XMLHttpRequest */ + try { + HTTPBindingClient.httpObjectName = "XMLHttpRequest"; + return new XMLHttpRequest(); + } catch(e) {} + + /* Microsoft MSXML ActiveX */ + for (var i=0; i < HTTPBindingClient.msxmlNames.length; i++) { + try { + HTTPBindingClient.httpObjectName = HTTPBindingClient.msxmlNames[i]; + return new ActiveXObject(HTTPBindingClient.msxmlNames[i]); + } catch (e) {} + } + + /* None found */ + HTTPBindingClient.httpObjectName = null; + throw new HTTPBindingClient.Exception(0, "Can't create XMLHttpRequest object"); +}; + + +HTTPBindingClient.prototype.get = function(id, responseFunction) { + var xhr = HTTPBindingClient.getHTTPRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + var strDocument = xhr.responseText; + var xmlDocument = xhr.responseXML; + if(!xmlDocument || xmlDocument.childNodes.length==0){ + xmlDocument = (new DOMParser()).parseFromString(strDocument, "text/xml"); + } + if (responseFunction != null) responseFunction(xmlDocument); + } else { + alert("get - Error getting data from the server"); + } + } + } + xhr.open("GET", this.uri + '/' + id, true); + xhr.send(null); +}; + +HTTPBindingClient.prototype.post = function (entry, responseFunction) { + var xhr = HTTPBindingClient.getHTTPRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 201) { + var strDocument = xhr.responseText; + var xmlDocument = xhr.responseXML; + if(!xmlDocument || xmlDocument.childNodes.length==0){ + xmlDocument = (new DOMParser()).parseFromString(strDocument, "text/xml"); + } + if (responseFunction != null) responseFunction(xmlDocument); + } else { + alert("post - Error getting data from the server"); + } + } + } + xhr.open("POST", this.uri, true); + xhr.setRequestHeader("Content-Type", "application/atom+xml;type=entry"); + xhr.send(entry); +}; + +HTTPBindingClient.prototype.put = function (id, entry, responseFunction) { + var xhr = HTTPBindingClient.getHTTPRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + var strDocument = xhr.responseText; + var xmlDocument = xhr.responseXML; + if(!xmlDocument || xmlDocument.childNodes.length==0){ + xmlDocument = (new DOMParser()).parseFromString(strDocument, "text/xml"); + } + if (responseFunction != null) responseFunction(xmlDocument); + } else { + alert("put - Error getting data from the server"); + } + } + } + xhr.open("PUT", this.uri + '/' + id, true); + xhr.setRequestHeader("Content-Type", "application/atom+xml;type=entry"); + xhr.send(entry); +}; + +HTTPBindingClient.prototype.del = function (id, responseFunction) { + var xhr = HTTPBindingClient.getHTTPRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + if (responseFunction != null) responseFunction(); + } else { + alert("delete - Error getting data from the server"); + } + } + } + xhr.open("DELETE", this.uri + '/' + id, true); + xhr.send(null); +}; + +/** + * Public API. + */ + +var sca = new Object(); + +/** + * Return a component. + */ +sca.component = function(name) { + function ClientComponent(name) { + this.name = name; + } + + return new ClientComponent(name); +}; + +/** + * Return a reference proxy. + */ +sca.reference = function(comp, name) { + return new HTTPBindingClient(comp.name, name); +}; + +/** + * Add proxy functions to a reference proxy. + */ +sca.defun = function(ref) { + function defapply(name) { + return function() { + var args = new Array(); + args[0] = name; + for (i = 0, n = arguments.length; i < n; i++) + args[i + 1] = arguments[i]; + return this.apply.apply(this, args); + }; + } + + for (f = 1; f < arguments.length; f++) { + var fn = arguments[f]; + ref[fn]= defapply(fn); + } + return ref; +}; + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/elemutil.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/elemutil.js new file mode 100644 index 0000000000..00baab06c8 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/elemutil.js @@ -0,0 +1,231 @@ +/* + * 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. + */ + +/** + * Functions to help represent data as lists of elements and attributes. + */ + +var element = "'element" +var attribute = "'attribute" +var atsign = "'@" + +/** + * Return true if a value is an element. + */ +function isElement(v) { + if (!isList(v) || isNil(v) || car(v) != element) + return false; + return true; +} + +/** + * Return true if a value is an attribute. + */ +function isAttribute(v) { + if (!isList(v) || isNil(v) || car(v) != attribute) + return false; + return true; +} + +/** + * Return the name of an attribute. + */ +function attributeName(l) { + return cadr(l); +} + +/** + * Return the value of an attribute. + */ +function attributeValue(l) { + return caddr(l); +} + +/** + * Return the name of an element. + */ +function elementName(l) { + return cadr(l); +} + +/** + * Return true if an element has children. + */ +function elementHasChildren(l) { + return !isNil(cddr(l)); +} + +/** + * Return the children of an element. + */ +function elementChildren(l) { + return cddr(l); +} + + +/** + * Return true if an element has a value. + */ +function elementHasValue(l) { + r = reverse(l); + if (isSymbol(car(r))) + return false; + if (isList(car(r)) && !isNil(car(r)) && isSymbol(car(car(r)))) + return false; + return true; +} + +/** + * Return the value of an element. + */ +function elementValue(l) { + return car(reverse(l)); +} + +/** + * Convert an element to a value. + */ +function elementToValueIsList(v) { + if (!isList(v)) + return false; + return isNil(v) || !isSymbol(car(v)); +} + +function elementToValue(t) { + if (isTaggedList(t, attribute)) + return mklist(atsign + attributeName(t).substring(1), attributeValue(t)); + if (isTaggedList(t, element)) { + if (elementHasValue(t)) { + if (!elementToValueIsList(elementValue(t))) + return mklist(elementName(t), elementValue(t)); + return cons(elementName(t), mklist(elementsToValues(elementValue(t)))); + } + return cons(elementName(t), elementsToValues(elementChildren(t))); + } + if (!isList(t)) + return t; + return elementsToValues(t); +} + +/** + * Convert a list of elements to a list of values. + */ +function elementToValueIsSymbol(v) { + if (!isList(v)) + return false; + if (isNil(v)) + return false; + if (!isSymbol(car(v))) + return false; + return true; +} + +function elementToValueGroupValues(v, l) { + if (isNil(l) || !elementToValueIsSymbol(v) || !elementToValueIsSymbol(car(l))) + return cons(v, l); + if (car(car(l)) != car(v)) + return cons(v, l); + if (!elementToValueIsList(cadr(car(l)))) { + var g = mklist(car(v), mklist(cdr(v), cdr(car(l)))); + return elementToValueGroupValues(g, cdr(l)); + } + var g = mklist(car(v), cons(cdr(v), cadr(car(l)))); + return elementToValueGroupValues(g, cdr(l)); +} + +function elementsToValues(e) { + if (isNil(e)) + return e; + return elementToValueGroupValues(elementToValue(car(e)), elementsToValues(cdr(e))); +} + +/** + * Convert a value to an element. + */ +function valueToElement(t) { + if (isList(t) && !isNil(t) && isSymbol(car(t))) { + var n = car(t); + var v = isNil(cdr(t))? mklist() : cadr(t); + if (!isList(v)) { + if (n.substring(0, 2) == atsign) + return mklist(attribute, n.substring(1), v); + return mklist(element, n, v); + } + if (isNil(v) || !isSymbol(car(v))) + return cons(element, cons(n, mklist(valuesToElements(v)))); + return cons(element, cons(n, valuesToElements(cdr(t)))); + } + if (!isList(t)) + return t; + return valuesToElements(t); +} + +/** + * Convert a list of values to a list of elements. + */ +function valuesToElements(l) { + if (isNil(l)) + return l; + return cons(valueToElement(car(l)), valuesToElements(cdr(l))); +} + +/** + * Return a selector lambda function which can be used to filter elements. + */ +function selector(s) { + function evalSelect(s, v) { + if (isNil(s)) + return true; + if (isNil(v)) + return false; + if (car(s) != car(v)) + return false; + return evalSelect(cdr(s), cdr(v)); + } + + return function(v) { return evalSelect(s, v); }; +} + +/** + * Return the value of the attribute with the given name. + */ +function namedAttributeValue(name, l) { + var f = filter(function(v) { return isAttribute(v) && attributeName(v) == name; }, l); + if (isNil(f)) + return null; + return caddr(car(f)); +} + +/** + * Return child elements with the given name. + */ +function namedElementChildren(name, l) { + return filter(function(v) { return isElement(v) && elementName(v) == name; }, l); +} + +/** + * Return the child element with the given name. + */ +function namedElementChild(name, l) { + var f = namedElementChildren(name, l); + if (isNil(f)) + return null; + return car(f); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/graph.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/graph.js new file mode 100644 index 0000000000..883b3aa801 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/graph.js @@ -0,0 +1,638 @@ +/* + * 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. + */ + +/** + * SVG and VML component rendering functions. + */ + +var graph = new Object(); + +/** + * Detect browser VML support. + */ +graph.supportsVML = function() { + if (typeof graph.supportsVML.supported != 'undefined') + return graph.supportsVML.supported; + graph.supportsVML.supported = navigator.appName == 'Microsoft Internet Explorer'; + return graph.supportsVML.supported; +}; + +/** + * Detect browser SVG support. + */ +graph.supportsSVG = function() { + if (typeof graph.supportsSVG.supported != 'undefined') + return graph.supportsSVG.supported; + graph.supportsSVG.supported = navigator.appName != 'Microsoft Internet Explorer'; + return graph.supportsSVG.supported; +}; + +/** + * Basic colors + */ +graph.red = 'red'; +graph.green = 'green'; +graph.blue = 'blue'; +graph.yellow = 'yellow'; +graph.orange = '#ffa500'; +graph.gray = 'gray' + +/** + * Base path class. + */ +graph.BasePath = function() { + this.path = ''; + this.x = 0; + this.y = 0; + + this.pos = function(x, y) { + this.x = x; + this.y = y; + return this; + }; + + this.xpos = function() { + return this.x; + }; + + this.ypos = function() { + return this.y; + }; + + this.rmove = function(x, y) { + return this.move(this.x + x, this.y + y); + }; + + this.rline = function(x, y) { + return this.line(this.x + x, this.y + y); + }; + + this.rcurve = function(x1, y1, x, y) { + return this.curve(this.x + x1, this.y + y1, this.x + x1 + x, this.y + y1 + y); + }; + + this.str = function() { + return this.path; + }; +}; + +/** + * Rendering functions that work both with VML and SVG. + */ +var graph; + +/** + * VML rendering. + */ +if (graph.supportsVML()) { + + graph.vmlns='urn:schemas-microsoft-com:vml'; + document.write('<xml:namespace ns="urn:schemas-microsoft-com:vml" prefix="v" />'); + + /** + * Make a graph. + */ + graph.mkgraph = function() { + var div = document.createElement('div'); + div.id = 'vmldiv'; + document.body.appendChild(div); + + var vmlg = document.createElement('v:group'); + vmlg.style.width = 500; + vmlg.style.height = 500; + vmlg.coordsize = '500,500'; + div.appendChild(vmlg); + + graph.dragging = null; + + function draggable(n) { + if (n == vmlg) + return null; + if (n.nodeName == 'group') + return n; + return draggable(n.parentNode); + } + + vmlg.onmousedown = function() { + window.event.returnValue = false; + graph.dragging = draggable(window.event.srcElement); + if (graph.dragging == null) + return false; + graph.dragging.parentNode.appendChild(graph.dragging); + graph.dragX = window.event.clientX; + graph.dragY = window.event.clientY; + vmlg.setCapture(); + return false; + }; + + vmlg.onmouseup = function() { + if (graph.dragging == null) + return false; + graph.dragging = null; + vmlg.releaseCapture(); + return false; + }; + + vmlg.onmousemove = function() { + if (graph.dragging == null) + return false; + var origX = graph.dragging.coordorigin.X; + var origY = graph.dragging.coordorigin.Y; + var newX = origX - (window.event.clientX - graph.dragX); + var newY = origY - (window.event.clientY - graph.dragY); + graph.dragX = window.event.clientX; + graph.dragY = window.event.clientY; + graph.dragging.setAttribute('coordorigin', newX + ' ' + newY); + return false; + }; + + graph.textWidthDiv = document.createElement('span'); + graph.textWidthDiv.style.visibility = 'hidden' + div.appendChild(graph.textWidthDiv); + + return vmlg; + }; + + /** + * Make a shape path. + */ + graph.mkpath = function() { + function Path() { + this.BasePath = graph.BasePath; + this.BasePath(); + + this.move = function(x, y) { + this.path += 'M ' + x + ',' + y + ' '; + return this.pos(x, y); + }; + + this.line = function(x, y) { + this.path += 'L ' + x + ',' + y + ' '; + return this.pos(x, y); + }; + + this.curve = function(x1, y1, x, y) { + this.path += 'QB ' + x1 + ',' + y1 + ',' + x + ',' + y + ' '; + return this.pos(x, y); + }; + + this.end = function() { + this.path += 'X E'; + return this; + }; + } + + return new Path(); + }; + + /** + * Make a title element. + */ + graph.mktitle = function(t) { + var title = document.createElement('v:textbox'); + title.style.left = '25'; + title.style.top = '5'; + title.style.position = 'absolute'; + var tnode = document.createTextNode(t); + title.appendChild(tnode); + return title; + }; + + /** + * Return the width of a title. + */ + graph.titlewidth = function(t) { + graph.textWidthDiv.innerHTML = t; + var twidth = graph.textWidthDiv.offsetWidth; + graph.textWidthDiv.innerHTML = ''; + return twidth; + }; + + /** + * Make a component shape. + */ + graph.mkcompshape = function(comp, cassoc) { + var name = scdl.name(comp); + var title = graph.mktitle(name); + + var d = graph.mkcomppath(comp, cassoc).str(); + + var shape = document.createElement('v:shape'); + shape.style.width = 500; + shape.style.height = 500; + shape.coordsize = '500,500'; + shape.path = d; + shape.fillcolor = graph.color(comp); + shape.stroked = 'false'; + + var contour = document.createElement('v:shape'); + contour.style.width = 500; + contour.style.height = 500; + contour.coordsize = '500,500'; + contour.setAttribute('path', d); + contour.filled = 'false'; + contour.strokecolor = graph.gray; + contour.strokeweight = '3'; + contour.style.top = 1; + contour.style.left = 1; + var stroke = document.createElement('v:stroke'); + stroke.opacity = '20%'; + contour.appendChild(stroke); + + var g = document.createElement('v:group'); + g.style.width = 500; + g.style.height = 500; + g.coordsize = '500,500'; + g.appendChild(shape); + g.appendChild(contour); + g.appendChild(title); + return g; + }; +} + +/** + * SVG rendering. + */ +if (graph.supportsSVG()) { + + graph.svgns='http://www.w3.org/2000/svg'; + + /** + * Make a graph. + */ + graph.mkgraph = function() { + var div = document.createElement('div'); + div.id = 'svgdiv'; + document.body.appendChild(div); + + var svg = document.createElementNS(graph.svgns, 'svg'); + svg.style.height = '100%'; + svg.style.width = '100%'; + div.appendChild(svg); + + graph.dragging = null; + + function draggable(n) { + if (n == svg) + return null; + if (n.nodeName == 'g') + return n; + return draggable(n.parentNode); + } + + svg.onmousedown = function(e) { + if (e.preventDefault) + e.preventDefault(); + else + e.returnValue= false; + graph.dragging = draggable(e.target); + if (graph.dragging == null) + return false; + graph.dragging.parentNode.appendChild(graph.dragging); + var pos = typeof e.touches != "undefined" ? e.touches[0] : e; + graph.dragX = pos.clientX; + graph.dragY = pos.clientY; + return false; + }; + + svg.ontouchstart = svg.onmousedown; + + svg.onmouseup = function(e) { + if (graph.dragging == null) + return false; + graph.dragging = null; + return false; + }; + + svg.ontouchend = svg.onmouseup; + + svg.onmousemove = function(e) { + if (graph.dragging == null) + return false; + var matrix = graph.dragging.getCTM(); + var pos = typeof e.touches != "undefined" ? e.touches[0] : e; + var newX = Number(matrix.e) + (pos.clientX - graph.dragX); + var newY = Number(matrix.f) + (pos.clientY - graph.dragY); + graph.dragX = pos.clientX; + graph.dragY = pos.clientY; + graph.dragging.setAttribute('transform', 'translate(' + newX + ',' + newY + ')'); + return false; + }; + + svg.ontouchmove = svg.onmousemove; + + graph.textWidthSvg = document.createElementNS(graph.svgns, 'svg'); + graph.textWidthSvg.style.visibility = 'hidden'; + graph.textWidthSvg.style.height = '0px'; + graph.textWidthSvg.style.width = '0px'; + div.appendChild(graph.textWidthSvg); + + return svg; + }; + + /** + * Make a shape path. + */ + graph.mkpath = function() { + function Path() { + this.BasePath = graph.BasePath; + this.BasePath(); + + this.move = function(x, y) { + this.path += 'M' + x + ',' + y + ' '; + return this.pos(x, y); + }; + + this.line = function(x, y) { + this.path += 'L' + x + ',' + y + ' '; + return this.pos(x, y); + }; + + this.curve = function(x1, y1, x, y) { + this.path += 'Q' + x1 + ',' + y1 + ' ' + x + ',' + y + ' '; + return this.pos(x, y); + }; + + this.end = function() { + this.path += 'Z'; + return this; + }; + } + + return new Path(); + }; + + /** + * Make a title element. + */ + graph.mktitle = function(t) { + var title = document.createElementNS(graph.svgns, 'text'); + title.setAttribute('text-anchor', 'start'); + title.setAttribute('x', 5); + title.setAttribute('y', 15); + title.appendChild(document.createTextNode(t)); + graph.textWidthSvg.appendChild(title); + return title; + }; + + /** + * Return a width of a title. + */ + graph.titlewidth = function(t) { + var title = graph.mktitle(t); + var width = title.getBBox().width; + graph.textWidthSvg.removeChild(title); + return width; + }; + + /** + * Make a component shape. + */ + graph.mkcompshape = function(comp, cassoc) { + var name = scdl.name(comp); + var title = graph.mktitle(name); + + var d = graph.mkcomppath(comp, cassoc).str(); + + var shape = document.createElementNS(graph.svgns, 'path'); + shape.setAttribute('d', d); + shape.setAttribute('fill', graph.color(comp)); + + var contour = document.createElementNS(graph.svgns, 'path'); + contour.setAttribute('d', d); + contour.setAttribute('fill', 'none'); + contour.setAttribute('stroke', graph.gray); + contour.setAttribute('stroke-width', '4'); + contour.setAttribute('stroke-opacity', '0.20'); + contour.setAttribute('transform', 'translate(1,1)'); + + var g = document.createElementNS(graph.svgns, 'g'); + g.appendChild(shape); + g.appendChild(contour); + g.appendChild(title); + return g; + }; +} + +/** + * Make a reference shape path, positioned to the right of a component shape. + */ +graph.mkrrefpath = function(ref, cassoc, path) { + var height = graph.refheight(ref, cassoc); + var ypos = path.ypos(); + return path.rline(0,10).rline(0,10).rcurve(0,5,-5,0).rcurve(-5,0,0,-5).rcurve(0,-5,-5,0).rcurve(-5,0,0,5).rline(0,20).rcurve(0,5,5,0).rcurve(5,0,0,-5).rcurve(0,-5,5,0).rcurve(5,0,0,5).line(path.xpos(),ypos + height); +}; + +/** + * Make a reference shape path, positioned at the bottom of a component shape. + */ +graph.mkbrefpath = function(ref, cassoc, path) { + var width = graph.refwidth(ref, cassoc); + var xpos = path.xpos(); + return path.line(xpos - width + 60,path.ypos()).rline(-10,0).rline(-10,0).rcurve(-5,0,0,-5).rcurve(0,-5,5,0).rcurve(5,0,0,-5).rcurve(0,-5,-5,0).rline(-20,0).rcurve(-5,0,0,5).rcurve(0,5,5,0).rcurve(5,0,0,5).rcurve(0,5,-5,0).line(xpos - width,path.ypos()); +}; + +/** + * Make a service shape path, positioned to the left of a component shape. + */ +graph.mklsvcpath = function(svc, path) { + var height = 60; + var ypos = path.ypos(); + return path.rline(0,-10).rline(0, -10).rcurve(0,-5,-5,0).rcurve(-5,0,0,5).rcurve(0,5,-5,0).rcurve(-5,0,0,-5).rline(0,-20).rcurve(0,-5,5,0).rcurve(5,0,0,5).rcurve(0,5,5,0).rcurve(5,0,0,-5).line(path.xpos(), ypos - height); +}; + +/** + * Make a service shape path, positioned at the top of a component shape. + */ +graph.mktsvcpath = function(svc, path) { + var width = 60; + var xpos = path.xpos(); + return path.rline(10,0).rline(10,0).rcurve(5,0,0,-5).rcurve(0,-5,-5,0).rcurve(-5,0,0,-5).rcurve(0,-5,5,0).rline(20,0).rcurve(5,0,0,5).rcurve(0,5,-5,0).rcurve(-5,0,0,5).rcurve(0,5,5,0).line(xpos + width,path.ypos()); +}; + + +/** + * Return the services and references of a component. + */ +graph.tsvcs = function(comp) { + return filter(function(s) { return scdl.align(s) == 'top'; }, scdl.services(comp)); +}; + +graph.lsvcs = function(comp) { + return filter(function(s) { var a = scdl.align(s); return a == null || a == 'left'; }, scdl.services(comp)); +}; + +graph.brefs = function(comp) { + return filter(function(r) { return scdl.align(r) == 'bottom'; }, scdl.references(comp)); +}; + +graph.rrefs = function(comp) { + return filter(function(r) { var a = scdl.align(r); return a == null || a == 'right'; }, scdl.references(comp)); +}; + +/** + * Return the color of a component. + */ +graph.color = function(comp) { + var c = scdl.color(comp); + return c == null? graph.blue : c; +} + +/** + * Return the height of a reference. + */ +graph.refheight = function(ref, cassoc) { + var target = assoc(scdl.target(ref), cassoc); + if (isNil(target)) + return 60; + return graph.compheight(cadr(target), cassoc); +} + +/** + * Return the total height of a list of references. + */ +graph.refsheight = function(refs, cassoc) { + if (isNil(refs)) + return 0; + return graph.refheight(car(refs), cassoc) + graph.refsheight(cdr(refs), cassoc); +} + +/** + * Return the height of a component. + */ +graph.compheight = function(comp, cassoc) { + var lsvcs = graph.lsvcs(comp); + var lsvcsh = Math.max(1, length(lsvcs)) * 60 + 20; + var rrefs = graph.rrefs(comp); + var rrefsh = graph.refsheight(rrefs, cassoc) + 20; + var height = Math.max(lsvcsh, rrefsh); + return height; +}; + +/** + * Return the width of a reference. + */ +graph.refwidth = function(ref, cassoc) { + var target = assoc(scdl.target(ref), cassoc); + if (isNil(target)) + return 60; + return graph.compwidth(cadr(target), cassoc); +} + +/** + * Return the total width of a list of references. + */ +graph.refswidth = function(refs, cassoc) { + if (isNil(refs)) + return 0; + return graph.refwidth(car(refs), cassoc) + graph.refswidth(cdr(refs), cassoc); +} + +/** + * Return the width of a component. + */ +graph.compwidth = function(comp, cassoc) { + var twidth = graph.titlewidth(scdl.name(comp)) + 20; + var tsvcs = graph.tsvcs(comp); + var tsvcsw = Math.max(1, length(tsvcs)) * 60 + 20; + var brefs = graph.brefs(comp); + var brefsw = graph.refswidth(brefs, cassoc) + 20; + var width = Math.max(twidth, Math.max(tsvcsw, brefsw)); + return width; +}; + +/** +* Make a component shape path. +*/ +graph.mkcomppath = function(comp, cassoc) { + var tsvcs = graph.tsvcs(comp); + var lsvcs = graph.lsvcs(comp); + var brefs = graph.brefs(comp); + var rrefs = graph.rrefs(comp); + + var height = graph.compheight(comp, cassoc); + var width = graph.compwidth(comp, cassoc); + + var path = graph.mkpath().move(10,0); + for (var s = 0; s < length(tsvcs); s++) + path = graph.mktsvcpath(tsvcs[s], path); + + path = path.line(width - 10,path.ypos()).rcurve(10,0,0,10); + for (var r = 0; r < length(rrefs); r++) + path = graph.mkrrefpath(rrefs[r], cassoc, path); + + var boffset = 10 + graph.refswidth(brefs, cassoc); + path = path.line(path.xpos(),height - 10).rcurve(0,10,-10,0).line(boffset, path.ypos()); + for (var r = 0; r < length(brefs); r++) + path = graph.mkbrefpath(brefs[r], cassoc, path); + + var loffset = 10 + (length(lsvcs) * 60); + path = path.line(10,path.ypos()).rcurve(-10,0,0,-10).line(path.xpos(), loffset); + for (var s = 0; s < length(lsvcs); s++) + path = graph.mklsvcpath(lsvcs[s], path); + + path = path.line(0,10).rcurve(0,-10,10,0); + return path.end(); +}; + +/** + * Render a component. + */ +graph.component = function(comp, cassoc) { + return graph.mkcompshape(comp, cassoc); +}; + +/** + * Render a composite. + */ +graph.composite = function(compos) { + var name = scdl.name(compos); + var comps = scdl.components(compos); + var cassoc = scdl.nameToElementAssoc(comps); + + function renderReference(ref, cassoc) { + var target = assoc(scdl.target(ref), cassoc); + if (isNil(target)) + return mklist(); + return renderComponent(cadr(target), cassoc); + } + + function renderReferences(refs, cassoc) { + if (isNil(refs)) + return mklist(); + var rref = renderReference(car(refs), cassoc); + if (isNil(rref)) + return renderReferences(cdr(refs), cassoc); + return append(rref, renderReferences(cdr(refs), cassoc)); + } + + function renderComponent(comp, cassoc) { + return append(renderReferences(scdl.references(comp), cassoc), mklist(graph.component(comp, cassoc))); + } + + function renderComponents(comps, cassoc) { + if (isNil(comps)) + return mklist(); + return append(renderComponent(car(comps), cassoc), renderComponents(cdr(comps), cassoc)); + } + + var rcomps = renderComponents(comps, cassoc); + return rcomps; +}; + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/scdl.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/scdl.js new file mode 100644 index 0000000000..baba0078fe --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/scdl.js @@ -0,0 +1,163 @@ +/* + * 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. + */ + +/** + * SCDL parsing functions. + */ +var scdl = new Object(); + +/** + * Returns a list of components in a composite. + */ +scdl.components = function(l) { + var cs = namedElementChildren("'composite", l); + if (isNil(cs)) + return cs; + return namedElementChildren("'component", car(cs)); +}; + +/** + * Returns the name of a component, service or reference. + */ +scdl.name = function(l) { + return namedAttributeValue("'name", l); +}; + +/** + * Returns the color of a component. + */ +scdl.color = function(l) { + return namedAttributeValue("'color", l); +}; + +/** + * Returns the implementation of a component. + */ +scdl.implementation = function(l) { + function filterImplementation(v) { + return isElement(v) && cadr(v).match("implementation.") != null; + } + + var n = filter(filterImplementation, l); + if (isNil(n)) + return null; + return car(n); +}; + +/** + * Returns the type of an implementation. + */ +scdl.implementationType = function(l) { + return elementName(l).substring(1); +}; + +/** + * Returns the URI of a service, reference or implementation. + */ +scdl.uri = function(l) { + return namedAttributeValue("'uri", l); +}; + +/** + * Returns the align attribute of a service or reference. + */ +scdl.align = function(l) { + return namedAttributeValue("'align", l); +}; + +/** + * Returns a list of services in a component. + */ +scdl.services = function(l) { + return namedElementChildren("'service", l); +}; + +/** + * Returns a list of references in a component. + */ +scdl.references = function(l) { + return namedElementChildren("'reference", l); +}; + +/** + * Returns a list of bindings in a service or reference. + */ +scdl.bindings = function(l) { + function filterBinding(v) { + return isElement(v) && cadr(v).match("binding.") != null; + } + + return filter(filterBinding, l); +}; + +/** + * Returns the type of a binding. + */ +scdl.bindingType = function(l) { + return elementName(l).substring(1); +}; + +/** + * Returns the target of a reference. + */ +scdl.target = function(l) { + function targetURI() { + function bindingsTarget(l) { + if (isNil(l)) + return null; + var u = uri(car(l)); + if (!isNil(u)) + return u; + return bindingsTarget(cdr(l)); + } + + var t = namedAttributeValue("'target", l); + if (!isNil(t)) + return t; + return bindingsTarget(scdl.bindings(l)); + } + var turi = targetURI(); + if (isNil(turi)) + return turi; + return car(tokens(turi)); +}; + +/** + * Returns a list of properties in a component. + */ +scdl.properties = function(l) { + return namedElementChildren("'property", l); +}; + +/** + * Returns the value of a property. + */ +scdl.propertyValue = function(l) { + return elementValue(l); +}; + +/** + * Convert a list of elements to a name -> element assoc list. + */ +scdl.nameToElementAssoc = function(l) { + if (isNil(l)) + return l; + return cons(mklist(scdl.name(car(l)), car(l)), scdl.nameToElementAssoc(cdr(l))); +}; + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/ui.css b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/ui.css new file mode 100644 index 0000000000..d1413018a0 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/ui.css @@ -0,0 +1,121 @@ +/* + * 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. + */ + +body { +white-space: margin: 0px; +font-family: arial,sans-serif; font-style: normal; font-variant: normal; font-size: 13px; +} + +table { +border: 1px; border-collapse: separate; +font-family: arial,sans-serif; font-style: normal; font-variant: normal; font-size: 13px; +} + +th { +font-weight: bold; background-color: #e5ecf9; color: #598edd; +text-align: left; padding-left: 2px; padding-right: 8px; padding-top: 2px; padding-bottom: 2px; vertical-align: text-top; +border-top: 1px; border-bottom: 1px; border-left: 0px; border-right: 0px; +border-style: solid; border-top-color: #a2bae7; border-bottom-color: #d1d3d4; +} + +td { +padding-left: 2px; padding-top: 2px; padding-right: 8px; vertical-align: text-top; +} + +iframe { +visibility: hidden; width: 0px; height: 0px; +} + +input { +vertical-align: middle; +-webkit-text-size-adjust: 140%; +} + +a:link { +color: blue; +} + +a:visited { +color: blue; +} + +.tdw { +padding-left: 2px; padding-top: 2px; padding-right: 8px; white-space: normal; vertical-align: text-top; +} + +.hd1 { +font-size: 150%; font-weight: bold; +} + +.hd2 { +font-weight: bold; +} + +.imgbutton { +width: 142px; height: 64px; margin-left: 20px; margin-right: 20px; padding: 0px; border: 1px; +cursor: pointer; cursor: hand; +} + +.tbar { +margin: 0px; +padding-top: 0px; padding-left: 0px; padding-right: 0px; padding-bottom: 3px; +border-bottom: 1px solid #a2bae7; +} + +.ltbar { +padding-left: 0px; padding-top: 0px; padding-right: 8px; white-space: nowrap; vertical-align: top; +} + +.rtbar { +padding-left: 8px; padding-right: 0px; padding-top: 0px; white-space: nowrap; vertical-align: top; +text-align: right; +} + +.suggest { +background-color: #e5ecf9; color: #598edd; +border-top: 1px; border-bottom: 1px; border-left: 1px; border-right: 1px; +border-style: solid; border-top-color: #a2bae7; border-bottom-color: #d1d3d4; +border-left-color: #d1d3d4; border-right-color: #d1d3d4; +position: absolute; +overflow: auto; overflow-x: hidden; +cursor: default; +padding: 0px; margin: 0px; +} + +.suggestTable { +border: 0px; border-collapse: separate; +padding-left: 5px; padding-right: 5px; padding-top: 2px; padding-bottom: 2px; +margin: 0px; +} + +.suggestItem { +padding-left: 2px; padding-top: 0px; padding-bottom: 0px; padding-right: 2px; vertical-align: text-top; +background-color: #e5ecf9; color: #598edd; +} + +.suggestHilighted { +padding-left: 2px; padding-top: 0px; padding-bottom: 0px; padding-right: 2px; vertical-align: text-top; +background-color: #598edd; color: #e5ecf9; +} + +v\: * { +behavior:url(#default#VML); +display:inline-block; +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/ui.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/ui.js new file mode 100644 index 0000000000..fcd61571d1 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/ui.js @@ -0,0 +1,233 @@ +/* + * 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. + */ + +/** + * UI utility functions. + */ + +var ui = new Object(); + +/** + * Build a menu bar. + */ +ui.menu = function(name, href) { + function Menu(n, h) { + this.name = n; + this.href = h; + + this.content = function() { + function complete(uri) { + if (uri.match('.*\.html$')) + return uri; + if (uri.match('.*/$')) + return uri + 'index.html'; + return uri + '/index.html'; + } + + if (complete(this.href) != complete(window.top.location.pathname)) + return '<a href="' + this.href + '" target="_parent">' + this.name + '</a>'; + return '<span><b>' + this.name + '</b></span>'; + }; + } + return new Menu(name, href); +}; + +ui.menubar = function(left, right) { + var bar = '<table cellpadding="0" cellspacing="0" width="100%" class=tbar><tr>' + + '<td class=ltbar><table border="0" cellspacing="0" cellpadding="0"><tr>'; + for (i in left) + bar = bar + '<td class=ltbar>' + left[i].content() + '</td>' + + bar = bar + '</tr></table></td>' + + '<td class=rtbar><table border="0" cellpadding="0" cellspacing="0" align="right"><tr>'; + for (i in right) + bar = bar + '<td class=rtbar>' + right[i].content() + '</td>' + + bar = bar + '</tr></table></td></tr></table>'; + return bar; +}; + +/** + * Autocomplete / suggest support for input fields + * To use it declare a 'suggest' function as follows: + * function suggestItems() { + * return new Array('abc', 'def', 'ghi'); + * } + * then hook it to an input field as follows: + * suggest(document.yourForm.yourInputField, suggestItems); + */ +ui.selectSuggestion = function(node, value) { + for (;;) { + node = node.parentNode; + if (node.tagName.toLowerCase() == 'div') + break; + } + node.selectSuggestion(value); +}; + +ui.hilightSuggestion = function(node, over) { + if (over) + node.className = 'suggestHilighted'; + node.className = 'suggestItem'; +}; + +ui.suggest = function(input, suggestFunction) { + input.suggest = suggestFunction; + + input.selectSuggestion = function(value) { + this.hideSuggestDiv(); + this.value = value; + } + + input.hideSuggestDiv = function() { + if (this.suggestDiv != null) { + this.suggestDiv.style.visibility = 'hidden'; + } + } + + input.showSuggestDiv = function() { + if (this.suggestDiv == null) { + this.suggestDiv = document.createElement('div'); + this.suggestDiv.input = this; + this.suggestDiv.className = 'suggest'; + input.parentNode.insertBefore(this.suggestDiv, input); + this.suggestDiv.style.visibility = 'hidden'; + this.suggestDiv.style.zIndex = '99'; + + this.suggestDiv.selectSuggestion = function(value) { + this.input.selectSuggestion(value); + } + } + + var values = this.suggest(); + var items = ''; + for (var i = 0; i < values.length; i++) { + if (values[i].indexOf(this.value) == -1) + continue; + if (items.length == 0) + items += '<table class=suggestTable>'; + items += '<tr><td class="suggestItem" ' + + 'onmouseover="ui.hilightSuggestion(this, true)" onmouseout="ui.hilightSuggestion(this, false)" ' + + 'onmousedown="ui.selectSuggestion(this, \'' + values[i] + '\')">' + values[i] + '</td></tr>'; + } + if (items.length != 0) + items += '</table>'; + this.suggestDiv.innerHTML = items; + + if (items.length != 0) { + var node = input; + var left = 0; + var top = 0; + for (;;) { + left += node.offsetLeft; + top += node.offsetTop; + node = node.offsetParent; + if (node.tagName.toLowerCase() == 'body') + break; + } + this.suggestDiv.style.left = left; + this.suggestDiv.style.top = top + input.offsetHeight; + this.suggestDiv.style.visibility = 'visible'; + } else + this.suggestDiv.style.visibility = 'hidden'; + } + + input.onkeydown = function(event) { + this.showSuggestDiv(); + }; + + input.onkeyup = function(event) { + this.showSuggestDiv(); + }; + + input.onmousedown = function(event) { + this.showSuggestDiv(); + }; + + input.onblur = function(event) { + setTimeout(function() { input.hideSuggestDiv(); }, 50); + }; +}; + +/** + * Return the content document of a window. + */ +ui.content = function(win) { + if (!isNil(win.document)) + return win.document; + if (!isNil(win.contentDocument)) + return win.contentDocument; + return null; +}; + +/** + * Return a child element of a node with the given id. + */ +ui.elementByID = function(node, id) { + for (var i in node.childNodes) { + var child = node.childNodes[i]; + if (child.id == id) + return child; + var gchild = ui.elementByID(child, id); + if (gchild != null) + return gchild; + } + return null; +}; + +/** + * Return the current document, or a child element with the given id. + */ +function $(id) { + if (id == document) { + if (!isNil(document.widget)) + return widget; + return document; + } + return ui.elementByID($(document), id); +}; + +/** + * Initialize a widget. + */ +ui.onloadwidget = function() { + if (isNil(window.parent) || isNil(window.parent.ui) || isNil(window.parent.ui.widgets)) + return true; + var pdoc = ui.content(window.parent); + for (w in window.parent.ui.widgets) { + var ww = ui.elementByID(pdoc, w).contentWindow; + if (ww == window) { + document.widget = ui.elementByID(pdoc, window.parent.ui.widgets[w]); + document.widget.innerHTML = document.body.innerHTML; + return true; + } + } + return true; +}; + +/** + * Load a widget into an element. + */ +ui.widgets = new Array(); + +ui.bindwidget = function(f, el) { + window.ui.widgets[f] = el; + return f; +}; + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/util.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/util.js new file mode 100644 index 0000000000..0f966b180e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/util.js @@ -0,0 +1,208 @@ +/* + * 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. + */ + +/** + * Simple utility functions. + */ + +/** + * Scheme-like lists. + */ +function cons(car, cdr) { + return new Array(car).concat(cdr); +} + +function car(l) { + return l[0]; +} + +function first(l) { + return car(l); +} + +function cdr(l) { + return l.slice(1); +} + +function rest(l) { + return cdr(l); +} + +function cadr(l) { + return car(cdr(l)); +} + +function cddr(l) { + return cdr(cdr(l)); +} + +function caddr(l) { + return car(cddr(l)); +} + +function append(a, b) { + return a.concat(b); +} + +function reverse(l) { + return l.slice(0).reverse(); +} + +function isNil(v) { + if (v == null) + return true; + if ('' + v == 'undefined') + return true; + try { + if (isList(v) && v.length == 0) + return true; + } catch (e) {} + return false; +} + +function isSymbol(v) { + if (typeof v == 'string' && v.slice(0, 1) == "'") + return true; + return false; +} + +function isString(v) { + if (typeof v == 'string') + return true; + return false; +} + +function isList(v) { + try { + if (v.constructor == Array) + return true; + } catch (e) {} + return false; +} + +function isTaggedList(v, t) { + if (isList(v) && !isNil(v) && car(v) == t) + return true; + return false; +} + +function mklist() { + var a = new Array(); + for (i = 0; i < arguments.length; i++) + a[i] = arguments[i]; + return a; +} + +function length(l) { + return l.length; +} + +/** + * Scheme-like associations. + */ +function assoc(k, l) { + if (isNil(l)) + return mklist(); + if (k == car(car(l))) + return car(l); + return assoc(k, cdr(l)); +} + +/** + * Map and filter functions. + */ +function map(f, l) { + if (isNil(l)) + return l; + return cons(f(car(l)), map(f, cdr(l))); +} + +function filter(f, l) { + if (isNil(l)) + return l; + if (f(car(l))) + return cons(car(l), filter(f, cdr(l))); + return filter(f, cdr(l)); +} + +/** + * Split a path into a list of segments. + */ +function tokens(path) { + return filter(function(s) { return length(s) != 0; }, path.split("/")); +} + +/** + * Log a value. + */ +function log(v) { + try { + console.log(v); + } catch (e) {} + return true; +} + +/** + * Dump an object to the debug console. + */ +function debug(o) { + try { + for (f in o) { + try { + console.log(f + '=' + o[f]); + } catch (e) {} + } + } catch (e) {} + return true; +} + +/** + * Write a list of strings. + */ +function writeStrings(l) { + if (isNil(l)) + return ''; + return car(l) + writeStrings(cdr(l)); +} + +/** + * Write a value using a Scheme-like syntax. + */ +function writeValue(v) { + function writePrimitive(p) { + if (isSymbol(p)) + return '' + p.substring(1); + if (isString(p)) + return '"' + p + '"'; + return '' + p; + } + + function writeList(l) { + if (isNil(l)) + return ''; + return ' ' + writeValue(car(l)) + writeList(cdr(l)); + } + + if (!isList(v)) + return writePrimitive(v); + if (isNil(v)) + return '()'; + return '(' + writeValue(car(v)) + writeList(cdr(v)) + ')'; +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/xmlutil.js b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/xmlutil.js new file mode 100644 index 0000000000..1bec45f9b9 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/htdocs/xmlutil.js @@ -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. + */ + +/** + * XML handling functions. + */ + +/** + * Convert a DOM node list to a regular list. + */ +function nodeList(n) { + var l = new Array(); + if (isNil(n)) + return l; + for (var i = 0; i < n.length; i++) + l[i] = n[i]; + return l; +} + +/** + * Return the child attributes of an element. + */ +function childAttributes(e) { + return filter(function(n) { return n.nodeType == 2; }, nodeList(e.attributes)); +} + +/** + * Return the child elements of an element. + */ +function childElements(e) { + return filter(function(n) { return n.nodeType == 1; }, nodeList(e.childNodes)); +} + +/** + * Return the child text nodes of an element. + */ +function childText(e) { + return filter(function(n) { return n.nodeType == 3; }, nodeList(e.childNodes)); +} + +/** + * Read a list of XML attributes. + */ +function readAttributes(a) { + if (isNil(a)) + return a; + return cons(mklist(attribute, "'" + car(a).nodeName, car(a).nodeValue), readAttributes(cdr(a))); +} + +/** + * Read an XML element. + */ +function readElement(e) { + var l = append(append(mklist(element, "'" + e.nodeName), readAttributes(childAttributes(e))), readElements(childElements(e))); + var t = childText(e); + if (isNil(t)) + return l; + return append(l, mklist(car(t).nodeValue)); +} + +/** + * Read a list of XML elements. + */ +function readElements(l) { + if (isNil(l)) + return l; + return cons(readElement(car(l)), readElements(cdr(l))); +} + +/** + * Return true if a list of strings contains an XML document. + */ +function isXML(l) { + if (isNil(l)) + return false; + return car(l).substring(0, 5) == '<?xml'; +} + +/** + * Parse a list of strings representing an XML document. + */ +function parseXML(l) { + var s = writeStrings(l); + if (window.DOMParser) { + var p =new DOMParser(); + return p.parseFromString(s, "text/xml"); + } + var doc; + try { + doc = new ActiveXObject("MSXML2.DOMDocument"); + } catch (e) { + doc = new ActiveXObject("Microsoft.XMLDOM"); + } + doc.async = 'false'; + doc.loadXML(s); + return doc; +} + +/** + * Read a list of values from an XML document. + */ +function readXMLDocument(doc) { + var root = childElements(doc); + if (isNil(root)) + return mklist(); + return mklist(readElement(car(root))); +} + +/** + * Read a list of values from a list of strings representing an XML document. + */ +function readXML(l) { + return readXMLDocument(parseXML(l)); +} + +/** + * Make an XML document. + */ +/** + * Return a list of strings representing an XML document. + */ +function writeXMLDocument(doc) { + if (typeof(XMLSerializer) != 'undefined') + return mklist(new XMLSerializer().serializeToString(doc)); + return mklist(doc.xml); +} + +/** + * Write a list of XML element and attribute tokens. + */ +function expandElementValues(n, l) { + if (isNil(l)) + return l; + return cons(cons(element, cons(n, car(l))), expandElementValues(n, cdr(l))); +} + +function writeList(l, node, doc) { + if (isNil(l)) + return node; + var token = car(l); + if (isTaggedList(token, attribute)) { + node.setAttribute(attributeName(token).substring(1), '' + attributeValue(token)); + } else if (isTaggedList(token, element)) { + if (elementHasValue(token)) { + var v = elementValue(token); + if (isList(v)) { + var e = expandElementValues(elementName(token), v); + writeList(e, node, doc); + } else { + var child = doc.createElement(elementName(token).substring(1)); + writeList(elementChildren(token), child, doc); + node.appendChild(child); + } + } else { + var child = doc.createElement(elementName(token).substring(1)); + writeList(elementChildren(token), child, doc); + node.appendChild(child); + } + } else + node.appendChild(doc.createTextNode('' + token)); + writeList(cdr(l), node, doc); + return node; +} + +/** + * Convert a list of values to a list of strings representing an XML document. + */ +function writeXML(l, xmlTag) { + function mkdoc() { + if (document.implementation && document.implementation.createDocument) + return document.implementation.createDocument('', '', null); + return new ActiveXObject("MSXML2.DOMDocument"); + } + + var doc = mkdoc(); + writeList(l, doc, doc); + if (!xmlTag) + return writeXMLDocument(doc); + return mklist('<?xml version="1.0" encoding="UTF-8"?>\n' + writeXMLDocument(doc) + '\n'); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/js/js-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/js/js-test.cpp new file mode 100644 index 0000000000..9cbf000ac3 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/js/js-test.cpp @@ -0,0 +1,52 @@ +/* + * 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 <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace js { + +bool testJSEval() { + failable<value> 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::cout << "Testing..." << tuscany::endl; + + tuscany::js::testJSEval(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/json/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/json/Makefile.am new file mode 100644 index 0000000000..7b5b3878db --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/json/Makefile.am @@ -0,0 +1,25 @@ +# 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/json + +json_test_SOURCES = json-test.cpp +json_test_LDFLAGS = -lmozjs + +noinst_PROGRAMS = json-test +TESTS = json-test diff --git a/sandbox/sebastien/cpp/apr-2/modules/json/json-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/json/json-test.cpp new file mode 100644 index 0000000000..6666b3f479 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/json/json-test.cpp @@ -0,0 +1,165 @@ +/* + * 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 <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "json.hpp" + +namespace tuscany { +namespace json { + +ostream* jsonWriter(const string& s, ostream* os) { + (*os) << s; + return os; +} + +bool testJSON() { + const js::JSContext cx; + + { + const list<value> ad = mklist<value>(mklist<value>(attribute, "city", string("san francisco")), mklist<value>(attribute, "state", string("ca"))); + const list<value> ac = mklist<value>(mklist<value>(element, "id", string("1234")), mklist<value>(attribute, "balance", 1000)); + const list<value> cr = mklist<value>(mklist<value> (attribute, "name", string("jdoe")), cons<value>(element, cons<value>("address", ad)), cons<value>(element, cons<value>("account", ac))); + const list<value> c = mklist<value>(cons<value>(element, cons<value>("customer", cr))); + + ostringstream os; + writeJSON<ostream*>(jsonWriter, &os, c, cx); + assert(str(os) == "{\"customer\":{\"@name\":\"jdoe\",\"address\":{\"@city\":\"san francisco\",\"@state\":\"ca\"},\"account\":{\"id\":\"1234\",\"@balance\":1000}}}"); + } + { + const list<value> phones = mklist<value> (string("408-1234"), string("650-1234")); + const list<value> l = mklist<value> (mklist<value> (element, "phones", phones), mklist<value> (element, "lastName", string("test\ttab")), mklist<value> (attribute, "firstName", string("test1"))); + + ostringstream os; + writeJSON<ostream*>(jsonWriter, &os, l, cx); + assert(str(os) == "{\"phones\":[\"408-1234\",\"650-1234\"],\"lastName\":\"test\\u0009tab\",\"@firstName\":\"test1\"}"); + + istringstream is(str(os)); + const list<string> il = streamList(is); + const list<value> r = content(readJSON(il, cx)); + assert(r == l); + + ostringstream wos; + write(content(writeJSON(r, cx)), wos); + assert(str(wos) == str(os)); + } + { + const list<value> l = mklist<value>(list<value>() + "ns1:echoString" + (list<value>() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (list<value>() + "text" + string("Hello World!"))); + ostringstream wos; + write(content(writeJSON(valuesToElements(l), cx)), wos); + assert(str(wos) == "{\"ns1:echoString\":{\"@xmlns:ns1\":\"http://ws.apache.org/axis2/services/echo\",\"text\":\"Hello World!\"}}"); + + istringstream is(str(wos)); + const list<string> il = streamList(is); + const list<value> r = elementsToValues(content(readJSON(il, cx))); + assert(r == l); + } + return true; +} + +bool testJSONRPC() { + js::JSContext cx; + { + const string lm("{\"id\": 1, \"method\": \"test\", \"params\": []}"); + const list<value> e = content(readJSON(mklist(lm), cx)); + const list<value> v = elementsToValues(e); + assert(assoc<value>("id", v) == mklist<value>("id", 1)); + assert(assoc<value>("method", v) == mklist<value>("method", string("test"))); + assert(assoc<value>("params", v) == mklist<value>("params", list<value>())); + } + { + const string i("{\"id\":3,\"result\":[{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"},{\"price\":\"$1.55\",\"name\":\"Pear\"}]}"); + const list<value> e = content(readJSON(mklist(i), cx)); + 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<value> e2 = content(readJSON(mklist(i), cx)); + assert(e == e2); + } + { + const string i("{\"id\":3,\"result\":[{\"price\":\"$2.99\",\"name\":\"Apple\"},{\"price\":\"$3.55\",\"name\":\"Orange\"},{\"price\":\"$1.55\",\"name\":\"Pear\"}]}"); + const list<value> e = content(readJSON(mklist(i), cx)); + ostringstream os; + write(content(writeJSON(e, cx)), os); + assert(str(os) == i); + const list<value> v = elementsToValues(e); + const list<value> r = valuesToElements(v); + assert(r == e); + } + { + const list<value> r = mklist<value>(mklist<value>("id", 1), mklist<value>("result", mklist<value>(string("Service.get"), string("Service.getTotal")))); + const list<value> e = valuesToElements(r); + ostringstream os; + write(content(writeJSON(e, cx)), os); + assert(str(os) == "{\"id\":1,\"result\":[\"Service.get\",\"Service.getTotal\"]}"); + } + { + const string f("{\"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 list<value> r = content(readJSON(mklist(f), cx)); + const list<value> v = elementsToValues(r); + const list<value> e = valuesToElements(v); + ostringstream os; + write(content(writeJSON(e, cx)), os); + assert(str(os) == f); + } + { + const list<value> arg = mklist<value>(list<value>() + "ns1:echoString" + (list<value>() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/services/echo")) + (list<value>() + "text" + string("Hello World!"))); + const failable<list<string> > r = jsonRequest(1, "echo", mklist<value>(arg), cx); + ostringstream os; + write(content(r), os); + assert(str(os) == "{\"id\":1,\"method\":\"echo\",\"params\":[{\"ns1:echoString\":{\"@xmlns:ns1\":\"http://ws.apache.org/axis2/services/echo\",\"text\":\"Hello World!\"}}]}"); + + istringstream is(str(os)); + const list<string> il = streamList(is); + const list<value> ir = elementsToValues(content(readJSON(il, cx))); + assert(car<value>(cadr<value>(caddr<value>(ir))) == arg); + } + { + const list<value> res = mklist<value>(list<value>() + "ns1:echoString" + (list<value>() + "@xmlns:ns1" + string("http://ws.apache.org/axis2/c/samples")) + (list<value>() + "text" + string("Hello World!"))); + const failable<list<string> > r = jsonResult(1, res, cx); + ostringstream os; + write(content(r), os); + assert(str(os) == "{\"id\":1,\"result\":{\"ns1:echoString\":{\"@xmlns:ns1\":\"http://ws.apache.org/axis2/c/samples\",\"text\":\"Hello World!\"}}}"); + + istringstream is(str(os)); + const list<string> il = streamList(is); + const list<value> ir = elementsToValues(content(readJSON(il, cx))); + assert(cdr<value>(cadr<value>(ir)) == res); + } + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::json::testJSON(); + tuscany::json::testJSONRPC(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/json/json.hpp b/sandbox/sebastien/cpp/apr-2/modules/json/json.hpp new file mode 100644 index 0000000000..df82fddbb5 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/json/json.hpp @@ -0,0 +1,194 @@ +/* + * 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<string>& 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<bool> consume(JSONParser* parser, const list<string>& 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_GetStringChars(jstr), (uint32)JS_GetStringLength(jstr))) + return mkfailure<bool>("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<list<value> > readJSON(const list<string>& ilist, const js::JSContext& cx) { + jsval val; + JSONParser* parser = JS_BeginJSONParse(cx, &val); + if(parser == NULL) + return mkfailure<list<value> >("JS_BeginJSONParse failed"); + + const failable<bool> consumed = consume(parser, ilist, cx); + + if(!JS_FinishJSONParse(cx, parser, JSVAL_NULL)) + return mkfailure<list<value> >("JS_FinishJSONParse failed"); + if(!hasContent(consumed)) + return mkfailure<list<value> >(reason(consumed)); + + return list<value>(js::jsValToValue(val, cx)); +} + +/** + * Context passed to the JSON write callback function. + */ +template<typename R> class WriteContext { +public: + WriteContext(const lambda<R(const string&, const R)>& reduce, const R& accum, const js::JSContext& cx) : cx(cx), reduce(reduce), accum(accum) { + } + const js::JSContext& cx; + const lambda<R(const string&, const R)> reduce; + R accum; +}; + +/** + * Called by JS_Stringify to write JSON out. + */ +template<typename R> JSBool writeCallback(const jschar *buf, uint32 len, void *data) { + WriteContext<R>& wcx = *(static_cast<WriteContext<R>*> (data)); + JSString* jstr = JS_NewUCStringCopyN(wcx.cx, buf, len); + wcx.accum = wcx.reduce(string(JS_GetStringBytes(jstr), JS_GetStringLength(jstr)), wcx.accum); + return JS_TRUE; +} + +/** + * Convert a list of values to a JSON document. + */ +template<typename R> const failable<R> writeJSON(const lambda<R(const string&, const R)>& reduce, const R& initial, const list<value>& 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<R> wcx(reduce, initial, cx); + if (!JS_Stringify(cx, &val, NULL, JSVAL_NULL, writeCallback<R>, &wcx)) + return mkfailure<R>("JS_Stringify failed"); + return wcx.accum; +} + +/** + * Convert a list of values to a list of strings representing a JSON document. + */ +const failable<list<string> > writeJSON(const list<value>& l, const js::JSContext& cx) { + const failable<list<string> > ls = writeJSON<list<string>>(rcons<string>, list<string>(), l, cx); + if (!hasContent(ls)) + return ls; + return reverse(list<string>(content(ls))); +} + +/** + * Convert a list of function + params to a JSON-RPC request. + */ +const failable<list<string> > jsonRequest(const value& id, const value& func, const value& params, js::JSContext& cx) { + const list<value> r = mklist<value>(mklist<value>("id", id), mklist<value>("method", string(func)), mklist<value>("params", params)); + return writeJSON(valuesToElements(r), cx); +} + +/** + * Convert a value to a JSON-RPC result. + */ +const failable<list<string> > jsonResult(const value& id, const value& val, js::JSContext& cx) { + return writeJSON(valuesToElements(mklist<value>(mklist<value>("id", id), mklist<value>("result", val))), cx); +} + +/** + * Convert a JSON-RPC result to a value. + */ +const failable<value> jsonResultValue(const list<string>& s, js::JSContext& cx) { + const failable<list<value> > jsres = json::readJSON(s, cx); + if (!hasContent(jsres)) + return mkfailure<value>(reason(jsres)); + const list<value> rval(cadr<value>(elementsToValues(content(jsres)))); + const value val = cadr(rval); + if (isList(val) && !js::isJSArray(val)) + return value(mklist<value>(val)); + return val; +} + +/** + * Convert a JSON payload to a list of values. + */ +const list<value> jsonValues(const list<value>& 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<value> queryParams(const list<list<value> >& a) { + if (isNil(a)) + return list<value>(); + const list<value> 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 */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/oauth/Makefile.am new file mode 100644 index 0000000000..6c0cd2bc57 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/Makefile.am @@ -0,0 +1,42 @@ +# 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_OAUTH + +INCLUDES = -I${HTTPD_INCLUDE} -I${LIBOAUTH_INCLUDE} + +dist_mod_SCRIPTS = oauth-conf oauth-memcached-conf oauth1-appkey-conf oauth2-appkey-conf +moddir=$(prefix)/modules/oauth + +mod_LTLIBRARIES = libmod_tuscany_oauth1.la libmod_tuscany_oauth2.la +noinst_DATA = libmod_tuscany_oauth1.so libmod_tuscany_oauth2.so + +libmod_tuscany_oauth1_la_SOURCES = mod-oauth1.cpp +libmod_tuscany_oauth1_la_LDFLAGS = -L${LIBOAUTH_LIB} -R${LIBOAUTH_LIB} -loauth -lxml2 -lcurl -lmozjs +libmod_tuscany_oauth1.so: + ln -s .libs/libmod_tuscany_oauth1.so + +libmod_tuscany_oauth2_la_SOURCES = mod-oauth2.cpp +libmod_tuscany_oauth2_la_LDFLAGS = -lxml2 -lcurl -lmozjs +libmod_tuscany_oauth2.so: + ln -s .libs/libmod_tuscany_oauth2.so + +EXTRA_DIST = oauth.composite user-info.scm htdocs/index.html htdocs/login/index.html htdocs/logout/index.html htdocs/public/index.html + +dist_noinst_SCRIPTS = start-test stop-test + +endif diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/index.html b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/index.html new file mode 100644 index 0000000000..7d26567214 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/index.html @@ -0,0 +1,58 @@ +<!-- + 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. +--> + +<html> +<head> +<script type="text/javascript" src="/component.js"></script> +<script type="text/javascript"> +var protected = sca.component("Protected"); +var userInfo = sca.defun(sca.reference(protected, "userInfo"), "getuser", "getemail", "getnickname", "getfullname", "getfirstname", "getlastname", "getrealm"); +var user = userInfo.getuser(); +var email = userInfo.apply("getemail"); +var nickname = userInfo.apply("getnickname"); +var fullname = userInfo.apply("getfullname"); +var firstname = userInfo.apply("getfirstname"); +var lastname = userInfo.apply("getlastname"); +var realm = userInfo.apply("getrealm"); +</script> +</head> +<body> +<h1>Protected area - It works!</h1> +<p>The following info is returned by a JSONRPC service:</p> +<div>User: <span id="user"></span></div> +<div>Email: <span id="email"></span></div> +<div>Nickname: <span id="nickname"></span></div> +<div>Fullname: <span id="fullname"></span></div> +<div>Firstname: <span id="firstname"></span></div> +<div>Lastname: <span id="lastname"></span></div> +<div>Realm: <span id="realm"></span></div> +<script type="text/javascript"> +document.getElementById('user').innerHTML=user; +document.getElementById('email').innerHTML=email; +document.getElementById('nickname').innerHTML=nickname; +document.getElementById('fullname').innerHTML=fullname; +document.getElementById('firstname').innerHTML=firstname; +document.getElementById('lastname').innerHTML=lastname; +document.getElementById('realm').innerHTML=realm; +</script> +<p><a href="info">User info</a></p> +<p><a href="login">Sign in</a></p> +<p><a href="logout">Sign out</a></p> +<p><a href="public">Public area</a></p> +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/login/index.html b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/login/index.html new file mode 100644 index 0000000000..c41c334b76 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/login/index.html @@ -0,0 +1,116 @@ +<!-- + 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. +--> + +<html><body><h1>Sign in with an OAuth provider</h1> + +<script type="text/javascript"> +function queryParams() { + qp = new Array(); + qs = window.location.search.substring(1).split('&'); + for (i = 0; i < qs.length; i++) { + e = qs[i].indexOf('='); + if (e > 0) + qp[qs[i].substring(0, e)] = unescape(qs[i].substring(e + 1)); + } + return qp; +} + +function oauthReferrer() { + r = queryParams()['openauth_referrer']; + if (typeof(r) == 'undefined') + return r; + q = r.indexOf('?'); + if (q > 0) + return r.substring(0, q); + return r; +} + +if (typeof(oauthReferrer()) == 'undefined') { + document.location = '/'; +} + +function submitSignin2(w) { + parms = w(); + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.signin2.mod_oauth2_authorize.value = parms[0]; + document.signin2.mod_oauth2_access_token.value = parms[1]; + document.signin2.mod_oauth2_client_id.value = parms[2]; + document.signin2.mod_oauth2_info.value = parms[3]; + document.signin2.action = oauthReferrer(); + document.signin2.submit(); +} + +function withFacebook() { + var parms = ['https://graph.facebook.com/oauth/authorize', 'https://graph.facebook.com/oauth/access_token', 'facebook.com', 'https://graph.facebook.com/me']; + return parms; +} + +function withGithub() { + var parms = ['https://github.com/login/oauth/authorize', 'https://github.com/login/oauth/access_token', 'github.com', 'https://github.com/api/v2/json/user/show']; + return parms; +} + +function submitSignin1(w) { + parms = w(); + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.signin1.mod_oauth1_request_token.value = parms[0]; + document.signin1.mod_oauth1_authorize.value = parms[1]; + document.signin1.mod_oauth1_access_token.value = parms[2]; + document.signin1.mod_oauth1_client_id.value = parms[3]; + document.signin1.mod_oauth1_info.value = parms[4]; + document.signin1.action = oauthReferrer(); + document.signin1.submit(); +} + +function withLinkedin() { + var parms = ['https://api.linkedin.com/uas/oauth/requestToken', 'https://www.linkedin.com/uas/oauth/authorize', 'https://api.linkedin.com/uas/oauth/accessToken', 'linkedin.com', 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,public-profile-url)']; + return parms; +} + +function withTwitter() { + var parms = ['https://api.twitter.com/oauth/request_token', 'https://api.twitter.com/oauth/authorize', 'https://api.twitter.com/oauth/access_token', 'twitter.com', 'https://api.twitter.com/1/statuses/user_timeline.json']; + return parms; +} +</script> + +<form name="fields"> +<p>Sign in with your Facebook account<br/><input type="button" onclick="submitSignin2(withFacebook)" value="Sign in"/></p> +<p>Sign in with your Github account<br/><input type="button" onclick="submitSignin2(withGithub)" value="Sign in"/></p> +<p>Sign in with your Linkedin account<br/><input type="button" onclick="submitSignin1(withLinkedin)" value="Sign in"/></p> +<p>Sign in with your Twitter account<br/><input type="button" onclick="submitSignin1(withTwitter)" value="Sign in"/></p> +</form> + +<form name="signin2" action="/" method="GET"> +<input type="hidden" name="mod_oauth2_authorize" value=""/> +<input type="hidden" name="mod_oauth2_access_token" value=""/> +<input type="hidden" name="mod_oauth2_client_id" value=""/> +<input type="hidden" name="mod_oauth2_info" value=""/> +<input type="hidden" name="mod_oauth2_step" value="authorize"/> +</form> + +<form name="signin1" action="/" method="GET"> +<input type="hidden" name="mod_oauth1_request_token" value=""/> +<input type="hidden" name="mod_oauth1_authorize" value=""/> +<input type="hidden" name="mod_oauth1_access_token" value=""/> +<input type="hidden" name="mod_oauth1_client_id" value=""/> +<input type="hidden" name="mod_oauth1_info" value=""/> +<input type="hidden" name="mod_oauth1_step" value="authorize"/> +</form> + +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/login/mixed.html b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/login/mixed.html new file mode 100644 index 0000000000..54673e01ee --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/login/mixed.html @@ -0,0 +1,211 @@ +<!-- + 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. +--> + +<html><body><h1>Sign in with a Form, an OpenID provider or an OAuth provider</h1> + +<script type="text/javascript"> +function submitFormSignin() { + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.formSignin.httpd_location.value = '/'; + document.formSignin.submit(); +} + +function queryParams() { + qp = new Array(); + qs = window.location.search.substring(1).split('&'); + for (i = 0; i < qs.length; i++) { + e = qs[i].indexOf('='); + if (e > 0) + qp[qs[i].substring(0, e)] = unescape(qs[i].substring(e + 1)); + } + return qp; +} + +function openauthReferrer() { + r = queryParams()['openauth_referrer']; + if (typeof(r) == 'undefined') + return r; + q = r.indexOf('?'); + if (q > 0) + return r.substring(0, q); + return r; +} + +if (typeof(openauthReferrer()) == 'undefined') { + document.location = '/'; +} + +function submitOpenIDSignin(w) { + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.openIDSignin.openid_identifier.value = w(); + document.openIDSignin.action = openauthReferrer(); + document.openIDSignin.submit(); +} + +function withGoogle() { + return 'https://www.google.com/accounts/o8/id'; +} + +function withYahoo() { + return 'https://me.yahoo.com/'; +} + +function withMyOpenID() { + return 'http://www.myopenid.com/xrds'; +} + +function withVerisign() { + return 'https://pip.verisignlabs.com/'; +} + +function withMySpace() { + return 'https://api.myspace.com/openid'; +} + +function withGoogleApps() { + return 'https://www.google.com/accounts/o8/site-xrds?ns=2&hd=' + document.fields.domain.value; +} + +function withLivejournal() { + return 'http://' + document.fields.ljuser.value + '.livejournal.com'; +} + +function withBlogspot() { + return 'http://' + document.fields.bsuser.value + '.blogspot.com'; +} + +function withBlogger() { + return 'http://' + document.fields.bguser.value + '.blogger.com'; +} + +function withXRDSEndpoint() { + return document.fields.endpoint.value; +} + +function submitOAuth2Signin(w) { + parms = w(); + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.oauth2Signin.mod_oauth2_authorize.value = parms[0]; + document.oauth2Signin.mod_oauth2_access_token.value = parms[1]; + document.oauth2Signin.mod_oauth2_client_id.value = parms[2]; + document.oauth2Signin.mod_oauth2_info.value = parms[3]; + document.oauth2Signin.action = openauthReferrer(); + document.oauth2Signin.submit(); +} + +function withFacebook() { + var parms = ['https://graph.facebook.com/oauth/authorize', 'https://graph.facebook.com/oauth/access_token', 'facebook.com', 'https://graph.facebook.com/me']; + return parms; +} + +function withGithub() { + var parms = ['https://github.com/login/oauth/authorize', 'https://github.com/login/oauth/access_token', 'github.com', 'https://github.com/api/v2/json/user/show']; + return parms; +} + +function submitOAuth1Signin(w) { + parms = w(); + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.oauth1Signin.mod_oauth1_request_token.value = parms[0]; + document.oauth1Signin.mod_oauth1_authorize.value = parms[1]; + document.oauth1Signin.mod_oauth1_access_token.value = parms[2]; + document.oauth1Signin.mod_oauth1_client_id.value = parms[3]; + document.oauth1Signin.mod_oauth1_info.value = parms[4]; + document.oauth1Signin.action = openauthReferrer(); + document.oauth1Signin.submit(); +} + +function withLinkedin() { + var parms = ['https://api.linkedin.com/uas/oauth/requestToken', 'https://www.linkedin.com/uas/oauth/authorize', 'https://api.linkedin.com/uas/oauth/accessToken', 'linkedin.com', 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,public-profile-url)']; + return parms; +} + +function withTwitter() { + var parms = ['https://api.twitter.com/oauth/request_token', 'https://api.twitter.com/oauth/authorize', 'https://api.twitter.com/oauth/access_token', 'twitter.com', 'https://api.twitter.com/1/statuses/user_timeline.json']; + return parms; +} +</script> + +<form name="formSignin" method="POST" action="/login/dologin"> +<p>Sign in with your user id and password<br/> +<table border="0"> +<tr><td>Username:</td><td><input type="text" name="httpd_username" value=""/></td></tr> +<tr><td>Password:</td><td><input type="password" name="httpd_password" value=""/></td></tr> +<tr><td><input type="button" onclick="submitFormSignin()" value="Sign in"/></td><td></td></tr> +</table> +</p> +<input type="hidden" name="httpd_location" value="/"/> +</form> + +<form name="fields"> +<p>Sign in with your Google account<br/><input type="button" onclick="submitOpenIDSignin(withGoogle)" value="Sign in"/></p> +<p>Sign in with your Yahoo account<br/><input type="button" onclick="submitOpenIDSignin(withYahoo)" value="Sign in"/></p> +<p>Sign in with your MyOpenID account<br/><input type="button" onclick="submitOpenIDSignin(withMyOpenID)" value="Sign in"/></p> +<p>Sign in with your Verisign account<br/><input type="button" onclick="submitOpenIDSignin(withVerisign)" value="Sign in"/></p> +<p>Sign in with your MySpace account<br/><input type="button" onclick="submitOpenIDSignin(withMySpace)" value="Sign in"/></p> + +<p>Sign in with a Google apps domain<br/> +<input type="text" size="20" name="domain" value="example.com"/><br/> +<input type="button" onclick="submitOpenIDSignin(withGoogleApps)" value="Sign in"/></p> + +<p>Sign in with your Livejournal account<br/> +<input type="text" size="10" name="ljuser" value=""/><br/> +<input type="button" onclick="submitOpenIDSignin(withLivejournal)" value="Sign in"/></p> + +<p>Sign in with your Blogspot account<br/> +<input type="text" size="10" name="bsuser" value=""/><br/> +<input type="button" onclick="submitOpenIDSignin(withBlogspot)" value="Sign in"/></p> + +<p>Sign in with your Blogger account<br/> +<input type="text" size="10" name="bguser" value=""/><br/> +<input type="button" onclick="submitOpenIDSignin(withBlogger)" value="Sign in"/></p> + +<p>Sign in with an OpenID endpoint<br/> +<input type="text" size="50" name="endpoint" value="https://www.google.com/accounts/o8/id"/><br/> +<input type="button" onclick="submitOpenIDSignin(withXRDSEndpoint)" value="Sign in"/></p> + +<p>Sign in with your Facebook account<br/><input type="button" onclick="submitOAuth2Signin(withFacebook)" value="Sign in"/></p> +<p>Sign in with your Github account<br/><input type="button" onclick="submitOAuth2Signin(withGithub)" value="Sign in"/></p> + +<p>Sign in with your Linkedin account<br/><input type="button" onclick="submitOAuth1Signin(withLinkedin)" value="Sign in"/></p> +<p>Sign in with your Twitter account<br/><input type="button" onclick="submitOAuth1Signin(withTwitter)" value="Sign in"/></p> +</form> + +<form name="openIDSignin" action="/" method="GET"> +<input type="hidden" name="openid_identifier" value=""/> +</form> + +<form name="oauth2Signin" action="/" method="GET"> +<input type="hidden" name="mod_oauth2_authorize" value=""/> +<input type="hidden" name="mod_oauth2_access_token" value=""/> +<input type="hidden" name="mod_oauth2_client_id" value=""/> +<input type="hidden" name="mod_oauth2_info" value=""/> +<input type="hidden" name="mod_oauth2_step" value="authorize"/> +</form> + +<form name="oauth1Signin" action="/" method="GET"> +<input type="hidden" name="mod_oauth1_request_token" value=""/> +<input type="hidden" name="mod_oauth1_authorize" value=""/> +<input type="hidden" name="mod_oauth1_access_token" value=""/> +<input type="hidden" name="mod_oauth1_client_id" value=""/> +<input type="hidden" name="mod_oauth1_info" value=""/> +<input type="hidden" name="mod_oauth1_step" value="authorize"/> +</form> + +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/logout/index.html b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/logout/index.html new file mode 100644 index 0000000000..02a92d1b31 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/logout/index.html @@ -0,0 +1,33 @@ +<!-- + 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. +--> + +<html><body> +<h1>Sign out</h1> + +<form name="signout" action="/login" method="GET"> +<script type="text/javascript"> +function submitSignout() { + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.signout.submit(); + return true; +} +</script> +<input type="button" onclick="submitSignout()" value="Sign out"/> +</form> +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/public/index.html b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/public/index.html new file mode 100644 index 0000000000..af2cd7ca19 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/htdocs/public/index.html @@ -0,0 +1,27 @@ +<!-- + 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. +--> + +<html> +<body> +<h1>Unprotected area - It works!</h1> +<p><a href="/info">User info</a></p> +<p><a href="/login">Sign in</a></p> +<p><a href="/logout">Sign out</a></p> +<p><a href="/">Protected area</a></p> +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/mod-oauth1.cpp b/sandbox/sebastien/cpp/apr-2/modules/oauth/mod-oauth1.cpp new file mode 100644 index 0000000000..0f190127db --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/mod-oauth1.cpp @@ -0,0 +1,580 @@ +/* + * 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$ */ + +/** + * HTTPD module for OAuth 1.0 authentication. + */ + +#include <stdlib.h> +#include <sys/stat.h> + +extern "C" { +#include <oauth.h> +} + +#include "string.hpp" +#include "stream.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "../json/json.hpp" +#include "../http/httpd.hpp" +#include "../http/http.hpp" +#include "../http/openauth.hpp" +#include "../../components/cache/memcache.hpp" + +extern "C" { +extern module AP_MODULE_DECLARE_DATA mod_tuscany_oauth1; +} + +namespace tuscany { +namespace oauth1 { + +/** + * Server configuration. + */ +class ServerConf { +public: + ServerConf(apr_pool_t* p, server_rec* s) : p(p), server(s) { + } + + const gc_pool p; + server_rec* server; + string ca; + string cert; + string key; + list<list<value> > appkeys; + list<string> mcaddrs; + memcache::MemCached mc; + http::CURLSession cs; +}; + +/** + * Directory configuration. + */ +class DirConf { +public: + DirConf(apr_pool_t* p, char* d) : p(p), dir(d), enabled(false), login("") { + } + + const gc_pool p; + const char* dir; + bool enabled; + string login; +}; + +/** + * Return the user info for a session. + */ +const failable<value> userInfo(const value& sid, const memcache::MemCached& mc) { + return memcache::get(mklist<value>("tuscanyOpenAuth", sid), mc); +} + +/** + * Handle an authenticated request. + */ +const failable<int> authenticated(const list<list<value> >& info, request_rec* r) { + debug(info, "modoauth1::authenticated::info"); + + // Store user info in the request + const list<value> realm = assoc<value>("realm", info); + if (isNil(realm) || isNil(cdr(realm))) + return mkfailure<int>("Couldn't retrieve realm"); + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "REALM"), apr_pstrdup(r->pool, c_str(cadr(realm)))); + + const list<value> id = assoc<value>("id", info); + if (isNil(id) || isNil(cdr(id))) + return mkfailure<int>("Couldn't retrieve user id"); + r->user = apr_pstrdup(r->pool, c_str(cadr(id))); + + const list<value> email = assoc<value>("email", info); + if (!isNil(email) && !isNil(cdr(email))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "EMAIL"), apr_pstrdup(r->pool, c_str(cadr(email)))); + + const list<value> screenname = assoc<value>("screen_name", info); + if (!isNil(screenname) && !isNil(cdr(screenname))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "NICKNAME"), apr_pstrdup(r->pool, c_str(cadr(screenname)))); + + const list<value> name = assoc<value>("name", info); + if (!isNil(name) && !isNil(cdr(name))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "FULLNAME"), apr_pstrdup(r->pool, c_str(cadr(name)))); + + const list<value> firstname = assoc<value>("first-name", info); + if (!isNil(firstname) && !isNil(cdr(firstname))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "FIRSTNAME"), apr_pstrdup(r->pool, c_str(cadr(firstname)))); + + const list<value> lastname = assoc<value>("last-name", info); + if (!isNil(lastname) && !isNil(cdr(lastname))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "LASTNAME"), apr_pstrdup(r->pool, c_str(cadr(lastname)))); + return OK; +} + +/** + * Convert a query string containing oauth args to an authorization header. + */ +const string header(const string& qs, const string& redir, const string& verif) { + const list<list<value> > args = httpd::queryArgs(qs); + ostringstream hdr; + hdr << "Authorization: OAuth " + << "oauth_nonce=\"" << string(cadr(assoc<value>("oauth_nonce", args))) << "\", "; + + if (length(redir) != 0) + hdr << "oauth_callback=\"" << httpd::escape(redir) << "\", "; + + hdr << "oauth_signature_method=\"" << string(cadr(assoc<value>("oauth_signature_method", args))) << "\", " + << "oauth_timestamp=\"" << string(cadr(assoc<value>("oauth_timestamp", args))) << "\", " + << "oauth_consumer_key=\"" << string(cadr(assoc<value>("oauth_consumer_key", args))) << "\", "; + + const list<value> atok = assoc<value>("oauth_token", args); + if (!isNil(atok) && !isNil(cdr(atok))) + hdr << "oauth_token=\"" << string(cadr(atok)) << "\", "; + + if (length(verif) != 0) + hdr << "oauth_verifier=\"" << verif << "\", "; + + hdr << "oauth_signature=\"" << string(cadr(assoc<value>("oauth_signature", args))) << "\", " + << "oauth_version=\"" << string(cadr(assoc<value>("oauth_version", args))) << "\""; + debug(str(hdr), "modoauth1::authheader"); + return str(hdr); +} + + +/** + * Sign a request. + */ +const list<string> sign(const string& verb, const string& uri, const list<value> appkey, const string& tok, const string& sec) { + char* qs = NULL; + char* suri = oauth_sign_url2(c_str(uri), &qs, OA_HMAC, c_str(verb), c_str(car(appkey)), c_str(cadr(appkey)), length(tok) != 0? c_str(tok) : NULL, length(sec) != 0? c_str(sec) : NULL); + const list<string> res = mklist<string>(suri, qs); + free(suri); + free(qs); + return res; +} + +/** + * Handle an authorize request. + */ +const failable<int> authorize(const list<list<value> >& args, request_rec* r, const ServerConf& sc) { + // Extract authorize, access_token, client ID and info URIs + const list<value> req = assoc<value>("mod_oauth1_request_token", args); + if (isNil(req) || isNil(cdr(req))) + return mkfailure<int>("Missing mod_oauth1_request_token parameter"); + const list<value> auth = assoc<value>("mod_oauth1_authorize", args); + if (isNil(auth) || isNil(cdr(auth))) + return mkfailure<int>("Missing mod_oauth1_authorize parameter"); + const list<value> tok = assoc<value>("mod_oauth1_access_token", args); + if (isNil(tok) || isNil(cdr(tok))) + return mkfailure<int>("Missing mod_oauth1_access_token parameter"); + const list<value> cid = assoc<value>("mod_oauth1_client_id", args); + if (isNil(cid) || isNil(cdr(cid))) + return mkfailure<int>("Missing mod_oauth1_client_id parameter"); + const list<value> info = assoc<value>("mod_oauth1_info", args); + if (isNil(info) || isNil(cdr(info))) + return mkfailure<int>("Missing mod_oauth1_info parameter"); + + // Build the redirect URI + const list<list<value> > redirargs = mklist<list<value> >(mklist<value>("mod_oauth1_step", "access_token"), tok, cid, info); + const string redir = httpd::url(r->uri, r) + string("?") + httpd::queryString(redirargs); + debug(redir, "modoauth1::authorize::redir"); + + // Lookup client app configuration + const list<value> app = assoc<value>(cadr(cid), sc.appkeys); + if (isNil(app) || isNil(cdr(app))) + return mkfailure<int>(string("client id not found: ") + cadr(cid)); + list<value> appkey = cadr(app); + + // Build and sign the request token URI + const string requri = httpd::unescape(cadr(req)) + string("&") + httpd::queryString(mklist<list<value> >(mklist<value>("oauth_callback", httpd::escape(redir)))); + const list<string> srequri = sign("POST", requri, appkey, "", ""); + debug(srequri, "modoauth1::authorize::srequri"); + + // Put the args into an oauth header + const string reqhdr = header(cadr(srequri), redir, ""); + + // Send the request token request + char* pres = oauth_http_post2(c_str(car(srequri)), "", c_str(reqhdr)); + if (pres == NULL) + return mkfailure<int>("Couldn't send request token request"); + const string res(pres); + free(pres); + debug(res, "modoauth1::authorize::res"); + const list<list<value> > resargs = httpd::queryArgs(res); + + // Retrieve the request token + const list<value> conf = assoc<value>("oauth_callback_confirmed", resargs); + if (isNil(conf) || isNil(cdr(conf)) || cadr(conf) != "true") + return mkfailure<int>("Couldn't confirm oauth_callback"); + const list<value> tv = assoc<value>("oauth_token", resargs); + if (isNil(tv) || isNil(cdr(tv))) + return mkfailure<int>("Couldn't retrieve oauth_token"); + const list<value> sv = assoc<value>("oauth_token_secret", resargs); + if (isNil(sv) || isNil(cdr(sv))) + return mkfailure<int>("Couldn't retrieve oauth_token_secret"); + + // Store the request token in memcached + const failable<bool> prc = memcache::put(mklist<value>("tuscanyOAuth1Token", cadr(tv)), cadr(sv), sc.mc); + if (!hasContent(prc)) + return mkfailure<int>(reason(prc)); + + // Redirect to the authorize URI + const string authuri = httpd::unescape(cadr(auth)) + string("?") + httpd::queryString(mklist<list<value> >(tv)); + debug(authuri, "modoauth1::authorize::authuri"); + return httpd::externalRedirect(authuri, r); +} + +/** + * Extract user info from a profile/info response. + * TODO This currently only works for Twitter, Foursquare and LinkedIn. + * User profile parsing needs to be made configurable. + */ +const failable<list<value> > profileUserInfo(const value& cid, const string& info) { + string b = substr(info, 0, 1); + if (b == "[") { + // Twitter JSON profile + js::JSContext cx; + const list<value> infov(json::jsonValues(content(json::readJSON(mklist<string>(info), cx)))); + if (isNil(infov)) + return mkfailure<list<value> >("Couldn't retrieve user info"); + debug(infov, "modoauth1::access_token::info"); + const list<value> uv = assoc<value>("user", car(infov)); + debug(uv, "modoauth1::access_token::userInfo"); + if (isNil(uv) || isNil(cdr(uv))) + return mkfailure<list<value> >("Couldn't retrieve user info"); + const list<value> iv = cdr(uv); + return cons<value>(mklist<value>("realm", cid), iv); + } + if (b == "{") { + // Foursquare JSON profile + js::JSContext cx; + const list<value> infov(json::jsonValues(content(json::readJSON(mklist<string>(info), cx)))); + if (isNil(infov)) + return mkfailure<list<value> >("Couldn't retrieve user info"); + debug(infov, "modoauth1::access_token::info"); + const list<value> uv = assoc<value>("user", infov); + debug(uv, "modoauth1::access_token::userInfo"); + if (isNil(uv) || isNil(cdr(uv))) + return mkfailure<list<value> >("Couldn't retrieve user info"); + const list<value> iv = cdr(uv); + return cons<value>(mklist<value>("realm", cid), iv); + } + if (b == "<") { + // XML profile + const list<value> infov = elementsToValues(readXML(mklist<string>(info))); + if (isNil(infov)) + return mkfailure<list<value> >("Couldn't retrieve user info"); + debug(infov, "modoauth1::access_token::info"); + const list<value> pv = car(infov); + debug(pv, "modoauth1::access_token::userInfo"); + if (isNil(pv) || isNil(cdr(pv))) + return mkfailure<list<value> >("Couldn't retrieve user info"); + const list<value> iv = cdr(pv); + return cons<value>(mklist<value>("realm", cid), iv); + } + return mkfailure<list<value> >("Couldn't retrieve user info"); +} + +/** + * Handle an access_token request. + */ +const failable<int> access_token(const list<list<value> >& args, request_rec* r, const ServerConf& sc) { + // Extract access_token URI, client ID and verification code + const list<value> tok = assoc<value>("mod_oauth1_access_token", args); + if (isNil(tok) || isNil(cdr(tok))) + return mkfailure<int>("Missing mod_oauth1_access_token parameter"); + const list<value> cid = assoc<value>("mod_oauth1_client_id", args); + if (isNil(cid) || isNil(cdr(cid))) + return mkfailure<int>("Missing mod_oauth1_client_id parameter"); + const list<value> info = assoc<value>("mod_oauth1_info", args); + if (isNil(info) || isNil(cdr(info))) + return mkfailure<int>("Missing mod_oauth1_info parameter"); + const list<value> tv = assoc<value>("oauth_token", args); + if (isNil(tv) || isNil(cdr(tv))) + return mkfailure<int>("Missing oauth_token parameter"); + const list<value> vv = assoc<value>("oauth_verifier", args); + if (isNil(vv) || isNil(cdr(vv))) + return mkfailure<int>("Missing oauth_verifier parameter"); + + // Lookup client app configuration + const list<value> app = assoc<value>(cadr(cid), sc.appkeys); + if (isNil(app) || isNil(cdr(app))) + return mkfailure<int>(string("client id not found: ") + cadr(cid)); + list<value> appkey = cadr(app); + + // Retrieve the request token from memcached + const failable<value> sv = memcache::get(mklist<value>("tuscanyOAuth1Token", cadr(tv)), sc.mc); + if (!hasContent(sv)) + return mkfailure<int>(reason(sv)); + + // Build and sign access token request URI + const string tokuri = httpd::unescape(cadr(tok)) + string("?") + httpd::queryString(mklist<list<value> >(vv)); + const list<string> stokuri = sign("POST", tokuri, appkey, cadr(tv), content(sv)); + debug(stokuri, "modoauth1::access_token::stokuri"); + + // Put the args into an oauth header + string tokhdr = header(cadr(stokuri), "", cadr(vv)); + + // Send the access token request + char* ptokres = oauth_http_post2(c_str(car(stokuri)), "", c_str(tokhdr)); + if (ptokres == NULL) + return mkfailure<int>("Couldn't post access_token request"); + const string tokres(ptokres); + free(ptokres); + debug(tokres, "modoauth1::access_token::res"); + const list<list<value> > tokresargs = httpd::queryArgs(tokres); + + // Retrieve the access token + const list<value> atv = assoc<value>("oauth_token", tokresargs); + if (isNil(atv) || isNil(cdr(atv))) + return mkfailure<int>("Couldn't retrieve oauth_token"); + const list<value> asv = assoc<value>("oauth_token_secret", tokresargs); + if (isNil(asv) || isNil(cdr(asv))) + return mkfailure<int>("Couldn't retrieve oauth_token_secret"); + debug(atv, "modoauth1::access_token::token"); + + // Build and sign user profile request URI + const string profuri = httpd::unescape(cadr(info)); + const list<string> sprofuri = sign("GET", profuri, appkey, cadr(atv), cadr(asv)); + debug(sprofuri, "modoauth1::access_token::sprofuri"); + + // Put the args into an oauth header + string profhdr = header(cadr(sprofuri), "", ""); + + // Send the user profile request + char* pprofres = oauth_http_get2(c_str(car(sprofuri)), NULL, c_str(profhdr)); + if (pprofres == NULL) + return mkfailure<int>("Couldn't get user info"); + const string profres(pprofres); + free(pprofres); + debug(profres, "modoauth1::access_token::profres"); + + // Retrieve the user info from the profile + const failable<list<value> > iv = profileUserInfo(cadr(cid), profres); + if (!hasContent(iv)) + return mkfailure<int>(reason(iv)); + + // Store user info in memcached keyed by session ID + const value sid = string("OAuth1_") + mkrand(); + const failable<bool> prc = memcache::put(mklist<value>("tuscanyOpenAuth", sid), content(iv), sc.mc); + if (!hasContent(prc)) + return mkfailure<int>(reason(prc)); + + // Send session ID to the client in a cookie + apr_table_set(r->err_headers_out, "Set-Cookie", c_str(openauth::cookie(sid))); + return httpd::externalRedirect(httpd::url(r->uri, r), r); +} + +/** + * Check user authentication. + */ +static int checkAuthn(request_rec *r) { + // Decline if we're not enabled or AuthType is not set to Open + const DirConf& dc = httpd::dirConf<DirConf>(r, &mod_tuscany_oauth1); + if (!dc.enabled) + return DECLINED; + const char* atype = ap_auth_type(r); + if (atype == NULL || strcasecmp(atype, "Open")) + return DECLINED; + + gc_scoped_pool pool(r->pool); + httpdDebugRequest(r, "modoauth1::checkAuthn::input"); + const ServerConf& sc = httpd::serverConf<ServerConf>(r, &mod_tuscany_oauth1); + + // Get session id from the request + const maybe<string> sid = openauth::sessionID(r); + if (hasContent(sid)) { + // Decline if the session id was not created by this module + if (substr(content(sid), 0, 7) != "OAuth1_") + return DECLINED; + + // If we're authenticated store the user info in the request + const failable<value> info = userInfo(content(sid), sc.mc); + if (hasContent(info)) { + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(authenticated(content(info), r)); + } + } + + // Get the request args + const list<list<value> > args = httpd::queryArgs(r); + + // Decline if the request is for another authentication provider + if (!isNil(assoc<value>("openid_identifier", args))) + return DECLINED; + if (!isNil(assoc<value>("mod_oauth2_step", args))) + return DECLINED; + + // Determine the OAuth protocol flow step, conveniently passed + // around in a request arg + const list<value> sl = assoc<value>("mod_oauth1_step", args); + const value step = !isNil(sl) && !isNil(cdr(sl))? cadr(sl) : ""; + + // Handle OAuth authorize request step + if (step == "authorize") { + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(authorize(args, r, sc)); + } + + // Handle OAuth access_token request step + if (step == "access_token") { + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(access_token(args, r, sc)); + } + + // Redirect to the login page + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(openauth::login(dc.login, r)); +} + +/** + * Process the module configuration. + */ +int postConfigMerge(ServerConf& mainsc, server_rec* s) { + if (s == NULL) + return OK; + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_oauth1); + debug(httpd::serverName(s), "modoauth1::postConfigMerge::serverName"); + + // Merge configuration from main server + if (isNil(sc.appkeys)) + sc.appkeys = mainsc.appkeys; + sc.mc = mainsc.mc; + sc.cs = mainsc.cs; + + return postConfigMerge(mainsc, s->next); +} + +int postConfig(apr_pool_t* p, unused apr_pool_t* plog, unused apr_pool_t* ptemp, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_oauth1); + debug(httpd::serverName(s), "modoauth1::postConfig::serverName"); + + // Merge server configurations + return postConfigMerge(sc, s); +} + +/** + * Child process initialization. + */ +void childInit(apr_pool_t* p, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf* psc = (ServerConf*)ap_get_module_config(s->module_config, &mod_tuscany_oauth1); + if(psc == NULL) { + cfailure << "[Tuscany] Due to one or more errors mod_tuscany_oauth1 loading failed. Causing apache to stop loading." << endl; + exit(APEXIT_CHILDFATAL); + } + ServerConf& sc = *psc; + + // Connect to Memcached + if (isNil(sc.mcaddrs)) + sc.mc = *(new (gc_new<memcache::MemCached>()) memcache::MemCached("localhost", 11211)); + else + sc.mc = *(new (gc_new<memcache::MemCached>()) memcache::MemCached(sc.mcaddrs)); + + // Setup a CURL session + sc.cs = *(new (gc_new<http::CURLSession>()) http::CURLSession(sc.ca, sc.cert, sc.key)); + + // Merge the updated configuration into the virtual hosts + postConfigMerge(sc, s->next); +} + +/** + * Configuration commands. + */ +const char* confAppKey(cmd_parms *cmd, unused void *c, const char *arg1, const char* arg2, const char* arg3) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth1); + sc.appkeys = cons<list<value> >(mklist<value>(arg1, mklist<value>(arg2, arg3)), sc.appkeys); + return NULL; +} +const char* confMemcached(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth1); + sc.mcaddrs = cons<string>(arg, sc.mcaddrs); + return NULL; +} +const char* confEnabled(cmd_parms *cmd, void *c, const int arg) { + gc_scoped_pool pool(cmd->pool); + DirConf& dc = httpd::dirConf<DirConf>(c); + dc.enabled = (bool)arg; + return NULL; +} +const char* confLogin(cmd_parms *cmd, void *c, const char* arg) { + gc_scoped_pool pool(cmd->pool); + DirConf& dc = httpd::dirConf<DirConf>(c); + dc.login = arg; + return NULL; +} +const char* confCAFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth1); + sc.ca = arg; + return NULL; +} +const char* confCertFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth1); + sc.cert = arg; + return NULL; +} +const char* confCertKeyFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth1); + sc.key = arg; + return NULL; +} + +/** + * HTTP server module declaration. + */ +const command_rec commands[] = { + AP_INIT_TAKE3("AddAuthOAuth1AppKey", (const char*(*)())confAppKey, NULL, RSRC_CONF, "OAuth 2.0 name app-id app-key"), + AP_INIT_ITERATE("AddAuthOAuthMemcached", (const char*(*)())confMemcached, NULL, RSRC_CONF, "Memcached server host:port"), + AP_INIT_FLAG("AuthOAuth", (const char*(*)())confEnabled, NULL, OR_AUTHCFG, "OAuth 2.0 authentication On | Off"), + AP_INIT_TAKE1("AuthOAuthLoginPage", (const char*(*)())confLogin, NULL, OR_AUTHCFG, "OAuth 2.0 login page"), + AP_INIT_TAKE1("AuthOAuthSSLCACertificateFile", (const char*(*)())confCAFile, NULL, RSRC_CONF, "OAUth 2.0 SSL CA certificate file"), + AP_INIT_TAKE1("AuthOAuthSSLCertificateFile", (const char*(*)())confCertFile, NULL, RSRC_CONF, "OAuth 2.0 SSL certificate file"), + AP_INIT_TAKE1("AuthOAuthSSLCertificateKeyFile", (const char*(*)())confCertKeyFile, NULL, RSRC_CONF, "OAuth 2.0 SSL certificate key file"), + {NULL, NULL, NULL, 0, NO_ARGS, NULL} +}; + +void registerHooks(unused apr_pool_t *p) { + ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_check_authn(checkAuthn, NULL, NULL, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_CONF); +} + +} +} + +extern "C" { + +module AP_MODULE_DECLARE_DATA mod_tuscany_oauth1 = { + STANDARD20_MODULE_STUFF, + // dir config and merger + tuscany::httpd::makeDirConf<tuscany::oauth1::DirConf>, NULL, + // server config and merger + tuscany::httpd::makeServerConf<tuscany::oauth1::ServerConf>, NULL, + // commands and hooks + tuscany::oauth1::commands, tuscany::oauth1::registerHooks +}; + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/mod-oauth2.cpp b/sandbox/sebastien/cpp/apr-2/modules/oauth/mod-oauth2.cpp new file mode 100644 index 0000000000..b52967977e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/mod-oauth2.cpp @@ -0,0 +1,432 @@ +/* + * 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$ */ + +/** + * HTTPD module for OAuth 2.0 authentication. + */ + +#include <sys/stat.h> + +#include "string.hpp" +#include "stream.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "../http/httpd.hpp" +#include "../http/http.hpp" +#include "../http/openauth.hpp" +#include "../../components/cache/memcache.hpp" + +extern "C" { +extern module AP_MODULE_DECLARE_DATA mod_tuscany_oauth2; +} + +namespace tuscany { +namespace oauth2 { + +/** + * Server configuration. + */ +class ServerConf { +public: + ServerConf(apr_pool_t* p, server_rec* s) : p(p), server(s) { + } + + const gc_pool p; + server_rec* server; + string ca; + string cert; + string key; + list<list<value> > appkeys; + list<string> mcaddrs; + memcache::MemCached mc; + http::CURLSession cs; +}; + +/** + * Directory configuration. + */ +class DirConf { +public: + DirConf(apr_pool_t* p, char* d) : p(p), dir(d), enabled(false), login("") { + } + + const gc_pool p; + const char* dir; + bool enabled; + string login; +}; + +/** + * Return the user info for a session. + */ +const failable<value> userInfo(const value& sid, const memcache::MemCached& mc) { + return memcache::get(mklist<value>("tuscanyOpenAuth", sid), mc); +} + +/** + * Handle an authenticated request. + */ +const failable<int> authenticated(const list<list<value> >& info, request_rec* r) { + debug(info, "modoauth2::authenticated::info"); + + // Store user info in the request + const list<value> realm = assoc<value>("realm", info); + if (isNil(realm) || isNil(cdr(realm))) + return mkfailure<int>("Couldn't retrieve realm"); + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "REALM"), apr_pstrdup(r->pool, c_str(cadr(realm)))); + + const list<value> id = assoc<value>("id", info); + if (isNil(id) || isNil(cdr(id))) + return mkfailure<int>("Couldn't retrieve user id"); + r->user = apr_pstrdup(r->pool, c_str(cadr(id))); + + const list<value> email = assoc<value>("email", info); + if (!isNil(email) && !isNil(cdr(email))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "EMAIL"), apr_pstrdup(r->pool, c_str(cadr(email)))); + + const list<value> fullname = assoc<value>("name", info); + if (!isNil(fullname) && !isNil(cdr(fullname))) { + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "NICKNAME"), apr_pstrdup(r->pool, c_str(cadr(fullname)))); + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "FULLNAME"), apr_pstrdup(r->pool, c_str(cadr(fullname)))); + } + + const list<value> firstname = assoc<value>("first_name", info); + if (!isNil(firstname) && !isNil(cdr(firstname))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "FIRSTNAME"), apr_pstrdup(r->pool, c_str(cadr(firstname)))); + + const list<value> lastname = assoc<value>("last_name", info); + if (!isNil(lastname) && !isNil(cdr(lastname))) + apr_table_set(r->subprocess_env, apr_pstrdup(r->pool, "LASTNAME"), apr_pstrdup(r->pool, c_str(cadr(lastname)))); + + return OK; +} + +/** + * Handle an authorize request. + */ +const failable<int> authorize(const list<list<value> >& args, request_rec* r, const ServerConf& sc) { + // Extract authorize, access_token, client ID and info URIs + const list<value> auth = assoc<value>("mod_oauth2_authorize", args); + if (isNil(auth) || isNil(cdr(auth))) + return mkfailure<int>("Missing mod_oauth2_authorize parameter"); + const list<value> tok = assoc<value>("mod_oauth2_access_token", args); + if (isNil(tok) || isNil(cdr(tok))) + return mkfailure<int>("Missing mod_oauth2_access_token parameter"); + const list<value> cid = assoc<value>("mod_oauth2_client_id", args); + if (isNil(cid) || isNil(cdr(cid))) + return mkfailure<int>("Missing mod_oauth2_client_id parameter"); + const list<value> info = assoc<value>("mod_oauth2_info", args); + if (isNil(info) || isNil(cdr(info))) + return mkfailure<int>("Missing mod_oauth2_info parameter"); + + // Build the redirect URI + const list<list<value> > rargs = mklist<list<value> >(mklist<value>("mod_oauth2_step", "access_token"), tok, cid, info); + const string redir = httpd::url(r->uri, r) + string("?") + httpd::queryString(rargs); + debug(redir, "modoauth2::authorize::redir"); + + // Lookup client app configuration + const list<value> app = assoc<value>(cadr(cid), sc.appkeys); + if (isNil(app) || isNil(cdr(app))) + return mkfailure<int>(string("client id not found: ") + cadr(cid)); + list<value> appkey = cadr(app); + + // Redirect to the authorize URI + const list<list<value> > aargs = mklist<list<value> >(mklist<value>("client_id", car(appkey)), mklist<value>("scope", "email"), mklist<value>("redirect_uri", httpd::escape(redir))); + const string uri = httpd::unescape(cadr(auth)) + string("?") + httpd::queryString(aargs); + debug(uri, "modoauth2::authorize::uri"); + return httpd::externalRedirect(uri, r); +} + +/** + * Extract user info from a profile/info response. + * TODO This currently only works for Facebook and Gowalla. + * User profile parsing needs to be made configurable. + */ +const failable<list<value> > profileUserInfo(const value& cid, const list<value>& info) { + return cons<value>(mklist<value>("realm", cid), info); +} + +/** + * Handle an access_token request. + */ +const failable<int> access_token(const list<list<value> >& args, request_rec* r, const ServerConf& sc) { + // Extract access_token URI, client ID and authorization code + const list<value> tok = assoc<value>("mod_oauth2_access_token", args); + if (isNil(tok) || isNil(cdr(tok))) + return mkfailure<int>("Missing mod_oauth2_access_token parameter"); + const list<value> cid = assoc<value>("mod_oauth2_client_id", args); + if (isNil(cid) || isNil(cdr(cid))) + return mkfailure<int>("Missing mod_oauth2_client_id parameter"); + const list<value> info = assoc<value>("mod_oauth2_info", args); + if (isNil(info) || isNil(cdr(info))) + return mkfailure<int>("Missing mod_oauth2_info parameter"); + const list<value> code = assoc<value>("code", args); + if (isNil(code) || isNil(cdr(code))) + return mkfailure<int>("Missing code parameter"); + + // Lookup client app configuration + const list<value> app = assoc<value>(cadr(cid), sc.appkeys); + if (isNil(app) || isNil(cdr(app))) + return mkfailure<int>(string("client id not found: ") + cadr(cid)); + list<value> appkey = cadr(app); + + // Build the redirect URI + const list<list<value> > rargs = mklist<list<value> >(mklist<value>("mod_oauth2_step", "access_token"), tok, cid, info); + const string redir = httpd::url(r->uri, r) + string("?") + httpd::queryString(rargs); + debug(redir, "modoauth2::access_token::redir"); + + // Request access token + const list<list<value> > targs = mklist<list<value> >(mklist<value>("client_id", car(appkey)), mklist<value>("redirect_uri", httpd::escape(redir)), mklist<value>("client_secret", cadr(appkey)), code); + const string turi = httpd::unescape(cadr(tok)) + string("?") + httpd::queryString(targs); + debug(turi, "modoauth2::access_token::tokenuri"); + const failable<value> tr = http::get(turi, sc.cs); + if (!hasContent(tr)) + return mkfailure<int>(reason(tr)); + debug(tr, "modoauth2::access_token::response"); + const list<value> tv = assoc<value>("access_token", httpd::queryArgs(join("", convertValues<string>(content(tr))))); + if (isNil(tv) || isNil(cdr(tv))) + return mkfailure<int>("Couldn't retrieve access_token"); + debug(tv, "modoauth2::access_token::token"); + + // Request user info + // TODO Make this step configurable + const list<list<value> > iargs = mklist<list<value> >(tv); + const string iuri = httpd::unescape(cadr(info)) + string("?") + httpd::queryString(iargs); + debug(iuri, "modoauth2::access_token::infouri"); + const failable<value> profres = http::get(iuri, sc.cs); + if (!hasContent(profres)) + return mkfailure<int>("Couldn't retrieve user info"); + debug(content(profres), "modoauth2::access_token::info"); + + // Retrieve the user info from the profile + const failable<list<value> > iv = profileUserInfo(cadr(cid), content(profres)); + if (!hasContent(iv)) + return mkfailure<int>(reason(iv)); + + // Store user info in memcached keyed by session ID + const value sid = string("OAuth2_") + mkrand(); + const failable<bool> prc = memcache::put(mklist<value>("tuscanyOpenAuth", sid), content(iv), sc.mc); + if (!hasContent(prc)) + return mkfailure<int>(reason(prc)); + + // Send session ID to the client in a cookie + apr_table_set(r->err_headers_out, "Set-Cookie", c_str(openauth::cookie(sid))); + return httpd::externalRedirect(httpd::url(r->uri, r), r); +} + +/** + * Check user authentication. + */ +static int checkAuthn(request_rec *r) { + // Decline if we're not enabled or AuthType is not set to Open + const DirConf& dc = httpd::dirConf<DirConf>(r, &mod_tuscany_oauth2); + if (!dc.enabled) + return DECLINED; + const char* atype = ap_auth_type(r); + if (atype == NULL || strcasecmp(atype, "Open")) + return DECLINED; + + gc_scoped_pool pool(r->pool); + httpdDebugRequest(r, "modoauth2::checkAuthn::input"); + const ServerConf& sc = httpd::serverConf<ServerConf>(r, &mod_tuscany_oauth2); + + // Get session id from the request + const maybe<string> sid = openauth::sessionID(r); + if (hasContent(sid)) { + // Decline if the session id was not created by this module + if (substr(content(sid), 0, 7) != "OAuth2_") + return DECLINED; + + // If we're authenticated store the user info in the request + const failable<value> info = userInfo(content(sid), sc.mc); + if (hasContent(info)) { + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(authenticated(content(info), r)); + } + } + + // Get the request args + const list<list<value> > args = httpd::queryArgs(r); + + // Decline if the request is for another authentication provider + if (!isNil(assoc<value>("openid_identifier", args))) + return DECLINED; + if (!isNil(assoc<value>("mod_oauth1_step", args))) + return DECLINED; + + // Determine the OAuth protocol flow step, conveniently passed + // around in a request arg + const list<value> sl = assoc<value>("mod_oauth2_step", args); + const value step = !isNil(sl) && !isNil(cdr(sl))? cadr(sl) : ""; + + // Handle OAuth authorize request step + if (step == "authorize") { + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(authorize(args, r, sc)); + } + + // Handle OAuth access_token request step + if (step == "access_token") { + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(access_token(args, r, sc)); + } + + // Redirect to the login page + r->ap_auth_type = const_cast<char*>(atype); + return httpd::reportStatus(openauth::login(dc.login, r)); +} + +/** + * Process the module configuration. + */ +int postConfigMerge(ServerConf& mainsc, server_rec* s) { + if (s == NULL) + return OK; + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_oauth2); + debug(httpd::serverName(s), "modoauth2::postConfigMerge::serverName"); + + // Merge configuration from main server + if (isNil(sc.appkeys)) + sc.appkeys = mainsc.appkeys; + sc.mc = mainsc.mc; + sc.cs = mainsc.cs; + + return postConfigMerge(mainsc, s->next); +} + +int postConfig(apr_pool_t* p, unused apr_pool_t* plog, unused apr_pool_t* ptemp, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_oauth2); + debug(httpd::serverName(s), "modoauth2::postConfig::serverName"); + + // Merge server configurations + return postConfigMerge(sc, s); +} + +/** + * Child process initialization. + */ +void childInit(apr_pool_t* p, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf* psc = (ServerConf*)ap_get_module_config(s->module_config, &mod_tuscany_oauth2); + if(psc == NULL) { + cfailure << "[Tuscany] Due to one or more errors mod_tuscany_oauth2 loading failed. Causing apache to stop loading." << endl; + exit(APEXIT_CHILDFATAL); + } + ServerConf& sc = *psc; + + // Connect to Memcached + if (isNil(sc.mcaddrs)) + sc.mc = *(new (gc_new<memcache::MemCached>()) memcache::MemCached("localhost", 11211)); + else + sc.mc = *(new (gc_new<memcache::MemCached>()) memcache::MemCached(sc.mcaddrs)); + + // Setup a CURL session + sc.cs = *(new (gc_new<http::CURLSession>()) http::CURLSession(sc.ca, sc.cert, sc.key)); + + // Merge the updated configuration into the virtual hosts + postConfigMerge(sc, s->next); +} + +/** + * Configuration commands. + */ +const char* confAppKey(cmd_parms *cmd, unused void *c, const char *arg1, const char* arg2, const char* arg3) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth2); + sc.appkeys = cons<list<value> >(mklist<value>(arg1, mklist<value>(arg2, arg3)), sc.appkeys); + return NULL; +} +const char* confMemcached(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth2); + sc.mcaddrs = cons<string>(arg, sc.mcaddrs); + return NULL; +} +const char* confEnabled(cmd_parms *cmd, void *c, const int arg) { + gc_scoped_pool pool(cmd->pool); + DirConf& dc = httpd::dirConf<DirConf>(c); + dc.enabled = (bool)arg; + return NULL; +} +const char* confLogin(cmd_parms *cmd, void *c, const char* arg) { + gc_scoped_pool pool(cmd->pool); + DirConf& dc = httpd::dirConf<DirConf>(c); + dc.login = arg; + return NULL; +} +const char* confCAFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth2); + sc.ca = arg; + return NULL; +} +const char* confCertFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth2); + sc.cert = arg; + return NULL; +} +const char* confCertKeyFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_oauth2); + sc.key = arg; + return NULL; +} + +/** + * HTTP server module declaration. + */ +const command_rec commands[] = { + AP_INIT_TAKE3("AddAuthOAuth2AppKey", (const char*(*)())confAppKey, NULL, RSRC_CONF, "OAuth 2.0 name app-id app-key"), + AP_INIT_ITERATE("AddAuthOAuthMemcached", (const char*(*)())confMemcached, NULL, RSRC_CONF, "Memcached server host:port"), + AP_INIT_FLAG("AuthOAuth", (const char*(*)())confEnabled, NULL, OR_AUTHCFG, "OAuth 2.0 authentication On | Off"), + AP_INIT_TAKE1("AuthOAuthLoginPage", (const char*(*)())confLogin, NULL, OR_AUTHCFG, "OAuth 2.0 login page"), + AP_INIT_TAKE1("AuthOAuthSSLCACertificateFile", (const char*(*)())confCAFile, NULL, RSRC_CONF, "OAUth 2.0 SSL CA certificate file"), + AP_INIT_TAKE1("AuthOAuthSSLCertificateFile", (const char*(*)())confCertFile, NULL, RSRC_CONF, "OAuth 2.0 SSL certificate file"), + AP_INIT_TAKE1("AuthOAuthSSLCertificateKeyFile", (const char*(*)())confCertKeyFile, NULL, RSRC_CONF, "OAuth 2.0 SSL certificate key file"), + {NULL, NULL, NULL, 0, NO_ARGS, NULL} +}; + +void registerHooks(unused apr_pool_t *p) { + ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_check_authn(checkAuthn, NULL, NULL, APR_HOOK_MIDDLE, AP_AUTH_INTERNAL_PER_CONF); +} + +} +} + +extern "C" { + +module AP_MODULE_DECLARE_DATA mod_tuscany_oauth2 = { + STANDARD20_MODULE_STUFF, + // dir config and merger + tuscany::httpd::makeDirConf<tuscany::oauth2::DirConf>, NULL, + // server config and merger + tuscany::httpd::makeServerConf<tuscany::oauth2::ServerConf>, NULL, + // commands and hooks + tuscany::oauth2::commands, tuscany::oauth2::registerHooks +}; + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth-conf b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth-conf new file mode 100755 index 0000000000..dc3a6ebc9d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth-conf @@ -0,0 +1,59 @@ +#!/bin/sh + +# 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. + +# Generate an OAuth server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +# Configure HTTPD mod_tuscany_oauth module +cat >>$root/conf/modules.conf <<EOF +# Generated by: oauth-conf $* +# Load support for OAuth authentication +LoadModule mod_tuscany_oauth1 $here/libmod_tuscany_oauth1.so +LoadModule mod_tuscany_oauth2 $here/libmod_tuscany_oauth2.so + +EOF + +cat >>$root/conf/auth.conf <<EOF +# Generated by: oauth-conf $* +# Enable OAuth authentication +<Location /> +AuthType Open +AuthName "$host" +AuthOAuth On +AuthOAuthLoginPage /login +Require valid-user +</Location> + +# Configure OAuth App keys +Include $root/cert/oauth-keys.conf +Include $HOME/.oauth/*-key.conf + +EOF + +cat >$root/cert/oauth-keys.conf <<EOF +# Generated by: oauth-conf $* +# OAuth App keys + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth-memcached-conf b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth-memcached-conf new file mode 100755 index 0000000000..23a82a0486 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth-memcached-conf @@ -0,0 +1,32 @@ +#!/bin/sh + +# 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. + +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` +host=$2 +port=$3 + +# Configure HTTPD mod_tuscany_oauth module cache +cat >>$root/conf/auth.conf <<EOF +# Generated by: oauth-memcached-conf $* +AddAuthOAuthMemcached $host:$port + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth.composite b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth.composite new file mode 100644 index 0000000000..c2025493c8 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth.composite @@ -0,0 +1,44 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * 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. +--> +<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912" + xmlns:t="http://tuscany.apache.org/xmlns/sca/1.1" + targetNamespace="http://tuscany.apache.org/xmlns/sca/components" + name="oauth"> + + <component name="Protected"> + <t:implementation.widget location="protected/index.html"/> + <reference name="userInfo" target="UserInfo"/> + </component> + + <component name="UserInfo"> + <t:implementation.scheme script="user-info.scm"/> + <service name="info"> + <t:binding.jsonrpc uri="info"/> + </service> + <property name="user">?</property> + <property name="email">?</property> + <property name="nickname">?</property> + <property name="fullname">?</property> + <property name="firstname">?</property> + <property name="lastname">?</property> + <property name="realm">?</property> + </component> + +</composite> diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth1-appkey-conf b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth1-appkey-conf new file mode 100755 index 0000000000..fca7d4e8f3 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth1-appkey-conf @@ -0,0 +1,36 @@ +#!/bin/sh + +# 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. + +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` +name=$2 +id=$3 +secret=$4 + +# Configure an OAuth 1.0 app key +mkdir -p $root/cert +umask 0007 + +cat >>$root/cert/oauth-keys.conf <<EOF +# Generated by: oauth1-appkey-conf $* +AddAuthOAuth1AppKey $name $id $secret + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth2-appkey-conf b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth2-appkey-conf new file mode 100755 index 0000000000..0a7986f07e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/oauth2-appkey-conf @@ -0,0 +1,36 @@ +#!/bin/sh + +# 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. + +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` +name=$2 +id=$3 +secret=$4 + +# Configure an OAuth 2.0 app key +mkdir -p $root/cert +umask 0007 + +cat >>$root/cert/oauth-keys.conf <<EOF +# Generated by: oauth2-appkey-conf $* +AddAuthOAuth2AppKey $name $id $secret + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/start-mixed-test b/sandbox/sebastien/cpp/apr-2/modules/oauth/start-mixed-test new file mode 100755 index 0000000000..bfd7667ce4 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/start-mixed-test @@ -0,0 +1,67 @@ +#!/bin/sh + +# 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. + +# Test supporting both OpenID and OAuth in the same app +here=`readlink -f $0`; here=`dirname $here` + +# Setup +../../components/cache/memcached-start 11212 +../../components/cache/memcached-start 11213 + +../../modules/http/ssl-ca-conf tmp localhost +../../modules/http/ssl-cert-conf tmp localhost +../../modules/http/httpd-conf tmp localhost 8090 htdocs +../../modules/http/httpd-ssl-conf tmp 8453 + +./oauth-conf tmp +./oauth-memcached-conf tmp localhost 11212 +./oauth-memcached-conf tmp localhost 11213 + +# Configure your app keys here +./oauth1-appkey-conf tmp twitter.com app2345 secret7890 +./oauth1-appkey-conf tmp linkedin.com app3456 secret4567 +./oauth2-appkey-conf tmp facebook.com app1234 secret6789 +./oauth2-appkey-conf tmp github.com app5678 secret8901 + +../openid/openid-conf tmp +../openid/openid-step2-conf tmp +../openid/openid-memcached-conf tmp localhost 11212 +../openid/openid-memcached-conf tmp localhost 11213 + +../http/open-auth-conf tmp +../http/passwd-auth-conf tmp foo foo + +# For this test to work you need to add your form, oauth and open id ids +# to the authorized user group +../../modules/http/group-auth-conf tmp foo +../../modules/http/group-auth-conf tmp 123456 +../../modules/http/group-auth-conf tmp https://www.google.com/accounts/o8/id?id=12345678 + +../../modules/server/server-conf tmp +../../modules/server/scheme-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite oauth.composite + +Alias /login/index.html $here/htdocs/login/mixed.html + +EOF + +../../modules/http/httpd-start tmp + diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/start-test b/sandbox/sebastien/cpp/apr-2/modules/oauth/start-test new file mode 100755 index 0000000000..0e859ce6e6 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/start-test @@ -0,0 +1,54 @@ +#!/bin/sh + +# 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. + +# Setup +../../ubuntu/ip-redirect-all 80 8090 +../../ubuntu/ip-redirect-all 443 8453 + +../../components/cache/memcached-start 11212 +../../components/cache/memcached-start 11213 + +../../modules/http/ssl-ca-conf tmp localhost +../../modules/http/ssl-cert-conf tmp localhost +../../modules/http/httpd-conf tmp localhost 8090/80 htdocs +../../modules/http/httpd-ssl-conf tmp 8453/443 + +./oauth-conf tmp +./oauth-memcached-conf tmp localhost 11212 +./oauth-memcached-conf tmp localhost 11213 + +# Configure your app keys here +./oauth1-appkey-conf tmp twitter.com app2345 secret7890 +./oauth1-appkey-conf tmp linkedin.com app3456 secret4567 +./oauth2-appkey-conf tmp facebook.com app1234 secret6789 +./oauth2-appkey-conf tmp github.com app5678 secret8901 + +# For this test to work you need to add your oauth user id to the +# authorized user group +../../modules/http/group-auth-conf tmp 123456 + +../../modules/server/server-conf tmp +../../modules/server/scheme-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite oauth.composite +EOF + +../../modules/http/httpd-start tmp + diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/stop-test b/sandbox/sebastien/cpp/apr-2/modules/oauth/stop-test new file mode 100755 index 0000000000..a0587f8cb7 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/stop-test @@ -0,0 +1,24 @@ +#!/bin/sh + +# 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. + +# Cleanup +../../modules/http/httpd-stop tmp + +../../components/cache/memcached-stop 11212 +../../components/cache/memcached-stop 11213 diff --git a/sandbox/sebastien/cpp/apr-2/modules/oauth/user-info.scm b/sandbox/sebastien/cpp/apr-2/modules/oauth/user-info.scm new file mode 100644 index 0000000000..4960a0a455 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/oauth/user-info.scm @@ -0,0 +1,36 @@ +; 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. + +; OAuth support test case + +(define (get id user email nickname fullname firstname lastname realm) (list "text/html" (list + "<html><body><p>The following info is generated on the server:</p><div>User: " (user) "</div><div>Email: " (email) "</div><div>Nickname: " (nickname) "</div><div>Fullname: " (fullname) "</div><div>Firstname: " (firstname) "</div><div>Lastname: " (lastname) "</div><div>Realm: " (realm) "</div></body></html>"))) + +(define (getuser user email nickname fullname firstname lastname realm) (user)) + +(define (getemail user email nickname fullname firstname lastname realm) (email)) + +(define (getnickname user email nickname fullname firstname lastname realm) (nickname)) + +(define (getfullname user email nickname fullname firstname lastname realm) (fullname)) + +(define (getfirstname user email nickname fullname firstname lastname realm) (firstname)) + +(define (getlastname user email nickname fullname firstname lastname realm) (lastname)) + +(define (getrealm user email nickname fullname firstname lastname realm) (realm)) + diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/openid/Makefile.am new file mode 100644 index 0000000000..a46dd56743 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/Makefile.am @@ -0,0 +1,32 @@ +# 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_OPENID + +dist_mod_SCRIPTS = openid-conf openid-step2-conf openid-memcached-conf +moddir = $(prefix)/modules/openid + +mod_DATA = openid.prefix +openid.prefix: $(top_builddir)/config.status + echo ${MODAUTHOPENID_PREFIX} >openid.prefix + +EXTRA_DIST = openid.composite user-info.scm htdocs/index.html htdocs/login/index.html htdocs/logout/index.html htdocs/public/index.html + +dist_noinst_SCRIPTS = start-test stop-test + +endif diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/index.html b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/index.html new file mode 100644 index 0000000000..98bbac0c57 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/index.html @@ -0,0 +1,46 @@ +<!-- + 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. +--> + +<html> +<head> +<script type="text/javascript" src="/component.js"></script> +<script type="text/javascript"> +var protected = sca.component("Protected"); +var userInfo = sca.defun(sca.reference(protected, "userInfo"), "getuser", "getemail", "getrealm"); +var user = userInfo.getuser(); +var email = userInfo.getemail(); +var realm = userInfo.getrealm(); +</script> +</head> +<body> +<h1>Protected area - It works!</h1> +<p>The following info is returned by a JSONRPC service:</p> +<div id="user"></div> +<div id="email"></div> +<div id="realm"></div> +<script type="text/javascript"> +document.getElementById('user').innerHTML="User: " + user; +document.getElementById('email').innerHTML="Email: " + email; +document.getElementById('realm').innerHTML="Realm: " + realm; +</script> +<p><a href="info">User info</a></p> +<p><a href="login">Sign in</a></p> +<p><a href="logout">Sign out</a></p> +<p><a href="public">Public area</a></p> +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/login/index.html b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/login/index.html new file mode 100644 index 0000000000..493227addc --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/login/index.html @@ -0,0 +1,129 @@ +<!-- + 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. +--> + +<html><body><h1>Sign in with an OpenID provider</h1> + +<script type="text/javascript"> +function queryParams() { + qp = new Array(); + qs = window.location.search.substring(1).split('&'); + for (i = 0; i < qs.length; i++) { + e = qs[i].indexOf('='); + if (e > 0) + qp[qs[i].substring(0, e)] = unescape(qs[i].substring(e + 1)); + } + return qp; +} + +function openidReferrer() { + r = queryParams()['openauth_referrer']; + if (typeof(r) == 'undefined') + return r; + q = r.indexOf('?'); + if (q > 0) + return r.substring(0, q); + return r; +} + +if (typeof(openidReferrer()) == 'undefined') { + document.location = '/'; +} + +function submitSignin(w) { + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.signin.openid_identifier.value = w(); + document.signin.action = openidReferrer(); + document.signin.submit(); +} + + +function withGoogle() { + return 'https://www.google.com/accounts/o8/id'; +} + +function withYahoo() { + return 'https://me.yahoo.com/'; +} + +function withMyOpenID() { + return 'http://www.myopenid.com/xrds'; +} + +function withVerisign() { + return 'https://pip.verisignlabs.com/'; +} + +function withMySpace() { + return 'https://api.myspace.com/openid'; +} + +function withGoogleApps() { + return 'https://www.google.com/accounts/o8/site-xrds?ns=2&hd=' + document.fields.domain.value; +} + +function withLivejournal() { + return 'http://' + document.fields.ljuser.value + '.livejournal.com'; +} + +function withBlogspot() { + return 'http://' + document.fields.bsuser.value + '.blogspot.com'; +} + +function withBlogger() { + return 'http://' + document.fields.bguser.value + '.blogger.com'; +} + +function withXRDSEndpoint() { + return document.fields.endpoint.value; +} +</script> + +<form name="signin" action="/" method="GET"> +<input type="hidden" name="openid_identifier" value="https://www.google.com/accounts/o8/id"/> +</form> + +<form name="fields"> +<p>Sign in with your Google account<br/><input type="button" onclick="submitSignin(withGoogle)" value="Sign in"/></p> +<p>Sign in with your Yahoo account<br/><input type="button" onclick="submitSignin(withYahoo)" value="Sign in"/></p> +<p>Sign in with your MyOpenID account<br/><input type="button" onclick="submitSignin(withMyOpenID)" value="Sign in"/></p> +<p>Sign in with your Verisign account<br/><input type="button" onclick="submitSignin(withVerisign)" value="Sign in"/></p> +<p>Sign in with your MySpace account<br/><input type="button" onclick="submitSignin(withMySpace)" value="Sign in"/></p> + +<p>Sign in with a Google apps domain<br/> +<input type="text" size="20" name="domain" value="example.com"/><br/> +<input type="button" onclick="submitSignin(withGoogleApps)" value="Sign in"/></p> + +<p>Sign in with your Livejournal account<br/> +<input type="text" size="10" name="ljuser" value=""/><br/> +<input type="button" onclick="submitSignin(withLivejournal)" value="Sign in"/></p> + +<p>Sign in with your Blogspot account<br/> +<input type="text" size="10" name="bsuser" value=""/><br/> +<input type="button" onclick="submitSignin(withBlogspot)" value="Sign in"/></p> + +<p>Sign in with your Blogger account<br/> +<input type="text" size="10" name="bguser" value=""/><br/> +<input type="button" onclick="submitSignin(withBlogger)" value="Sign in"/></p> + +<p>Sign in with an OpenID endpoint<br/> +<input type="text" size="50" name="endpoint" value="https://www.google.com/accounts/o8/id"/><br/> +<input type="button" onclick="submitSignin(withXRDSEndpoint)" value="Sign in"/></p> +</form> + +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/logout/index.html b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/logout/index.html new file mode 100644 index 0000000000..02a92d1b31 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/logout/index.html @@ -0,0 +1,33 @@ +<!-- + 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. +--> + +<html><body> +<h1>Sign out</h1> + +<form name="signout" action="/login" method="GET"> +<script type="text/javascript"> +function submitSignout() { + document.cookie = 'TuscanyOpenAuth=;expires=' + new Date(1970,01,01).toGMTString() + ';path=/;secure=TRUE'; + document.signout.submit(); + return true; +} +</script> +<input type="button" onclick="submitSignout()" value="Sign out"/> +</form> +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/public/index.html b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/public/index.html new file mode 100644 index 0000000000..af2cd7ca19 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/htdocs/public/index.html @@ -0,0 +1,27 @@ +<!-- + 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. +--> + +<html> +<body> +<h1>Unprotected area - It works!</h1> +<p><a href="/info">User info</a></p> +<p><a href="/login">Sign in</a></p> +<p><a href="/logout">Sign out</a></p> +<p><a href="/">Protected area</a></p> +</body></html> diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/openid-conf b/sandbox/sebastien/cpp/apr-2/modules/openid/openid-conf new file mode 100755 index 0000000000..797f8b0607 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/openid-conf @@ -0,0 +1,67 @@ +#!/bin/sh + +# 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. + +# Generate an OpenID server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` +openid_prefix=`cat $here/openid.prefix` + +# Configure OpenID authentication +cat >>$root/conf/modules.conf <<EOF +# Generated by: openid-conf $* +# Load support for OpenID authentication +LoadModule authopenid_module $openid_prefix/modules/mod_auth_openid.so + +EOF + +cat >>$root/conf/auth.conf <<EOF +# Generated by: openid-conf $* +# Enable OpenID authentication +<Location /> +AuthType Open +AuthName "$host" +Require valid-user +AuthOpenIDEnabled On +AuthOpenIDCookiePath / +AuthOpenIDCookieName TuscanyOpenAuth +AuthOpenIDSecureCookie On +AuthOpenIDLoginPage /login +AuthOpenIDAXAdd EMAIL http://axschema.org/contact/email +AuthOpenIDAXAdd FULLNAME http://axschema.org/namePerson +AuthOpenIDAXAdd NICKNAME http://axschema.org/namePerson/friendly +AuthOpenIDAXAdd FIRSTNAME http://axschema.org/namePerson/first +AuthOpenIDAXAdd LASTNAME http://axschema.org/namePerson/last +</Location> + +EOF + +cat >>$root/conf/httpd.conf <<EOF +# Generated by: openid-conf $* +# Allow access to /openid location +<Location /openid> +AuthType None +Require all granted +</Location> + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/openid-memcached-conf b/sandbox/sebastien/cpp/apr-2/modules/openid/openid-memcached-conf new file mode 100755 index 0000000000..1717b3ce92 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/openid-memcached-conf @@ -0,0 +1,32 @@ +#!/bin/sh + +# 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. + +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` +host=$2 +port=$3 + +# Configure HTTPD mod_auth_openid module cache +cat >>$root/conf/auth.conf <<EOF +# Generated by: openid-cache-conf $* +AddAuthOpenIDMemcached $host:$port + +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/openid-step2-conf b/sandbox/sebastien/cpp/apr-2/modules/openid/openid-step2-conf new file mode 100755 index 0000000000..559a62d20b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/openid-step2-conf @@ -0,0 +1,78 @@ +#!/bin/sh + +# 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. + +# Generate an OpenID Step2 server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` + +# Configure HTTPD to serve OpenID XRDS and LRDD documents +cat >>$root/conf/auth.conf <<EOF +# Generated by: openid-step2-conf $* +# Serve OpenID XRDS document +Alias /openid $root/conf/openid.xrds +<Location /openid> +ForceType application/xrds+xml +</Location> + +# Serve OpenID LRDD document +Alias /.well-known/host-meta $root/conf/openid.lrdd +<Location /.well-known/host-meta> +ForceType text/plain +</Location> + +EOF + +cat >>$root/conf/httpd.conf <<EOF +# Generated by: openid-conf $* +# Allow access to /.well-known/host-meta location +<Location /.well-known/host-meta> +AuthType None +Require all granted +</Location> + +EOF + +# Generate OpenID XRDS document +cat >$root/conf/openid.xrds <<EOF +<?xml version="1.0" encoding="UTF-8"?> +<xrds:XRDS xmlns:xrds="xri://\$xrds" xmlns="xri://\$xrd*(\$v*2.0)"> +<XRD> +<CanonicalID>$host</CanonicalID> +<Service priority="0"> +<Type>http://specs.openid.net/auth/2.0/server</Type> +<Type>http://specs.openid.net/auth/2.0/signon</Type> +<Type>http://openid.net/srv/ax/1.0</Type> +<Type>http://specs.openid.net/extensions/ui/1.0/mode/popup</Type> +<Type>http://specs.openid.net/extensions/ui/1.0/icon</Type> +<Type>http://specs.openid.net/extensions/pape/1.0</Type> +<URI>https://www.google.com/a/$host/o8/ud?be=o8</URI> +</Service> +</XRD> +</xrds:XRDS> +EOF + +# Generate OpenID LRDD document +cat >$root/conf/openid.lrdd <<EOF +Link: <https://www.google.com/accounts/o8/site-xrds?hd=$host>; rel="describedby http://reltype.google.com/openid/xrd-op"; type="application/xrds+xml" +EOF + diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/openid.composite b/sandbox/sebastien/cpp/apr-2/modules/openid/openid.composite new file mode 100644 index 0000000000..08bb74b7c7 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/openid.composite @@ -0,0 +1,40 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * 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. +--> +<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912" + xmlns:t="http://tuscany.apache.org/xmlns/sca/1.1" + targetNamespace="http://tuscany.apache.org/xmlns/sca/components" + name="openid"> + + <component name="Protected"> + <t:implementation.widget location="protected/index.html"/> + <reference name="userInfo" target="UserInfo"/> + </component> + + <component name="UserInfo"> + <t:implementation.scheme script="user-info.scm"/> + <service name="info"> + <t:binding.jsonrpc uri="info"/> + </service> + <property name="user">anonymous</property> + <property name="email">anonymous@example.com</property> + <property name="realm">example.com</property> + </component> + +</composite> diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/start-test b/sandbox/sebastien/cpp/apr-2/modules/openid/start-test new file mode 100755 index 0000000000..7ae27c57cd --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/start-test @@ -0,0 +1,46 @@ +#!/bin/sh + +# 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. + +# Setup +../../components/cache/memcached-start 11212 +../../components/cache/memcached-start 11213 + +../../modules/http/ssl-ca-conf tmp localhost +../../modules/http/ssl-cert-conf tmp localhost +../../modules/http/httpd-conf tmp localhost 8090 htdocs +../../modules/http/httpd-ssl-conf tmp 8453 + +./openid-conf tmp +./openid-memcached-conf tmp localhost 11212 +./openid-memcached-conf tmp localhost 11213 +./openid-step2-conf tmp + +# For this test to work you need to add your openid to the +# the authorized user group +../../modules/http/group-auth-conf tmp https://www.google.com/accounts/o8/id?id=1234567 + +../../modules/server/server-conf tmp +../../modules/server/scheme-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite openid.composite +EOF + +../../modules/http/httpd-start tmp + diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/stop-test b/sandbox/sebastien/cpp/apr-2/modules/openid/stop-test new file mode 100755 index 0000000000..a0587f8cb7 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/stop-test @@ -0,0 +1,24 @@ +#!/bin/sh + +# 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. + +# Cleanup +../../modules/http/httpd-stop tmp + +../../components/cache/memcached-stop 11212 +../../components/cache/memcached-stop 11213 diff --git a/sandbox/sebastien/cpp/apr-2/modules/openid/user-info.scm b/sandbox/sebastien/cpp/apr-2/modules/openid/user-info.scm new file mode 100644 index 0000000000..b1ef74c6bd --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/openid/user-info.scm @@ -0,0 +1,28 @@ +; 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. + +; OpenID support test case + +(define (get id user email realm) (list "text/html" (list + "<html><body><p>The following info is generated on the server:</p><div>User: " (user) "</div><div>Email: " (email) "</div><div>Realm: " (realm) "</div></body></html>"))) + +(define (getuser user email realm) (user)) + +(define (getemail user email realm) (email)) + +(define (getrealm user email realm) (realm)) + diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/python/Makefile.am new file mode 100644 index 0000000000..2f56b9a1db --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/Makefile.am @@ -0,0 +1,56 @@ +# 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_PYTHON + +INCLUDES = -I${PYTHON_INCLUDE} + +incl_HEADERS = *.hpp +incldir = $(prefix)/include/modules/python + +dist_mod_SCRIPTS = python-conf +moddir = $(prefix)/modules/python + +prefix_DATA = python.prefix +prefixdir = $(prefix)/modules/python +python.prefix: $(top_builddir)/config.status + echo ${PYTHON_PREFIX} >python.prefix + +EXTRA_DIST = domain-test.composite client-test.py server-test.py + +mod_LTLIBRARIES = libmod_tuscany_python.la +libmod_tuscany_python_la_SOURCES = mod-python.cpp +libmod_tuscany_python_la_LDFLAGS = -lxml2 -lcurl -lmozjs -L${PYTHON_LIB} -R${PYTHON_LIB} -lpython2.6 +noinst_DATA = libmod_tuscany_python.so +libmod_tuscany_python.so: + ln -s .libs/libmod_tuscany_python.so + +python_test_SOURCES = python-test.cpp +python_test_LDFLAGS = -L${PYTHON_LIB} -R${PYTHON_LIB} -lpython2.6 + +python_shell_SOURCES = python-shell.cpp +python_shell_LDFLAGS = -L${PYTHON_LIB} -R${PYTHON_LIB} -lpython2.6 + +client_test_SOURCES = client-test.cpp +client_test_LDFLAGS = -lxml2 -lcurl -lmozjs + +dist_noinst_SCRIPTS = server-test wiring-test +noinst_PROGRAMS = python-test python-shell client-test +TESTS = python-test server-test + +endif diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/client-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/python/client-test.cpp new file mode 100644 index 0000000000..21fda53e05 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/client-test.cpp @@ -0,0 +1,39 @@ +/* + * 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 HTTP client functions. + */ + +#include "stream.hpp" +#include "string.hpp" +#include "../server/client-test.hpp" + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + tuscany::server::testURI = "http://localhost:8090/python"; + + tuscany::server::testServer(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/client-test.py b/sandbox/sebastien/cpp/apr-2/modules/python/client-test.py new file mode 100644 index 0000000000..3c7183e865 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/client-test.py @@ -0,0 +1,40 @@ +# 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. + +import unittest + +# JSON-RPC test case + +def echo(x, ref): + e1 = ref("echo", x) + e2 = ref.echo(x) + assert e1 == e2 + return e1 + +# ATOMPub test case + +def get(id, ref): + return ref.get(id); + +def post(collection, item, ref): + return ref.post(collection, item) + +def put(id, item, ref): + return ref.put(id, item) + +def delete(id, ref): + return ref.delete(id) diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/domain-test.composite b/sandbox/sebastien/cpp/apr-2/modules/python/domain-test.composite new file mode 100644 index 0000000000..c8e92b286e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/domain-test.composite @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * 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. +--> +<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912" + xmlns:t="http://tuscany.apache.org/xmlns/sca/1.1" + targetNamespace="http://domain/test" + name="domain-test"> + + <component name="python-test"> + <t:implementation.python script="server-test.py"/> + <service name="test"> + <t:binding.http uri="python"/> + </service> + </component> + + <component name="client-test"> + <t:implementation.python script="client-test.py"/> + <service name="client"> + <t:binding.http uri="client"/> + </service> + <reference name="ref" target="python-test"> + <t:binding.http/> + </reference> + </component> + +</composite> diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/driver.hpp b/sandbox/sebastien/cpp/apr-2/modules/python/driver.hpp new file mode 100644 index 0000000000..79897b0c5e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/driver.hpp @@ -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. + */ + +/* $Rev$ $Date$ */ + +#ifndef tuscany_python_driver_hpp +#define tuscany_python_driver_hpp + +/** + * Python evaluator main driver loop. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "monad.hpp" +#include "../scheme/driver.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace python { + +const value evalDriverLoop(PyObject* script, istream& in, ostream& out) { + scheme::promptForInput(scheme::evalInputPrompt, out); + value input = scheme::readValue(in); + if (isNil(input)) + return input; + const failable<value> output = evalScript(input, script); + scheme::announceOutput(scheme::evalOutputPrompt, out); + scheme::userPrint(content(output), out); + return evalDriverLoop(script, in, out); +} + +const bool evalDriverRun(const char* path, istream& in, ostream& out) { + PythonRuntime py; + scheme::setupDisplay(out); + ifstream is(path); + failable<PyObject*> script = readScript(moduleName(path), path, is); + if (!hasContent(script)) + return true; + evalDriverLoop(content(script), in, out); + Py_DECREF(content(script)); + return true; +} + +} +} +#endif /* tuscany_python_driver_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/eval.hpp b/sandbox/sebastien/cpp/apr-2/modules/python/eval.hpp new file mode 100644 index 0000000000..2dd4b8ba33 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/eval.hpp @@ -0,0 +1,351 @@ +/* + * 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_python_eval_hpp +#define tuscany_python_eval_hpp + +/** + * Python script evaluation logic. + */ +#include <python2.6/Python.h> + +#include "list.hpp" +#include "value.hpp" + +namespace tuscany { +namespace python { + +/** + * Represent a Python runtime. + */ +class PythonRuntime { +public: + PythonRuntime() { + if (Py_IsInitialized()) + return; + Py_InitializeEx(0); + const char* arg0 = ""; + PySys_SetArgv(0, const_cast<char**>(&arg0)); + } +}; + +/** + * Return the last python error. + */ +const string lastError() { + if(PyErr_Occurred()) { + PyObject* type; + PyObject* val; + PyObject* trace; + PyErr_Fetch(&type, &val, &trace); + if (type != NULL && val != NULL) { + PyObject* stype = PyObject_Str(type); + PyObject* sval = PyObject_Str(val); + string msg = string() + PyString_AsString(stype) + " : " + PyString_AsString(sval); + Py_DECREF(stype); + Py_DECREF(sval); + Py_DECREF(type); + Py_DECREF(val); + Py_XDECREF(trace); + PyErr_Print(); + return msg; + } + PyErr_Print(); + Py_XDECREF(type); + Py_XDECREF(val); + Py_XDECREF(trace); + PyErr_Print(); + return "Unknown Python error"; + } + return ""; +} + +/** + * Declare conversion functions. + */ +PyObject* valueToPyObject(const value& v); +const value pyObjectToValue(PyObject *o); +PyObject* valuesToPyTuple(const list<value>& v); +const list<value> pyTupleToValues(PyObject* o); + +/** + * Callable python type used to represent a lambda expression. + */ +typedef struct { + PyObject_HEAD + lambda<value(const list<value>&)> func; +} pyLambda; + +PyObject *mkPyLambda(const lambda<value(const list<value>&)>& l); + +void pyLambda_dealloc(PyObject* self) { + PyMem_DEL(self); +} + +const string pyRepr(PyObject * o) { + return PyString_AsString(PyObject_Repr(o)); +} + +PyObject* pyLambda_call(PyObject* self, PyObject* args, unused PyObject* kwds) { + debug("python::call"); + const pyLambda* pyl = (pyLambda*)self; + const value result = pyl->func(pyTupleToValues(args)); + debug(result, "python::call::result"); + Py_DECREF(args); + PyObject *pyr = valueToPyObject(result); + Py_INCREF(pyr); + return pyr; +} + +struct pyProxy { + const value name; + const lambda<value(const list<value>&)> func; + + pyProxy(const value& name, const lambda<value(const list<value>&)>& func) : name(name), func(func) { + } + + const value operator()(const list<value>& args) const { + debug(name, "python::proxy::name"); + const value result = func(cons<value>(name, args)); + debug(result, "python::proxy::result"); + return result; + } +}; + +PyObject* pyLambda_getattr(PyObject *self, PyObject *attrname) { + const string name = PyString_AsString(attrname); + if (substr(name, 0, 1) == "_") + return PyObject_GenericGetAttr(self, attrname); + + if (name == "eval") { + Py_INCREF(self); + return self; + } + + const pyLambda* pyl = (pyLambda*)self; + debug(name, "python::getattr::name"); + PyObject* pyr = mkPyLambda(pyProxy(name, pyl->func)); + Py_INCREF(pyr); + return pyr; +} + +PyTypeObject pyLambda_type = { + PyObject_HEAD_INIT(0) + 0, + "lambda", + sizeof(pyLambda), + 0, + (destructor)pyLambda_dealloc, + 0, 0, 0, 0, 0, 0, 0, 0, 0, + (ternaryfunc)pyLambda_call, + 0, + (binaryfunc)pyLambda_getattr, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0 +}; + +/** + * Create a new python object representing a lambda expression. + */ +PyObject *mkPyLambda(const lambda<value(const list<value>&)>& l) { + pyLambda* pyl = NULL; + pyl = PyObject_NEW(pyLambda, &pyLambda_type); + if (pyl != NULL) + pyl->func = l; + return (PyObject *)pyl; +} + +/** + * Convert a list of values to a python list. + */ +PyObject* valuesToPyListHelper(PyObject* l, const list<value>& v) { + if (isNil(v)) + return l; + PyList_Append(l, valueToPyObject(car(v))); + return valuesToPyListHelper(l, cdr(v)); +} + +PyObject* valuesToPyTuple(const list<value>& v) { + return PyList_AsTuple(valuesToPyListHelper(PyList_New(0), v)); +} + +/** + * Convert a value to a python object. + */ +PyObject* valueToPyObject(const value& v) { + switch (type(v)) { + case value::List: + return valuesToPyTuple(v); + case value::Lambda: + return mkPyLambda(v); + case value::Symbol: + return PyString_FromString(c_str(string("'") + v)); + case value::String: + return PyString_FromString(c_str(v)); + case value::Number: + return PyFloat_FromDouble((double)v); + case value::Bool: + return (bool)v? Py_True : Py_False; + default: + return Py_None; + } +} + +/** + * Convert a python tuple to a list of values. + */ + +const list<value> pyTupleToValuesHelper(PyObject* o, const size_t i, const size_t size) { + if (i == size) + return list<value>(); + return cons(pyObjectToValue(PyTuple_GetItem(o, i)), pyTupleToValuesHelper(o, i + 1, size)); +} + +const list<value> pyTupleToValues(PyObject* o) { + return pyTupleToValuesHelper(o, 0, PyTuple_Size(o)); +} + +/** + * Lambda function used to represent a python callable object. + */ +struct pyCallable { + PyObject* func; + + pyCallable(PyObject* func) : func(func) { + Py_INCREF(func); + } + + ~pyCallable() { + Py_DECREF(func); + } + + const value operator()(const list<value>& args) const { + PyObject* pyargs = valuesToPyTuple(args); + PyObject* result = PyObject_CallObject(func, pyargs); + Py_DECREF(pyargs); + const value v = pyObjectToValue(result); + Py_DECREF(result); + return v; + } +}; + +/** + * Convert a python object to a value. + */ +const value pyObjectToValue(PyObject *o) { + if (PyString_Check(o)) { + const char* s = PyString_AsString(o); + if (*s == '\'') + return value(s + 1); + return value(string(s)); + } + if (PyBool_Check(o)) + return value(o == Py_True); + if (PyInt_Check(o)) + return value((double)PyInt_AsLong(o)); + if (PyLong_Check(o)) + return value((double)PyLong_AsLong(o)); + if (PyFloat_Check(o)) + return value((double)PyFloat_AsDouble(o)); + if (PyTuple_Check(o)) + return pyTupleToValues(o); + if (PyCallable_Check(o)) + return lambda<value(const list<value>&)>(pyCallable(o)); + return value(); +} + +/** + * Convert a python script path to a module name. + */ +const string moduleName(const string& path) { + return join(".", tokenize("/", substr(path, 0, length(path) -3))); +} + +/** + * Evaluate an expression against a script provided as a python object. + */ +const failable<value> evalScript(const value& expr, PyObject* script) { + + // Get the requested function + PyObject* func = PyObject_GetAttrString(script, c_str(car<value>(expr))); + if (func == NULL) { + + // The start, stop, and restart functions are optional + const value fn = car<value>(expr); + if (fn == "start" || fn == "stop") { + PyErr_Clear(); + return value(lambda<value(const list<value>&)>()); + } + + return mkfailure<value>(string("Couldn't find function: ") + car<value>(expr) + " : " + lastError()); + } + if (!PyCallable_Check(func)) { + Py_DECREF(func); + return mkfailure<value>(string("Couldn't find callable function: ") + car<value>(expr)); + } + + // Convert args to python objects + PyObject* args = valuesToPyTuple(cdr<value>(expr)); + + // Call the function + PyObject* result = PyObject_CallObject(func, args); + Py_DECREF(args); + Py_DECREF(func); + if (result == NULL) + return mkfailure<value>(string("Function call failed: ") + car<value>(expr) + " : " + lastError()); + + // Convert python result to a value + const value v = pyObjectToValue(result); + Py_DECREF(result); + return v; +} + +/** + * Read a python script from an input stream. + */ +const failable<PyObject*> readScript(const string& name, const string& path, istream& is) { + const list<string> ls = streamList(is); + ostringstream os; + write(ls, os); + PyObject* code = Py_CompileStringFlags(c_str(str(os)), c_str(path), Py_file_input, NULL); + if (code == NULL) + return mkfailure<PyObject*>(string("Couldn't compile script: ") + path + " : " + lastError()); + PyObject* mod = PyImport_ExecCodeModuleEx(const_cast<char*>(c_str(name)), code, const_cast<char*>(c_str(path))); + if (mod == NULL) + return mkfailure<PyObject*>(string("Couldn't import module: ") + path + " : " + lastError()); + return mod; +} + +/** + * Evaluate an expression against a script provided as an input stream. + */ +const failable<value> evalScript(const value& expr, istream& is) { + failable<PyObject*> script = readScript("script", "script.py", is); + if (!hasContent(script)) + return mkfailure<value>(reason(script)); + return evalScript(expr, content(script)); +} + +} +} +#endif /* tuscany_python_eval_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/mod-python.cpp b/sandbox/sebastien/cpp/apr-2/modules/python/mod-python.cpp new file mode 100644 index 0000000000..8561a1fbf4 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/mod-python.cpp @@ -0,0 +1,66 @@ +/* + * 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$ */ + +/** + * HTTPD module used to eval Python component implementations. + */ + +#include "string.hpp" +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "../server/mod-cpp.hpp" +#include "../server/mod-eval.hpp" +#include "mod-python.hpp" + +namespace tuscany { +namespace server { +namespace modeval { + +/** + * Apply a lifecycle start or restart event. + */ +const value applyLifecycle(unused const list<value>& params) { + + // Create a Python runtime + new (gc_new<python::PythonRuntime>()) python::PythonRuntime(); + + // Return a nil function as we don't need to handle the stop event + return failable<value>(lambda<value(const list<value>&)>()); +} + +/** + * Evaluate a Python component implementation and convert it to an applicable + * lambda function. + */ +const failable<lambda<value(const list<value>&)> > evalImplementation(const string& path, const value& impl, const list<value>& px, unused const lambda<value(const list<value>&)>& lifecycle) { + const string itype(elementName(impl)); + if (contains(itype, ".python")) + return modpython::evalImplementation(path, impl, px); + if (contains(itype, ".cpp")) + return modcpp::evalImplementation(path, impl, px); + return mkfailure<lambda<value(const list<value>&)> >(string("Unsupported implementation type: ") + itype); +} + +} +} +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/mod-python.hpp b/sandbox/sebastien/cpp/apr-2/modules/python/mod-python.hpp new file mode 100644 index 0000000000..0121779530 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/mod-python.hpp @@ -0,0 +1,80 @@ +/* + * 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_modpython_hpp +#define tuscany_modpython_hpp + +/** + * Evaluation functions used by mod-eval to evaluate Python + * component implementations. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace server { +namespace modpython { + +/** + * Apply a Python component implementation function. + */ +struct applyImplementation { + PyObject* impl; + const list<value> px; + applyImplementation(PyObject* impl, const list<value>& px) : impl(impl), px(px) { + } + const value operator()(const list<value>& params) const { + const value expr = append<value>(params, px); + debug(expr, "modeval::python::applyImplementation::input"); + const failable<value> res = python::evalScript(expr, impl); + const value val = !hasContent(res)? mklist<value>(value(), reason(res)) : mklist<value>(content(res)); + debug(val, "modeval::python::applyImplementation::result"); + return val; + } +}; + +/** + * Evaluate a Python component implementation and convert it to an applicable + * lambda function. + */ +const failable<lambda<value(const list<value>&)> > evalImplementation(const string& path, const value& impl, const list<value>& px) { + const string spath(attributeValue("script", impl)); + const string fpath(path + spath); + ifstream is(fpath); + if (fail(is)) + return mkfailure<lambda<value(const list<value>&)> >(string("Could not read implementation: ") + fpath); + const failable<PyObject*> script = python::readScript(python::moduleName(spath), fpath, is); + if (!hasContent(script)) + return mkfailure<lambda<value(const list<value>&)> >(reason(script)); + return lambda<value(const list<value>&)>(applyImplementation(content(script), px)); +} + +} +} +} + +#endif /* tuscany_modpython_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/python-conf b/sandbox/sebastien/cpp/apr-2/modules/python/python-conf new file mode 100755 index 0000000000..a5b45357fc --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/python-conf @@ -0,0 +1,30 @@ +#!/bin/sh + +# 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. + +# Generate a Python server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +cat >>$root/conf/modules.conf <<EOF +# Generated by: python-conf $* +# Support for Python SCA components +LoadModule mod_tuscany_eval $here/libmod_tuscany_python.so + +EOF diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/python-shell.cpp b/sandbox/sebastien/cpp/apr-2/modules/python/python-shell.cpp new file mode 100644 index 0000000000..89b47b8d44 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/python-shell.cpp @@ -0,0 +1,40 @@ +/* + * 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$ */ + +/** + * Python script evaluator shell, used for interactive testing of scripts. + */ + +#include <assert.h> +#include "gc.hpp" +#include "stream.hpp" +#include "string.hpp" +#include "driver.hpp" + +int main(const int argc, char** argv) { + tuscany::gc_scoped_pool pool; + if (argc != 2) { + tuscany::cerr << "Usage: python-shell <script.py>" << tuscany::endl; + return 1; + } + tuscany::python::evalDriverRun(argv[1], tuscany::cin, tuscany::cout); + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/python-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/python/python-test.cpp new file mode 100644 index 0000000000..41889e6d0e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/python-test.cpp @@ -0,0 +1,109 @@ +/* + * 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 Python script evaluator. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "driver.hpp" + +namespace tuscany { +namespace python { + +const string testPythonAdd = + "def add(x, y):\n" + " return x + y\n"; + +bool testEvalExpr() { + gc_scoped_pool pool; + PythonRuntime py; + + istringstream is(testPythonAdd); + failable<PyObject*> script = readScript("script", "script.py", is); + assert(hasContent(script)); + + const value exp = mklist<value>("add", 2, 3); + const failable<value> r = evalScript(exp, content(script)); + assert(hasContent(r)); + assert(content(r) == value(5)); + + return true; +} + +const value mult(const list<value>& args) { + const double x = car(args); + const double y = cadr(args); + return x * y; +} + +const string testReturnLambda( + "def mul(x, y):\n" + " return x * y\n" + "\n" + "def testReturnLambda():\n" + " return mul\n"); + +const string testCallLambda( + "def testCallLambda(l, x, y):\n" + " return l(x, y)\n"); + +bool testEvalLambda() { + gc_scoped_pool pool; + PythonRuntime py; + + const value trl = mklist<value>("testReturnLambda"); + istringstream trlis(testReturnLambda); + const failable<value> trlv = evalScript(trl, trlis); + + assert(hasContent(trlv)); + assert(isLambda(content(trlv))); + const lambda<value(const list<value>&)> trll(content(trlv)); + assert(trll(mklist<value>(2, 3)) == value(6)); + + istringstream tclis(testCallLambda); + const value tcl = mklist<value>("testCallLambda", content(trlv), 2, 3); + const failable<value> tclv = evalScript(tcl, tclis); + assert(hasContent(tclv)); + assert(content(tclv) == value(6)); + + istringstream tcelis(testCallLambda); + const value tcel = mklist<value>("testCallLambda", lambda<value(const list<value>&)>(mult), 3, 4); + const failable<value> tcelv = evalScript(tcel, tcelis); + assert(hasContent(tcelv)); + assert(content(tcelv) == value(12)); + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::python::testEvalExpr(); + tuscany::python::testEvalLambda(); + + tuscany::cout << "OK" << tuscany::endl; + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/server-test b/sandbox/sebastien/cpp/apr-2/modules/python/server-test new file mode 100755 index 0000000000..b01f5f501d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/server-test @@ -0,0 +1,39 @@ +#!/bin/sh + +# 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. + +# Setup +../http/httpd-conf tmp localhost 8090 ../server/htdocs +../server/server-conf tmp +./python-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite domain-test.composite +EOF + +../http/httpd-start tmp +sleep 2 + +# Test +./client-test 2>/dev/null +rc=$? + +# Cleanup +../http/httpd-stop tmp +sleep 2 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/server-test.py b/sandbox/sebastien/cpp/apr-2/modules/python/server-test.py new file mode 100644 index 0000000000..29404c3753 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/server-test.py @@ -0,0 +1,42 @@ +# 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. + +# JSON-RPC test case + +def echo(x): + return x + +# ATOMPub test case + +def get(id): + if id == (): + return ("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)))) + + entry = (("'name", "Apple"), ("'currencyCode", "USD"), ("'currencySymbol", "$"), ("'price", 2.99)) + return ("Item", id[0], entry) + +def post(collection, item): + return ("123456789",) + +def put(id, item): + return True + +def delete(id): + return True diff --git a/sandbox/sebastien/cpp/apr-2/modules/python/wiring-test b/sandbox/sebastien/cpp/apr-2/modules/python/wiring-test new file mode 100755 index 0000000000..c571981bbd --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/python/wiring-test @@ -0,0 +1,78 @@ +#!/bin/sh + +# 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. + +echo "Testing..." +here=`readlink -f $0`; here=`dirname $here` +curl_prefix=`cat $here/../http/curl.prefix` + +# Setup +../http/httpd-conf tmp localhost 8090 ../server/htdocs +../server/server-conf tmp +./python-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite domain-test.composite +EOF + +../http/httpd-start tmp +sleep 2 + +# Test HTTP GET +$curl_prefix/bin/curl http://localhost:8090/index.html 2>/dev/null >tmp/index.html +diff tmp/index.html ../server/htdocs/index.html +rc=$? + +# Test ATOMPub +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ >tmp/feed.xml 2>/dev/null + diff tmp/feed.xml ../server/htdocs/test/feed.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 >tmp/entry.xml 2>/dev/null + diff tmp/entry.xml ../server/htdocs/test/entry.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ -X POST -H "Content-type: application/atom+xml" --data @../server/htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 -X PUT -H "Content-type: application/atom+xml" --data @../server/htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 -X DELETE 2>/dev/null + rc=$? +fi + +# Test JSON-RPC +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ -X POST -H "Content-type: application/json-rpc" --data @../server/htdocs/test/json-request.txt >tmp/json-result.txt 2>/dev/null + diff tmp/json-result.txt ../server/htdocs/test/json-result.txt + rc=$? +fi + +# Cleanup +../http/httpd-stop tmp +sleep 2 +if [ "$rc" = "0" ]; then + echo "OK" +fi +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/rss/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/rss/Makefile.am new file mode 100644 index 0000000000..06a67f3c3f --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/rss/Makefile.am @@ -0,0 +1,25 @@ +# 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/rss + +rss_test_SOURCES = rss-test.cpp +rss_test_LDFLAGS = -lxml2 + +noinst_PROGRAMS = rss-test +TESTS = rss-test diff --git a/sandbox/sebastien/cpp/apr-2/modules/rss/rss-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/rss/rss-test.cpp new file mode 100644 index 0000000000..9bfd620835 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/rss/rss-test.cpp @@ -0,0 +1,214 @@ +/* + * 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 RSS data conversion functions. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "rss.hpp" + +namespace tuscany { +namespace rss { + +ostream* writer(const string& s, ostream* os) { + (*os) << s; + return os; +} + +string itemEntry("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<item>" + "<title>fruit</title>" + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</link>" + "<description>" + "<item>" + "<name>Apple</name><price>$2.99</price>" + "</item>" + "</description>" + "</item>\n"); + +string itemTextEntry("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<item>" + "<title>fruit</title>" + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</link>" + "<description>Apple</description>" + "</item>\n"); + +string incompleteEntry("<item>" + "<title>fruit</title><description>" + "<Item xmlns=\"http://services/\">" + "<name xmlns=\"\">Orange</name>" + "<price xmlns=\"\">3.55</price>" + "</Item>" + "</description>" + "</item>"); + +string completedEntry("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<item>" + "<title>fruit</title>" + "<link></link>" + "<description>" + "<Item xmlns=\"http://services/\">" + "<name xmlns=\"\">Orange</name>" + "<price xmlns=\"\">3.55</price>" + "</Item>" + "</description>" + "</item>\n"); + +bool testEntry() { + { + const list<value> i = list<value>() + element + value("item") + + value(list<value>() + element + value("name") + value(string("Apple"))) + + value(list<value>() + element + value("price") + value(string("$2.99"))); + const list<value> a = mklist<value>(string("fruit"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + ostringstream os; + writeRSSEntry<ostream*>(writer, &os, a); + assert(str(os) == itemEntry); + } + { + const list<value> a = mklist<value>(string("fruit"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), "Apple"); + ostringstream os; + writeRSSEntry<ostream*>(writer, &os, a); + assert(str(os) == itemTextEntry); + } + { + const list<value> a = content(readRSSEntry(mklist(itemEntry))); + ostringstream os; + writeRSSEntry<ostream*>(writer, &os, a); + assert(str(os) == itemEntry); + } + { + const list<value> a = content(readRSSEntry(mklist(itemTextEntry))); + ostringstream os; + writeRSSEntry<ostream*>(writer, &os, a); + assert(str(os) == itemTextEntry); + } + { + const list<value> a = content(readRSSEntry(mklist(incompleteEntry))); + ostringstream os; + writeRSSEntry<ostream*>(writer, &os, a); + assert(str(os) == completedEntry); + } + return true; +} + +string emptyFeed("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<rss version=\"2.0\">" + "<channel>" + "<title>Feed</title>" + "<link>1234</link>" + "<description>Feed</description>" + "</channel>" + "</rss>\n"); + +string itemFeed("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + "<rss version=\"2.0\">" + "<channel>" + "<title>Feed</title>" + "<link>1234</link>" + "<description>Feed</description>" + "<item>" + "<title>fruit</title>" + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</link>" + "<description>" + "<item>" + "<name>Apple</name><price>$2.99</price>" + "</item>" + "</description>" + "</item>" + "<item>" + "<title>fruit</title>" + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c</link>" + "<description>" + "<item>" + "<name>Orange</name><price>$3.55</price>" + "</item>" + "</description>" + "</item>" + "</channel>" + "</rss>\n"); + +bool testFeed() { + { + ostringstream os; + writeRSSFeed<ostream*>(writer, &os, mklist<value>("Feed", "1234")); + assert(str(os) == emptyFeed); + } + { + const list<value> a = content(readRSSFeed(mklist(emptyFeed))); + ostringstream os; + writeRSSFeed<ostream*>(writer, &os, a); + assert(str(os) == emptyFeed); + } + { + const list<value> i = list<value>() + + (list<value>() + "fruit" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b" + + (list<value>() + element + "item" + + (list<value>() + element + "name" + "Apple") + + (list<value>() + element + "price" + "$2.99"))) + + (list<value>() + "fruit" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c" + + (list<value>() + element + "item" + + (list<value>() + element + "name" + "Orange") + + (list<value>() + element + "price" + "$3.55"))); + const list<value> a = cons<value>("Feed", cons<value>("1234", i)); + ostringstream os; + writeRSSFeed<ostream*>(writer, &os, a); + assert(str(os) == itemFeed); + } + { + const list<value> i = list<value>() + + (list<value>() + "fruit" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b" + + valueToElement(list<value>() + "item" + + (list<value>() + "name" + "Apple") + + (list<value>() + "price" + "$2.99"))) + + (list<value>() + "fruit" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c" + + valueToElement(list<value>() + "item" + + (list<value>() + "name" + "Orange") + + (list<value>() + "price" + "$3.55"))); + const list<value> a = cons<value>("Feed", cons<value>("1234", i)); + ostringstream os; + writeRSSFeed<ostream*>(writer, &os, a); + assert(str(os) == itemFeed); + } + { + const list<value> a = content(readRSSFeed(mklist(itemFeed))); + ostringstream os; + writeRSSFeed<ostream*>(writer, &os, a); + assert(str(os) == itemFeed); + } + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::rss::testEntry(); + tuscany::rss::testFeed(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/rss/rss.hpp b/sandbox/sebastien/cpp/apr-2/modules/rss/rss.hpp new file mode 100644 index 0000000000..506d1f4a6d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/rss/rss.hpp @@ -0,0 +1,201 @@ +/* + * 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_rss_hpp +#define tuscany_rss_hpp + +/** + * RSS data conversion functions. + */ + +#include "string.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "xml.hpp" + +namespace tuscany { +namespace rss { + +/** + * Convert a list of elements to a list of values representing an RSS entry. + */ +const list<value> entryElementsToValues(const list<value>& e) { + const list<value> lt = filter<value>(selector(mklist<value>(element, "title")), e); + const value t = isNil(lt)? value(emptyString) : elementValue(car(lt)); + const list<value> li = filter<value>(selector(mklist<value>(element, "link")), e); + const value i = isNil(li)? value(emptyString) : elementValue(car(li)); + const list<value> ld = filter<value>(selector(mklist<value>(element, "description")), e); + return mklist<value>(t, i, elementValue(car(ld))); +} + +/** + * Convert a list of elements to a list of values representing RSS entries. + */ +const list<value> entriesElementsToValues(const list<value>& e) { + if (isNil(e)) + return e; + return cons<value>(entryElementsToValues(car(e)), entriesElementsToValues(cdr(e))); +} + +/** + * Return true if a list of strings contains an RSS feed. + */ +const bool isRSSFeed(const list<string>& ls) { + if (!isXML(ls)) + return false; + return contains(car(ls), "<rss"); +} + +/** + * Convert a list of strings to a list of values representing an RSS entry. + */ +const failable<list<value> > readRSSEntry(const list<string>& ilist) { + const list<value> e = readXML(ilist); + if (isNil(e)) + return mkfailure<list<value> >("Empty entry"); + return entryElementsToValues(car(e)); +} + +/** + * Convert a list of values representing an RSS entry to a value. + */ +const value entryValue(const list<value>& e) { + const list<value> v = elementsToValues(mklist<value>(caddr(e))); + return cons(car(e), mklist<value>(cadr(e), isList(car(v))? (value)cdr<value>(car(v)) : car(v))); +} + +/** + * Convert a list of strings to a list of values representing an RSS feed. + */ +const failable<list<value> > readRSSFeed(const list<string>& ilist) { + const list<value> f = readXML(ilist); + if (isNil(f)) + return mkfailure<list<value> >("Empty feed"); + const list<value> c = filter<value>(selector(mklist<value>(element, "channel")), car(f)); + const list<value> t = filter<value>(selector(mklist<value>(element, "title")), car(c)); + const list<value> i = filter<value>(selector(mklist<value>(element, "link")), car(c)); + const list<value> e = filter<value>(selector(mklist<value>(element, "item")), car(c)); + if (isNil(e)) + return mklist<value>(elementValue(car(t)), elementValue(car(i))); + return cons<value>(elementValue(car(t)), cons(elementValue(car(i)), entriesElementsToValues(e))); +} + +/** + * Convert an RSS feed containing elements to an RSS feed containing values. + */ +const list<value> feedValuesLoop(const list<value> e) { + if (isNil(e)) + return e; + return cons<value>(entryValue(car(e)), feedValuesLoop(cdr(e))); +} + +const list<value> feedValues(const list<value>& e) { + return cons(car<value>(e), cons<value>(cadr<value>(e), feedValuesLoop(cddr<value>(e)))); +} + +/** + * Convert a list of values representing an RSS entry to a list of elements. + * The first two values in the list are the entry title and id. + */ +const list<value> entryElement(const list<value>& l) { + return list<value>() + + element + "item" + + (list<value>() + element + "title" + car(l)) + + (list<value>() + element + "link" + cadr(l)) + + (list<value>() + element + "description" + caddr(l)); +} + +/** + * Convert a list of values representing RSS entries to a list of elements. + */ +const list<value> entriesElements(const list<value>& l) { + if (isNil(l)) + return l; + return cons<value>(entryElement(car(l)), entriesElements(cdr(l))); +} + +/** + * Convert a list of values representing an RSS entry to an RSS entry. + * The first two values in the list are the entry id and title. + */ +template<typename R> const failable<R> writeRSSEntry(const lambda<R(const string&, const R)>& reduce, const R& initial, const list<value>& l) { + return writeXML<R>(reduce, initial, mklist<value>(entryElement(l))); +} + +const failable<list<string> > writeRSSEntry(const list<value>& l) { + const failable<list<string> > ls = writeRSSEntry<list<string> >(rcons<string>, list<string>(), l); + if (!hasContent(ls)) + return ls; + return reverse(list<string>(content(ls))); +} + +/** + * Convert a list of values representing an RSS feed to an RSS feed. + * The first two values in the list are the feed id and title. + */ +template<typename R> const failable<R> writeRSSFeed(const lambda<R(const string&, const R)>& reduce, const R& initial, const list<value>& l) { + const list<value> c = list<value>() + + (list<value>() + element + "title" + car(l)) + + (list<value>() + element + "link" + cadr(l)) + + (list<value>() + element + "description" + car(l)); + const list<value> ce = isNil(cddr(l))? c : append(c, entriesElements(cddr(l))); + const list<value> fe = list<value>() + + element + "rss" + (list<value>() + attribute + "version" + "2.0") + + append(list<value>() + element + "channel", ce); + return writeXML<R>(reduce, initial, mklist<value>(fe)); +} + +/** + * Convert a list of values representing an RSS feed to a list of strings. + * The first two values in the list are the feed id and title. + */ +const failable<list<string> > writeRSSFeed(const list<value>& l) { + const failable<list<string> > ls = writeRSSFeed<list<string>>(rcons<string>, list<string>(), l); + if (!hasContent(ls)) + return ls; + return reverse(list<string>(content(ls))); +} + +/** + * Convert an RSS entry containing a value to an RSS entry containing an item element. + */ +const list<value> entryValuesToElements(const list<value> val) { + return cons(car(val), cons(cadr(val), valuesToElements(mklist<value>(cons<value>("item", (list<value>)caddr(val)))))); +} + +/** + * Convert an RSS feed containing values to an RSS feed containing elements. + */ +const list<value> feedValuesToElementsLoop(const list<value> val) { + if (isNil(val)) + return val; + return cons<value>(entryValuesToElements(car(val)), feedValuesToElementsLoop(cdr(val))); +} + +const list<value> feedValuesToElements(const list<value>& val) { + return cons(car<value>(val), cons<value>(cadr<value>(val), feedValuesToElementsLoop(cddr<value>(val)))); +} + +} +} + +#endif /* tuscany_rss_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/scdl/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/scdl/Makefile.am new file mode 100644 index 0000000000..09cbd35ec0 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scdl/Makefile.am @@ -0,0 +1,27 @@ +# 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/scdl + +scdl_test_SOURCES = scdl-test.cpp +scdl_test_LDFLAGS = -lxml2 + +EXTRA_DIST = test.composite + +noinst_PROGRAMS = scdl-test +TESTS = scdl-test validate-test diff --git a/sandbox/sebastien/cpp/apr-2/modules/scdl/scdl-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/scdl/scdl-test.cpp new file mode 100644 index 0000000000..e8ee77eb4e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scdl/scdl-test.cpp @@ -0,0 +1,124 @@ +/* + * 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 SCDL read functions. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "scdl.hpp" + +namespace tuscany { +namespace scdl { + +bool testComposite() { + ifstream is("test.composite"); + const list<value> c = readXML(streamList(is)); + return true; +} + +bool testComponents() { + ifstream is("test.composite"); + const list<value> c = components(readXML(streamList(is))); + assert(length(c) == 4); + + const value store = car(c); + assert(name(store) == string("Store")); + const value impl = implementation(store); + assert(uri(impl) == string("store.html")); + assert(implementationType(impl) == "t:implementation.scheme"); + + const value catalog = named(string("Catalog"), c); + assert(name(catalog) == string("Catalog")); + + const list<value> t = mkbtree(sort(nameToElementAssoc(c))); + assert(assoctree<value>("Catalog", t) == mklist<value>("Catalog" , cadr(c))); + return true; +} + +bool testServices() { + ifstream is("test.composite"); + const list<value> c = components(readXML(streamList(is))); + const value store = car(c); + + assert(length(services(store)) == 1); + const value widget = car(services(store)); + assert(name(widget) == string("Widget")); + + assert(length(bindings(widget)) == 1); + const value binding = car(bindings(widget)); + assert(uri(binding) == string("/store")); + assert(bindingType(binding) == "t:binding.http"); + return true; +} + +bool testReferences() { + ifstream is("test.composite"); + const list<value> c = components(readXML(streamList(is))); + const value store = car(c); + + assert(length(references(store)) == 3); + const value catalog = car(references(store)); + assert(name(catalog) == string("catalog")); + assert(target(catalog) == string("Catalog")); + + assert(length(bindings(catalog)) == 1); + const value binding = car(bindings(catalog)); + assert(uri(binding) == value()); + assert(bindingType(binding) == "t:binding.jsonrpc"); + + const list<value> t = mkbtree(sort(referenceToTargetAssoc(references(store)))); + assert(assoctree<value>("shoppingCart", t) == mklist<value>(string("shoppingCart"), string("ShoppingCart/Cart"))); + return true; +} + +bool testProperties() { + ifstream is("test.composite"); + const list<value> c = components(readXML(streamList(is))); + const value catalog = named(string("Catalog"), c); + + assert(length(properties(catalog)) == 1); + const value currencyCode = car(properties(catalog)); + assert(name(currencyCode) == string("currencyCode")); + assert(propertyValue(currencyCode) == string("USD")); + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::scdl::testComposite(); + tuscany::scdl::testComponents(); + tuscany::scdl::testServices(); + tuscany::scdl::testReferences(); + tuscany::scdl::testProperties(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/scdl/scdl.hpp b/sandbox/sebastien/cpp/apr-2/modules/scdl/scdl.hpp new file mode 100644 index 0000000000..0f008dc3a8 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scdl/scdl.hpp @@ -0,0 +1,190 @@ +/* + * 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_scdl_hpp +#define tuscany_scdl_hpp + +/** + * SCDL read functions. + */ + +#include "string.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "xml.hpp" + +namespace tuscany { +namespace scdl { + +/** + * Returns a list of components in a composite. + */ +const list<value> components(const value& l) { + const list<value> cs = elementChildren("composite", l); + if (isNil(cs)) + return cs; + return elementChildren("component", car(cs)); +} + +/** + * Returns the name of a component, service or reference. + */ +const value name(const value& l) { + return attributeValue("name", l); +} + +/** + * Convert a list of elements to a name -> element assoc list. + */ +const list<value> nameToElementAssoc(const list<value>& l) { + if (isNil(l)) + return l; + const value e(car(l)); + return cons<value>(mklist<value>(name(e), e), nameToElementAssoc(cdr(l))); +} + +/** + * Returns the scdl declaration with the given name. + */ +struct filterName { + const value n; + filterName(const value& n) : n(n) { + } + const bool operator()(const value& v) const { + return name(v) == n; + } +}; + +const value named(const value& name, const value& l) { + const list<value> c = filter<value>(filterName(name), l); + if (isNil(c)) + return value(); + return car(c); +} + +/** + * Returns the implementation of a component. + */ +const bool filterImplementation(const value& v) { + return isElement(v) && contains(string(cadr<value>(v)), "implementation."); +} + +const value implementation(const value& l) { + const list<value> n = filter<value>(filterImplementation, l); + if (isNil(n)) + return value(); + return car(n); +} + +/** + * Returns the URI of a service, reference or implementation. + */ +const value uri(const value& l) { + return attributeValue("uri", l); +} + +/** + * Returns a list of services in a component. + */ +const list<value> services(const value& l) { + return elementChildren("service", l); +} + +/** + * Returns a list of references in a component. + */ +const list<value> references(const value& l) { + return elementChildren("reference", l); +} + +/** + * Returns a list of bindings in a service or reference. + */ +const bool filterBinding(const value& v) { + return isElement(v) && contains(string(cadr<value>(v)), "binding."); +} + +const list<value> bindings(const value& l) { + return filter<value>(filterBinding, l); +} + +/** + * Returns the target of a reference. + */ +const value bindingsTarget(const list<value>& l) { + if (isNil(l)) + return value(); + const value u = uri(car(l)); + if (!isNil(u)) + return u; + return bindingsTarget(cdr(l)); +} + +const value target(const value& l) { + const value target = attributeValue("target", l); + if (!isNil(target)) + return target; + return bindingsTarget(bindings(l)); +} + +/** + * Convert a list of references to a reference name -> target assoc list. + */ +const list<value> referenceToTargetAssoc(const list<value>& r) { + if (isNil(r)) + return r; + const value ref(car(r)); + return cons<value>(mklist<value>(scdl::name(ref), scdl::target(ref)), referenceToTargetAssoc(cdr(r))); +} + +/** + * Returns a list of properties in a component. + */ +const list<value> properties(const value& l) { + return elementChildren("property", l); +} + +/** + * Returns the type of an implementation. + */ +const value implementationType(const value& l) { + return elementName(l); +} + +/** + * Returns the type of a binding. + */ +const value bindingType(const value& l) { + return elementName(l); +} + +/** + * Returns the value of a property. + */ +const value propertyValue(const value& l) { + return elementValue(l); +} + +} +} + +#endif /* tuscany_scdl_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/scdl/test.composite b/sandbox/sebastien/cpp/apr-2/modules/scdl/test.composite new file mode 100644 index 0000000000..f6fdba7f5f --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scdl/test.composite @@ -0,0 +1,64 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * 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. +--> +<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912" + xmlns:t="http://tuscany.apache.org/xmlns/sca/1.1" + targetNamespace="http://store" + name="store"> + + <component name="Store"> + <t:implementation.scheme script="store.scm"/> + <service name="Widget"> + <t:binding.http uri="/store"/> + </service> + <reference name="catalog" target="Catalog"> + <t:binding.jsonrpc/> + </reference> + <reference name="shoppingCart" target="ShoppingCart/Cart"> + <t:binding.atom/> + </reference> + <reference name="shoppingTotal" target="ShoppingCart/Total"> + <t:binding.jsonrpc/> + </reference> + </component> + + <component name="Catalog"> + <t:implementation.scheme script="fruits-catalog.scm"/> + <property name="currencyCode">USD</property> + <service name="Catalog"> + <t:binding.jsonrpc/> + </service> + <reference name="currencyConverter" target="CurrencyConverter"/> + </component> + + <component name="ShoppingCart"> + <t:implementation.scheme script="shopping-cart.scm"/> + <service name="Cart"> + <t:binding.atom uri="/ShoppingCart"/> + </service> + <service name="Total"> + <t:binding.jsonrpc/> + </service> + </component> + + <component name="CurrencyConverter"> + <t:implementation.scheme script="currency-converter.scm"/> + </component> + +</composite> diff --git a/sandbox/sebastien/cpp/apr-2/modules/scdl/validate-test b/sandbox/sebastien/cpp/apr-2/modules/scdl/validate-test new file mode 100755 index 0000000000..e70fe67aa0 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scdl/validate-test @@ -0,0 +1,23 @@ +#!/bin/sh + +# 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. + +# Validate test composite +../../kernel/xsd-test ../../xsd/tuscany-sca-1.1.xsd test.composite 2>/dev/null +rc=$? +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/scheme/Makefile.am new file mode 100644 index 0000000000..8e2141e724 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/Makefile.am @@ -0,0 +1,44 @@ +# 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/scheme + +eval_test_SOURCES = eval-test.cpp + +eval_shell_SOURCES = eval-shell.cpp + +value_element_SOURCES = value-element.cpp +value_element_LDFLAGS = + +element_value_SOURCES = element-value.cpp +element_value_LDFLAGS = + +xml_value_SOURCES = xml-value.cpp +xml_value_LDFLAGS = -lxml2 + +value_xml_SOURCES = value-xml.cpp +value_xml_LDFLAGS = -lxml2 + +json_value_SOURCES = json-value.cpp +json_value_LDFLAGS = -lmozjs + +value_json_SOURCES = value-json.cpp +value_json_LDFLAGS = -lmozjs + +noinst_PROGRAMS = eval-test eval-shell element-value value-element xml-value value-xml json-value value-json +TESTS = eval-test diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/driver.hpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/driver.hpp new file mode 100644 index 0000000000..112c226ed1 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/driver.hpp @@ -0,0 +1,76 @@ +/* + * 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_scheme_driver_hpp +#define tuscany_scheme_driver_hpp + +/** + * Script evaluator main driver loop. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace scheme { + +const string evalOutputPrompt("; "); +const string evalInputPrompt("=> "); + +const bool promptForInput(const string& str, ostream& out) { + out << endl << endl << str; + return true; +} + +const bool announceOutput(const string str, ostream& out) { + out << endl << str; + return true; +} + +const bool userPrint(const value val, ostream& out) { + if(isCompoundProcedure(val)) + writeValue(mklist<value>(compoundProcedureSymbol, procedureParameters(val), procedureBody(val), "<procedure-env>"), out); + writeValue(val, out); + return true; +} + +const value evalDriverLoop(istream& in, ostream& out, Env& env) { + promptForInput(evalInputPrompt, out); + value input = readValue(in); + if (isNil(input)) + return input; + const value output = evalExpr(input, env); + announceOutput(evalOutputPrompt, out); + userPrint(output, out); + return evalDriverLoop(in, out, env); +} + +const bool evalDriverRun(istream& in, ostream& out) { + setupDisplay(out); + Env env = setupEnvironment(); + evalDriverLoop(in, out, env); + return true; +} + +} +} +#endif /* tuscany_scheme_driver_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/element-value.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/element-value.cpp new file mode 100644 index 0000000000..8a443dbdb2 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/element-value.cpp @@ -0,0 +1,46 @@ +/* + * 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$ */ + +/** + * Convert a scheme value representing an element to a value. + */ + +#include "fstream.hpp" +#include "string.hpp" +#include "element.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace scheme { + +int elementValue() { + const value v = elementsToValues(readValue(cin)); + cout << writeValue(v); + return 0; +} + +} +} + +int main() { + return tuscany::scheme::elementValue(); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/environment.hpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/environment.hpp new file mode 100644 index 0000000000..bfb415a978 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/environment.hpp @@ -0,0 +1,179 @@ +/* + * 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_scheme_environment_hpp +#define tuscany_scheme_environment_hpp + +/** + * Script evaluator environment implementation. + */ + +#include "string.hpp" +#include "list.hpp" +#include "value.hpp" +#include "primitive.hpp" +#include <string> + +namespace tuscany { +namespace scheme { + +typedef value Frame; +typedef list<value> Env; + +const value trueSymbol("true"); +const value falseSymbol("false"); +const value defineSymbol("define"); +const value setSymbol("set!"); +const value dotSymbol("."); + +const Env theEmptyEnvironment() { + return list<value>(); +} + +const bool isDefinition(const value& exp) { + return isTaggedList(exp, defineSymbol); +} + +const bool isAssignment(const value& exp) { + return isTaggedList(exp, setSymbol); +} + +const bool isVariable(const value& exp) { + return isSymbol(exp); +} + +const Env enclosingEnvironment(const Env& env) { + return cdr(env); +} + +const gc_ptr<Frame> firstFrame(const Env& env) { + return car(env); +} + +list<value> frameVariables(const Frame& frame) { + return car((list<value> )frame); +} + +list<value> frameValues(const Frame& frame) { + return cdr((list<value> )frame); +} + +const bool isDotVariable(const value& var) { + return var == dotSymbol; +} + +const Frame makeBinding(const Frame& frameSoFar, const list<value>& variables, const list<value> values) { + if (isNil(variables)) { + if (!isNil(values)) + logStream() << "Too many arguments supplied " << values << endl; + return frameSoFar; + } + if (isDotVariable(car(variables))) + return makeBinding(frameSoFar, cdr(variables), mklist<value>(values)); + + if (isNil(values)) { + if (!isNil(variables)) + logStream() << "Too few arguments supplied " << variables << endl; + return frameSoFar; + } + + const list<value> vars = cons(car(variables), frameVariables(frameSoFar)); + const list<value> vals = cons(car(values), frameValues(frameSoFar)); + const Frame newFrame = cons(value(vars), vals); + + return makeBinding(newFrame, cdr(variables), cdr(values)); +} + +const gc_ptr<Frame> makeFrame(const list<value>& variables, const list<value> values) { + gc_ptr<Frame> frame = new (gc_new<Frame>()) Frame(); + *frame = value(makeBinding(cons(value(list<value>()), list<value>()), variables, values)); + return frame; +} + +const value definitionVariable(const value& exp) { + const list<value> exps(exp); + if(isSymbol(car(cdr(exps)))) + return car(cdr(exps)); + const list<value> lexps(car(cdr(exps))); + return car(lexps); +} + +const value definitionValue(const value& exp) { + const list<value> exps(exp); + if(isSymbol(car(cdr(exps)))) + return car(cdr(cdr(exps))); + const list<value> lexps(car(cdr(exps))); + return makeLambda(cdr(lexps), cdr(cdr(exps))); +} + +const value assignmentVariable(const value& exp) { + return car(cdr((list<value> )exp)); +} + +const value assignmentValue(const value& exp) { + return car(cdr(cdr((list<value> )exp))); +} + +const Frame addBindingToFrame(const value& var, const value& val, const Frame& frame) { + return cons(value(cons(var, frameVariables(frame))), cons(val, frameValues(frame))); +} + +const bool defineVariable(const value& var, const value& val, Env& env) { + *firstFrame(env) = addBindingToFrame(var, val, *firstFrame(env)); + return true; +} + +const Env extendEnvironment(const list<value>& vars, const list<value>& vals, const Env& baseEnv) { + return cons<value>(makeFrame(vars, vals), baseEnv); +} + +const Env setupEnvironment() { + Env env = extendEnvironment(primitiveProcedureNames(), primitiveProcedureObjects(), theEmptyEnvironment()); + defineVariable(trueSymbol, true, env); + defineVariable(falseSymbol, false, env); + return env; +} + +const value lookupEnvLoop(const value& var, const Env& env); + +const value lookupEnvScan(const value& var, const list<value>& vars, const list<value>& vals, const Env& env) { + if(isNil(vars)) + return lookupEnvLoop(var, enclosingEnvironment(env)); + if(var == car(vars)) + return car(vals); + return lookupEnvScan(var, cdr(vars), cdr(vals), env); +} + +const value lookupEnvLoop(const value& var, const Env& env) { + if(env == theEmptyEnvironment()) { + logStream() << "Unbound variable " << var << endl; + return value(); + } + return lookupEnvScan(var, frameVariables(*firstFrame(env)), frameValues(*firstFrame(env)), env); +} + +const value lookupVariableValue(const value& var, const Env& env) { + return lookupEnvLoop(var, env); +} + +} +} +#endif /* tuscany_scheme_environment_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/eval-shell.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/eval-shell.cpp new file mode 100644 index 0000000000..4aa67c2375 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/eval-shell.cpp @@ -0,0 +1,36 @@ +/* + * 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$ */ + +/** + * Script evaluator shell, used for interactive testing of scripts. + */ + +#include <assert.h> +#include "gc.hpp" +#include "stream.hpp" +#include "string.hpp" +#include "driver.hpp" + +int main() { + tuscany::gc_scoped_pool pool; + tuscany::scheme::evalDriverRun(tuscany::cin, tuscany::cout); + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/eval-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/eval-test.cpp new file mode 100644 index 0000000000..7c4c0c69c4 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/eval-test.cpp @@ -0,0 +1,231 @@ +/* + * 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 script evaluator. + */ + +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "driver.hpp" + +namespace tuscany { +namespace scheme { + +bool testEnv() { + gc_scoped_pool pool; + Env globalEnv = list<value>(); + Env env = extendEnvironment(mklist<value>("a"), mklist<value>(1), globalEnv); + defineVariable("x", env, env); + assert(lookupVariableValue(value("x"), env) == env); + assert(lookupVariableValue("a", env) == value(1)); + return true; +} + +bool testEnvGC() { + resetLambdaCounters(); + resetListCounters(); + resetValueCounters(); + testEnv(); + assert(checkValueCounters()); + assert(checkLambdaCounters()); + assert(checkListCounters()); + return true; +} + +bool testRead() { + istringstream is("abcd"); + assert(readValue(is) == "abcd"); + + istringstream is2("123"); + assert(readValue(is2) == value(123)); + + istringstream is3("(abcd)"); + assert(readValue(is3) == mklist(value("abcd"))); + + istringstream is4("(abcd xyz)"); + assert(readValue(is4) == mklist<value>("abcd", "xyz")); + + istringstream is5("(abcd (xyz tuv))"); + assert(readValue(is5) == mklist<value>("abcd", mklist<value>("xyz", "tuv"))); + + return true; +} + +bool testWrite() { + const list<value> i = list<value>() + + (list<value>() + "item" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b" + + (list<value>() + "item" + + (list<value>() + "name" + "Apple") + + (list<value>() + "price" + "$2.99"))) + + (list<value>() + "item" + "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c" + + (list<value>() + "item" + + (list<value>() + "name" + "Orange") + + (list<value>() + "price" + "$3.55"))); + const list<value> a = cons<value>("Feed", cons<value>("feed-1234", i)); + ostringstream os; + writeValue(a, os); + istringstream is(str(os)); + assert(readValue(is) == a); + return true; +} + +const string testSchemeNumber( + "(define (testNumber) (if (= 1 1) (display \"testNumber ok\") (error \"testNumber\"))) " + "(testNumber)"); + +const string testSchemeString( + "(define (testString) (if (= \"abc\" \"abc\") (display \"testString ok\") (error \"testString\"))) " + "(testString)"); + +const string testSchemeDefinition( + "(define a \"abc\") (define (testDefinition) (if (= a \"abc\") (display \"testDefinition ok\") (error \"testDefinition\"))) " + "(testDefinition)"); + +const string testSchemeIf( + "(define (testIf) (if (= \"abc\" \"abc\") (if (= \"xyz\" \"xyz\") (display \"testIf ok\") (error \"testNestedIf\")) (error \"testIf\"))) " + "(testIf)"); + +const string testSchemeCond( + "(define (testCond) (cond ((= \"abc\" \"abc\") (display \"testCond ok\")) (else (error \"testIf\"))))" + "(testCond)"); + +const string testSchemeBegin( + "(define (testBegin) " + "(begin " + "(define a \"abc\") " + "(if (= a \"abc\") (display \"testBegin1 ok\") (error \"testBegin\")) " + "(define x \"xyz\") " + "(if (= x \"xyz\") (display \"testBegin2 ok\") (error \"testBegin\")) " + ") " + ") " + "(testBegin)"); + +const string testSchemeLambda( + "(define sqrt (lambda (x) (* x x))) " + "(define (testLambda) (if (= 4 (sqrt 2)) (display \"testLambda ok\") (error \"testLambda\"))) " + "(testLambda)"); + +const string testSchemeForward( + "(define (testLambda) (if (= 4 (sqrt 2)) (display \"testForward ok\") (error \"testForward\"))) " + "(define sqrt (lambda (x) (* x x))) " + "(testLambda)"); + +const string evalOutput(const string& scm) { + istringstream is(scm); + ostringstream os; + evalDriverRun(is, os); + return str(os); +} + +bool testEval() { + gc_scoped_pool pool; + assert(contains(evalOutput(testSchemeNumber), "testNumber ok")); + assert(contains(evalOutput(testSchemeString), "testString ok")); + assert(contains(evalOutput(testSchemeDefinition), "testDefinition ok")); + assert(contains(evalOutput(testSchemeIf), "testIf ok")); + assert(contains(evalOutput(testSchemeCond), "testCond ok")); + assert(contains(evalOutput(testSchemeBegin), "testBegin1 ok")); + assert(contains(evalOutput(testSchemeBegin), "testBegin2 ok")); + assert(contains(evalOutput(testSchemeLambda), "testLambda ok")); + assert(contains(evalOutput(testSchemeForward), "testForward ok")); + return true; +} + +bool testEvalExpr() { + gc_scoped_pool pool; + const value exp = mklist<value>("+", 2, 3); + Env env = setupEnvironment(); + const value r = evalExpr(exp, env); + assert(r == value(5)); + return true; +} + +bool testEvalRun() { + gc_scoped_pool pool; + evalDriverRun(cin, cout); + return true; +} + +const value mult(const list<value>& args) { + const double x = car(args); + const double y = cadr(args); + return x * y; +} + +const string testReturnLambda( + "(define (testReturnLambda) * )"); + +const string testCallLambda( + "(define (testCallLambda l x y) (l x y))"); + +bool testEvalLambda() { + gc_scoped_pool pool; + Env env = setupEnvironment(); + + const value trl = mklist<value>("testReturnLambda"); + istringstream trlis(testReturnLambda); + const value trlv = evalScript(trl, trlis, env); + + istringstream tclis(testCallLambda); + const value tcl = cons<value>("testCallLambda", quotedParameters(mklist<value>(trlv, 2, 3))); + const value tclv = evalScript(tcl, tclis, env); + assert(tclv == value(6)); + + istringstream tcelis(testCallLambda); + const value tcel = cons<value>("testCallLambda", quotedParameters(mklist<value>(primitiveProcedure(mult), 3, 4))); + const value tcelv = evalScript(tcel, tcelis, env); + assert(tcelv == value(12)); + return true; +} + +bool testEvalGC() { + resetLambdaCounters(); + resetListCounters(); + resetValueCounters(); + testEval(); + testEvalExpr(); + testEvalLambda(); + assert(checkValueCounters()); + assert(checkLambdaCounters()); + assert(checkListCounters()); + return true; +} + +} +} + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + + tuscany::scheme::testEnv(); + tuscany::scheme::testEnvGC(); + tuscany::scheme::testRead(); + tuscany::scheme::testWrite(); + tuscany::scheme::testEval(); + tuscany::scheme::testEvalExpr(); + tuscany::scheme::testEvalLambda(); + tuscany::scheme::testEvalGC(); + + tuscany::cout << "OK" << tuscany::endl; + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/eval.hpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/eval.hpp new file mode 100644 index 0000000000..34d1a7bc17 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/eval.hpp @@ -0,0 +1,290 @@ +/* + * 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_scheme_eval_hpp +#define tuscany_scheme_eval_hpp + +/** + * Core script evaluation logic. + */ + +#include <string.h> +#include "list.hpp" +#include "value.hpp" +#include "primitive.hpp" +#include "io.hpp" +#include "environment.hpp" + +namespace tuscany { +namespace scheme { + +const value evalExpr(const value& exp, Env& env); + +const value compoundProcedureSymbol("compound-procedure"); +const value procedureSymbol("procedure"); +const value applySymbol("apply"); +const value beginSymbol("begin"); +const value condSymbol("cond"); +const value elseSymbol("else"); +const value ifSymbol("if"); + +const bool isBegin(const value& exp) { + return isTaggedList(exp, beginSymbol); +} + +const list<value> beginActions(const value& exp) { + return cdr((list<value> )exp); +} + +const bool isLambdaExpr(const value& exp) { + return isTaggedList(exp, lambdaSymbol); +} + +const list<value> lambdaParameters(const value& exp) { + return car(cdr((list<value> )exp)); +} + +static list<value> lambdaBody(const value& exp) { + return cdr(cdr((list<value> )exp)); +} + +const value makeProcedure(const list<value>& parameters, const value& body, const Env& env) { + return mklist<value>(procedureSymbol, parameters, body, env); +} + +const bool isApply(const value& exp) { + return isTaggedList(exp, applySymbol); +} + +const bool isApplication(const value& exp) { + return isList(exp); +} + +const value operat(const value& exp) { + return car((list<value> )exp); +} + +const list<value> operands(const value& exp) { + return cdr((list<value> )exp); +} + +const list<value> listOfValues(const list<value> exps, Env& env) { + if(isNil(exps)) + return list<value> (); + return cons(evalExpr(car(exps), env), listOfValues(cdr(exps), env)); +} + +const value applyOperat(const value& exp) { + return cadr((list<value> )exp); +} + +const value applyOperand(const value& exp) { + return caddr((list<value> )exp); +} + +const bool isCompoundProcedure(const value& procedure) { + return isTaggedList(procedure, procedureSymbol); +} + +const list<value> procedureParameters(const value& exp) { + return car(cdr((list<value> )exp)); +} + +const value procedureBody(const value& exp) { + return car(cdr(cdr((list<value> )exp))); +} + +const Env procedureEnvironment(const value& exp) { + return (Env)car(cdr(cdr(cdr((list<value> )exp)))); +} + +const bool isLastExp(const list<value>& seq) { + return isNil(cdr(seq)); +} + +const value firstExp(const list<value>& seq) { + return car(seq); +} + +const list<value> restExp(const list<value>& seq) { + return cdr(seq); +} + +const value makeBegin(const list<value> seq) { + return cons(beginSymbol, seq); +} + +const value evalSequence(const list<value>& exps, Env& env) { + if(isLastExp(exps)) + return evalExpr(firstExp(exps), env); + evalExpr(firstExp(exps), env); + return evalSequence(restExp(exps), env); +} + +const value applyProcedure(const value& procedure, list<value>& arguments) { + if(isPrimitiveProcedure(procedure)) + return applyPrimitiveProcedure(procedure, arguments); + if(isCompoundProcedure(procedure)) { + Env env = extendEnvironment(procedureParameters(procedure), arguments, procedureEnvironment(procedure)); + return evalSequence(procedureBody(procedure), env); + } + logStream() << "Unknown procedure type " << procedure << endl; + return value(); +} + +const value sequenceToExp(const list<value> exps) { + if(isNil(exps)) + return exps; + if(isLastExp(exps)) + return firstExp(exps); + return makeBegin(exps); +} + +const list<value> condClauses(const value& exp) { + return cdr((list<value> )exp); +} + +const value condPredicate(const value& clause) { + return car((list<value> )clause); +} + +const list<value> condActions(const value& clause) { + return cdr((list<value> )clause); +} + +const value ifPredicate(const value& exp) { + return car(cdr((list<value> )exp)); +} + +const value ifConsequent(const value& exp) { + return car(cdr(cdr((list<value> )exp))); +} + +const value ifAlternative(const value& exp) { + if(!isNil(cdr(cdr(cdr((list<value> )exp))))) + return car(cdr(cdr(cdr((list<value> )exp)))); + return false; +} + +const bool isCond(const value& exp) { + return isTaggedList(exp, condSymbol); +} + +const bool isCondElseClause(const value& clause) { + return condPredicate(clause) == elseSymbol; +} + +const bool isIf(const value& exp) { + return isTaggedList(exp, ifSymbol); +} + +const value makeIf(value predicate, value consequent, value alternative) { + return mklist(ifSymbol, predicate, consequent, alternative); +} + +const value expandClauses(const list<value>& clauses) { + if(isNil(clauses)) + return false; + const value first = car(clauses); + const list<value> rest = cdr(clauses); + if(isCondElseClause(first)) { + if(isNil(rest)) + return sequenceToExp(condActions(first)); + logStream() << "else clause isn't last " << clauses << endl; + return value(); + } + return makeIf(condPredicate(first), sequenceToExp(condActions(first)), expandClauses(rest)); +} + +value condToIf(const value& exp) { + return expandClauses(condClauses(exp)); +} + +value evalIf(const value& exp, Env& env) { + if(isTrue(evalExpr(ifPredicate(exp), env))) + return evalExpr(ifConsequent(exp), env); + return evalExpr(ifAlternative(exp), env); +} + +const value evalDefinition(const value& exp, Env& env) { + defineVariable(definitionVariable(exp), evalExpr(definitionValue(exp), env), env); + return definitionVariable(exp); +} + +const value evalExpr(const value& exp, Env& env) { + if(isSelfEvaluating(exp)) + return exp; + if(isQuoted(exp)) + return textOfQuotation(exp); + if(isDefinition(exp)) + return evalDefinition(exp, env); + if(isIf(exp)) + return evalIf(exp, env); + if(isBegin(exp)) + return evalSequence(beginActions(exp), env); + if(isCond(exp)) + return evalExpr(condToIf(exp), env); + if(isLambdaExpr(exp)) + return makeProcedure(lambdaParameters(exp), lambdaBody(exp), env); + if(isVariable(exp)) + return lookupVariableValue(exp, env); + if(isApply(exp)) { + list<value> applyOperandValues = evalExpr(applyOperand(exp), env); + return applyProcedure(evalExpr(applyOperat(exp), env), applyOperandValues); + } + if(isApplication(exp)) { + list<value> operandValues = listOfValues(operands(exp), env); + return applyProcedure(evalExpr(operat(exp), env), operandValues); + } + logStream() << "Unknown expression type " << exp << endl; + return value(); +} + +const list<value> quotedParameters(const list<value>& p) { + if (isNil(p)) + return p; + return cons<value>(mklist<value>(quoteSymbol, car(p)), quotedParameters(cdr(p))); +} + +/** + * Evaluate an expression against a script provided as a list of values. + */ +const value evalScriptLoop(const value& expr, const list<value>& script, scheme::Env& env) { + if (isNil(script)) + return scheme::evalExpr(expr, env); + scheme::evalExpr(car(script), env); + return evalScriptLoop(expr, cdr(script), env); +} + +const value evalScript(const value& expr, const value& script, Env& env) { + return evalScriptLoop(expr, script, env); +} + +/** + * Evaluate an expression against a script provided as an input stream. + */ +const value evalScript(const value& expr, istream& is, Env& env) { + return evalScript(expr, readScript(is), env); +} + +} +} +#endif /* tuscany_scheme_eval_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/io.hpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/io.hpp new file mode 100644 index 0000000000..6928739d17 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/io.hpp @@ -0,0 +1,222 @@ +/* + * 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_scheme_io_hpp +#define tuscany_scheme_io_hpp + +/** + * Script evaluator IO functions. + */ + +#include <ctype.h> +#include "stream.hpp" +#include "string.hpp" + +#include "list.hpp" +#include "value.hpp" +#include "primitive.hpp" + +namespace tuscany { +namespace scheme { + +const value rightParenthesis(mklist<value>(")")); +const value leftParenthesis(mklist<value>("(")); +const value comment(mklist<value>(";")); + +const double stringToNumber(const string& str) { + return atof(c_str(str)); +} + +const bool isWhitespace(const char ch) { + return ch != -1 && isspace(ch); +} + +const bool isIdentifierStart(const char ch) { + return ch != -1 && !isspace(ch) && !isdigit(ch); +} + +const bool isIdentifierPart(const char ch) { + return ch != -1 && !isspace(ch) && ch != '(' && ch != ')'; +} + +const bool isDigit(const char ch) { + return isdigit(ch) || ch == '.'; +} + +const bool isLeftParenthesis(const value& token) { + return leftParenthesis == token; +} + +const bool isRightParenthesis(const value& token) { + return rightParenthesis == token; +} + +const char readChar(istream& in) { + if(in.eof()) { + return -1; + } + char c = (char)get(in); + return c; +} + +const char peekChar(istream& in) { + if(eof(in)) + return -1; + char c = (char)peek(in); + return c; +} + +const bool isQuote(const value& token) { + return token == quoteSymbol; +} + +const value skipComment(istream& in); +const value readQuoted(istream& in); +const value readIdentifier(const char chr, istream& in); +const value readString(istream& in); +const value readNumber(const char chr, istream& in); +const value readValue(istream& in); + +const value readToken(istream& in) { + const char firstChar = readChar(in); + if(isWhitespace(firstChar)) + return readToken(in); + if(firstChar == ';') + return skipComment(in); + if(firstChar == '\'') + return readQuoted(in); + if(firstChar == '(') + return leftParenthesis; + if(firstChar == ')') + return rightParenthesis; + if(firstChar == '"') + return readString(in); + if(isIdentifierStart(firstChar)) + return readIdentifier(firstChar, in); + if(isDigit(firstChar)) + return readNumber(firstChar, in); + if(firstChar == -1) + return value(); + logStream() << "Illegal lexical syntax '" << firstChar << "'" << endl; + return readToken(in); +} + +const value skipComment(istream& in) { + const char nextChar = readChar(in); + if (nextChar == '\n') + return readToken(in); + return skipComment(in); +} + +const value readQuoted(istream& in) { + return mklist(quoteSymbol, readValue(in)); +} + +const list<value> readList(const list<value>& listSoFar, istream& in) { + const value token = readToken(in); + if(isNil(token) || isRightParenthesis(token)) + return reverse(listSoFar); + if(isLeftParenthesis(token)) + return readList(cons(value(readList(list<value> (), in)), listSoFar), in); + return readList(cons(token, listSoFar), in); +} + +const string listToString(const list<char>& l) { + if(isNil(l)) + return ""; + const char buf[1] = { car(l) }; + return string(buf, 1) + listToString(cdr(l)); +} + +const list<char> readIdentifierHelper(const list<char>& listSoFar, istream& in) { + const char nextChar = peekChar(in); + if(isIdentifierPart(nextChar)) + return readIdentifierHelper(cons(readChar(in), listSoFar), in); + return reverse(listSoFar); +} + +const value readIdentifier(const char chr, istream& in) { + const value val = c_str(listToString(readIdentifierHelper(mklist(chr), in))); + if (val == "false") + return value((bool)false); + if (val == "true") + return value((bool)true); + return val; +} + +const list<char> readStringHelper(const list<char>& listSoFar, istream& in) { + const char nextChar = readChar(in); + if(nextChar != -1 && nextChar != '"') + return readStringHelper(cons(nextChar, listSoFar), in); + return reverse(listSoFar); +} + +const value readString(istream& in) { + return listToString(readStringHelper(list<char>(), in)); +} + +const list<char> readNumberHelper(const list<char>& listSoFar, istream& in) { + const char nextChar = peekChar(in); + if(isDigit(nextChar)) + return readNumberHelper(cons(readChar(in), listSoFar), in); + return reverse(listSoFar); +} + +const value readNumber(const char chr, istream& in) { + return stringToNumber(listToString(readNumberHelper(mklist(chr), in))); +} + +const value readValue(istream& in) { + const value nextToken = readToken(in); + if(isLeftParenthesis(nextToken)) + return readList(list<value> (), in); + return nextToken; +} + +const value readValue(const string s) { + istringstream in(s); + const value nextToken = readToken(in); + if(isLeftParenthesis(nextToken)) + return readList(list<value> (), in); + return nextToken; +} + +const bool writeValue(const value& val, ostream& out) { + out << val; + return true; +} + +const string writeValue(const value& val) { + ostringstream out; + out << val; + return str(out); +} + +const value readScript(istream& in) { + const value val = readValue(in); + if (isNil(val)) + return list<value>(); + return cons(val, (list<value>)readScript(in)); +} + +} +} +#endif /* tuscany_scheme_io_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/json-value.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/json-value.cpp new file mode 100644 index 0000000000..0ab9c85854 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/json-value.cpp @@ -0,0 +1,53 @@ +/* + * 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$ */ + +/** + * Convert a JSON document to a scheme value. + */ + +#include "fstream.hpp" +#include "string.hpp" +#include "../json/json.hpp" +#include "element.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace scheme { + +int jsonValue() { + const js::JSContext cx; + const failable<list<value> > lv = json::readJSON(streamList(cin), cx); + if (!hasContent(lv)) { + cerr << reason(lv); + return 1; + } + const value v = elementsToValues(content(lv)); + cout << writeValue(v); + return 0; +} + +} +} + +int main() { + return tuscany::scheme::jsonValue(); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/primitive.hpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/primitive.hpp new file mode 100644 index 0000000000..6f3f71f4cd --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/primitive.hpp @@ -0,0 +1,279 @@ +/* + * 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_scheme_primitive_hpp +#define tuscany_scheme_primitive_hpp + +/** + * Script evaluator primitive functions. + */ + +#include "stream.hpp" +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" + +namespace tuscany { +namespace scheme { + +const value primitiveSymbol("primitive"); +const value quoteSymbol("'"); +const value lambdaSymbol("lambda"); + +#ifdef WANT_THREADS +__thread +#endif +ostream* displayOutStream = NULL; + +#ifdef WANT_THREADS +__thread +#endif +ostream* logOutStream = NULL; + +const bool setupDisplay(ostream& out) { + displayOutStream = &out; + return true; +} + +ostream& displayStream() { + if (displayOutStream == NULL) + return cout; + return *displayOutStream; +} + +const bool setupLog(ostream& out) { + logOutStream = &out; + return true; +} + +ostream& logStream() { + if (logOutStream == NULL) + return cerr; + return *logOutStream; +} + +const value carProc(const list<value>& args) { + return car((list<value> )car(args)); +} + +const value cdrProc(const list<value>& args) { + return cdr((list<value> )car(args)); +} + +const value consProc(const list<value>& args) { + return cons(car(args), (list<value> )cadr(args)); +} + +const value listProc(const list<value>& args) { + return args; +} + +const value assocProc(const list<value>& args) { + return assoc(car(args), (list<list<value> >)cadr(args)); +} + +const value nulProc(const list<value>& args) { + const value v(car(args)); + if (isNil(v)) + return true; + if (isList(v)) + return isNil(list<value>(v)); + return false; +} + +const value equalProc(const list<value>& args) { + return (bool)(car(args) == cadr(args)); +} + +const value addProc(const list<value>& args) { + if (isNil(cdr(args))) + return (double)car(args); + return (double)car(args) + (double)cadr(args); +} + +const value subProc(const list<value>& args) { + if (isNil(cdr(args))) + return (double)0 - (double)car(args); + return (double)car(args) - (double)cadr(args); +} + +const value mulProc(const list<value>& args) { + return (double)car(args) * (double)cadr(args); +} + +const value divProc(const list<value>& args) { + return (double)car(args) / (double)cadr(args); +} + +const value displayProc(const list<value>& args) { + if (isNil(args)) { + displayStream() << endl; + return true; + } + displayStream() << car(args); + return displayProc(cdr(args)); +} + +const value logProc(const list<value>& args) { + if (isNil(args)) { + logStream() << endl; + return true; + } + logStream() << car(args); + return logProc(cdr(args)); +} + +const value uuidProc(unused const list<value>& args) { + return mkuuid(); +} + +const value cadrProc(unused const list<value>& args) { + return cadr((list<value> )car(args)); +} + +const value caddrProc(unused const list<value>& args) { + return caddr((list<value> )car(args)); +} + +const value cadddrProc(unused const list<value>& args) { + return cadddr((list<value> )car(args)); +} + +const value cddrProc(unused const list<value>& args) { + return cddr((list<value> )car(args)); +} + +const value cdddrProc(unused const list<value>& args) { + return cdddr((list<value> )car(args)); +} + +const value startProc(unused const list<value>& args) { + return lambda<value(const list<value>&)>(); +} + +const value stopProc(unused const list<value>& args) { + return lambda<value(const list<value>&)>(); +} + +const value applyPrimitiveProcedure(const value& proc, list<value>& args) { + const lambda<value(const list<value>&)> func(cadr((list<value>)proc)); + return func(args); +} + +const bool isPrimitiveProcedure(const value& proc) { + return isTaggedList(proc, primitiveSymbol); +} + +const bool isSelfEvaluating(const value& exp) { + if(isNil(exp)) + return true; + if(isNumber(exp)) + return true; + if(isString(exp)) + return true; + if(isBool(exp)) + return true; + if(isLambda(exp)) + return true; + return false; +} + +const value primitiveImplementation(const list<value>& proc) { + return car(cdr(proc)); +} + +template<typename F> const value primitiveProcedure(const F& f) { + return mklist<value>(primitiveSymbol, (lambda<value(const list<value>&)>)f); +} + +const list<value> primitiveProcedureNames() { + return mklist<value>("car") + + "cdr" + + "cons" + + "list" + + "nul" + + "=" + + "equal?" + + "+" + + "-" + + "*" + + "/" + + "assoc" + + "cadr" + + "caddr" + + "cadddr" + + "cddr" + + "cdddr" + + "display" + + "log" + + "uuid" + + "start" + + "stop"; +} + +const list<value> primitiveProcedureObjects() { + return mklist(primitiveProcedure(carProc)) + + primitiveProcedure(cdrProc) + + primitiveProcedure(consProc) + + primitiveProcedure(listProc) + + primitiveProcedure(nulProc) + + primitiveProcedure(equalProc) + + primitiveProcedure(equalProc) + + primitiveProcedure(addProc) + + primitiveProcedure(subProc) + + primitiveProcedure(mulProc) + + primitiveProcedure(divProc) + + primitiveProcedure(assocProc) + + primitiveProcedure(cadrProc) + + primitiveProcedure(caddrProc) + + primitiveProcedure(cadddrProc) + + primitiveProcedure(cddrProc) + + primitiveProcedure(cdddrProc) + + primitiveProcedure(displayProc) + + primitiveProcedure(logProc) + + primitiveProcedure(uuidProc) + + primitiveProcedure(startProc) + + primitiveProcedure(stopProc); +} + +const bool isFalse(const value& exp) { + return (bool)exp == false; +} + +const bool isTrue(const value& exp) { + return (bool)exp == true; +} + +const bool isQuoted(const value& exp) { + return isTaggedList(exp, quoteSymbol); +} + +const value textOfQuotation(const value& exp) { + return car(cdr((list<value> )exp)); +} + +const value makeLambda(const list<value>& parameters, const list<value>& body) { + return cons(lambdaSymbol, cons<value>(parameters, body)); +} + +} +} +#endif /* tuscany_scheme_primitive_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/value-element.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/value-element.cpp new file mode 100644 index 0000000000..a4acdaf2d7 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/value-element.cpp @@ -0,0 +1,46 @@ +/* + * 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$ */ + +/** + * Convert a scheme value to a value representing an element. + */ + +#include "fstream.hpp" +#include "string.hpp" +#include "element.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace scheme { + +int valueElement() { + const value v = valuesToElements(readValue(cin)); + cout << writeValue(v); + return 0; +} + +} +} + +int main() { + return tuscany::scheme::valueElement(); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/value-json.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/value-json.cpp new file mode 100644 index 0000000000..40cc8891dd --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/value-json.cpp @@ -0,0 +1,52 @@ +/* + * 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$ */ + +/** + * Convert a scheme value to a JSON document. + */ + +#include "fstream.hpp" +#include "string.hpp" +#include "../json/json.hpp" +#include "element.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace scheme { + +int valueJSON() { + const js::JSContext cx; + failable<list<string> > s = json::writeJSON(valuesToElements(readValue(cin)), cx); + if (!hasContent(s)) { + cerr << reason(s); + return 1; + } + write(content(s), cout); + return 0; +} + +} +} + +int main() { + return tuscany::scheme::valueJSON(); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/value-xml.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/value-xml.cpp new file mode 100644 index 0000000000..1508f7b516 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/value-xml.cpp @@ -0,0 +1,51 @@ +/* + * 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$ */ + +/** + * Convert a scheme value to an XML document. + */ + +#include "fstream.hpp" +#include "string.hpp" +#include "xml.hpp" +#include "element.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace scheme { + +int valueXML() { + failable<list<string> > s = writeXML(valuesToElements(readValue(cin))); + if (!hasContent(s)) { + cerr << reason(s); + return 1; + } + write(content(s), cout); + return 0; +} + +} +} + +int main() { + return tuscany::scheme::valueXML(); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/scheme/xml-value.cpp b/sandbox/sebastien/cpp/apr-2/modules/scheme/xml-value.cpp new file mode 100644 index 0000000000..0b95174e33 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/scheme/xml-value.cpp @@ -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. + */ + +/* $Rev$ $Date$ */ + +/** + * Convert an XML document to a scheme value. + */ + +#include "fstream.hpp" +#include "string.hpp" +#include "xml.hpp" +#include "element.hpp" +#include "eval.hpp" + +namespace tuscany { +namespace scheme { + +int xmlValue() { + const value v = elementsToValues(readXML(streamList(cin))); + cout << writeValue(v); + return 0; +} + +} +} + +int main() { + return tuscany::scheme::xmlValue(); +} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/server/Makefile.am new file mode 100644 index 0000000000..30c89da85d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/Makefile.am @@ -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. + +INCLUDES = -I${HTTPD_INCLUDE} + +incl_HEADERS = *.hpp +incldir = $(prefix)/include/modules/server + +dist_mod_SCRIPTS = cpp-conf scheme-conf server-conf +moddir = $(prefix)/modules/server + +EXTRA_DIST = domain-test.composite client-test.scm server-test.scm htdocs/*.xml htdocs/*.txt htdocs/*.html + +mod_LTLIBRARIES = libmod_tuscany_eval.la libmod_tuscany_wiring.la +noinst_DATA = libmod_tuscany_eval.so libmod_tuscany_wiring.so + +libmod_tuscany_eval_la_SOURCES = mod-eval.cpp +libmod_tuscany_eval_la_LDFLAGS = -lxml2 -lcurl -lmozjs +libmod_tuscany_eval.so: + ln -s .libs/libmod_tuscany_eval.so + +libmod_tuscany_wiring_la_SOURCES = mod-wiring.cpp +libmod_tuscany_wiring_la_LDFLAGS = -lxml2 -lcurl -lmozjs +libmod_tuscany_wiring.so: + ln -s .libs/libmod_tuscany_wiring.so + +noinst_test_LTLIBRARIES = libimpl-test.la +noinst_testdir = `pwd`/tmp +noinst_DATA += libimpl-test.so + +libimpl_test_la_SOURCES = impl-test.cpp +libimpl-test.so: + ln -s .libs/libimpl-test.so + +client_test_SOURCES = client-test.cpp +client_test_LDFLAGS = -lxml2 -lcurl -lmozjs + +dist_noinst_SCRIPTS = httpd-test server-test wiring-test +noinst_PROGRAMS = client-test +TESTS = httpd-test server-test wiring-test + diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/client-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/server/client-test.cpp new file mode 100644 index 0000000000..5de7ab6e7b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/client-test.cpp @@ -0,0 +1,39 @@ +/* + * 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 HTTP client functions. + */ + +#include "stream.hpp" +#include "string.hpp" +#include "client-test.hpp" + +int main() { + tuscany::cout << "Testing..." << tuscany::endl; + tuscany::server::testURI = "http://localhost:8090/test"; + + tuscany::server::testServer(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/client-test.hpp b/sandbox/sebastien/cpp/apr-2/modules/server/client-test.hpp new file mode 100644 index 0000000000..c17f012012 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/client-test.hpp @@ -0,0 +1,350 @@ +/* + * 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 HTTP client functions. + */ + +#include <sys/types.h> +#include <sys/wait.h> +#include <unistd.h> +#include <assert.h> +#include "stream.hpp" +#include "string.hpp" +#include "parallel.hpp" +#include "perf.hpp" +#include "../http/http.hpp" + +namespace tuscany { +namespace server { + +string testURI = "http://localhost:8090/test"; +bool testBlobs = true; + +ostream* curlWriter(const string& s, ostream* os) { + (*os) << s; + return os; +} + +const bool testGet() { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + { + ostringstream os; + const failable<list<ostream*> > r = http::get<ostream*>(curlWriter, &os, "http://localhost:8090/index.html", ch); + assert(hasContent(r)); + assert(contains(str(os), "HTTP/1.1 200") || contains(str(os), "HTTP/1.0 200")); + assert(contains(str(os), "It works")); + } + { + const failable<value> r = http::getcontent("http://localhost:8090/index.html", ch); + assert(hasContent(r)); + assert(contains(car(reverse(list<value>(content(r)))), "It works")); + } + return true; +} + +struct getLoop { + http::CURLSession ch; + getLoop(http::CURLSession& ch) : ch(ch) { + } + const bool operator()() const { + const failable<value> r = http::getcontent("http://localhost:8090/index.html", ch); + assert(hasContent(r)); + assert(contains(car(reverse(list<value>(content(r)))), "It works")); + return true; + } +}; + +const bool testGetPerf() { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + const lambda<bool()> gl = getLoop(ch); + cout << "Static GET test " << time(gl, 5, 200) << " ms" << endl; + return true; +} + +const bool testEval() { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + const value val = content(http::evalExpr(mklist<value>(string("echo"), string("Hello")), testURI, ch)); + assert(val == string("Hello")); + return true; +} + +struct evalLoop { + const string uri; + http::CURLSession ch; + evalLoop(const string& uri, http::CURLSession& ch) : uri(uri), ch(ch) { + } + const bool operator()() const { + const value val = content(http::evalExpr(mklist<value>(string("echo"), string("Hello")), uri, ch)); + assert(val == string("Hello")); + return true; + } +}; + +const value blob(string(2048, 'A')); +const list<value> blobs = mklist(blob, blob); + +struct blobEvalLoop { + const string uri; + http::CURLSession ch; + blobEvalLoop(const string& uri, http::CURLSession& ch) : uri(uri), ch(ch) { + } + const bool operator()() const { + const value val = content(http::evalExpr(mklist<value>(string("echo"), blobs), uri, ch)); + assert(val == blobs); + return true; + } +}; + +const bool testEvalPerf() { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + const lambda<bool()> el = evalLoop(testURI, ch); + cout << "JSON-RPC eval echo test " << time(el, 5, 200) << " ms" << endl; + + if (testBlobs) { + const lambda<bool()> bel = blobEvalLoop(testURI, ch); + cout << "JSON-RPC eval blob test " << time(bel, 5, 200) << " ms" << endl; + } + return true; +} + +bool testPost() { + gc_scoped_pool pool; + const list<value> i = list<value>() + + (list<value>() + "name" + string("Apple")) + + (list<value>() + "price" + string("$2.99")); + const list<value> a = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + http::CURLSession ch("", "", ""); + const failable<value> id = http::post(a, testURI, ch); + assert(hasContent(id)); + return true; +} + +struct postLoop { + const string uri; + const value val; + http::CURLSession ch; + postLoop(const string& uri, const value& val, http::CURLSession& ch) : uri(uri), val(val), ch(ch) { + } + const bool operator()() const { + const failable<value> id = http::post(val, uri, ch); + assert(hasContent(id)); + return true; + } +}; + +struct postBlobLoop { + const string uri; + const value val; + http::CURLSession ch; + postBlobLoop(const string& uri, const value& val, http::CURLSession& ch) : uri(uri), val(val), ch(ch) { + } + const bool operator()() const { + gc_scoped_pool pool; + const failable<value> id = http::post(val, uri, ch); + assert(hasContent(id)); + return true; + } +}; + +const bool testPostPerf() { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + { + const list<value> i = list<value>() + + (list<value>() + "name" + string("Apple")) + + (list<value>() + "price" + string("$2.99")); + const list<value> val = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + const lambda<bool()> pl = postLoop(testURI, val, ch); + cout << "ATOMPub POST small test " << time(pl, 5, 200) << " ms" << endl; + } + if (testBlobs) { + const list<value> i = list<value>() + + (list<value>() + "name" + string("Apple")) + + (list<value>() + "blob1" + blob) + + (list<value>() + "blob2" + blob) + + (list<value>() + "price" + string("$2.99")); + const list<value> val = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + const lambda<bool()> pl = postBlobLoop(testURI, val, ch); + cout << "ATOMPub POST blob test " << time(pl, 5, 200) << " ms" << endl; + } + return true; +} + +#ifdef WANT_THREADS + +const bool postThread(const string& uri, const int count, const value& val) { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + const lambda<bool()> pl = postLoop(uri, val, ch); + time(pl, 0, count); + return true; +} + +const list<future<bool> > startPost(worker& w, const int threads, const lambda<bool()>& l) { + if (threads == 0) + return list<future<bool> >(); + return cons(submit(w, l), startPost(w, threads - 1, l)); +} + +const bool checkPost(const list<future<bool> >& r) { + if (isNil(r)) + return true; + assert(car(r) == true); + return checkPost(cdr(r)); +} + +struct postThreadLoop { + const lambda<bool()> l; + const int threads; + const gc_ptr<worker> w; + postThreadLoop(const lambda<bool()>& l, const int threads) : l(l), threads(threads), w(new (gc_new<worker>()) worker(threads)) { + } + const bool operator()() const { + list<future<bool> > r = startPost(*w, threads, l); + checkPost(r); + return true; + } +}; + +const bool testPostThreadPerf() { + gc_scoped_pool pool; + const int count = 50; + const int threads = 10; + + const list<value> i = list<value>() + + (list<value>() + "name" + string("Apple")) + + (list<value>() + "price" + string("$2.99")); + const value val = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + + const lambda<bool()> pl= curry(lambda<bool(const string, const int, const value)>(postThread), testURI, count, val); + const lambda<bool()> ptl = postThreadLoop(pl, threads); + double t = time(ptl, 0, 1) / (threads * count); + cout << "ATOMPub POST thread test " << t << " ms" << endl; + + return true; +} + +#else + +const bool postProc(const string& uri, const int count, const value& val) { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + const lambda<bool()> pl = postLoop(uri, val, ch); + time(pl, 0, count); + return true; +} + +const list<pid_t> startPost(const int procs, const lambda<bool()>& l) { + if (procs == 0) + return list<pid_t>(); + pid_t pid = fork(); + if (pid == 0) { + assert(l() == true); + exit(0); + } + return cons(pid, startPost(procs - 1, l)); +} + +const bool checkPost(const list<pid_t>& r) { + if (isNil(r)) + return true; + int status; + waitpid(car(r), &status, 0); + assert(status == 0); + return checkPost(cdr(r)); +} + +struct postForkLoop { + const lambda<bool()> l; + const int procs; + postForkLoop(const lambda<bool()>& l, const int procs) : l(l), procs(procs) { + } + const bool operator()() const { + list<pid_t> r = startPost(procs, l); + checkPost(r); + return true; + } +}; + +const bool testPostForkPerf() { + gc_scoped_pool pool; + const int count = 50; + const int procs = 10; + + const list<value> i = list<value>() + + (list<value>() + "name" + string("Apple")) + + (list<value>() + "price" + string("$2.99")); + const value val = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + + const lambda<bool()> pl= curry(lambda<bool(const string, const int, const value)>(postProc), testURI, count, val); + const lambda<bool()> ptl = postForkLoop(pl, procs); + double t = time(ptl, 0, 1) / (procs * count); + cout << "ATOMPub POST fork test " << t << " ms" << endl; + + return true; +} + +#endif + +const bool testPut() { + gc_scoped_pool pool; + const list<value> i = list<value>() + + (list<value>() + "name" + string("Apple")) + + (list<value>() + "price" + string("$2.99")); + const list<value> a = mklist<value>(string("item"), string("cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b"), i); + http::CURLSession ch("", "", ""); + value rc = content(http::put(a, testURI + "/111", ch)); + assert(rc == value(true)); + return true; +} + +const bool testDel() { + gc_scoped_pool pool; + http::CURLSession ch("", "", ""); + value rc = content(http::del(testURI + "/111", ch)); + assert(rc == value(true)); + return true; +} + +const bool testServer() { + tuscany::server::testGet(); + tuscany::server::testPost(); + tuscany::server::testPut(); + tuscany::server::testDel(); + tuscany::server::testEval(); + tuscany::server::testGetPerf(); + tuscany::server::testPostPerf(); +#ifdef WANT_THREADS + tuscany::server::testPostThreadPerf(); +#else + tuscany::server::testPostForkPerf(); +#endif + tuscany::server::testEvalPerf(); + return true; +} + +} +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/client-test.scm b/sandbox/sebastien/cpp/apr-2/modules/server/client-test.scm new file mode 100644 index 0000000000..47b799d390 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/client-test.scm @@ -0,0 +1,38 @@ +; 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. + +; JSON-RPC test case + +(define (echo x ref) (ref "echo" x)) + +; ATOMPub test case + +(define (get id ref) + (ref "get" id) +) + +(define (post coll entry ref) + (ref "post" coll entry) +) + +(define (put id entry ref) + (ref "put" id entry) +) + +(define (delete id ref) + (ref "delete" id) +) diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/cpp-conf b/sandbox/sebastien/cpp/apr-2/modules/server/cpp-conf new file mode 100755 index 0000000000..086bb49d38 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/cpp-conf @@ -0,0 +1,30 @@ +#!/bin/sh + +# 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. + +# Generate a C++ server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +cat >>$root/conf/modules.conf <<EOF +# Generated by: cpp-conf $* +# Support for C++ SCA components +LoadModule mod_tuscany_eval $here/libmod_tuscany_eval.so + +EOF diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/domain-test.composite b/sandbox/sebastien/cpp/apr-2/modules/server/domain-test.composite new file mode 100644 index 0000000000..048c451ef6 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/domain-test.composite @@ -0,0 +1,49 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * 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. +--> +<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912" + xmlns:t="http://tuscany.apache.org/xmlns/sca/1.1" + targetNamespace="http://domain/test" + name="domain-test"> + + <component name="scheme-test"> + <t:implementation.scheme script="server-test.scm"/> + <service name="test"> + <t:binding.http uri="test"/> + </service> + </component> + + <component name="cpp-test"> + <implementation.cpp path="." library="libimpl-test"/> + <service name="cpp"> + <t:binding.http uri="cpp"/> + </service> + </component> + + <component name="client-test"> + <t:implementation.scheme script="client-test.scm"/> + <service name="client"> + <t:binding.http uri="client"/> + </service> + <reference name="ref" target="scheme-test"> + <t:binding.http/> + </reference> + </component> + +</composite> diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/index.html b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/index.html new file mode 100644 index 0000000000..1bfb3e30c2 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/index.html @@ -0,0 +1,21 @@ +<!-- + 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. +--> + +<html><body><h1>It works!</h1></body></html> + diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/entry.xml b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/entry.xml new file mode 100644 index 0000000000..6528c793e3 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/entry.xml @@ -0,0 +1,2 @@ +<?xml version="1.0" encoding="UTF-8"?> +<entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>111</id><content type="application/xml"><item><name>Apple</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>2.99</price></item></content><link href="111"/></entry> diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/feed.xml b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/feed.xml new file mode 100644 index 0000000000..bcb304f9c2 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/feed.xml @@ -0,0 +1,2 @@ +<?xml version="1.0" encoding="UTF-8"?> +<feed xmlns="http://www.w3.org/2005/Atom"><title type="text">Sample Feed</title><id>123456789</id><entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>111</id><content type="application/xml"><item><name>Apple</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>2.99</price></item></content><link href="111"/></entry><entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>222</id><content type="application/xml"><item><name>Orange</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>3.55</price></item></content><link href="222"/></entry><entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>333</id><content type="application/xml"><item><name>Pear</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>1.55</price></item></content><link href="333"/></entry></feed> diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/json-request.txt b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/json-request.txt new file mode 100644 index 0000000000..b4bd07fc46 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/json-request.txt @@ -0,0 +1 @@ +{"id":1,"method":"echo","params":["Hello"]} diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/json-result.txt b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/json-result.txt new file mode 100644 index 0000000000..121bf74902 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/test/json-result.txt @@ -0,0 +1 @@ +{"id":1,"result":"Hello"}
\ No newline at end of file diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/wiring/ref.js b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/wiring/ref.js new file mode 100644 index 0000000000..95a84c01a5 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/htdocs/wiring/ref.js @@ -0,0 +1,574 @@ +/* + * 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. + * + * The JSON-RPC client code is based on Jan-Klaas' JavaScript + * o lait library (jsolait). + * + * $Id: jsonrpc.js,v 1.36.2.3 2006/03/08 15:09:37 mclark Exp $ + * + * Copyright (c) 2003-2004 Jan-Klaas Kollhof + * Copyright (c) 2005 Michael Clark, Metaparadigm Pte Ltd + * + * Licensed under the Apache License, Version 2.0 (the "License"). + */ + +/** + * Escape a character. + */ +var JSONClient = new Object(); + +JSONClient.escapeJSONChar = function(c) { + if(c == "\"" || c == "\\") return "\\" + c; + else if (c == "\b") return "\\b"; + else if (c == "\f") return "\\f"; + else if (c == "\n") return "\\n"; + else if (c == "\r") return "\\r"; + else if (c == "\t") return "\\t"; + var hex = c.charCodeAt(0).toString(16); + if(hex.length == 1) return "\\u000" + hex; + else if(hex.length == 2) return "\\u00" + hex; + else if(hex.length == 3) return "\\u0" + hex; + else return "\\u" + hex; +}; + +/** + * Encode a string into JSON format. + */ +JSONClient.escapeJSONString = function(s) { + /* The following should suffice but Safari's regex is broken + (doesn't support callback substitutions) + return "\"" + s.replace(/([^\u0020-\u007f]|[\\\"])/g, + JSONClient.escapeJSONChar) + "\""; + */ + + /* Rather inefficient way to do it */ + var parts = s.split(""); + for(var i = 0; i < parts.length; i++) { + var c = parts[i]; + if(c == '"' || + c == '\\' || + c.charCodeAt(0) < 32 || + c.charCodeAt(0) >= 128) + parts[i] = JSONClient.escapeJSONChar(parts[i]); + } + return "\"" + parts.join("") + "\""; +}; + +/** + * Marshall objects to JSON format. + */ +JSONClient.toJSON = function(o) { + if(o == null) { + return "null"; + } else if(o.constructor == String) { + return JSONClient.escapeJSONString(o); + } else if(o.constructor == Number) { + return o.toString(); + } else if(o.constructor == Boolean) { + return o.toString(); + } else if(o.constructor == Date) { + return '{javaClass: "java.util.Date", time: ' + o.valueOf() +'}'; + } else if(o.constructor == Array) { + var v = []; + for(var i = 0; i < o.length; i++) v.push(JSONClient.toJSON(o[i])); + return "[" + v.join(", ") + "]"; + } else { + var v = []; + for(attr in o) { + if(o[attr] == null) v.push("\"" + attr + "\": null"); + else if(typeof o[attr] == "function"); /* skip */ + else v.push(JSONClient.escapeJSONString(attr) + ": " + JSONClient.toJSON(o[attr])); + } + return "{" + v.join(", ") + "}"; + } +}; + +/** + * HTTPBindingClient.Exception. + */ +HTTPBindingClient.Exception = function(code, message, javaStack) { + this.code = code; + var name; + if(javaStack) { + this.javaStack = javaStack; + var m = javaStack.match(/^([^:]*)/); + if(m) name = m[0]; + } + if(name) this.name = name; + else this.name = "HTTPBindingClientException"; + this.message = message; +}; + +HTTPBindingClient.Exception.CODE_REMOTE_EXCEPTION = 490; +HTTPBindingClient.Exception.CODE_ERR_CLIENT = 550; +HTTPBindingClient.Exception.CODE_ERR_PARSE = 590; +HTTPBindingClient.Exception.CODE_ERR_NOMETHOD = 591; +HTTPBindingClient.Exception.CODE_ERR_UNMARSHALL = 592; +HTTPBindingClient.Exception.CODE_ERR_MARSHALL = 593; + +HTTPBindingClient.Exception.prototype = new Error(); +HTTPBindingClient.Exception.prototype.toString = function(code, msg) { + return this.name + ": " + this.message; +}; + +/** + * Default top level exception handler. + */ +HTTPBindingClient.default_ex_handler = function(e) { + alert(e); +}; + +/** + * Client settable variables + */ +HTTPBindingClient.toplevel_ex_handler = HTTPBindingClient.default_ex_handler; +HTTPBindingClient.profile_async = false; +HTTPBindingClient.max_req_active = 1; +HTTPBindingClient.requestId = 1; + +/** + * HTTPBindingClient implementation + */ +HTTPBindingClient.prototype._createApplyMethod = function() { + var fn = function() { + var args = []; + var callback = null; + var methodName = arguments[0]; + for(var i = 1; i < arguments.length; i++) args.push(arguments[i]); + + if(typeof args[args.length - 1] == "function") callback = args.pop(); + + var req = fn.client._makeRequest.call(fn.client, methodName, args, callback); + if(callback == null) { + return fn.client._sendRequest.call(fn.client, req); + } else { + HTTPBindingClient.async_requests.push(req); + HTTPBindingClient.kick_async(); + return req.requestId; + } + }; + fn.client = this; + return fn; +}; + +HTTPBindingClient._getCharsetFromHeaders = function(http) { + try { + var contentType = http.getResponseHeader("Content-type"); + var parts = contentType.split(/\s*;\s*/); + for(var i = 0; i < parts.length; i++) { + if(parts[i].substring(0, 8) == "charset=") + return parts[i].substring(8, parts[i].length); + } + } catch (e) {} + return "UTF-8"; +}; + +/** + * Async queue globals + */ +HTTPBindingClient.async_requests = []; +HTTPBindingClient.async_inflight = {}; +HTTPBindingClient.async_responses = []; +HTTPBindingClient.async_timeout = null; +HTTPBindingClient.num_req_active = 0; + +HTTPBindingClient._async_handler = function() { + HTTPBindingClient.async_timeout = null; + + while(HTTPBindingClient.async_responses.length > 0) { + var res = HTTPBindingClient.async_responses.shift(); + if(res.canceled) continue; + if(res.profile) res.profile.dispatch = new Date(); + try { + res.cb(res.result, res.ex, res.profile); + } catch(e) { + HTTPBindingClient.toplevel_ex_handler(e); + } + } + + while(HTTPBindingClient.async_requests.length > 0 && HTTPBindingClient.num_req_active < HTTPBindingClient.max_req_active) { + var req = HTTPBindingClient.async_requests.shift(); + if(req.canceled) continue; + req.client._sendRequest.call(req.client, req); + } +}; + +HTTPBindingClient.kick_async = function() { + if(HTTPBindingClient.async_timeout == null) + HTTPBindingClient.async_timeout = setTimeout(HTTPBindingClient._async_handler, 0); +}; + +HTTPBindingClient.cancelRequest = function(requestId) { + /* If it is in flight then mark it as canceled in the inflight map + and the XMLHttpRequest callback will discard the reply. */ + if(HTTPBindingClient.async_inflight[requestId]) { + HTTPBindingClient.async_inflight[requestId].canceled = true; + return true; + } + + /* If its not in flight yet then we can just mark it as canceled in + the the request queue and it will get discarded before being sent. */ + for(var i in HTTPBindingClient.async_requests) { + if(HTTPBindingClient.async_requests[i].requestId == requestId) { + HTTPBindingClient.async_requests[i].canceled = true; + return true; + } + } + + /* It may have returned from the network and be waiting for its callback + to be dispatched, so mark it as canceled in the response queue + and the response will get discarded before calling the callback. */ + for(var i in HTTPBindingClient.async_responses) { + if(HTTPBindingClient.async_responses[i].requestId == requestId) { + HTTPBindingClient.async_responses[i].canceled = true; + return true; + } + } + + return false; +}; + +HTTPBindingClient.prototype._makeRequest = function(methodName, args, cb) { + var req = {}; + req.client = this; + req.requestId = HTTPBindingClient.requestId++; + + var obj = {}; + obj.id = req.requestId; + if (this.objectID) + obj.method = ".obj#" + this.objectID + "." + methodName; + else + obj.method = methodName; + obj.params = args; + + if (cb) req.cb = cb; + if (HTTPBindingClient.profile_async) + req.profile = { "submit": new Date() }; + req.data = JSONClient.toJSON(obj); + + return req; +}; + +HTTPBindingClient.prototype._sendRequest = function(req) { + if(req.profile) req.profile.start = new Date(); + + /* Get free http object from the pool */ + var http = HTTPBindingClient.poolGetHTTPRequest(); + HTTPBindingClient.num_req_active++; + + /* Send the request */ + http.open("POST", this.uri, (req.cb != null)); + + /* setRequestHeader is missing in Opera 8 Beta */ + try { + http.setRequestHeader("Content-type", "text/plain"); + } catch(e) {} + + /* Construct call back if we have one */ + if(req.cb) { + var self = this; + http.onreadystatechange = function() { + if(http.readyState == 4) { + http.onreadystatechange = function () {}; + var res = { "cb": req.cb, "result": null, "ex": null}; + if (req.profile) { + res.profile = req.profile; + res.profile.end = new Date(); + } + try { res.result = self._handleResponse(http); } + catch(e) { res.ex = e; } + if(!HTTPBindingClient.async_inflight[req.requestId].canceled) + HTTPBindingClient.async_responses.push(res); + delete HTTPBindingClient.async_inflight[req.requestId]; + HTTPBindingClient.kick_async(); + } + }; + } else { + http.onreadystatechange = function() {}; + } + + HTTPBindingClient.async_inflight[req.requestId] = req; + + try { + http.send(req.data); + } catch(e) { + HTTPBindingClient.poolReturnHTTPRequest(http); + HTTPBindingClient.num_req_active--; + throw new HTTPBindingClient.Exception(HTTPBindingClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + if(!req.cb) return this._handleResponse(http); +}; + +HTTPBindingClient.prototype._handleResponse = function(http) { + /* Get the charset */ + if(!this.charset) { + this.charset = HTTPBindingClient._getCharsetFromHeaders(http); + } + + /* Get request results */ + var status, statusText, data; + try { + status = http.status; + statusText = http.statusText; + data = http.responseText; + } catch(e) { + HTTPBindingClient.poolReturnHTTPRequest(http); + HTTPBindingClient.num_req_active--; + HTTPBindingClient.kick_async(); + throw new HTTPBindingClient.Exception(HTTPBindingClient.Exception.CODE_ERR_CLIENT, "Connection failed"); + } + + /* Return http object to the pool; */ + HTTPBindingClient.poolReturnHTTPRequest(http); + HTTPBindingClient.num_req_active--; + + /* Unmarshall the response */ + if(status != 200) { + throw new HTTPBindingClient.Exception(status, statusText); + } + var obj; + try { + eval("obj = " + data); + } catch(e) { + throw new HTTPBindingClient.Exception(550, "error parsing result"); + } + if(obj.error) + throw new HTTPBindingClient.Exception(obj.error.code, obj.error.msg, obj.error.trace); + var res = obj.result; + + /* Handle CallableProxy */ + if(res && res.objectID && res.JSONRPCType == "CallableReference") + return new HTTPBindingClient(this.uri, res.objectID); + + return res; +}; + + +/** + * XMLHttpRequest wrapper code + */ +HTTPBindingClient.http_spare = []; +HTTPBindingClient.http_max_spare = 8; + +HTTPBindingClient.poolGetHTTPRequest = function() { + if(HTTPBindingClient.http_spare.length > 0) { + return HTTPBindingClient.http_spare.pop(); + } + return HTTPBindingClient.getHTTPRequest(); +}; + +HTTPBindingClient.poolReturnHTTPRequest = function(http) { + if(HTTPBindingClient.http_spare.length >= HTTPBindingClient.http_max_spare) + delete http; + else + HTTPBindingClient.http_spare.push(http); +}; + +HTTPBindingClient.msxmlNames = [ "MSXML2.XMLHTTP.5.0", + "MSXML2.XMLHTTP.4.0", + "MSXML2.XMLHTTP.3.0", + "MSXML2.XMLHTTP", + "Microsoft.XMLHTTP" ]; + +HTTPBindingClient.getHTTPRequest = function() { + /* Mozilla XMLHttpRequest */ + try { + HTTPBindingClient.httpObjectName = "XMLHttpRequest"; + return new XMLHttpRequest(); + } catch(e) {} + + /* Microsoft MSXML ActiveX */ + for (var i=0; i < HTTPBindingClient.msxmlNames.length; i++) { + try { + HTTPBindingClient.httpObjectName = HTTPBindingClient.msxmlNames[i]; + return new ActiveXObject(HTTPBindingClient.msxmlNames[i]); + } catch (e) {} + } + + /* None found */ + HTTPBindingClient.httpObjectName = null; + throw new HTTPBindingClient.Exception(0, "Can't create XMLHttpRequest object"); +}; + + +HTTPBindingClient.prototype.get = function(id, responseFunction) { + var xhr = this.createXMLHttpRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + var strDocument = xhr.responseText; + var xmlDocument = xhr.responseXML; + if(!xmlDocument || xmlDocument.childNodes.length==0){ + xmlDocument = (new DOMParser()).parseFromString(strDocument, "text/xml"); + } + if (responseFunction != null) responseFunction(xmlDocument); + } else { + alert("get - Error getting data from the server"); + } + } + } + xhr.open("GET", this.uri + '/' + id, true); + xhr.send(null); +}; + +HTTPBindingClient.prototype.post = function (entry, responseFunction) { + var xhr = this.createXMLHttpRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 201) { + var strDocument = xhr.responseText; + var xmlDocument = xhr.responseXML; + if(!xmlDocument || xmlDocument.childNodes.length==0){ + xmlDocument = (new DOMParser()).parseFromString(strDocument, "text/xml"); + } + if (responseFunction != null) responseFunction(xmlDocument); + } else { + alert("post - Error getting data from the server"); + } + } + } + xhr.open("POST", this.uri, true); + xhr.setRequestHeader("Content-Type", "application/atom+xml"); + xhr.send(entry); +}; + +HTTPBindingClient.prototype.put = function (id, entry, responseFunction) { + var xhr = this.createXMLHttpRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + var strDocument = xhr.responseText; + var xmlDocument = xhr.responseXML; + if(!xmlDocument || xmlDocument.childNodes.length==0){ + xmlDocument = (new DOMParser()).parseFromString(strDocument, "text/xml"); + } + if (responseFunction != null) responseFunction(xmlDocument); + } else { + alert("put - Error getting data from the server"); + } + } + } + xhr.open("PUT", this.uri + '/' + id, true); + xhr.setRequestHeader("Content-Type", "application/atom+xml"); + xhr.send(entry); +}; + +HTTPBindingClient.prototype.del = function (id, responseFunction) { + var xhr = this.createXMLHttpRequest(); + xhr.onreadystatechange = function() { + if (xhr.readyState == 4) { + if (xhr.status == 200) { + if (responseFunction != null) responseFunction(); + } else { + alert("delete - Error getting data from the server"); + } + } + } + xhr.open("DELETE", this.uri + '/' + id, true); + xhr.send(null); +}; + +HTTPBindingClient.prototype.createXMLHttpRequest = function () { + /* Mozilla XMLHttpRequest */ + try { return new XMLHttpRequest(); } catch(e) {} + + /* Microsoft MSXML ActiveX */ + for (var i = 0; i < HTTPBindingClient.msxmlNames.length; i++) { + try { return new ActiveXObject(HTTPBindingClient.msxmlNames[i]); } catch (e) {} + } + alert("XML http request not supported"); + return null; +} + +/** + * Construct an HTTPBindingClient. + */ +function HTTPBindingClient(cname, uri, objectID) { + this.uri = "/references/" + cname + "/" + uri; + this.objectID = objectID; + this.apply = this._createApplyMethod(); + + if (typeof DOMParser == "undefined") { + DOMParser = function () {} + + DOMParser.prototype.parseFromString = function (str, contentType) { + if (typeof ActiveXObject != "undefined") { + var d = new ActiveXObject("MSXML.DomDocument"); + d.loadXML(str); + return d; + } else if (typeof XMLHttpRequest != "undefined") { + var req = new XMLHttpRequest; + req.open("GET", "data:" + (contentType || "application/xml") + + ";charset=utf-8," + encodeURIComponent(str), false); + if (req.overrideMimeType) { + req.overrideMimeType(contentType); + } + req.send(null); + return req.responseXML; + } + } + } +}; + +/** + * Construct a component. + */ +function ClientComponent(name) { + this.name = name; +} + +/** + * Public API. + */ + +/** + * Return a component. + */ +function component(name) { + return new ClientComponent(name); +} + +/** + * Return a reference proxy. + */ +function reference(comp, name) { + return new HTTPBindingClient(comp.name, name); +}; + +/** + * Add proxy functions to a reference proxy. + */ +function defun(ref) { + function defapply(name) { + return function() { + var args = new Array(); + args[0] = name; + for (i = 0, n = arguments.length; i < n; i++) + args[i + 1] = arguments[i]; + return this.apply.apply(this, args); + }; + } + + for (f = 1; f < arguments.length; f++) { + var fn = arguments[f]; + ref[fn]= defapply(fn); + } + return ref; +}; + diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/httpd-test b/sandbox/sebastien/cpp/apr-2/modules/server/httpd-test new file mode 100755 index 0000000000..050becdb24 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/httpd-test @@ -0,0 +1,78 @@ +#!/bin/sh + +# 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. + +echo "Testing..." +here=`readlink -f $0`; here=`dirname $here` +curl_prefix=`cat $here/../http/curl.prefix` + +# Setup +../http/httpd-conf tmp localhost 8090 htdocs +./server-conf tmp +./scheme-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite domain-test.composite +EOF + +../http/httpd-start tmp +sleep 2 + +# Test HTTP GET +$curl_prefix/bin/curl http://localhost:8090/index.html 2>/dev/null >tmp/index.html +diff tmp/index.html htdocs/index.html +rc=$? + +# Test ATOMPub +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/test/ >tmp/feed.xml 2>/dev/null + diff tmp/feed.xml htdocs/test/feed.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/test/111 >tmp/entry.xml 2>/dev/null + diff tmp/entry.xml htdocs/test/entry.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/test/ -X POST -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/test/111 -X PUT -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/test/111 -X DELETE 2>/dev/null + rc=$? +fi + +# Test JSON-RPC +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/test/ -X POST -H "Content-type: application/json-rpc" --data @htdocs/test/json-request.txt >tmp/json-result.txt 2>/dev/null + diff tmp/json-result.txt htdocs/test/json-result.txt + rc=$? +fi + +# Cleanup +../http/httpd-stop tmp +sleep 2 +if [ "$rc" = "0" ]; then + echo "OK" +fi +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/impl-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/server/impl-test.cpp new file mode 100644 index 0000000000..1bd0843745 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/impl-test.cpp @@ -0,0 +1,76 @@ +/* + * 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 component implementation. + */ + +#include "string.hpp" + +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" + +namespace tuscany { +namespace server { + +const failable<value> get(unused const list<value>& params) { + return value(mklist<value>("text/html", mklist<value>("Hey"))); +} + +const failable<value> post(unused const list<value>& params) { + return value(mklist<value>(string("123456789"))); +} + +const failable<value> put(unused const list<value>& params) { + return value(true); +} + +const failable<value> del(unused const list<value>& params) { + return value(true); +} + +const failable<value> echo(const list<value>& params) { + return value(car(params)); +} + +} +} + +extern "C" { + +const tuscany::value apply(const tuscany::list<tuscany::value>& params) { + const tuscany::value func(car(params)); + if (func == "get") + return tuscany::server::get(cdr(params)); + if (func == "post") + return tuscany::server::post(cdr(params)); + if (func == "put") + return tuscany::server::put(cdr(params)); + if (func == "delete") + return tuscany::server::del(cdr(params)); + if (func == "echo") + return tuscany::server::echo(cdr(params)); + return tuscany::mkfailure<tuscany::value>(); +} + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/mod-cpp.hpp b/sandbox/sebastien/cpp/apr-2/modules/server/mod-cpp.hpp new file mode 100644 index 0000000000..8cae35e493 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/mod-cpp.hpp @@ -0,0 +1,104 @@ +/* + * 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_modcpp_hpp +#define tuscany_modcpp_hpp + +/** + * Evaluation functions used by mod-eval to evaluate C++ + * component implementations. + */ + +#include "string.hpp" +#include "stream.hpp" + +#include "function.hpp" +#include "list.hpp" +#include "element.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "dynlib.hpp" +#include "../scheme/driver.hpp" + +namespace tuscany { +namespace server { +namespace modcpp { + +/** + * Apply a C++ component implementation function. + */ +const list<value> failableResult(const value& func, const list<value>& v) { + if (isNil(cdr(v))) + return v; + + // Report a failure with an empty reason as 'function not supported' + // Except for the start, and stop functions, which are optional + const value reason = cadr(v); + if (length(reason) == 0) { + if (func == "start" || func == "stop") + return mklist<value>(lambda<value(const list<value>&)>()); + return mklist<value>(value(), string("Function not supported: ") + func); + } + return v; +} + +struct applyImplementation { + const lib ilib; + const lambda<value(const list<value>&)> impl; + const list<value> px; + + applyImplementation(const lib& ilib, const lambda<value(const list<value>&)>& impl, const list<value>& px) : ilib(ilib), impl(impl), px(px) { + } + + const value operator()(const list<value>& params) const { + debug(params, "modeval::cpp::applyImplementation::input"); + + // Apply the component implementation function + const value val = failableResult(car(params), impl(append(params, px))); + + debug(val, "modeval::cpp::applyImplementation::result"); + return val; + } +}; + +/** + * Evaluate a C++ component implementation and convert it to + * an applicable lambda function. + */ +const failable<lambda<value(const list<value>&)> > evalImplementation(const string& path, const value& impl, const list<value>& px) { + + // Configure the implementation's lambda function + const value ipath(attributeValue("path", impl)); + const value iname(attributeValue("library", impl)); + const string fpath(isNil(ipath)? path + iname : path + ipath + "/" + iname); + const lib ilib(*(new (gc_new<lib>()) lib(fpath + dynlibExt))); + const failable<lambda<value(const list<value>&)> > evalf(dynlambda<value(const list<value>&)>("apply", ilib)); + if (!hasContent(evalf)) + return evalf; + const lambda<value(const list<value>&)> l(applyImplementation(ilib, content(evalf), px)); + return l; +} + +} +} +} + +#endif /* tuscany_modcpp_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/mod-eval.cpp b/sandbox/sebastien/cpp/apr-2/modules/server/mod-eval.cpp new file mode 100644 index 0000000000..a94ccf5bbe --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/mod-eval.cpp @@ -0,0 +1,62 @@ +/* + * 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$ */ + +/** + * HTTPD module used to eval C++ and Scheme component implementations. + */ + +#include "string.hpp" +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "mod-eval.hpp" +#include "mod-scheme.hpp" +#include "mod-cpp.hpp" + +namespace tuscany { +namespace server { +namespace modeval { + +/** + * Apply a lifecycle start or restart event. + */ +const value applyLifecycle(unused const list<value>& params) { + // Return a nil function as we don't need to handle any subsequent events + return failable<value>(lambda<value(const list<value>&)>()); +} + +/** + * Evaluate a Scheme or C++ component implementation and convert it to an + * applicable lambda function. + */ +const failable<lambda<value(const list<value>&)> > evalImplementation(const string& path, const value& impl, const list<value>& px, unused const lambda<value(const list<value>&)>& lifecycle) { + const string itype(elementName(impl)); + if (contains(itype, ".scheme")) + return modscheme::evalImplementation(path, impl, px); + if (contains(itype, ".cpp")) + return modcpp::evalImplementation(path, impl, px); + return mkfailure<lambda<value(const list<value>&)> >(string("Unsupported implementation type: ") + itype); +} + +} +} +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/mod-eval.hpp b/sandbox/sebastien/cpp/apr-2/modules/server/mod-eval.hpp new file mode 100644 index 0000000000..b8d3147459 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/mod-eval.hpp @@ -0,0 +1,896 @@ +/* + * 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_modeval_hpp +#define tuscany_modeval_hpp + +/** + * HTTPD module used to eval component implementations. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "function.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "value.hpp" +#include "element.hpp" +#include "monad.hpp" +#include "../atom/atom.hpp" +#include "../json/json.hpp" +#include "../scdl/scdl.hpp" +#include "../http/http.hpp" +#include "../http/httpd.hpp" + +extern "C" { +extern module AP_MODULE_DECLARE_DATA mod_tuscany_eval; +} + +namespace tuscany { +namespace server { +namespace modeval { + +/** + * Server configuration. + */ +class ServerConf { +public: + ServerConf(apr_pool_t* p, server_rec* s) : p(p), server(s), wiringServerName(""), contributionPath(""), compositeName(""), virtualHostContributionPath(""), virtualHostCompositeName(""), ca(""), cert(""), key("") { + } + + const gc_pool p; + server_rec* server; + lambda<value(const list<value>&)> lifecycle; + string wiringServerName; + string contributionPath; + string compositeName; + string virtualHostContributionPath; + string virtualHostCompositeName; + string ca; + string cert; + string key; + list<value> implementations; + list<value> implTree; +}; + +/** + * Return true if a server contains a composite configuration. + */ +const bool hasCompositeConf(const ServerConf& sc) { + return sc.contributionPath != "" && sc.compositeName != ""; +} + +/** + * Return true if a server contains a virtual host composite configuration. + */ +const bool hasVirtualCompositeConf(const ServerConf& sc) { + return sc.virtualHostContributionPath != "" && sc.virtualHostCompositeName != ""; +} + +/** + * Convert a result represented as a content + failure pair to a + * failable monad. + */ +const failable<value> failableResult(const list<value>& v) { + if (isNil(cdr(v))) + return car(v); + return mkfailure<value>(string(cadr(v))); +} + +/** + * Handle an HTTP GET. + */ +const failable<int> get(request_rec* r, const lambda<value(const list<value>&)>& impl) { + debug(r->uri, "modeval::get::uri"); + + // Inspect the query string + const list<list<value> > args = httpd::queryArgs(r); + const list<value> ia = assoc(value("id"), args); + const list<value> ma = assoc(value("method"), args); + + // Evaluate a JSON-RPC request and return a JSON result + if (!isNil(ia) && !isNil(ma)) { + + // Extract the request id, method and params + const value id = cadr(ia); + const value func = c_str(json::funcName(string(cadr(ma)))); + + // Apply the requested function + const failable<value> val = failableResult(impl(cons(func, json::queryParams(args)))); + if (!hasContent(val)) + return mkfailure<int>(reason(val)); + + // Return JSON result + js::JSContext cx; + return httpd::writeResult(json::jsonResult(id, content(val), cx), "application/json-rpc", r); + } + + // Evaluate the GET expression + const list<value> path(pathValues(r->uri)); + const failable<value> val = failableResult(impl(cons<value>("get", mklist<value>(cddr(path))))); + if (!hasContent(val)) + return mkfailure<int>(reason(val)); + const value c = content(val); + + // Write content-type / content-list pair + if (isString(car<value>(c)) && isList(cadr<value>(c))) + return httpd::writeResult(convertValues<string>(cadr<value>(c)), car<value>(c), r); + + // Write ATOM feed or entry + if (isString(car<value>(c)) && isString(cadr<value>(c))) { + if (isNil(cddr(path))) + return httpd::writeResult(atom::writeATOMFeed(atom::feedValuesToElements(c)), "application/atom+xml;type=feed", r); + else + return httpd::writeResult(atom::writeATOMEntry(atom::entryValuesToElements(c)), "application/atom+xml;type=entry", r); + } + + // Write JSON value + js::JSContext cx; + return httpd::writeResult(json::writeJSON(valuesToElements(c), cx), "application/json", r); +} + +/** + * Handle an HTTP POST. + */ +const failable<int> post(request_rec* r, const lambda<value(const list<value>&)>& impl) { + debug(r->uri, "modeval::post::url"); + + // Evaluate a JSON-RPC request and return a JSON result + const string ct = httpd::contentType(r); + if (contains(ct, "application/json-rpc") || contains(ct, "text/plain") || contains(ct, "application/x-www-form-urlencoded")) { + + // Read the JSON request + const int rc = httpd::setupReadPolicy(r); + if(rc != OK) + return rc; + const list<string> ls = httpd::read(r); + debug(ls, "modeval::post::input"); + js::JSContext cx; + const list<value> json = elementsToValues(content(json::readJSON(ls, cx))); + const list<list<value> > args = httpd::postArgs(json); + + // Extract the request id, method and params + const value id = cadr(assoc(value("id"), args)); + const value func = c_str(json::funcName(cadr(assoc(value("method"), args)))); + const list<value> params = (list<value>)cadr(assoc(value("params"), args)); + + // Evaluate the request expression + const failable<value> val = failableResult(impl(cons<value>(func, params))); + if (!hasContent(val)) + return mkfailure<int>(reason(val)); + + // Return JSON result + return httpd::writeResult(json::jsonResult(id, content(val), cx), "application/json-rpc", r); + } + + // Evaluate an ATOM POST request and return the location of the corresponding created resource + if (contains(ct, "application/atom+xml")) { + + // Read the ATOM entry + const list<value> path(pathValues(r->uri)); + const int rc = httpd::setupReadPolicy(r); + if(rc != OK) + return rc; + const list<string> ls = httpd::read(r); + debug(ls, "modeval::post::input"); + const value entry = atom::entryValue(content(atom::readATOMEntry(ls))); + + // Evaluate the POST expression + const failable<value> val = failableResult(impl(cons<value>("post", mklist<value>(cddr(path), entry)))); + if (!hasContent(val)) + return mkfailure<int>(reason(val)); + + // Return the created resource location + debug(content(val), "modeval::post::location"); + apr_table_setn(r->headers_out, "Location", apr_pstrdup(r->pool, c_str(httpd::url(r->uri, content(val), r)))); + r->status = HTTP_CREATED; + return OK; + } + + // Unknown content type, wrap the HTTP request struct in a value and pass it to + // the component implementation function + const failable<value> val = failableResult(impl(cons<value>("handle", mklist<value>(httpd::requestValue(r))))); + if (!hasContent(val)) + return mkfailure<int>(reason(val)); + return (int)content(val); +} + +/** + * Handle an HTTP PUT. + */ +const failable<int> put(request_rec* r, const lambda<value(const list<value>&)>& impl) { + debug(r->uri, "modeval::put::url"); + + // Read the ATOM entry + const list<value> path(pathValues(r->uri)); + const int rc = httpd::setupReadPolicy(r); + if(rc != OK) + return rc; + const list<string> ls = httpd::read(r); + debug(ls, "modeval::put::input"); + const value entry = atom::entryValue(content(atom::readATOMEntry(ls))); + + // Evaluate the PUT expression and update the corresponding resource + const failable<value> val = failableResult(impl(cons<value>("put", mklist<value>(cddr(path), entry)))); + if (!hasContent(val)) + return mkfailure<int>(reason(val)); + if (val == value(false)) + return HTTP_NOT_FOUND; + return OK; +} + +/** + * Handle an HTTP DELETE. + */ +const failable<int> del(request_rec* r, const lambda<value(const list<value>&)>& impl) { + debug(r->uri, "modeval::delete::url"); + + // Evaluate an ATOM delete request + const list<value> path(pathValues(r->uri)); + const failable<value> val = failableResult(impl(cons<value>("delete", mklist<value>(cddr(path))))); + if (!hasContent(val)) + return mkfailure<int>(reason(val)); + if (val == value(false)) + return HTTP_NOT_FOUND; + return OK; +} + +/** + * Translate a component request. + */ +int translate(request_rec *r) { + if(r->method_number != M_GET && r->method_number != M_POST && r->method_number != M_PUT && r->method_number != M_DELETE) + return DECLINED; + if (strncmp(r->uri, "/components/", 12) != 0) + return DECLINED; + r->handler = "mod_tuscany_eval"; + return OK; +} + +/** + * Make an HTTP proxy lambda. + */ +const value mkhttpProxy(const ServerConf& sc, const string& ref, const string& base) { + const string uri = base + ref; + debug(uri, "modeval::mkhttpProxy::uri"); + return lambda<value(const list<value>&)>(http::proxy(uri, sc.ca, sc.cert, sc.key, sc.p)); +} + +/** + * Return a component implementation proxy lambda. + */ +class implProxy { +public: + implProxy(const ServerConf& sc, const value& name) : sc(sc), name(name) { + } + + const value operator()(const list<value>& params) const { + debug(params, "modeval::implProxy::input"); + + // Lookup the component implementation + const list<value> impl(assoctree<value>(name, sc.implTree)); + if (isNil(impl)) + return mkfailure<value>(string("Couldn't find component implementation: ") + name); + + // Call its lambda function + const lambda<value(const list<value>&)> l(cadr<value>(impl)); + const value func = c_str(car(params)); + const failable<value> val = failableResult(l(cons(func, cdr(params)))); + debug(val, "modeval::implProxy::result"); + if (!hasContent(val)) + return value(); + return content(val); + } + +private: + const ServerConf& sc; + const value name; +}; + +const value mkimplProxy(const ServerConf& sc, const value& name) { + debug(name, "modeval::implProxy::impl"); + return lambda<value(const list<value>&)>(implProxy(sc, name)); +} + +/** + * Convert a list of component references to a list of proxy lambdas. + */ +const value mkrefProxy(const ServerConf& sc, const value& ref, const string& base) { + const value target = scdl::target(ref); + debug(ref, "modeval::mkrefProxy::ref"); + debug(target, "modeval::mkrefProxy::target"); + + // Use an HTTP proxy or an internal proxy to the component implementation + if (isNil(target) || httpd::isAbsolute(target)) + return mkhttpProxy(sc, scdl::name(ref), base); + return mkimplProxy(sc, car(pathValues(target))); +} + +const list<value> refProxies(const ServerConf& sc, const list<value>& refs, const string& base) { + if (isNil(refs)) + return refs; + return cons(mkrefProxy(sc, car(refs), base), refProxies(sc, cdr(refs), base)); +} + +/** + * Store current HTTP request for access from property lambda functions. + */ +#ifdef WANT_THREADS +__thread +#endif +request_rec* currentRequest = NULL; + +class ScopedRequest { +public: + ScopedRequest(request_rec* r) { + currentRequest = r; + } + + ~ScopedRequest() { + currentRequest = NULL; + } +}; + +/** + * Convert a list of component properties to a list of lambda functions that just return + * the property value. The host, user and email properties are configured with the values + * from the HTTP request, if any. + */ +struct propProxy { + const value v; + propProxy(const value& v) : v(v) { + } + const value operator()(unused const list<value>& params) const { + return v; + } +}; + +struct hostPropProxy { + const value v; + hostPropProxy(const value& v) : v(v) { + } + const value operator()(unused const list<value>& params) const { + return httpd::hostName(currentRequest, v); + } +}; + +struct envPropProxy { + const string name; + const value v; + envPropProxy(const string& name, const value& v) : name(name), v(v) { + } + const value operator()(unused const list<value>& params) const { + const char* env = apr_table_get(currentRequest->subprocess_env, c_str(name)); + if (env == NULL || *env == '\0') + return v; + return string(env); + } +}; + +struct userPropProxy { + const value v; + userPropProxy(const value& v) : v(v) { + } + const value operator()(unused const list<value>& params) const { + if (currentRequest->user == NULL) + return v; + return string(currentRequest->user); + } +}; + +const value mkpropProxy(const value& prop) { + if (scdl::name(prop) == "host") + return lambda<value(const list<value>&)>(hostPropProxy(elementValue(prop))); + if (scdl::name(prop) == "user") + return lambda<value(const list<value>&)>(userPropProxy(elementValue(prop))); + if (scdl::name(prop) == "realm") + return lambda<value(const list<value>&)>(envPropProxy("REALM", elementValue(prop))); + if (scdl::name(prop) == "email") + return lambda<value(const list<value>&)>(envPropProxy("EMAIL", elementValue(prop))); + if (scdl::name(prop) == "nickname") + return lambda<value(const list<value>&)>(envPropProxy("NICKNAME", elementValue(prop))); + if (scdl::name(prop) == "fullname") + return lambda<value(const list<value>&)>(envPropProxy("FULLNAME", elementValue(prop))); + if (scdl::name(prop) == "firstname") + return lambda<value(const list<value>&)>(envPropProxy("FIRSTNAME", elementValue(prop))); + if (scdl::name(prop) == "lastname") + return lambda<value(const list<value>&)>(envPropProxy("LASTNAME", elementValue(prop))); + return lambda<value(const list<value>&)>(propProxy(elementValue(prop))); +} + +const list<value> propProxies(const list<value>& props) { + if (isNil(props)) + return props; + return cons(mkpropProxy(car(props)), propProxies(cdr(props))); +} + +/** + * Evaluate a component and convert it to an applicable lambda function. + */ +struct implementationFailure { + const value reason; + implementationFailure(const value& r) : reason(r) { + } + + // Default implementation representing an implementation that + // couldn't be evaluated. Report the evaluation error on all + // subsequent calls expect start/stop. + const value operator()(unused const list<value>& params) const { + const value func = car(params); + if (func == "start" || func == "stop") + return mklist<value>(lambda<value(const list<value>&)>()); + return mklist<value>(value(), reason); + } +}; + +const value evalComponent(ServerConf& sc, const value& comp) { + extern const failable<lambda<value(const list<value>&)> > evalImplementation(const string& cpath, const value& impl, const list<value>& px, const lambda<value(const list<value>&)>& lifecycle); + + const value impl = scdl::implementation(comp); + debug(comp, "modeval::evalComponent::comp"); + debug(impl, "modeval::evalComponent::impl"); + + // Convert component references to configured proxy lambdas + ostringstream base; + base << sc.wiringServerName << "/references/" << string(scdl::name(comp)) << "/"; + const list<value> rpx(refProxies(sc, scdl::references(comp), str(base))); + + // Convert component proxies to configured proxy lambdas + const list<value> ppx(propProxies(scdl::properties(comp))); + + // Evaluate the component implementation and convert it to an applicable lambda function + const failable<lambda<value(const list<value>&)> > cimpl(evalImplementation(sc.contributionPath, impl, append(rpx, ppx), sc.lifecycle)); + if (!hasContent(cimpl)) + return lambda<value(const list<value>&)>(implementationFailure(reason(cimpl))); + return content(cimpl); +} + +/** + * Return a list of component-name + configured-implementation pairs. + */ +const list<value> componentToImplementationAssoc(ServerConf& sc, const list<value>& c) { + if (isNil(c)) + return c; + return cons<value>(mklist<value>(scdl::name(car(c)), evalComponent(sc, car(c))), componentToImplementationAssoc(sc, cdr(c))); +} + +/** + * Read the components declared in a composite. + */ +const failable<list<value> > readComponents(const string& path) { + ifstream is(path); + if (fail(is)) + return mkfailure<list<value> >(string("Could not read composite: ") + path); + return scdl::components(readXML(streamList(is))); +} + +/** + * Apply a list of component implementations to a start or restart lifecycle expression. + * Return the functions returned by the component implementations. + */ +const failable<list<value> > applyLifecycleExpr(const list<value>& impls, const list<value>& expr) { + if (isNil(impls)) + return list<value>(); + + // Evaluate lifecycle expression against a component implementation lambda + const lambda<value(const list<value>&)> l = cadr<value>(car(impls)); + const failable<value> r = failableResult(l(expr)); + if (!hasContent(r)) + return mkfailure<list<value> >(reason(r)); + const lambda<value(const list<value>&)> rl = content(r); + + // Use the returned lambda function, if any, from now on + const lambda<value(const list<value>&)> al = isNil(rl)? l : rl; + + // Continue with the rest of the list + const failable<list<value> > nr = applyLifecycleExpr(cdr(impls), expr); + if (!hasContent(nr)) + return nr; + return cons<value>(mklist<value>(car<value>(car(impls)), value(al)), content(nr)); +} + +/** + * Configure the components declared in the deployed composite. + */ +const failable<bool> confComponents(ServerConf& sc) { + if (!hasCompositeConf(sc)) + return false; + debug(sc.contributionPath, "modeval::confComponents::contributionPath"); + debug(sc.compositeName, "modeval::confComponents::compositeName"); + if (sc.ca != "") debug(sc.ca, "modeval::confComponents::sslCA"); + if (sc.cert != "") debug(sc.cert, "modeval::confComponents::sslCert"); + if (sc.key != "") debug(sc.key, "modeval::confComponents::sslKey"); + + // Read the components and get their implementation lambda functions + const failable<list<value> > comps = readComponents(sc.contributionPath + sc.compositeName); + if (!hasContent(comps)) + return mkfailure<bool>(reason(comps)); + sc.implementations = componentToImplementationAssoc(sc, content(comps)); + debug(sc.implementations, "modeval::confComponents::implementations"); + return true; +} + +/** + * Start the components declared in the deployed composite. + */ +const failable<bool> startComponents(ServerConf& sc) { + + // Start the components and record the returned implementation lambda functions + debug(sc.implementations, "modeval::startComponents::start"); + const failable<list<value> > impls = applyLifecycleExpr(sc.implementations, mklist<value>("start")); + if (!hasContent(impls)) + return mkfailure<bool>(reason(impls)); + sc.implementations = content(impls); + debug(sc.implementations, "modeval::startComponents::implementations"); + return true; +} + +/** + * Virtual host scoped server configuration. + */ +class VirtualHostConf { +public: + VirtualHostConf(const gc_pool& p, const ServerConf& sc) : sc(sc), vsc(pool(p), sc.server) { + vsc.virtualHostContributionPath = sc.virtualHostContributionPath; + vsc.virtualHostCompositeName = sc.virtualHostCompositeName; + vsc.ca = sc.ca; + vsc.cert = sc.cert; + vsc.key = sc.key; + } + + ~VirtualHostConf() { + extern const failable<bool> virtualHostCleanup(const ServerConf& vsc, const ServerConf& sc); + virtualHostCleanup(vsc, sc); + } + + const ServerConf& sc; + ServerConf vsc; +}; + +/** + * Configure and start the components deployed in a virtual host. + */ +const failable<bool> virtualHostConfig(ServerConf& vsc, const ServerConf& sc, request_rec* r) { + + // Determine the server name and wiring server name + debug(httpd::serverName(vsc.server), "modeval::virtualHostConfig::serverName"); + debug(httpd::serverName(r), "modeval::virtualHostConfig::virtualHostName"); + vsc.wiringServerName = httpd::serverName(r); + debug(vsc.wiringServerName, "modeval::virtualHostConfig::wiringServerName"); + debug(vsc.virtualHostContributionPath, "modwiring::virtualHostConfig::virtualHostContributionPath"); + + // Resolve the configured virtual contribution under + // the virtual host's SCA contribution root + vsc.contributionPath = vsc.virtualHostContributionPath + httpd::subdomain(httpd::hostName(r)) + "/"; + vsc.compositeName = vsc.virtualHostCompositeName; + + // Chdir to the virtual host's contribution + if (chdir(c_str(sc.contributionPath)) != 0) + return mkfailure<bool>(string("Couldn't chdir to the deployed contribution: ") + sc.contributionPath); + + // Configure the deployed components + const failable<bool> cr = confComponents(vsc); + if (!hasContent(cr)) + return cr; + + // Start the configured components + const failable<bool> sr = startComponents(vsc); + if (!hasContent(sr)) + return sr; + + // Store the implementation lambda functions (from both the virtual host and the + // main server) in a tree for fast retrieval + vsc.implTree = mkbtree(sort(append(vsc.implementations, sc.implementations))); + return true; +} + +/** + * Cleanup a virtual host. + */ +const failable<bool> virtualHostCleanup(const ServerConf& vsc, const ServerConf& sc) { + if (!hasCompositeConf(vsc)) + return true; + debug("modeval::virtualHostCleanup"); + + // Stop the component implementations + applyLifecycleExpr(vsc.implementations, mklist<value>("stop")); + + // Chdir back to the main server's contribution + if (chdir(c_str(sc.contributionPath)) != 0) + return mkfailure<bool>(string("Couldn't chdir to the deployed contribution: ") + sc.contributionPath); + return true; +} + +/** + * HTTP request handler. + */ +int handler(request_rec *r) { + if(r->method_number != M_GET && r->method_number != M_POST && r->method_number != M_PUT && r->method_number != M_DELETE) + return DECLINED; + if(strcmp(r->handler, "mod_tuscany_eval")) + return DECLINED; + + gc_scoped_pool pool(r->pool); + ScopedRequest sr(r); + httpdDebugRequest(r, "modeval::handler::input"); + + // Get the server configuration + const ServerConf& sc = httpd::serverConf<ServerConf>(r, &mod_tuscany_eval); + + // Process dynamic virtual host configuration, if any + VirtualHostConf vhc(gc_pool(r->pool), sc); + const bool usevh = hasVirtualCompositeConf(vhc.vsc) && httpd::isVirtualHostRequest(sc.server, r); + if (usevh) { + const failable<bool> cr = virtualHostConfig(vhc.vsc, sc, r); + if (!hasContent(cr)) + return httpd::reportStatus(mkfailure<int>(reason(cr))); + } + + // Get the component implementation lambda + const list<value> path(pathValues(r->uri)); + const list<value> impl(assoctree<value>(cadr(path), usevh? vhc.vsc.implTree : sc.implTree)); + if (isNil(impl)) + return httpd::reportStatus(mkfailure<int>(string("Couldn't find component implementation: ") + cadr(path))); + + // Handle HTTP method + const lambda<value(const list<value>&)> l(cadr<value>(impl)); + if (r->header_only) + return OK; + if(r->method_number == M_GET) + return httpd::reportStatus(get(r, l)); + if(r->method_number == M_POST) + return httpd::reportStatus(post(r, l)); + if(r->method_number == M_PUT) + return httpd::reportStatus(put(r, l)); + if(r->method_number == M_DELETE) + return httpd::reportStatus(del(r, l)); + return HTTP_NOT_IMPLEMENTED; +} + +/** + * Cleanup callback, called when the server is stopped or restarted. + */ +apr_status_t serverCleanup(void* v) { + gc_pool pool; + ServerConf& sc = *(ServerConf*)v; + debug("modeval::serverCleanup"); + + // Stop the component implementations + applyLifecycleExpr(sc.implementations, mklist<value>("stop")); + + // Call the module lifecycle function + if (isNil(sc.lifecycle)) + return APR_SUCCESS; + debug("modeval::serverCleanup::stop"); + sc.lifecycle(mklist<value>("stop")); + + return APR_SUCCESS; +} + +/** + * Called after all the configuration commands have been run. + * Process the server configuration and configure the deployed components. + */ +const int postConfigMerge(const ServerConf& mainsc, server_rec* s) { + if (s == NULL) + return OK; + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_eval); + debug(httpd::serverName(s), "modeval::postConfigMerge::serverName"); + if (sc.wiringServerName == "") + sc.wiringServerName = mainsc.wiringServerName != ""? mainsc.wiringServerName : httpd::serverName(s); + debug(sc.wiringServerName, "modeval::postConfigMerge::wiringServerName"); + sc.contributionPath = mainsc.contributionPath; + sc.compositeName = mainsc.compositeName; + sc.virtualHostContributionPath = mainsc.virtualHostContributionPath; + sc.virtualHostCompositeName = mainsc.virtualHostCompositeName; + if (sc.ca == "") sc.ca = mainsc.ca; + if (sc.cert == "") sc.cert = mainsc.cert; + if (sc.key == "") sc.key = mainsc.key; + sc.implementations = mainsc.implementations; + sc.implTree = mainsc.implTree; + return postConfigMerge(mainsc, s->next); +} + +int postConfig(apr_pool_t *p, unused apr_pool_t *plog, unused apr_pool_t *ptemp, server_rec *s) { + extern const value applyLifecycle(const list<value>&); + + gc_scoped_pool pool(p); + + // Get the server configuration and determine the wiring server name + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_eval); + debug(httpd::serverName(s), "modeval::postConfig::serverName"); + if (sc.wiringServerName == "") sc.wiringServerName = httpd::serverName(s); + debug(sc.wiringServerName, "modeval::postConfig::wiringServerName"); + + // Count the calls to post config + const string k("tuscany::modeval::postConfig"); + const long int count = (long int)httpd::userData(k, s); + httpd::putUserData(k, (void*)(count + 1), s); + + // Count == 0, do nothing as post config is always called twice, + // count == 1 is the first start, count > 1 is a restart + if (count == 0) + return OK; + + if (count == 1) { + // Chdir to the deployed contribution + if (chdir(c_str(sc.contributionPath)) != 0) { + mkfailure<bool>(string("Couldn't chdir to the deployed contribution: ") + sc.contributionPath); + return -1; + } + + debug("modeval::postConfig::start"); + const failable<value> r = failableResult(applyLifecycle(mklist<value>("start"))); + if (!hasContent(r)) + return -1; + sc.lifecycle = content(r); + } + if (count > 1) { + debug("modeval::postConfig::restart"); + const failable<value> r = failableResult(applyLifecycle(mklist<value>("restart"))); + if (!hasContent(r)) + return -1; + sc.lifecycle = content(r); + } + + // Configure the deployed components + const failable<bool> res = confComponents(sc); + if (!hasContent(res)) { + cfailure << "[Tuscany] Due to one or more errors mod_tuscany_eval loading failed. Causing apache to stop loading." << endl; + return -1; + } + + // Register a cleanup callback, called when the server is stopped or restarted + apr_pool_pre_cleanup_register(p, (void*)&sc, serverCleanup); + + // Merge the configuration into the virtual hosts + return postConfigMerge(sc, s->next); +} + +/** + * Child process initialization. + */ +void childInit(apr_pool_t* p, server_rec* s) { + gc_scoped_pool pool(p); + ServerConf* psc = (ServerConf*)ap_get_module_config(s->module_config, &mod_tuscany_eval); + if(psc == NULL) { + cfailure << "[Tuscany] Due to one or more errors mod_tuscany_eval loading failed. Causing apache to stop loading." << endl; + exit(APEXIT_CHILDFATAL); + } + ServerConf& sc = *psc; + + // Start the components in the child process + const failable<bool> res = startComponents(sc); + if (!hasContent(res)) { + cfailure << "[Tuscany] Due to one or more errors mod_tuscany_eval loading failed. Causing apache to stop loading." << endl; + exit(APEXIT_CHILDFATAL); + } + + // Store the implementation lambda functions in a tree for fast retrieval + sc.implTree = mkbtree(sort(sc.implementations)); + + // Merge the updated configuration into the virtual hosts + postConfigMerge(sc, s->next); + + // Register a cleanup callback, called when the child is stopped or restarted + apr_pool_pre_cleanup_register(p, (void*)psc, serverCleanup); +} + +/** + * Configuration commands. + */ +const char* confWiringServerName(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.wiringServerName = arg; + return NULL; +} +const char* confContribution(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.contributionPath = arg; + return NULL; +} +const char* confComposite(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.compositeName = arg; + return NULL; +} +const char* confVirtualContribution(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.virtualHostContributionPath = arg; + return NULL; +} +const char* confVirtualComposite(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.virtualHostCompositeName = arg; + return NULL; +} +const char* confCAFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.ca = arg; + return NULL; +} +const char* confCertFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.cert = arg; + return NULL; +} +const char* confCertKeyFile(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_eval); + sc.key = arg; + return NULL; +} +const char* confEnv(unused cmd_parms *cmd, unused void *c, const char *name, const char *value) { + gc_scoped_pool pool(cmd->pool); + setenv(name, value != NULL? value : "", 1); + return NULL; +} + +/** + * HTTP server module declaration. + */ +const command_rec commands[] = { + AP_INIT_TAKE1("SCAWiringServerName", (const char*(*)())confWiringServerName, NULL, RSRC_CONF, "SCA wiring server name"), + AP_INIT_TAKE1("SCAContribution", (const char*(*)())confContribution, NULL, RSRC_CONF, "SCA contribution location"), + AP_INIT_TAKE1("SCAComposite", (const char*(*)())confComposite, NULL, RSRC_CONF, "SCA composite location"), + AP_INIT_TAKE1("SCAVirtualContribution", (const char*(*)())confVirtualContribution, NULL, RSRC_CONF, "SCA virtual host contribution location"), + AP_INIT_TAKE1("SCAVirtualComposite", (const char*(*)())confVirtualComposite, NULL, RSRC_CONF, "SCA virtual composite location"), + AP_INIT_TAKE12("SCASetEnv", (const char*(*)())confEnv, NULL, OR_FILEINFO, "Environment variable name and optional value"), + AP_INIT_TAKE1("SCAWiringSSLCACertificateFile", (const char*(*)())confCAFile, NULL, RSRC_CONF, "SCA wiring SSL CA certificate file"), + AP_INIT_TAKE1("SCAWiringSSLCertificateFile", (const char*(*)())confCertFile, NULL, RSRC_CONF, "SCA wiring SSL certificate file"), + AP_INIT_TAKE1("SCAWiringSSLCertificateKeyFile", (const char*(*)())confCertKeyFile, NULL, RSRC_CONF, "SCA wiring SSL certificate key file"), + {NULL, NULL, NULL, 0, NO_ARGS, NULL} +}; + + +void registerHooks(unused apr_pool_t *p) { + ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_translate_name(translate, NULL, NULL, APR_HOOK_FIRST); +} + +} +} +} + +extern "C" { + +module AP_MODULE_DECLARE_DATA mod_tuscany_eval = { + STANDARD20_MODULE_STUFF, + // dir config and merger + NULL, NULL, + // server config and merger + tuscany::httpd::makeServerConf<tuscany::server::modeval::ServerConf>, NULL, + // commands and hooks + tuscany::server::modeval::commands, tuscany::server::modeval::registerHooks +}; + +} + +#endif diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/mod-scheme.hpp b/sandbox/sebastien/cpp/apr-2/modules/server/mod-scheme.hpp new file mode 100644 index 0000000000..43d7bf4041 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/mod-scheme.hpp @@ -0,0 +1,91 @@ +/* + * 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_modscheme_hpp +#define tuscany_modscheme_hpp + +/** + * Evaluation functions used by mod-eval to evaluate Scheme + * component implementations. + */ + +#include "string.hpp" +#include "stream.hpp" +#include "function.hpp" +#include "list.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "../scheme/eval.hpp" + +namespace tuscany { +namespace server { +namespace modscheme { + +/** + * Convert proxy lambdas to evaluator primitive procedures. + */ +const list<value> primitiveProcedures(const list<value>& l) { + if (isNil(l)) + return l; + return cons<value>(mklist<value>(scheme::primitiveSymbol, car(l)), primitiveProcedures(cdr(l))); +} + +/** + * Apply a Scheme component implementation function. + */ +struct applyImplementation { + const value impl; + const list<value> px; + + applyImplementation(const value& impl, const list<value>& px) : impl(impl), px(scheme::quotedParameters(primitiveProcedures(px))) { + } + + const value operator()(const list<value>& params) const { + const value expr = cons<value>(car(params), append(scheme::quotedParameters(cdr(params)), px)); + debug(expr, "modeval::scheme::applyImplementation::input"); + scheme::Env env = scheme::setupEnvironment(); + const value res = scheme::evalScript(expr, impl, env); + const value val = isNil(res)? mklist<value>(value(), string("Could not evaluate expression")) : mklist<value>(res); + debug(val, "modeval::scheme::applyImplementation::result"); + return val; + } +}; + +/** + * Evaluate a Scheme component implementation and convert it to an + * applicable lambda function. + */ +const failable<lambda<value(const list<value>&)> > evalImplementation(const string& path, const value& impl, const list<value>& px) { + const string fpath(path + attributeValue("script", impl)); + ifstream is(fpath); + if (fail(is)) + return mkfailure<lambda<value(const list<value>&)> >(string("Could not read implementation: ") + fpath); + const value script = scheme::readScript(is); + if (isNil(script)) + return mkfailure<lambda<value(const list<value>&)> >(string("Could not read implementation: ") + fpath); + return lambda<value(const list<value>&)>(applyImplementation(script, px)); +} + +} +} +} + +#endif /* tuscany_modscheme_hpp */ diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/mod-wiring.cpp b/sandbox/sebastien/cpp/apr-2/modules/server/mod-wiring.cpp new file mode 100644 index 0000000000..0ab61f5af8 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/mod-wiring.cpp @@ -0,0 +1,472 @@ +/* + * 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$ */ + +/** + * HTTPD module used to wire component references and route requests to + * target service components. + */ + +#include <sys/stat.h> + +#include "string.hpp" +#include "stream.hpp" +#include "list.hpp" +#include "tree.hpp" +#include "value.hpp" +#include "monad.hpp" +#include "../scdl/scdl.hpp" +#include "../http/httpd.hpp" + +extern "C" { +extern module AP_MODULE_DECLARE_DATA mod_tuscany_wiring; +} + +namespace tuscany { +namespace server { +namespace modwiring { + +/** + * Set to true to wire using mod_proxy, false to wire using HTTP client redirects. + */ +const bool useModProxy = true; + +/** + * Server configuration. + */ +class ServerConf { +public: + ServerConf(apr_pool_t* p, server_rec* s) : p(p), server(s), contributionPath(""), compositeName(""), virtualHostContributionPath(""), virtualHostCompositeName("") { + } + + const gc_pool p; + server_rec* server; + string contributionPath; + string compositeName; + string virtualHostContributionPath; + string virtualHostCompositeName; + list<value> references; + list<value> services; +}; + +/** + * Return true if a server contains a composite configuration. + */ +const bool hasCompositeConf(const ServerConf& sc) { + return sc.contributionPath != "" && sc.compositeName != ""; +} + +/** + * Return true if a server contains a virtual host composite configuration. + */ +const bool hasVirtualCompositeConf(const ServerConf& sc) { + return sc.virtualHostContributionPath != "" && sc.virtualHostCompositeName != ""; +} + +/** + * Route a /references/component-name/reference-name request, + * to the target of the component reference. + */ +int translateReference(const ServerConf& sc, request_rec *r) { + httpdDebugRequest(r, "modwiring::translateReference::input"); + debug(r->uri, "modwiring::translateReference::uri"); + + // Find the requested component + const list<value> rpath(pathValues(r->uri)); + const list<value> comp(assoctree(cadr(rpath), sc.references)); + if (isNil(comp)) + return HTTP_NOT_FOUND; + + // Find the requested reference and target configuration + const list<value> ref(assoctree<value>(caddr(rpath), cadr(comp))); + if (isNil(ref)) + return HTTP_NOT_FOUND; + const string target(cadr(ref)); + debug(target, "modwiring::translateReference::target"); + + // Route to an absolute target URI using mod_proxy or an HTTP client redirect + const list<value> pathInfo = cdddr(rpath); + if (httpd::isAbsolute(target)) { + if (useModProxy) { + // Build proxy URI + // current request's protocol scheme, reference target uri and request path info + string turi = httpd::scheme(r) + substr(target, find(target, "://")) + path(pathInfo); + r->filename = apr_pstrdup(r->pool, c_str(string("proxy:") + turi)); + debug(r->filename, "modwiring::translateReference::filename"); + r->proxyreq = PROXYREQ_REVERSE; + r->handler = "proxy-server"; + apr_table_setn(r->notes, "proxy-nocanon", "1"); + return OK; + } + + debug(target, "modwiring::translateReference::location"); + r->handler = "mod_tuscany_wiring"; + return httpd::externalRedirect(target, r); + } + + // Route to a relative target URI using a local internal redirect + // /components/, target component name and request path info + const value tname = substr(target, 0, find(target, '/')); + const string tpath = path(cons(tname, pathInfo)); + r->filename = apr_pstrdup(r->pool, c_str(string("/redirect:/components") + tpath)); + debug(r->filename, "modwiring::translateReference::filename"); + r->handler = "mod_tuscany_wiring"; + return OK; +} + +/** + * Find a leaf matching a request path in a tree of URI paths. + */ +const int matchPath(const list<value>& k, const list<value>& p) { + if (isNil(p)) + return true; + if (isNil(k)) + return false; + if (car(k) != car(p)) + return false; + return matchPath(cdr(k), cdr(p)); +} + +const list<value> assocPath(const value& k, const list<value>& tree) { + if (isNil(tree)) + return tree; + if (matchPath(k, car<value>(car(tree)))) + return car(tree); + if (k < car<value>(car(tree))) + return assocPath(k, cadr(tree)); + return assocPath(k, caddr(tree)); +} + +/** + * Route a service request to the component providing the requested service. + */ +int translateService(const ServerConf& sc, request_rec *r) { + httpdDebugRequest(r, "modwiring::translateService::input"); + debug(r->uri, "modwiring::translateService::uri"); + + // Find the requested component + debug(sc.services, "modwiring::translateService::services"); + const list<value> p(pathValues(r->uri)); + const list<value> svc(assocPath(p, sc.services)); + if (isNil(svc)) + return DECLINED; + debug(svc, "modwiring::translateService::service"); + + // Build a component-name + path-info URI + const list<value> target(cons<value>(cadr(svc), httpd::pathInfo(p, car(svc)))); + debug(target, "modwiring::translateService::target"); + + // Dispatch to the target component using a local internal redirect + const string tp(path(target)); + debug(tp, "modwiring::translateService::path"); + const string redir(string("/redirect:/components") + tp); + debug(redir, "modwiring::translateService::redirect"); + r->filename = apr_pstrdup(r->pool, c_str(redir)); + r->handler = "mod_tuscany_wiring"; + return OK; +} + +/** + * Read the components declared in a composite. + */ +const failable<list<value> > readComponents(const string& path) { + ifstream is(path); + if (fail(is)) + return mkfailure<list<value> >(string("Could not read composite: ") + path); + return scdl::components(readXML(streamList(is))); +} + +/** + * Return a list of component-name + references pairs. The references are + * arranged in trees of reference-name + reference-target pairs. + */ +const list<value> componentReferenceToTargetTree(const value& c) { + return mklist<value>(scdl::name(c), mkbtree(sort(scdl::referenceToTargetAssoc(scdl::references(c))))); +} + +const list<value> componentReferenceToTargetAssoc(const list<value>& c) { + if (isNil(c)) + return c; + return cons<value>(componentReferenceToTargetTree(car(c)), componentReferenceToTargetAssoc(cdr(c))); +} + +/** + * Return a list of service-URI-path + component-name pairs. Service-URI-paths are + * represented as lists of URI path fragments. + */ +const list<value> defaultBindingURI(const string& cn, const string& sn) { + return mklist<value>(cn, sn); +} + +const list<value> bindingToComponentAssoc(const string& cn, const string& sn, const list<value>& b) { + if (isNil(b)) + return b; + const value uri(scdl::uri(car(b))); + if (isNil(uri)) + return cons<value>(mklist<value>(defaultBindingURI(cn, sn), cn), bindingToComponentAssoc(cn, sn, cdr(b))); + return cons<value>(mklist<value>(pathValues(c_str(string(uri))), cn), bindingToComponentAssoc(cn, sn, cdr(b))); +} + +const list<value> serviceToComponentAssoc(const string& cn, const list<value>& s) { + if (isNil(s)) + return s; + const string sn(scdl::name(car(s))); + const list<value> btoc(bindingToComponentAssoc(cn, sn, scdl::bindings(car(s)))); + if (isNil(btoc)) + return cons<value>(mklist<value>(defaultBindingURI(cn, sn), cn), serviceToComponentAssoc(cn, cdr(s))); + return append<value>(btoc, serviceToComponentAssoc(cn, cdr(s))); +} + +const list<value> uriToComponentAssoc(const list<value>& c) { + if (isNil(c)) + return c; + return append<value>(serviceToComponentAssoc(scdl::name(car(c)), scdl::services(car(c))), uriToComponentAssoc(cdr(c))); +} + +/** + * Configure the components declared in the server's deployment composite. + */ +const bool confComponents(ServerConf& sc) { + if (!hasCompositeConf(sc)) + return true; + debug(sc.contributionPath, "modwiring::confComponents::contributionPath"); + debug(sc.compositeName, "modwiring::confComponents::compositeName"); + + // Read the component configuration and store the references and service URIs + // in trees for fast retrieval later + const failable<list<value> > comps = readComponents(sc.contributionPath + sc.compositeName); + if (!hasContent(comps)) + return true; + const list<value> refs = componentReferenceToTargetAssoc(content(comps)); + debug(refs, "modwiring::confComponents::references"); + sc.references = mkbtree(sort(refs)); + + const list<value> svcs = uriToComponentAssoc(content(comps)); + debug(svcs, "modwiring::confComponents::services"); + sc.services = mkbtree(sort(svcs)); + return true; +} + +/** + * Virtual host scoped server configuration. + */ +class VirtualHostConf { +public: + VirtualHostConf(const gc_pool& p, const ServerConf& ssc) : sc(pool(p), ssc.server) { + sc.virtualHostContributionPath = ssc.virtualHostContributionPath; + sc.virtualHostCompositeName = ssc.virtualHostCompositeName; + } + + ~VirtualHostConf() { + } + + ServerConf sc; +}; + +/** + * Configure and start the components deployed in a virtual host. + */ +const failable<bool> virtualHostConfig(ServerConf& sc, request_rec* r) { + debug(httpd::serverName(sc.server), "modwiring::virtualHostConfig::serverName"); + debug(httpd::serverName(r), "modwiring::virtualHostConfig::virtualHostName"); + debug(sc.virtualHostContributionPath, "modwiring::virtualHostConfig::virtualHostContributionPath"); + + // Resolve the configured virtual contribution under + // the virtual host's SCA contribution root + sc.contributionPath = sc.virtualHostContributionPath + httpd::subdomain(httpd::hostName(r)) + "/"; + sc.compositeName = sc.virtualHostCompositeName; + + // Configure the wiring for the deployed components + confComponents(sc); + return true; +} + +/** + * Translate an HTTP service or reference request and route it + * to the target component. + */ +int translate(request_rec *r) { + if(r->method_number != M_GET && r->method_number != M_POST && r->method_number != M_PUT && r->method_number != M_DELETE) + return DECLINED; + + // No translation needed for a component or tunnel request + if (!strncmp(r->uri, "/components/", 12)) + return DECLINED; + + // Get the server configuration + gc_scoped_pool pool(r->pool); + const ServerConf& sc = httpd::serverConf<ServerConf>(r, &mod_tuscany_wiring); + + // Process dynamic virtual host configuration + VirtualHostConf vhc(gc_pool(r->pool), sc); + const bool usevh = hasVirtualCompositeConf(vhc.sc) && httpd::isVirtualHostRequest(sc.server, r); + if (usevh) { + const failable<bool> cr = virtualHostConfig(vhc.sc, r); + if (!hasContent(cr)) + return -1; + } + + // Translate a component reference request + if (!strncmp(r->uri, "/references/", 12)) + return translateReference(usevh? vhc.sc: sc, r); + + // Translate a service request + return translateService(usevh? vhc.sc : sc, r); +} + +/** + * HTTP request handler, redirect to a target component. + */ +int handler(request_rec *r) { + if(r->method_number != M_GET && r->method_number != M_POST && r->method_number != M_PUT && r->method_number != M_DELETE) + return DECLINED; + if(strcmp(r->handler, "mod_tuscany_wiring")) + return DECLINED; + if (r->filename == NULL || strncmp(r->filename, "/redirect:", 10) != 0) + return DECLINED; + + // Nothing to do for an external redirect + if (r->status == HTTP_MOVED_TEMPORARILY) + return OK; + + // Do an internal redirect + gc_scoped_pool pool(r->pool); + httpdDebugRequest(r, "modwiring::handler::input"); + + debug(r->uri, "modwiring::handler::uri"); + debug(r->filename, "modwiring::handler::filename"); + debug(r->path_info, "modwiring::handler::path info"); + if (r->args == NULL) + return httpd::internalRedirect(httpd::redirectURI(string(r->filename + 10), string(r->path_info)), r); + return httpd::internalRedirect(httpd::redirectURI(string(r->filename + 10), string(r->path_info), string(r->args)), r); +} + +/** + * Called after all the configuration commands have been run. + * Process the server configuration and configure the wiring for the deployed components. + */ +const int postConfigMerge(const ServerConf& mainsc, server_rec* s) { + if (s == NULL) + return OK; + debug(httpd::serverName(s), "modwiring::postConfigMerge::serverName"); + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_wiring); + sc.contributionPath = mainsc.contributionPath; + sc.compositeName = mainsc.compositeName; + sc.virtualHostContributionPath = mainsc.virtualHostContributionPath; + sc.virtualHostCompositeName = mainsc.virtualHostCompositeName; + sc.references = mainsc.references; + sc.services = mainsc.services; + return postConfigMerge(mainsc, s->next); +} + +int postConfig(apr_pool_t *p, unused apr_pool_t *plog, unused apr_pool_t *ptemp, server_rec *s) { + gc_scoped_pool pool(p); + + // Count the calls to post config, skip the first one as + // postConfig is always called twice + const string k("tuscany::modwiring::postConfig"); + const long int count = (long int)httpd::userData(k, s); + httpd::putUserData(k, (void*)(count + 1), s); + if (count == 0) + return OK; + + // Configure the wiring for the deployed components + debug(httpd::serverName(s), "modwiring::postConfig::serverName"); + ServerConf& sc = httpd::serverConf<ServerConf>(s, &mod_tuscany_wiring); + confComponents(sc); + + // Merge the config into any virtual hosts + return postConfigMerge(sc, s->next); +} + +/** + * Child process initialization. + */ +void childInit(apr_pool_t* p, server_rec* s) { + gc_scoped_pool pool(p); + if(ap_get_module_config(s->module_config, &mod_tuscany_wiring) == NULL) { + cfailure << "[Tuscany] Due to one or more errors mod_tuscany_wiring loading failed. Causing apache to stop loading." << endl; + exit(APEXIT_CHILDFATAL); + } +} + +/** + * Configuration commands. + */ +const char *confContribution(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_wiring); + sc.contributionPath = arg; + return NULL; +} +const char *confComposite(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_wiring); + sc.compositeName = arg; + return NULL; +} +const char *confVirtualContribution(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_wiring); + sc.virtualHostContributionPath = arg; + return NULL; +} +const char *confVirtualComposite(cmd_parms *cmd, unused void *c, const char *arg) { + gc_scoped_pool pool(cmd->pool); + ServerConf& sc = httpd::serverConf<ServerConf>(cmd, &mod_tuscany_wiring); + sc.virtualHostCompositeName = arg; + return NULL; +} + +/** + * HTTP server module declaration. + */ +const command_rec commands[] = { + AP_INIT_TAKE1("SCAContribution", (const char*(*)())confContribution, NULL, RSRC_CONF, "SCA contribution location"), + AP_INIT_TAKE1("SCAComposite", (const char*(*)())confComposite, NULL, RSRC_CONF, "SCA composite location"), + AP_INIT_TAKE1("SCAVirtualContribution", (const char*(*)())confVirtualContribution, NULL, RSRC_CONF, "SCA virtual host contribution location"), + AP_INIT_TAKE1("SCAVirtualComposite", (const char*(*)())confVirtualComposite, NULL, RSRC_CONF, "SCA virtual host composite location"), + {NULL, NULL, NULL, 0, NO_ARGS, NULL} +}; + +void registerHooks(unused apr_pool_t *p) { + ap_hook_post_config(postConfig, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_child_init(childInit, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_handler(handler, NULL, NULL, APR_HOOK_MIDDLE); + ap_hook_translate_name(translate, NULL, NULL, APR_HOOK_FIRST); +} + +} +} +} + +extern "C" { + +module AP_MODULE_DECLARE_DATA mod_tuscany_wiring = { + STANDARD20_MODULE_STUFF, + // dir config and merger + NULL, NULL, + // server config and merger + tuscany::httpd::makeServerConf<tuscany::server::modwiring::ServerConf>, NULL, + // commands and hooks + tuscany::server::modwiring::commands, tuscany::server::modwiring::registerHooks +}; + +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/scheme-conf b/sandbox/sebastien/cpp/apr-2/modules/server/scheme-conf new file mode 100755 index 0000000000..cd3c82b280 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/scheme-conf @@ -0,0 +1,30 @@ +#!/bin/sh + +# 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. + +# Generate a Scheme server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +cat >>$root/conf/modules.conf <<EOF +# Generated by: scheme-conf $* +# Support for Scheme SCA components +LoadModule mod_tuscany_eval $here/libmod_tuscany_eval.so + +EOF diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/server-conf b/sandbox/sebastien/cpp/apr-2/modules/server/server-conf new file mode 100755 index 0000000000..742d48d614 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/server-conf @@ -0,0 +1,103 @@ +#!/bin/sh + +# 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. + +# Generate a server conf +here=`readlink -f $0`; here=`dirname $here` +mkdir -p $1 +root=`readlink -f $1` + +jsprefix=`readlink -f $here/../js` + +conf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-conf"` +host=`echo $conf | awk '{ print $6 }'` +port=`echo $conf | awk '{ print $7 }' | awk -F "/" '{ print $1 }'` +pport=`echo $conf | awk '{ print $7 }' | awk -F "/" '{ print $2 }'` +if [ "$pport" = "" ]; then + pport=$port +fi +servername="http://$host:$pport" + +sslconf=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-ssl-conf"` +if [ "$sslconf" != "" ]; then + sslport=`echo $sslconf | awk '{ print $6 }' | awk -F "/" '{ print $1 }'` + sslpport=`echo $sslconf | awk '{ print $6 }' | awk -F "/" '{ print $2 }'` + if [ "$sslpport" = "" ]; then + sslpport=$sslport + fi + servername="https://$host:$sslpport" +fi + +cat >>$root/conf/modules.conf <<EOF +# Generated by: server-conf $* +# Support for SCA component wiring +LoadModule mod_tuscany_wiring $here/libmod_tuscany_wiring.so + +EOF + +cat >>$root/conf/httpd.conf <<EOF +# Generated by: server-conf $* +# Route all wiring through the configured server name +SCAWiringServerName $servername + +# Serve JavaScript client scripts +Alias /component.js $jsprefix/htdocs/component.js +Alias /util.js $jsprefix/htdocs/util.js +Alias /elemutil.js $jsprefix/htdocs/elemutil.js +Alias /xmlutil.js $jsprefix/htdocs/xmlutil.js +Alias /atomutil.js $jsprefix/htdocs/atomutil.js +Alias /ui.js $jsprefix/htdocs/ui.js +Alias /ui.css $jsprefix/htdocs/ui.css +Alias /scdl.js $jsprefix/htdocs/scdl.js +Alias /graph.js $jsprefix/htdocs/graph.js + +<Location /component.js> +AuthType None +Require all granted +</Location> +<Location /scdl.js> +AuthType None +Require all granted +</Location> +<Location /util.js> +AuthType None +Require all granted +</Location> +<Location /ui.js> +AuthType None +Require all granted +</Location> +<Location /ui.css> +AuthType None +Require all granted +</Location> + +EOF + +ssl=`cat $root/conf/httpd.conf | grep "# Generated by: httpd-ssl-conf"` +if [ "$ssl" != "" ]; then + cat >>$root/conf/httpd.conf <<EOF +# Configure SSL certificates +SCAWiringSSLCACertificateFile "$root/cert/ca.crt" +SCAWiringSSLCertificateFile "$root/cert/server.crt" +SCAWiringSSLCertificateKeyFile "$root/cert/server.key" + +EOF + +fi + diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/server-test b/sandbox/sebastien/cpp/apr-2/modules/server/server-test new file mode 100755 index 0000000000..e53c7f5ef1 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/server-test @@ -0,0 +1,39 @@ +#!/bin/sh + +# 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. + +# Setup +../http/httpd-conf tmp localhost 8090 htdocs +./server-conf tmp +./scheme-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite domain-test.composite +EOF + +../http/httpd-start tmp +sleep 2 + +# Test +./client-test 2>/dev/null +rc=$? + +# Cleanup +../http/httpd-stop tmp +sleep 2 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/server-test.scm b/sandbox/sebastien/cpp/apr-2/modules/server/server-test.scm new file mode 100644 index 0000000000..c23adb7f51 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/server-test.scm @@ -0,0 +1,44 @@ +; 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. + +; JSON-RPC test case + +(define (echo x) x) + +; ATOMPub test case + +(define (get id) + (if (nul id) + '("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)))) + + (list "Item" (car id) '((name "Apple") (currencyCode "USD") (currencySymbol "$") (price 2.99)))) +) + +(define (post collection item) + '("123456789") +) + +(define (put id item) + true +) + +(define (delete id) + true +) diff --git a/sandbox/sebastien/cpp/apr-2/modules/server/wiring-test b/sandbox/sebastien/cpp/apr-2/modules/server/wiring-test new file mode 100755 index 0000000000..e791ec555b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/server/wiring-test @@ -0,0 +1,78 @@ +#!/bin/sh + +# 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. + +echo "Testing..." +here=`readlink -f $0`; here=`dirname $here` +curl_prefix=`cat $here/../http/curl.prefix` + +# Setup +../http/httpd-conf tmp localhost 8090 htdocs +./server-conf tmp +./scheme-conf tmp +cat >>tmp/conf/httpd.conf <<EOF +SCAContribution `pwd`/ +SCAComposite domain-test.composite +EOF + +../http/httpd-start tmp +sleep 2 + +# Test HTTP GET +$curl_prefix/bin/curl http://localhost:8090/index.html 2>/dev/null >tmp/index.html +diff tmp/index.html htdocs/index.html +rc=$? + +# Test ATOMPub +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ >tmp/feed.xml 2>/dev/null + diff tmp/feed.xml htdocs/test/feed.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 >tmp/entry.xml 2>/dev/null + diff tmp/entry.xml htdocs/test/entry.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ -X POST -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 -X PUT -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/111 -X DELETE 2>/dev/null + rc=$? +fi + +# Test JSON-RPC +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/client/ -X POST -H "Content-type: application/json-rpc" --data @htdocs/test/json-request.txt >tmp/json-result.txt 2>/dev/null + diff tmp/json-result.txt htdocs/test/json-result.txt + rc=$? +fi + +# Cleanup +../http/httpd-stop tmp +sleep 2 +if [ "$rc" = "0" ]; then + echo "OK" +fi +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/Makefile.am b/sandbox/sebastien/cpp/apr-2/modules/wsgi/Makefile.am new file mode 100644 index 0000000000..9f67ab37c0 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/Makefile.am @@ -0,0 +1,58 @@ +# 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_PYTHON + +INCLUDES = -I${PYTHON_INCLUDE} + +dist_mod_SCRIPTS = composite.py wsgi-start wsgi-stop gae-start gae-stop +moddir = $(prefix)/modules/wsgi + +dist_mod_DATA = app.yaml scdl.py util.py elemutil.py xmlutil.py atomutil.py jsonutil.py + +noinst_DATA = target.stamp + +target.stamp: app.yaml *.py *.composite htdocs/* + mkdir -p target + cp app.yaml *.py *.composite target + cp -R htdocs target/htdocs + touch target.stamp + +clean-local: + rm -rf target.stamp target + +prefix_DATA = gae.prefix +prefixdir=$(prefix)/modules/wsgi +gae.prefix: $(top_builddir)/config.status + echo ${GAE_PREFIX} >gae.prefix + +EXTRA_DIST = domain-test.composite *.py htdocs/*.xml htdocs/*.txt htdocs/*.html + +client_test_SOURCES = client-test.cpp +client_test_LDFLAGS = -lxml2 -lcurl -lmozjs + +noinst_PROGRAMS = client-test + +dist_noinst_SCRIPTS = util-test wsgi-test wiring-test http-test server-test +TESTS = util-test wsgi-test wiring-test http-test server-test + +if WANT_GAE +dist_noinst_SCRIPTS += gae-test +TESTS += gae-test +endif + +endif diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/app.yaml b/sandbox/sebastien/cpp/apr-2/modules/wsgi/app.yaml new file mode 100644 index 0000000000..bc70aceced --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/app.yaml @@ -0,0 +1,50 @@ +# 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.
+
+application: sca-wsgi
+version: 1
+runtime: python
+api_version: 1
+skip_files:
+- ^(.*/)?app\.yaml
+- ^(.*/)?app\.yml
+- ^(.*/)?index\.yaml
+- ^(.*/)?index\.yml
+- ^(.*/)?#.*#
+- ^(.*/)?.*~
+- ^(.*/)?.*\.py[co]
+- ^(.*/)?.*/RCS/.*
+- ^(.*/)?\..*
+- ^(.*/)?.*-test$
+- ^(.*/)?.*\.cpp$
+- ^(.*/)?.*\.o$
+- ^(.*/)?core$
+- ^(.*/)?.*\.out$
+- ^(.*/)?.*\.log$
+- ^(.*/)?Makefile.*
+- ^(.*/)?tmp/.*
+- ^(.*/)?wsgi-start
+- ^(.*/)?wsgi-stop
+
+handlers:
+- url: /(.*\.(html|js|png))
+ static_files: htdocs/\1
+ upload: htdocs/(.*\.(html|js|png))
+
+- url: /.*
+ script: composite.py
+
diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/atom-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/atom-test.py new file mode 100755 index 0000000000..81a6106519 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/atom-test.py @@ -0,0 +1,168 @@ +#!/usr/bin/python +# 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. + +# Test ATOM data conversion functions + +import unittest +from elemutil import * +from atomutil import * + +itemEntry = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title type=\"text\">item</title>" \ + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</id>" \ + "<content type=\"application/xml\">" \ + "<item>" \ + "<name>Apple</name><price>$2.99</price>" \ + "</item>" \ + "</content>" \ + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b\" />" \ + "</entry>\n" + +textEntry = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title type=\"text\">item</title>" \ + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</id>" \ + "<content type=\"text\">" \ + "Apple" \ + "</content>" \ + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b\" />" \ + "</entry>\n" + +incompleteEntry = \ + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title>item</title><content type=\"text/xml\">" \ + "<Item xmlns=\"http://services/\">" \ + "<name xmlns=\"\">Orange</name>" \ + "<price xmlns=\"\">3.55</price>" \ + "</Item>" \ + "</content>" \ + "</entry>" + +completedEntry = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title type=\"text\">item</title>" \ + "<id />" \ + "<content type=\"application/xml\">" \ + "<Item xmlns=\"http://services/\">" \ + "<name xmlns=\"\">Orange</name>" \ + "<price xmlns=\"\">3.55</price>" \ + "</Item>" \ + "</content><link href=\"\" />" \ + "</entry>\n" + +def testEntry(): + i = (element, "'item", (element, "'name", "Apple"), (element, "'price", "$2.99")) + a = ("item", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", i) + s = writeATOMEntry(a); + assert car(s) == itemEntry + + a2 = readATOMEntry((itemEntry,)) + s2 = writeATOMEntry(a2) + assert car(s2) == itemEntry + + a3 = readATOMEntry((textEntry,)) + s3 = writeATOMEntry(a3) + assert car(s3) == textEntry + + a4 = readATOMEntry((incompleteEntry,)) + s4 = writeATOMEntry(a4) + assert car(s4) == completedEntry + return True + +emptyFeed = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<feed xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title type=\"text\">Feed</title>" \ + "<id>1234</id>" \ + "</feed>\n" + +itemFeed = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<feed xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title type=\"text\">Feed</title>" \ + "<id>1234</id>" \ + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title type=\"text\">item</title>" \ + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</id>" \ + "<content type=\"application/xml\">" \ + "<item>" \ + "<name>Apple</name><price>$2.99</price>" \ + "</item>" \ + "</content>" \ + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b\" />" \ + "</entry>" \ + "<entry xmlns=\"http://www.w3.org/2005/Atom\">" \ + "<title type=\"text\">item</title>" \ + "<id>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c</id>" \ + "<content type=\"application/xml\">" \ + "<item>" \ + "<name>Orange</name><price>$3.55</price>" \ + "</item>" \ + "</content>" \ + "<link href=\"cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c\" />" \ + "</entry>" \ + "</feed>\n" + +def testFeed(): + s = writeATOMFeed(("Feed", "1234")) + assert car(s) == emptyFeed + + a2 = readATOMFeed((emptyFeed,)) + s2 = writeATOMFeed(a2) + assert car(s2) == emptyFeed + + i3 = (("item", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", + (element, "'item", (element, "'name", "Apple"), (element, "'price", "$2.99"))), + ("item", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c", + (element, "'item", (element, "'name", "Orange"), (element, "'price", "$3.55")))) + a3 = cons("Feed", cons("1234", i3)) + s3 = writeATOMFeed(a3) + assert car(s3) == itemFeed + + i4 = (("item", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", + valueToElement(("'item", ("'name", "Apple"), ("'price", "$2.99")))), + ("item", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c", + valueToElement(("'item", ("'name", "Orange"), ("'price", "$3.55"))))) + a4 = cons("Feed", cons("1234", i4)) + s4 = writeATOMFeed(a4) + assert car(s4) == itemFeed + + a5 = readATOMFeed((itemFeed,)); + s5 = writeATOMFeed(a5); + assert car(s5) == itemFeed + + i6 = (("item", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", + (("'name", "Apple"), ("'price", "$2.99"))), + ("item", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c", + (("'name", "Orange"), ("'price", "$3.55")))) + a6 = cons("Feed", cons("1234", i6)) + s6 = writeATOMFeed(feedValuesToElements(a6)) + assert car(s6) == itemFeed + + return True + +if __name__ == "__main__": + print "Testing..." + testEntry() + testFeed() + print "OK" + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/atomutil.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/atomutil.py new file mode 100644 index 0000000000..1e6a7c31b5 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/atomutil.py @@ -0,0 +1,120 @@ +# 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. + +# ATOM data conversion functions + +from util import * +from elemutil import * +from xmlutil import * + +# Convert a list of elements to a list of values representing an ATOM entry +def entryElementsToValues(e): + lt = filter(selector((element, "'title")), e) + t = "" if isNil(lt) else elementValue(car(lt)) + li = filter(selector((element, "'id")), e) + i = "" if isNil(li) else elementValue(car(li)) + lc = filter(selector((element, "'content")), e) + return (t, i, elementValue(car(lc))) + +# Convert a list of elements to a list of values representing ATOM entries +def entriesElementsToValues(e): + if isNil(e): + return e + return cons(entryElementsToValues(car(e)), entriesElementsToValues(cdr(e))) + +# Convert a list of strings to a list of values representing an ATOM entry +def readATOMEntry(l): + e = readXML(l) + if isNil(e): + return () + return entryElementsToValues(car(e)) + +# Convert a list of values representy an ATOM entry to a value +def entryValue(e): + v = elementsToValues((caddr(e),)) + return cons(car(e), (cadr(e), cdr(car(v)))) + +# Return true if a list of strings represents an ATOM feed +def isATOMFeed(l): + if not isXML(l): + return False + return contains(car(l), "<feed") and contains(car(l), "=\"http://www.w3.org/2005/Atom\"") + +# Convert a list of strings to a list of values representing an ATOM feed +def readATOMFeed(l): + f = readXML(l) + if isNil(f): + return () + t = filter(selector((element, "'title")), car(f)) + i = filter(selector((element, "'id")), car(f)) + e = filter(selector((element, "'entry")), car(f)) + if isNil(e): + return (elementValue(car(t)), elementValue(car(i))) + return cons(elementValue(car(t)), cons(elementValue(car(i)), entriesElementsToValues(e))) + +# Convert an ATOM feed containing elements to an ATOM feed containing values +def feedValuesLoop(e): + if (isNil(e)): + return e + return cons(entryValue(car(e)), feedValuesLoop(cdr(e))) + +def feedValues(e): + return cons(car(e), cons(cadr(e), feedValuesLoop(cddr(e)))) + +# Convert a list of values representy an ATOM entry to a list of elements +def entryElement(l): + return (element, "'entry", (attribute, "'xmlns", "http://www.w3.org/2005/Atom"), + (element, "'title", (attribute, "'type", "text"), car(l)), + (element, "'id", cadr(l)), + (element, "'content", (attribute, "'type", ("application/xml" if isList(caddr(l)) else "text")), caddr(l)), + (element, "'link", (attribute, "'href", cadr(l)))) + +# Convert a list of values representing ATOM entries to a list of elements +def entriesElements(l): + if isNil(l): + return l + return cons(entryElement(car(l)), entriesElements(cdr(l))) + +# Convert a list of values representing an ATOM entry to an ATOM entry +def writeATOMEntry(l): + return writeXML((entryElement(l),), True) + +# Convert a list of values representing an ATOM feed to an ATOM feed +def writeATOMFeed(l): + f = (element, "'feed", (attribute, "'xmlns", "http://www.w3.org/2005/Atom"), + (element, "'title", (attribute, "'type", "text"), car(l)), + (element, "'id", cadr(l))) + if isNil(cddr(l)): + return writeXML((f,), True) + fe = append(f, entriesElements(cddr(l))) + return writeXML((fe,), True) + +# Convert an ATOM entry containing a value to an ATOM entry containing an item element +def entryValuesToElements(v): + if isList(caddr(v)): + return cons(car(v), cons(cadr(v), valuesToElements((cons("'item", caddr(v)),)))) + return cons(car(v), cons(cadr(v), valuesToElements((("'item", caddr(v)),)))) + +# Convert an ATOM feed containing values to an ATOM feed containing elements +def feedValuesToElementsLoop(v): + if isNil(v): + return v + return cons(entryValuesToElements(car(v)), feedValuesToElementsLoop(cdr(v))) + +def feedValuesToElements(v): + return cons(car(v), cons(cadr(v), feedValuesToElementsLoop(cddr(v)))) + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/client-test.cpp b/sandbox/sebastien/cpp/apr-2/modules/wsgi/client-test.cpp new file mode 100644 index 0000000000..da4fff973b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/client-test.cpp @@ -0,0 +1,40 @@ +/* + * 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 HTTP client functions. + */ + +#include "stream.hpp" +#include "string.hpp" +#include "../server/client-test.hpp" + +int main(const int argc, const char** argv) { + tuscany::cout << "Testing..." << tuscany::endl; + tuscany::server::testURI = argc < 2? "http://localhost:8090/wsgi" : argv[1]; + tuscany::server::testBlobs = false; + + tuscany::server::testServer(); + + tuscany::cout << "OK" << tuscany::endl; + + return 0; +} diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/client-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/client-test.py new file mode 100644 index 0000000000..867222e792 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/client-test.py @@ -0,0 +1,40 @@ +# 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. + +import unittest + +# JSON-RPC test case + +def echo(x, ref): + e1 = ref("echo", x) + e2 = ref.echo(x) + assert e1 == e2 + return e1 + +# ATOMPub test case + +def get(id, ref): + return ref.get(id) + +def post(collection, item, ref): + return ref.post(collection, item) + +def put(id, item, ref): + return ref.put(id, item) + +def delete(id, ref): + return ref.delete(id) diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/composite.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/composite.py new file mode 100755 index 0000000000..7044483f70 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/composite.py @@ -0,0 +1,251 @@ +#!/usr/bin/python +# 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. + +# Composite deployment and integration with WSGI + +from wsgiref.simple_server import make_server +from wsgiref.handlers import CGIHandler +from wsgiref.util import request_uri +from wsgiref.util import FileWrapper +from os import environ +import os.path +import hashlib +from sys import stderr, argv +from util import * +from scdl import * +from atomutil import * +from jsonutil import * + +# Cache the deployed components between requests +comps = None + +# Return the path of an HTTP request +def requestPath(e): + return e.get("PATH_INFO", "") + +# Return the method of an HTTP request +def requestMethod(e): + return e.get("REQUEST_METHOD", "") + +# Return the method of an HTTP request +def requestContentType(e): + return e.get("CONTENT_TYPE", "") + +# Return the request body input stream +def requestBody(e): + i = e.get("wsgi.input", None) + if i == None: + return () + l = int(e.get("CONTENT_LENGTH", "0")) + return (i.read(l),) + +def requestIfNoneMatch(e): + return e.get("HTTP_IF_NONE_MATCH", ""); + +# Hash a list of strings into an MD5 signature +def md5update(md, s): + if isNil(s): + return md.hexdigest() + md.update(car(s)) + return md5update(md, cdr(s)) + +def md5(s): + return md5update(hashlib.md5(), s) + +# Return an HTTP success result +def result(e, r, st, h = (), b = None): + if st == 201: + r("201 Created", list(h)) + return () + + if st == 200: + if b == None: + r("200 OK", list(h)) + return () + + # Handle etags to minimize bandwidth usage + md = md5(b) + if (md == requestIfNoneMatch(e)): + r("304 Not Modified", list((("Etag", md), ("Expires", "Tue, 01 Jan 1980 00:00:00 GMT")))) + return () + r("200 OK", list(h + (("Etag", md), ("Expires", "Tue, 01 Jan 1980 00:00:00 GMT")))) + return b + + if st == 301: + r("301 Moved Permanently", list(h)) + + return failure(e, r, 500) + +# Return an HTTP failure result +def failure(e, r, st): + s = "404 Not Found" if st == 404 else str(st) + " " + "Internal Server Error" + r(s, list((("Content-type", "text/html"),))) + return ("<html><head><title>"+ s + "</title></head><body><h1>" + s[4:] + "</h1></body></html>",) + +# Return a static file +def fileresult(e, r, ct, f): + + # Read the file, return a 404 if not found + p = "htdocs" + f + if not os.path.exists(p): + return failure(e, r, 404) + c = tuple(FileWrapper(open("htdocs" + f))) + + # Handle etags to minimize bandwidth usage + md = md5(c) + r("200 OK", list((("Content-type", ct),("Etag", md)))) + return c + +# Converts the args received in a POST to a list of key value pairs +def postArgs(a): + if isNil(a): + return ((),) + l = car(a); + return cons(l, postArgs(cdr(a))) + +# Return the URL used to sign out +def signout(ruri): + try: + from google.appengine.api import users + return users.create_logout_url(ruri) + except: + return None + +# Return the URL used to sign in +def signin(ruri): + try: + from google.appengine.api import users + return users.create_login_url(ruri) + except: + return None + +# WSGI application function +def application(e, r): + m = requestMethod(e) + fpath = requestPath(e) + + # Serve static files + if m == "GET": + if fpath.endswith(".html"): + return fileresult(e, r, "text/html", fpath) + if fpath.endswith(".js"): + return fileresult(e, r, "application/x-javascript", fpath) + if fpath.endswith(".png"): + return fileresult(e, r, "image/png", fpath) + if fpath == "/": + return result(e, r, 301, (("Location", "/index.html"),)) + + # Debug hook + if fpath == "/debug": + return result(e, r, 200, (("Content-type", "text/plain"),), ("Debug",)) + + # Sign in and out + if fpath == "/login": + redir = signin("/") + if redir: + return result(e, r, 301, (("Location", redir),)) + if fpath == "/logout": + redir = signout(signin("/")) + if redir: + return result(e, r, 301, (("Location", redir),)) + + # Find the requested component + path = tokens(fpath) + uc = uriToComponent(path, comps) + uri = car(uc) + if uri == None: + return failure(e, r, 404) + comp = cadr(uc) + + # Call the requested component function + id = path[len(uri):] + if m == "GET": + v = comp("get", id) + + # Write returned content-type / content pair + if not isinstance(cadr(v), basestring): + return result(e, r, 200, (("Content-type", car(v)),), cadr(v)) + + # Write an ATOM feed or entry + if isNil(id): + return result(e, r, 200, (("Content-type", "application/atom+xml;type=feed"),), writeATOMFeed(feedValuesToElements(v))) + return result(e, r, 200, (("Content-type", "application/atom+xml;type=entry"),), writeATOMEntry(entryValuesToElements(v))) + + if m == "POST": + ct = requestContentType(e) + + # Handle a JSON-RPC function call + if ct.find("application/json-rpc") != -1 or ct.find("text/plain") != -1 or ct.find("application/x-www-form-urlencoded") != -1: + json = elementsToValues(readJSON(requestBody(e))) + args = postArgs(json) + jid = cadr(assoc("'id", args)) + func = funcName(cadr(assoc("'method", args))) + params = cadr(assoc("'params", args)) + v = comp(func, *params) + return result(e, r, 200, (("Content-type", "application/json-rpc"),), jsonResult(jid, v)) + + # Handle an ATOM entry POST + if ct.find("application/atom+xml") != -1: + ae = entryValue(readATOMEntry(requestBody(e))) + v = comp("post", id, ae) + if isNil(v): + return failure(e, r, 500) + return result(e, r, 201, (("Location", request_uri(e) + "/" + "/".join(v)),)) + return failure(e, r, 500) + + if m == "PUT": + # Handle an ATOM entry PUT + ae = entryValue(readATOMEntry(requestBody(e))) + v = comp("put", id, ae) + if v == False: + return failure(e, r, 404) + return result(e, r, 200) + + if m == "DELETE": + v = comp("delete", id) + if v == False: + return failure(e, r, 404) + return result(e, r, 200) + + return failure(e, r, 500) + +# Return the WSGI server type +def serverType(e): + return e.get("SERVER_SOFTWARE", "") + +def main(): + # Read the deployed composite and evaluate the configured components + global comps + if comps == None: + domain = "domain.composite" if os.path.exists("domain.composite") else "domain-test.composite" + comps = evalComponents(components(parse(domain))) + + # Handle the WSGI request with the WSGI runtime + st = serverType(environ) + if st.find("App Engine") != -1 or st.find("Development") != -1: + from google.appengine.ext.webapp.util import run_wsgi_app + run_wsgi_app(application) + elif st != "": + CGIHandler().run(application) + else: + make_server("", int(argv[1]), application).serve_forever() + +# Run the WSGI application +if __name__ == "__main__": + main() + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/domain-test.composite b/sandbox/sebastien/cpp/apr-2/modules/wsgi/domain-test.composite new file mode 100644 index 0000000000..9c44ebf5d8 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/domain-test.composite @@ -0,0 +1,42 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + * 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. +--> +<composite xmlns="http://docs.oasis-open.org/ns/opencsa/sca/200912" + xmlns:t="http://tuscany.apache.org/xmlns/sca/1.1" + targetNamespace="http://domain/test" + name="domain-test"> + + <component name="wsgi-test"> + <t:implementation.python script="server-test.py"/> + <service name="test"> + <t:binding.http uri="wsgi"/> + </service> + </component> + + <component name="client-test"> + <t:implementation.python script="client-test.py"/> + <service name="client"> + <t:binding.http uri="client"/> + </service> + <reference name="ref" target="wsgi-test"> + <t:binding.http/> + </reference> + </component> + +</composite> diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/elemutil.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/elemutil.py new file mode 100644 index 0000000000..b4b28d5110 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/elemutil.py @@ -0,0 +1,168 @@ +# 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. + +# Functions to help represent data as lists of elements and attributes + +from util import * + +element = "'element" +attribute = "'attribute" +atsign = "'@" + +# Return true if a value is an element +def isElement(v): + if not isList(v) or isNil(v) or v == None or car(v) != element: + return False + return True + +# Return true if a value is an attribute +def isAttribute(v): + if not isList(v) or isNil(v) or v == None or car(v) != attribute: + return False + return True + +# Return the name of attribute +def attributeName(l): + return cadr(l) + +# Return the value of attribute +def attributeValue(l): + return caddr(l) + +# Return the name of an element +def elementName(l): + return cadr(l) + +# Return true if an element has children +def elementHasChildren(l): + return not isNil(cddr(l)) + +# Return the children of an element +def elementChildren(l): + return cddr(l) + +# Return true if an element has a value +def elementHasValue(l): + r = reverse(l) + if isSymbol(car(r)): + return False + if isList(car(r)) and not isNil(car(r)) and isSymbol(car(car(r))): + return False + return True + +# Return the value of an element +def elementValue(l): + return car(reverse(l)) + +# Convert an element to a value +def elementToValueIsList(v): + if not isList(v): + return False + return isNil(v) or not isSymbol(car(v)) + +def elementToValue(t): + if isTaggedList(t, attribute): + return (atsign + attributeName(t)[1:], attributeValue(t)) + if isTaggedList(t, element): + if elementHasValue(t): + if not elementToValueIsList(elementValue(t)): + return (elementName(t), elementValue(t)) + return cons(elementName(t), (elementsToValues(elementValue(t)),)) + return cons(elementName(t), elementsToValues(elementChildren(t))) + if not isList(t): + return t + return elementsToValues(t) + +# Convert a list of elements to a list of values +def elementToValueIsSymbol(v): + if not isList(v): + return False + if (isNil(v)): + return False + if not isSymbol(car(v)): + return False + return True + +def elementToValueGroupValues(v, l): + if isNil(l) or not elementToValueIsSymbol(v) or not elementToValueIsSymbol(car(l)): + return cons(v, l) + if car(car(l)) != car(v): + return cons(v, l) + if not elementToValueIsList(cadr(car(l))): + g = (car(v), (cdr(v), cdr(car(l)))) + return elementToValueGroupValues(g, cdr(l)) + g = (car(v), cons(cdr(v), cadr(car(l)))) + return elementToValueGroupValues(g, cdr(l)) + +def elementsToValues(e): + if isNil(e): + return e + return elementToValueGroupValues(elementToValue(car(e)), elementsToValues(cdr(e))) + +# Convert a value to an element +def valueToElement(t): + if isList(t) and not isNil(t) and isSymbol(car(t)): + n = car(t) + v = () if isNil(cdr(t)) else cadr(t) + if not isList(v): + if n[0:2] == atsign: + return (attribute, n[1:], v) + return (element, n, v) + if isNil(v) or not isSymbol(car(v)): + return cons(element, cons(n, (valuesToElements(v),))) + return cons(element, cons(n, valuesToElements(cdr(t)))) + if not isList(t): + return t + return valuesToElements(t) + +# Convert a list of values to a list of elements +def valuesToElements(l): + if isNil(l): + return l + return cons(valueToElement(car(l)), valuesToElements(cdr(l))) + +# Return a selector lambda function which can be used to filter elements +def evalSelect(s, v): + if isNil(s): + return True + if isNil(v): + return False + if car(s) != car(v): + return False + return evalSelect(cdr(s), cdr(v)) + +def selector(s): + return lambda v: evalSelect(s, v) + +# Return the value of the attribute with the given name +def namedAttributeValue(name, l): + f = filter(lambda v: isAttribute(v) and attributeName(v) == name, l) + if isNil(f): + return None + return caddr(car(f)) + +# Return child elements with the given name +def namedElementChildren(name, l): + return filter(lambda v: isElement(v) and elementName(v) == name, l) + +# Return the child element with the given name +def namedElementChild(name, l): + f = namedElementChildren(name, l) + if isNil(f): + return None + return car(f) + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-start b/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-start new file mode 100755 index 0000000000..a3ee8765cb --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-start @@ -0,0 +1,29 @@ +#!/bin/sh + +# 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. + +# Start Google AppEngine server +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` +port=$2 + +python_prefix=`cat $here/../python/python.prefix` +gae_prefix=`cat $here/gae.prefix` +cd $root +$python_prefix/bin/python $gae_prefix/dev_appserver.py -a 0.0.0.0 -p $port $root & + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-stop b/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-stop new file mode 100755 index 0000000000..69de7f0c2b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-stop @@ -0,0 +1,29 @@ +#!/bin/sh + +# 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. + +# Stop Google AppEngine server +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` +port=$2 + +python_prefix=`cat $here/../python/python.prefix` +gae_prefix=`cat $here/gae.prefix` +py="$python_prefix/bin/python $gae_prefix/dev_appserver.py -a 0.0.0.0 -p $port $root" + +kill `ps -ef | grep -v grep | grep "${py}" | awk '{ print $2 }'` diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-test b/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-test new file mode 100755 index 0000000000..1791a830ca --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/gae-test @@ -0,0 +1,30 @@ +#!/bin/sh + +# 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. + +# Setup +./gae-start target 8090 2>/dev/null +sleep 2 + +# Test +./client-test 2>/dev/null +rc=$? + +# Cleanup +./gae-stop target 8090 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/index.html b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/index.html new file mode 100644 index 0000000000..cd25bf17b3 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/index.html @@ -0,0 +1 @@ +<html><body><h1>It works!</h1></body></html>
\ No newline at end of file diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/entry.xml b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/entry.xml new file mode 100644 index 0000000000..d26a46f25b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/entry.xml @@ -0,0 +1,2 @@ +<?xml version='1.0' encoding='UTF-8'?> +<entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>111</id><content type="application/xml"><item><name>Apple</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>2.99</price></item></content><link href="111" /></entry> diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/feed.xml b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/feed.xml new file mode 100644 index 0000000000..0be99f6eaf --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/feed.xml @@ -0,0 +1,2 @@ +<?xml version='1.0' encoding='UTF-8'?> +<feed xmlns="http://www.w3.org/2005/Atom"><title type="text">Sample Feed</title><id>123456789</id><entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>111</id><content type="application/xml"><item><name>Apple</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>2.99</price></item></content><link href="111" /></entry><entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>222</id><content type="application/xml"><item><name>Orange</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>3.55</price></item></content><link href="222" /></entry><entry xmlns="http://www.w3.org/2005/Atom"><title type="text">Item</title><id>333</id><content type="application/xml"><item><name>Pear</name><currencyCode>USD</currencyCode><currencySymbol>$</currencySymbol><price>1.55</price></item></content><link href="333" /></entry></feed> diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/json-request.txt b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/json-request.txt new file mode 100644 index 0000000000..b4bd07fc46 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/json-request.txt @@ -0,0 +1 @@ +{"id":1,"method":"echo","params":["Hello"]} diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/json-result.txt b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/json-result.txt new file mode 100644 index 0000000000..121bf74902 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/htdocs/test/json-result.txt @@ -0,0 +1 @@ +{"id":1,"result":"Hello"}
\ No newline at end of file diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/http-test b/sandbox/sebastien/cpp/apr-2/modules/wsgi/http-test new file mode 100755 index 0000000000..6676f6514c --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/http-test @@ -0,0 +1,39 @@ +#!/bin/sh + +# 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. + +uri=$1 +if [ "$uri" = "" ]; then + uri="http://localhost:8090" +fi + +# Setup +mkdir -p tmp +./wsgi-start target 8090 2>/dev/null +sleep 2 + +# Test JSON-RPC +here=`readlink -f $0`; here=`dirname $here` +python_prefix=`cat $here/../python/python.prefix` +$python_prefix/bin/python http-test.py +rc=$? + +# Cleanup +./wsgi-stop target 8090 +sleep 2 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/http-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/http-test.py new file mode 100755 index 0000000000..45a1ecd3cc --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/http-test.py @@ -0,0 +1,32 @@ +#!/usr/bin/python +# 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. + +# HTTP client proxy functions + +from httputil import * + +def testClient(): + c = mkclient("http://localhost:8090/wsgi") + assert c.echo("Hey") == "Hey" + return True + +if __name__ == "__main__": + print "Testing..." + testClient() + print "OK" + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/httputil.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/httputil.py new file mode 100644 index 0000000000..723e1a7284 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/httputil.py @@ -0,0 +1,93 @@ +#!/usr/bin/python +# 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. + +# HTTP client proxy functions + +from httplib import HTTPConnection, HTTPSConnection +from urlparse import urlparse +from StringIO import StringIO +import os.path +from string import strip +from base64 import b64encode +from sys import stderr +from util import * +from atomutil import * +from jsonutil import * + +# JSON request id +id = 1 + +# Make a callable HTTP client +class client: + def __init__(self, url): + self.url = urlparse(url) + + def __call__(self, func, *args): + + # Connect to the configured URL + print >> stderr, "Client POST", self.url.geturl() + c, headers = connect(self.url) + + # POST a JSON-RPC request + global id + req = StringIO() + writeStrings(jsonRequest(id, func, args), req) + id = id + 1 + headers["Content-type"] = "application/json-rpc" + c.request("POST", self.url.path, req.getvalue(), headers) + res = c.getresponse() + print >> stderr, "Client status", res.status + if res.status != 200: + return None + return jsonResultValue((res.read(),)) + + def __getattr__(self, name): + if name[0] == '_': + raise AttributeError() + if name == "eval": + return self + l = lambda *args: self.__call__(name, *args) + self.__dict__[name] = l + return l + + def __repr__(self): + return repr((self.url,)) + +def mkclient(url): + return client(url) + +# Connect to a URL, return a connection and any authorization headers +def connect(url): + if url.scheme == "https": + + # With HTTPS, use a cerficate or HTTP basic authentication + if os.path.exists("server.key"): + c = HTTPSConnection(url.hostname, 443 if url.port == None else url.port, "server.key", "server.crt") + return c, {} + else: + c = HTTPSConnection(url.hostname, 443 if url.port == None else url.port) + + # For HTTP basic authentication the user and password are + # provided by htpasswd.py + import htpasswd + auth = 'Basic ' + b64encode(htpasswd.user + ':' + htpasswd.passwd) + return c, {"Authorization": auth} + else: + c = HTTPConnection(url.hostname, 80 if url.port == None else url.port) + return c, {} + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/json-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/json-test.py new file mode 100755 index 0000000000..2f2a755bff --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/json-test.py @@ -0,0 +1,59 @@ +#!/usr/bin/python +# 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. + +# Test JSON data conversion functions + +import unittest +from elemutil import * +from jsonutil import * + +def testJSON(): + ad = ((attribute, "'city", "san francisco"), (attribute, "'state", "ca")) + ac = ((element, "'id", "1234"), (attribute, "'balance", 1000)) + cr = ((attribute, "'name", "jdoe"), cons(element, cons("'address", ad)), cons(element, cons("'account", ac))) + c = (cons(element, cons("'customer", cr)),) + s = writeJSON(c); + assert car(s) == "{\"customer\":{\"account\":{\"@balance\":1000,\"id\":\"1234\"},\"@name\":\"jdoe\",\"address\":{\"@city\":\"san francisco\",\"@state\":\"ca\"}}}" + + phones = ("408-1234", "650-1234") + l = ((element, "'phones", phones), (element, "'lastName", "test\ttab"), (attribute, "'firstName", "test1")) + s2 = writeJSON(l); + assert car(s2) == "{\"phones\":[\"408-1234\",\"650-1234\"],\"@firstName\":\"test1\",\"lastName\":\"test\\ttab\"}" + + r = readJSON(s2) + assert r == ((element, "'lastName", "test\ttab"), (attribute, "'firstName", "test1"), (element, "'phones", phones)) + w = writeJSON(r) + assert car(w) == "{\"lastName\":\"test\\ttab\",\"@firstName\":\"test1\",\"phones\":[\"408-1234\",\"650-1234\"]}" + + l4 = (("'ns1:echoString", ("'@xmlns:ns1", "http://ws.apache.org/axis2/services/echo"), ("'text", "Hello World!")),) + s4 = writeJSON(valuesToElements(l4)) + assert car(s4) == "{\"ns1:echoString\":{\"@xmlns:ns1\":\"http://ws.apache.org/axis2/services/echo\",\"text\":\"Hello World!\"}}" + + r4 = elementsToValues(readJSON(s4)) + assert r4 == (("'ns1:echoString", ("'text", 'Hello World!'), ("'@xmlns:ns1", 'http://ws.apache.org/axis2/services/echo')),) + return True + +def testJSONRPC(): + return True + +if __name__ == "__main__": + print "Testing..." + testJSON() + testJSONRPC() + print "OK" + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/jsonutil.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/jsonutil.py new file mode 100644 index 0000000000..ad8f5fcc6b --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/jsonutil.py @@ -0,0 +1,152 @@ +# 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. + +# JSON data conversion functions + +try: + import json +except: + from django.utils import simplejson as json + +from StringIO import StringIO +from util import * +from elemutil import * + +# Return true if a list represents a JS array +def isJSArray(l): + if isNil(l): + return True + v = car(l) + if isSymbol(v): + return False + if isList(v): + if not isNil(v) and isSymbol(car(v)): + return False + return True + +# Converts JSON properties to values +def jsPropertiesToValues(propertiesSoFar, o, i): + if isNil(i): + return propertiesSoFar + p = car(i) + jsv = o[p] + v = jsValToValue(jsv) + + if isinstance(p, basestring): + n = str(p) + if n[0:1] == "@": + return jsPropertiesToValues(cons((attribute, "'" + n[1:], v), propertiesSoFar), o, cdr(i)) + if isList(v) and not isJSArray(v): + return jsPropertiesToValues(cons(cons(element, cons("'" + n, v)), propertiesSoFar), o, cdr(i)) + return jsPropertiesToValues(cons((element, "'" + n, v), propertiesSoFar), o, cdr(i)) + return jsPropertiesToValues(cons(v, propertiesSoFar), o, cdr(i)) + +# Converts a JSON val to a value +def jsValToValue(jsv): + if isinstance(jsv, dict): + return jsPropertiesToValues((), jsv, tuple(jsv.keys())) + if isList(jsv): + return jsPropertiesToValues((), jsv, tuple(reversed(range(0, len(jsv))))) + if isinstance(jsv, basestring): + return str(jsv) + return jsv + +# Return true if a list of strings contains a JSON document +def isJSON(l): + if isNil(l): + return False + s = car(l)[0:1] + return s == "[" or s == "{" + +# Convert a list of strings representing a JSON document to a list of values +def readJSON(l): + s = StringIO() + writeStrings(l, s) + val = json.loads(s.getvalue()) + return jsValToValue(val) + +# Convert a list of values to JSON array elements +def valuesToJSElements(a, l, i): + if isNil(l): + return a + pv = valueToJSVal(car(l)) + a[i] = pv + return valuesToJSElements(a, cdr(l), i + 1) + +# Convert a value to a JSON value +def valueToJSVal(v): + if not isList(v): + return v + if isJSArray(v): + return valuesToJSElements(list(range(0, len(v))), v, 0) + return valuesToJSProperties({}, v) + +# Convert a list of values to JSON properties +def valuesToJSProperties(o, l): + if isNil(l): + return o + token = car(l) + if isTaggedList(token, attribute): + pv = valueToJSVal(attributeValue(token)) + o["@" + attributeName(token)[1:]] = pv + elif isTaggedList(token, element): + if elementHasValue(token): + pv = valueToJSVal(elementValue(token)) + o[elementName(token)[1:]] = pv + else: + child = {} + o[elementName(token)[1:]] = child + valuesToJSProperties(child, elementChildren(token)) + return valuesToJSProperties(o, cdr(l)) + +# Convert a list of values to a list of strings representing a JSON document +def writeJSON(l): + if isJSArray(l): + jsv = valuesToJSElements(list(range(0, len(l))), l, 0) + else: + jsv = valuesToJSProperties({}, l) + s = json.dumps(jsv, separators=(',',':')) + return (s,) + +# Convert a list + params to a JSON-RPC request +def jsonRequest(id, func, params): + r = (("'id", id), ("'method", func), ("'params", params)) + return writeJSON(valuesToElements(r)) + +# Convert a value to a JSON-RPC result +def jsonResult(id, val): + return writeJSON(valuesToElements((("'id", id), ("'result", val)))) + +# Convert a JSON-RPC result to a value +def jsonResultValue(s): + jsres = readJSON(s) + res = elementsToValues(jsres) + val = cadr(assoc("'result", res)) + if isList(val) and not isJSArray(val): + return (val,) + return val + +# Return a portable function name from a JSON-RPC function name +def funcName(f): + if f.startswith("."): + return f[1:] + if f.startswith("system."): + return f[7:] + if f.startswith("Service."): + return f[8:] + return f + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/rss-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/rss-test.py new file mode 100755 index 0000000000..e8a094b7d8 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/rss-test.py @@ -0,0 +1,170 @@ +#!/usr/bin/python +# 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. + +# Test RSS data conversion functions + +import unittest +from elemutil import * +from rssutil import * + +itemEntry = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<item>" \ + "<title>fruit</title>" \ + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</link>" \ + "<description>" \ + "<item>" \ + "<name>Apple</name><price>$2.99</price>" \ + "</item>" \ + "</description>" \ + "</item>\n" + +textEntry = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<item>" \ + "<title>fruit</title>" \ + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</link>" \ + "<description>" \ + "Apple" \ + "</description>" \ + "</item>\n" + +incompleteEntry = \ + "<item>" \ + "<title>fruit</title><description>" \ + "<fruit xmlns=\"http://services/\">" \ + "<name xmlns=\"\">Orange</name>" \ + "<price xmlns=\"\">3.55</price>" \ + "</fruit>" \ + "</description>" \ + "</item>" + +completedEntry = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<item>" \ + "<title>fruit</title>" \ + "<link />" \ + "<description>" \ + "<fruit xmlns=\"http://services/\">" \ + "<name xmlns=\"\">Orange</name>" \ + "<price xmlns=\"\">3.55</price>" \ + "</fruit>" \ + "</description>" \ + "</item>\n" + +def testEntry(): + i = (element, "'item", (element, "'name", "Apple"), (element, "'price", "$2.99")) + a = ("fruit", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", i) + s = writeRSSEntry(a); + assert car(s) == itemEntry + + a2 = readRSSEntry((itemEntry,)) + s2 = writeRSSEntry(a2) + assert car(s2) == itemEntry + + a3 = readRSSEntry((textEntry,)) + s3 = writeRSSEntry(a3) + assert car(s3) == textEntry + + a4 = readRSSEntry((incompleteEntry,)) + s4 = writeRSSEntry(a4) + assert car(s4) == completedEntry + return True + +emptyFeed = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<rss version=\"2.0\">" \ + "<channel>" \ + "<title>Feed</title>" \ + "<link>1234</link>" \ + "<description>Feed</description>" \ + "</channel>" \ + "</rss>\n" + +itemFeed = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<rss version=\"2.0\">" \ + "<channel>" \ + "<title>Feed</title>" \ + "<link>1234</link>" \ + "<description>Feed</description>" \ + "<item>" \ + "<title>fruit</title>" \ + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b</link>" \ + "<description>" \ + "<item>" \ + "<name>Apple</name><price>$2.99</price>" \ + "</item>" \ + "</description>" \ + "</item>" \ + "<item>" \ + "<title>fruit</title>" \ + "<link>cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c</link>" \ + "<description>" \ + "<item>" \ + "<name>Orange</name><price>$3.55</price>" \ + "</item>" \ + "</description>" \ + "</item>" \ + "</channel>" \ + "</rss>\n" + +def testFeed(): + s = writeRSSFeed(("Feed", "1234")) + assert car(s) == emptyFeed + + a2 = readRSSFeed((emptyFeed,)) + s2 = writeRSSFeed(a2) + assert car(s2) == emptyFeed + + i3 = (("fruit", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", + (element, "'item", (element, "'name", "Apple"), (element, "'price", "$2.99"))), + ("fruit", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c", + (element, "'item", (element, "'name", "Orange"), (element, "'price", "$3.55")))) + a3 = cons("Feed", cons("1234", i3)) + s3 = writeRSSFeed(a3) + assert car(s3) == itemFeed + + i4 = (("fruit", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", + valueToElement(("'item", ("'name", "Apple"), ("'price", "$2.99")))), + ("fruit", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c", + valueToElement(("'item", ("'name", "Orange"), ("'price", "$3.55"))))) + a4 = cons("Feed", cons("1234", i4)) + s4 = writeRSSFeed(a4) + assert car(s4) == itemFeed + + a5 = readRSSFeed((itemFeed,)); + s5 = writeRSSFeed(a5); + assert car(s5) == itemFeed + + i6 = (("fruit", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83b", + (("'name", "Apple"), ("'price", "$2.99"))), + ("fruit", "cart-53d67a61-aa5e-4e5e-8401-39edeba8b83c", + (("'name", "Orange"), ("'price", "$3.55")))) + a6 = cons("Feed", cons("1234", i6)) + s6 = writeRSSFeed(feedValuesToElements(a6)) + assert car(s6) == itemFeed + + return True + +if __name__ == "__main__": + print "Testing..." + testEntry() + testFeed() + print "OK" + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/rssutil.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/rssutil.py new file mode 100644 index 0000000000..984d71b690 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/rssutil.py @@ -0,0 +1,117 @@ +# 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. + +# RSS data conversion functions + +from util import * +from elemutil import * +from xmlutil import * + +# Convert a list of elements to a list of values representing an RSS entry +def entryElementsToValues(e): + lt = filter(selector((element, "'title")), e) + t = "" if isNil(lt) else elementValue(car(lt)) + li = filter(selector((element, "'link")), e) + i = "" if isNil(li) else elementValue(car(li)) + lc = filter(selector((element, "'description")), e) + return (t, i, elementValue(car(lc))) + +# Convert a list of elements to a list of values representing RSS entries +def entriesElementsToValues(e): + if isNil(e): + return e + return cons(entryElementsToValues(car(e)), entriesElementsToValues(cdr(e))) + +# Convert a list of strings to a list of values representing an RSS entry +def readRSSEntry(l): + e = readXML(l) + if isNil(e): + return () + return entryElementsToValues(car(e)) + +# Convert a list of values representy an RSS entry to a value +def entryValue(e): + v = elementsToValues((caddr(e),)) + return cons(car(e), (cadr(e), cdr(car(v)))) + +# Return true if a list of strings represents an RSS feed +def isRSSFeed(l): + if not isXML(l): + return False + return contains(car(l), "<rss") + +# Convert a list of strings to a list of values representing an RSS feed +def readRSSFeed(l): + f = readXML(l) + if isNil(f): + return () + c = filter(selector((element, "'channel")), car(f)) + t = filter(selector((element, "'title")), car(c)) + i = filter(selector((element, "'link")), car(c)) + e = filter(selector((element, "'item")), car(c)) + if isNil(e): + return (elementValue(car(t)), elementValue(car(i))) + return cons(elementValue(car(t)), cons(elementValue(car(i)), entriesElementsToValues(e))) + +# Convert an RSS feed containing elements to an RSS feed containing values +def feedValuesLoop(e): + if (isNil(e)): + return e + return cons(entryValue(car(e)), feedValuesLoop(cdr(e))) + +def feedValues(e): + return cons(car(e), cons(cadr(e), feedValuesLoop(cddr(e)))) + +# Convert a list of values representy an RSS entry to a list of elements +def entryElement(l): + return (element, "'item", + (element, "'title", car(l)), + (element, "'link", cadr(l)), + (element, "'description", caddr(l))) + +# Convert a list of values representing RSS entries to a list of elements +def entriesElements(l): + if isNil(l): + return l + return cons(entryElement(car(l)), entriesElements(cdr(l))) + +# Convert a list of values representing an RSS entry to an RSS entry +def writeRSSEntry(l): + return writeXML((entryElement(l),), True) + +# Convert a list of values representing an RSS feed to an RSS feed +def writeRSSFeed(l): + c = ((element, "'title", car(l)), + (element, "'link", cadr(l)), + (element, "'description", car(l))) + ce = c if isNil(cddr(l)) else append(c, entriesElements(cddr(l))) + fe = (element, "'rss", (attribute, "'version", "2.0"), append((element, "'channel"), ce)) + return writeXML((fe,), True) + +# Convert an RSS entry containing a value to an RSS entry containing an item element +def entryValuesToElements(v): + return cons(car(v), cons(cadr(v), valuesToElements((cons("'item", caddr(v)),)))) + +# Convert an RSS feed containing values to an RSS feed containing elements +def feedValuesToElementsLoop(v): + if isNil(v): + return v + return cons(entryValuesToElements(car(v)), feedValuesToElementsLoop(cdr(v))) + +def feedValuesToElements(v): + return cons(car(v), cons(cadr(v), feedValuesToElementsLoop(cddr(v)))) + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/scdl.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/scdl.py new file mode 100644 index 0000000000..97c2f7dd69 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/scdl.py @@ -0,0 +1,272 @@ +# 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. + +# SCDL parsing functions + +from xml.etree.cElementTree import iterparse +from sys import stderr +from os import environ +from util import * +from httputil import * + +# Element tree utility functions, used to parse SCDL documents +def parse(file): + return map(lambda x: x, iterparse(file, events=("start", "end"))) + +def evt(e): + return car(e) + +def elt(e): + return cadr(e) + +def att(e): + return elt(e).attrib + +def text(e): + return elt(e).text + +def match(e, ev, tag): + return evt(e) == ev and elt(e).tag.find("}" + tag) != -1 + +# Make a callable component +class component: + def __init__(self, name, impl, svcs, refs, props): + self.name = name + self.impl = impl + self.mod = None + self.svcs = svcs + self.refs = refs + self.props = props + self.proxies = () + + def __call__(self, func, *args): + return self.mod.__getattribute__(func)(*(args + self.proxies)) + + def __getattr__(self, name): + if name[0] == '_': + raise AttributeError() + if name == "eval": + return self + l = lambda *args: self.__call__(name, *args) + self.__dict__[name] = l + return l + + def __repr__(self): + return repr((self.name, self.impl, self.mod, self.svcs, self.refs, self.props, self.proxies)) + +def mkcomponent(name, impl, svcs, refs, props): + return component(name, impl, svcs, refs, props) + +# Return the Python module name of a component implementation +def implementation(e): + if len(e) == 0 or match(car(e), "end", "component") == True: + return "" + if match(car(e), "start", "implementation.python") == False: + return implementation(cdr(e)) + if "script" in att(car(e)): + s = att(car(e))["script"] + return s[0:len(s) - 3] + return None + +# Return the URI of a binding under a SCDL service or reference element +def binding(e): + if len(e) == 0 or match(car(e), "end", "reference") == True or match(car(e), "end", "service") == True: + return () + if match(car(e), "start", "binding.") == False: + return binding(cdr(e)) + return att(car(e))["uri"] + +# Return the list of references under a SCDL component element +def references(e): + if len(e) == 0 or match(car(e), "end", "component") == True: + return () + if match(car(e), "start", "reference") == False: + return references(cdr(e)) + if "target" in att(car(e)): + return cons((att(car(e))["name"], car(tokens(att(car(e))["target"]))), references(cdr(e))) + return cons((att(car(e))["name"], binding(e)), references(cdr(e))) + +# Return the list of properties under a SCDL component element +def properties(e): + if len(e) == 0 or match(car(e), "end", "component") == True: + return () + if match(car(e), "start", "property") == False: + return properties(cdr(e)) + return cons((att(car(e))["name"], text(car(e))), properties(cdr(e))) + +# Return the list of services under a SCDL component element +def services(e): + if len(e) == 0 or match(car(e), "end", "component") == True: + return () + if match(car(e), "start", "service") == False: + return services(cdr(e)) + return cons(tokens(binding(e)), services(cdr(e))) + +# Return the name attribute of a SCDL element +def name(e): + return att(car(e))["name"] + +# Return the list of components under a SCDL composite element +def components(e): + if len(e) == 0: + return () + if match(car(e), "start", "component") == False: + return components(cdr(e)) + n = name(e) + return cons(mkcomponent(n, implementation(e), services(e), references(e), properties(e)), components(cdr(e))) + +# Find a component with a given name +def nameToComponent(name, comps): + if comps == (): + return None + if car(comps).name == name: + return car(comps) + return nameToComponent(name, cdr(comps)) + +# Find the URI matching a given URI in a list of service URIs +def matchingURI(u, svcs): + if svcs == (): + return None + if car(svcs) == u[0:len(car(svcs))]: + return car(svcs) + return matchingURI(u, cdr(svcs)) + +# Return the (service URI, component) pair matching a given URI +def uriToComponent(u, comps): + if car(u) == "components": + return componentURIToComponent(u, comps) + if car(u) == "references": + return referenceURIToComponent(u, comps) + return serviceURIToComponent(u, comps) + +def serviceURIToComponent(u, comps): + if comps == (): + return (None, None) + m = matchingURI(u, car(comps).svcs) + if m != None: + return (m, car(comps)) + return serviceURIToComponent(u, cdr(comps)) + +def componentURIToComponent(u, comps): + comp = nameToComponent(cadr(u), comps) + if comps == None: + return (None, None) + return (u[0:2], comp) + +def referenceURIToComponent(u, comps): + sc = nameToComponent(cadr(u), comps) + if sc == None: + return (None, None) + + def referenceToComponent(r, refs): + if refs == (): + return None + if r == car(car(refs)): + return cadr(car(refs)) + return referenceToComponent(r, cdr(refs)) + + tn = referenceToComponent(caddr(u), sc.refs) + if tn == None: + return (None, None) + tc = nameToComponent(tn, comps) + if tc == None: + return (None, None) + return (u[0:3], tc) + +# Evaluate a reference, return a proxy to the resolved component or an +# HTTP client configured with the reference target uri +def evalReference(r, comps): + t = cadr(r) + if t.startswith("http://") or t.startswith("https://"): + return mkclient(t) + return nameToComponent(t, comps) + +# Make a callable property +class property: + def __init__(self, name, l): + self.name = name + self.l = l + + def __call__(self, *args): + return self.l(*args) + + def __getattr__(self, name): + if name == "eval": + return self + raise AttributeError() + + def __repr__(self): + return repr((self.name, self.l())) + +def mkproperty(name, l): + return property(name, l) + +# Evaluate a property, return a lambda function returning the property +# value. The host, user, realm, nickname and email properties are configured +# with the values from the HTTP request, if any. +def evalProperty(p): + if car(p) == "host": + return mkproperty(car(p), lambda: hostProperty(cadr(p), environ)) + if car(p) == "user": + return mkproperty(car(p), lambda: userProperty(cadr(p))) + if car(p) == "realm": + return mkproperty(car(p), lambda: hostProperty(cadr(p), environ)) + if car(p) == "nickname": + return mkproperty(car(p), lambda: nicknameProperty(cadr(p))) + if car(p) == "email": + return mkproperty(car(p), lambda: emailProperty(cadr(p))) + return mkproperty(car(p), lambda: cadr(p)) + +def currentUser(): + try: + from google.appengine.api import users + return users.get_current_user() + except: + return None + +def userProperty(v): + user = currentUser() + return user.federated_identity() if user else v + +def nicknameProperty(v): + user = currentUser() + return user.nickname() if user else v + +def hostProperty(v, e): + return e.get("HTTP_HOST", e.get("SERVER_NAME", v)).split(":")[0] + +def emailProperty(v): + user = currentUser() + return user.email() if user else v + +# Evaluate a component, resolve its implementation, references and +# properties +def evalComponent(comp, comps): + comp.mod = __import__(comp.impl) + + # Make a list of proxy lambda functions for the component references and properties + # A reference proxy is the callable lambda function of the component wired to the reference + # A property proxy is a lambda function that returns the value of the property + print >> stderr, "evalComponent", comp.impl, comp.svcs, comp.refs, comp.props + comp.proxies = tuple(map(lambda r: evalReference(r, comps), comp.refs)) + tuple(map(lambda p: evalProperty(p), comp.props)) + + return comp + +# Evaluate a list of components +def evalComponents(comps): + return tuple(map(lambda c: evalComponent(c, comps), comps)) + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/server-test b/sandbox/sebastien/cpp/apr-2/modules/wsgi/server-test new file mode 100755 index 0000000000..9bd862c53a --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/server-test @@ -0,0 +1,30 @@ +#!/bin/sh + +# 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. + +# Setup +./wsgi-start target 8090 2>/dev/null +sleep 2 + +# Test +./client-test 2>/dev/null +rc=$? + +# Cleanup +./wsgi-stop target 8090 +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/server-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/server-test.py new file mode 100644 index 0000000000..28f88efefc --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/server-test.py @@ -0,0 +1,44 @@ +# 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. + +# JSON-RPC test case + +def echo(x): + return x + +# ATOMPub test case + +def get(id): + if id == ("index.html",): + return ("text/plain", ("It works!",)) + if id == (): + return ("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)))) + + entry = (("'name", "Apple"), ("'currencyCode", "USD"), ("'currencySymbol", "$"), ("'price", 2.99)) + return ("Item", id[0], entry) + +def post(collection, item): + return ("123456789",) + +def put(id, item): + return True + +def delete(id): + return True diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/stream-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/stream-test.py new file mode 100755 index 0000000000..2cff038f1e --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/stream-test.py @@ -0,0 +1,47 @@ +#!/usr/bin/python +# 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. + +# Test stream functions + +import unittest +from util import * + +def testStream(): + + s = cons_stream(0, lambda: cons_stream(1, lambda: cons(2, ()))) + assert len(s) == 3 + assert car(s) == 0 + assert cadr(s) == 1 + assert len(cdr(s)) == 2 + assert s[0] == 0 + assert s[1] == 1 + assert s[2] == 2 + assert s[:1] == (0, 1) + assert s[:5] == (0, 1, 2) + assert s[2:5] == (2,) + assert s[4:5] == () + assert s[0:] == (0, 1, 2) + assert (0, 1, 2) == s[0:] + + return True + +if __name__ == "__main__": + print "Testing..." + testStream() + print "OK" + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/util-test b/sandbox/sebastien/cpp/apr-2/modules/wsgi/util-test new file mode 100755 index 0000000000..aa8725a200 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/util-test @@ -0,0 +1,43 @@ +#!/bin/sh + +# 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. + +# Run Python util test cases +here=`readlink -f $0`; here=`dirname $here` +python_prefix=`cat $here/../python/python.prefix` + +$python_prefix/bin/python stream-test.py +rc=$? +if [ "$rc" = "0" ]; then + $python_prefix/bin/python xml-test.py + rc=$? +fi +if [ "$rc" = "0" ]; then + $python_prefix/bin/python atom-test.py + rc=$? +fi +if [ "$rc" = "0" ]; then + $python_prefix/bin/python rss-test.py + rc=$? +fi +if [ "$rc" = "0" ]; then + $python_prefix/bin/python json-test.py + rc=$? +fi + +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/util.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/util.py new file mode 100644 index 0000000000..560101e32d --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/util.py @@ -0,0 +1,145 @@ +# 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. + +# Simple utility functions +from sys import maxint + +# Scheme-like lists +def cons(a, b): + return (a,) + b + +def car(l): + return l[0] + +def first(l): + return car(l) + +def cdr(l): + return l[1:] + +def rest(l): + return cdr(l) + +def cadr(l): + return car(cdr(l)) + +def cddr(l): + return cdr(cdr(l)) + +def caddr(l): + return car(cddr(l)) + +def append(a, b): + return a + b + +def reverse(l): + r = list(l) + r.reverse() + return tuple(r) + +def isNil(l): + if isinstance(l, streampair): + return l.isNil() + return l == () + +def isSymbol(v): + return isinstance(v, basestring) and v[0:1] == "'" + +def isList(v): + if getattr(v, '__iter__', False) == False: + return False + if isinstance(v, basestring) or isinstance(v, dict): + return False + return True + +def isTaggedList(v, t): + return isList(v) and not isNil(v) and car(v) == t + + +# Scheme-like streams +class streampair(object): + def __init__(self, car, cdr): + self.car = car + self.cdr = cdr + + def __repr__(self): + return repr(self[0:len(self)]) + + def isNil(self): + return self.cdr == () + + def __len__(self): + if self.cdr == (): + return 0 + return 1 + len(self.cdr()) + + def __getitem__(self, i): + if i == 0: + return self.car + return self.cdr()[i - 1] + + def __getslice__(self, i, j): + if isNil(self): + return () + if i > 0: + if j == maxint: + return self.cdr()[i - 1: j] + return self.cdr()[i - 1: j - 1] + if j == maxint: + return self + if j == 0: + return (self.car,) + return (self.car,) + self.cdr()[: j - 1] + + def __eq__(self, other): + sl = len(self) + ol = len(other) + if sl != ol: + return False + return self[0: sl] == other[0: ol] + + def __ne__(self, other): + return not self.__eq__(other) + +def cons_stream(car, cdr): + return streampair(car, cdr) + + +# Scheme-like associations +def assoc(k, l): + if l == (): + return None + + if k == car(car(l)): + return car(l) + return assoc(k, cdr(l)) + +# Currying / partial function application +def curry(f, *args): + return lambda *a: f(*(args + a)) + +# Split a path into a list of segments +def tokens(path): + return tuple(filter(lambda s: len(s) != 0, path.split("/"))) + +# Write a list of strings to a stream +def writeStrings(l, os): + if l == (): + return os + os.write(car(l)) + return writeStrings(cdr(l), os) + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/wiring-test b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wiring-test new file mode 100755 index 0000000000..f3c1bbb840 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wiring-test @@ -0,0 +1,75 @@ +#!/bin/sh + +# 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. + +echo "Testing..." +here=`readlink -f $0`; here=`dirname $here` +curl_prefix=`cat $here/../http/curl.prefix` +uri=$1 +if [ "$uri" = "" ]; then + uri="http://localhost:8090" +fi + +# Setup +mkdir -p tmp +./wsgi-start target 8090 2>/dev/null +sleep 2 + +# Test HTTP GET +$curl_prefix/bin/curl $uri/index.html 2>/dev/null >tmp/index.html +diff tmp/index.html htdocs/index.html +rc=$? + +# Test ATOMPub +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl $uri/client/ >tmp/feed.xml 2>/dev/null + diff tmp/feed.xml htdocs/test/feed.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl $uri/client/111 >tmp/entry.xml 2>/dev/null + diff tmp/entry.xml htdocs/test/entry.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl $uri/client/ -X POST -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl $uri/client/111 -X PUT -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl $uri/client/111 -X DELETE 2>/dev/null + rc=$? +fi + +# Test JSON-RPC +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl $uri/client/ -X POST -H "Content-type: application/json-rpc" --data @htdocs/test/json-request.txt >tmp/json-result.txt 2>/dev/null + diff tmp/json-result.txt htdocs/test/json-result.txt + rc=$? +fi + +# Cleanup +./wsgi-stop target 8090 +sleep 2 +if [ "$rc" = "0" ]; then + echo "OK" +fi +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-start b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-start new file mode 100755 index 0000000000..d020f3da14 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-start @@ -0,0 +1,28 @@ +#!/bin/sh + +# 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. + +# Start WSGI server +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` +port=$2 + +python_prefix=`cat $here/../python/python.prefix` +cd $root +$python_prefix/bin/python composite.py $port & + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-stop b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-stop new file mode 100755 index 0000000000..7e12967adb --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-stop @@ -0,0 +1,28 @@ +#!/bin/sh + +# 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. + +# Stop WSGI server +here=`readlink -f $0`; here=`dirname $here` +root=`readlink -f $1` +port=$2 + +python_prefix=`cat $here/../python/python.prefix` +py="$python_prefix/bin/python composite.py $port" + +kill `ps -ef | grep -v grep | grep "${py}" | awk '{ print $2 }'` diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-test b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-test new file mode 100755 index 0000000000..369ca5a677 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/wsgi-test @@ -0,0 +1,71 @@ +#!/bin/sh + +# 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. + +echo "Testing..." +here=`readlink -f $0`; here=`dirname $here` +curl_prefix=`cat $here/../http/curl.prefix` + +# Setup +mkdir -p tmp +./wsgi-start target 8090 2>/dev/null +sleep 2 + +# Test HTTP GET +$curl_prefix/bin/curl http://localhost:8090/index.html 2>/dev/null >tmp/index.html +diff tmp/index.html htdocs/index.html +rc=$? + +# Test ATOMPub +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/wsgi/ >tmp/feed.xml 2>/dev/null + diff tmp/feed.xml htdocs/test/feed.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/wsgi/111 >tmp/entry.xml 2>/dev/null + diff tmp/entry.xml htdocs/test/entry.xml + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/wsgi/ -X POST -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/wsgi/111 -X PUT -H "Content-type: application/atom+xml" --data @htdocs/test/entry.xml 2>/dev/null + rc=$? +fi +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/wsgi/111 -X DELETE 2>/dev/null + rc=$? +fi + +# Test JSON-RPC +if [ "$rc" = "0" ]; then + $curl_prefix/bin/curl http://localhost:8090/wsgi/ -X POST -H "Content-type: application/json-rpc" --data @htdocs/test/json-request.txt >tmp/json-result.txt 2>/dev/null + diff tmp/json-result.txt htdocs/test/json-result.txt + rc=$? +fi + +# Cleanup +./wsgi-stop target 8090 +sleep 2 +if [ "$rc" = "0" ]; then + echo "OK" +fi +return $rc diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/xml-test.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/xml-test.py new file mode 100755 index 0000000000..f60322bdc1 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/xml-test.py @@ -0,0 +1,74 @@ +#!/usr/bin/python +# 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. + +# Test XML handling functions + +import unittest +from elemutil import * +from xmlutil import * + +customerXML = \ + "<?xml version=\'1.0\' encoding=\'UTF-8\'?>\n" \ + "<customer>" \ + "<name>jdoe</name>" \ + "<address><city>san francisco</city><state>ca</state></address>" \ + "<account><id>1234</id><balance>1000</balance></account>" \ + "<account><id>6789</id><balance>2000</balance></account>" \ + "<account><id>4567</id><balance>3000</balance></account>" \ + "</customer>\n" + +def testElements(): + ad = (("'city", "san francisco"), ("'state", "ca")) + ac1 = (("'id", "1234"), ("'balance", 1000)) + ac2 = (("'id", "6789"), ("'balance", 2000)) + ac3 = (("'id", "4567"), ("'balance", 3000)) + c = (("'customer", ("'name", "jdoe"), cons("'address", ad), ("'account", (ac1, ac2, ac3))),) + e = valuesToElements(c) + v = elementsToValues(e) + assert v == c + s = writeXML(e, True) + assert car(s) == customerXML + + c2 = (("'customer", ("'name", "jdoe"), cons("'address", ad), cons("'account", ac1), cons("'account", ac2), cons("'account", ac3)),) + e2 = valuesToElements(c2); + v2 = elementsToValues(e2); + s2 = writeXML(e2, True) + assert car(s2) == customerXML + + c3 = readXML((customerXML,)) + v3 = elementsToValues(c3) + e3 = valuesToElements(v3) + s3 = writeXML(e3, True) + assert car(s3) == customerXML + return True + +def testValues(): + l = (("'ns1:echoString", ("'@xmlns:ns1", "http://ws.apache.org/axis2/services/echo"), ("'text", "Hello World!")),) + e = valuesToElements(l) + lx = writeXML(e, True) + x = readXML(lx) + v = elementsToValues(x) + assert v == l + return True + +if __name__ == "__main__": + print "Testing..." + testElements() + testValues() + print "OK" + diff --git a/sandbox/sebastien/cpp/apr-2/modules/wsgi/xmlutil.py b/sandbox/sebastien/cpp/apr-2/modules/wsgi/xmlutil.py new file mode 100644 index 0000000000..35ccb7f803 --- /dev/null +++ b/sandbox/sebastien/cpp/apr-2/modules/wsgi/xmlutil.py @@ -0,0 +1,122 @@ +# 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. + +# XML handling functions + +from StringIO import StringIO +from xml.parsers import expat +import xml.etree.ElementTree as et +from util import * +from elemutil import * + +# Read a list of XML attributes +def readAttributes(a): + if a == (): + return a + return cons((attribute, "'" + car(car(a)), cadr(car(a))), readAttributes(cdr(a))) + +# Read an XML element +def readElement(e): + l = (element, "'" + e.tag) + readAttributes(tuple(e.items())) + readElements(tuple(e.getchildren())) + if e.text == None: + return l + return l + (e.text,) + +# Read a list of XML elements +def readElements(l): + if l == (): + return l + return cons(readElement(car(l)), readElements(cdr(l))) + +# Return true if a list of strings represents an XML document +def isXML(l): + if isNil(l): + return False + if car(l)[0:5] != "<?xml": + return False + return True + +# Parse a list of strings representing an XML document +class NamespaceParser(et.XMLTreeBuilder): + def __init__(self): + et.XMLTreeBuilder.__init__(self) + self._parser = parser = expat.ParserCreate(None) + parser.DefaultHandlerExpand = self._default + parser.StartElementHandler = self._start + parser.EndElementHandler = self._end + parser.CharacterDataHandler = self._data + try: + parser.buffer_text = 1 + except AttributeError: + pass + try: + parser.ordered_attributes = 1 + parser.specified_attributes = 1 + parser.StartElementHandler = self._start_list + except AttributeError: + pass + +def parseXML(l): + s = StringIO() + writeStrings(l, s) + parser = NamespaceParser() + parser.feed(s.getvalue()) + return parser.close() + +# Read a list of values from a list of strings representing an XML document +def readXML(l): + e = parseXML(l) + return (readElement(e),) + +# Write a list of XML element and attribute tokens +def expandElementValues(n, l): + if isNil(l): + return l + return cons(cons(element, cons(n, car(l))), expandElementValues(n, cdr(l))) + +def writeList(l, xml): + if isNil(l): + return xml + token = car(l) + if isTaggedList(token, attribute): + xml.attrib[attributeName(token)[1:]] = str(attributeValue(token)) + elif isTaggedList(token, element): + if elementHasValue(token): + v = elementValue(token) + if isList(v): + e = expandElementValues(elementName(token), v) + writeList(e, xml) + else: + child = et.Element(elementName(token)[1:]) + writeList(elementChildren(token), child) + xml.append(child) + else: + child = et.Element(elementName(token)[1:]) + writeList(elementChildren(token), child) + xml.append(child) + else: + xml.text = str(token) + writeList(cdr(l), xml) + return xml + +# Convert a list of values to a list of strings representing an XML document +def writeXML(l, xmlTag): + e = writeList(l, []) + if not xmlTag: + return (et.tostring(car(e)),) + return (et.tostring(car(e), "UTF-8") + "\n",) + |