You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@synapse.apache.org by sa...@apache.org on 2006/05/30 10:31:32 UTC

svn commit: r410216 [3/3] - in /incubator/synapse/trunk/java/modules/extensions: src/META-INF/services/ src/org/apache/synapse/config/xml/ src/org/apache/synapse/json/ src/org/apache/synapse/mediators/ext/json/ test/org/apache/synapse/ test/org/apache/...

Added: incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XML.java
URL: http://svn.apache.org/viewvc/incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XML.java?rev=410216&view=auto
==============================================================================
--- incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XML.java (added)
+++ incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XML.java Tue May 30 01:31:30 2006
@@ -0,0 +1,417 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.synapse.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+import java.util.Iterator;
+
+
+/**
+ * This provides static methods to convert an XML text into a JSONObject,
+ * and to covert a JSONObject into an XML text.
+ * @author JSON.org
+ * @version 2
+ */
+public class XML {
+
+    /** The Character '&'. */
+    public static final Character AMP   = new Character('&');
+
+    /** The Character '''. */
+    public static final Character APOS  = new Character('\'');
+
+    /** The Character '!'. */
+    public static final Character BANG  = new Character('!');
+
+    /** The Character '='. */
+    public static final Character EQ    = new Character('=');
+
+    /** The Character '>'. */
+    public static final Character GT    = new Character('>');
+
+    /** The Character '<'. */
+    public static final Character LT    = new Character('<');
+
+    /** The Character '?'. */
+    public static final Character QUEST = new Character('?');
+
+    /** The Character '"'. */
+    public static final Character QUOT  = new Character('"');
+
+    /** The Character '/'. */
+    public static final Character SLASH = new Character('/');
+
+    /**
+     * Replace special characters with XML escapes:
+     * <pre>
+     * &amp; <small>(ampersand)</small> is replaced by &amp;amp;
+     * &lt; <small>(less than)</small> is replaced by &amp;lt;
+     * &gt; <small>(greater than)</small> is replaced by &amp;gt;
+     * &quot; <small>(double quote)</small> is replaced by &amp;quot;
+     * </pre>
+     * @param string The string to be escaped.
+     * @return The escaped string.
+     */
+    public static String escape(String string) {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0, len = string.length(); i < len; i++) {
+            char c = string.charAt(i);
+            switch (c) {
+            case '&':
+                sb.append("&amp;");
+                break;
+            case '<':
+                sb.append("&lt;");
+                break;
+            case '>':
+                sb.append("&gt;");
+                break;
+            case '"':
+                sb.append("&quot;");
+                break;
+            default:
+                sb.append(c);
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Scan the content following the named tag, attaching it to the context.
+     * @param x       The XMLTokener containing the source string.
+     * @param context The JSONObject that will include the new material.
+     * @param name    The tag name.
+     * @return true if the close tag is processed.
+     * @throws JSONException
+     */
+    private static boolean parse(XMLTokener x, JSONObject context,
+                                 String name) throws JSONException {
+        char       c;
+        int        i;
+        String     n;
+        JSONObject o = null;
+        String     s;
+        Object     t;
+
+// Test for and skip past these forms:
+//      <!-- ... -->
+//      <!   ...   >
+//      <![  ... ]]>
+//      <?   ...  ?>
+// Report errors for these forms:
+//      <>
+//      <=
+//      <<
+
+        t = x.nextToken();
+
+// <!
+
+        if (t == BANG) {
+            c = x.next();
+            if (c == '-') {
+                if (x.next() == '-') {
+                    x.skipPast("-->");
+                    return false;
+                }
+                x.back();
+            } else if (c == '[') {
+                t = x.nextToken();
+                if (t.equals("CDATA")) {
+                    if (x.next() == '[') {
+                        s = x.nextCDATA();
+                        if (s.length() > 0) {
+                            context.accumulate("content", s);
+                        }
+                        return false;
+                    }
+                }
+                throw x.syntaxError("Expected 'CDATA['");
+            }
+            i = 1;
+            do {
+                t = x.nextMeta();
+                if (t == null) {
+                    throw x.syntaxError("Missing '>' after '<!'.");
+                } else if (t == LT) {
+                    i += 1;
+                } else if (t == GT) {
+                    i -= 1;
+                }
+            } while (i > 0);
+            return false;
+        } else if (t == QUEST) {
+
+// <?
+
+            x.skipPast("?>");
+            return false;
+        } else if (t == SLASH) {
+
+// Close tag </
+
+            if (name == null || !x.nextToken().equals(name)) {
+                throw x.syntaxError("Mismatched close tag");
+            }
+            if (x.nextToken() != GT) {
+                throw x.syntaxError("Misshaped close tag");
+            }
+            return true;
+
+        } else if (t instanceof Character) {
+            throw x.syntaxError("Misshaped tag");
+
+// Open tag <
+
+        } else {
+            n = (String)t;
+            t = null;
+            o = new JSONObject();
+            for (;;) {
+                if (t == null) {
+                    t = x.nextToken();
+                }
+
+// attribute = value
+
+                if (t instanceof String) {
+                    s = (String)t;
+                    t = x.nextToken();
+                    if (t == EQ) {
+                        t = x.nextToken();
+                        if (!(t instanceof String)) {
+                            throw x.syntaxError("Missing value");
+                        }
+                        o.accumulate(s, t);
+                        t = null;
+                    } else {
+                        o.accumulate(s, "");
+                    }
+
+// Empty tag <.../>
+
+                } else if (t == SLASH) {
+                    if (x.nextToken() != GT) {
+                        throw x.syntaxError("Misshaped tag");
+                    }
+                    context.accumulate(n, o);
+                    return false;
+
+// Content, between <...> and </...>
+
+                } else if (t == GT) {
+                    for (;;) {
+                        t = x.nextContent();
+                        if (t == null) {
+                            if (name != null) {
+                                throw x.syntaxError("Unclosed tag " + name);
+                            }
+                            return false;
+                        } else if (t instanceof String) {
+                            s = (String)t;
+                            if (s.length() > 0) {
+                                o.accumulate("content", s);
+                            }
+
+// Nested element
+
+                        } else if (t == LT) {
+                            if (parse(x, o, n)) {
+                                if (o.length() == 0) {
+                                    context.accumulate(n, "");
+                                } else if (o.length() == 1 &&
+                                       o.opt("content") != null) {
+                                    context.accumulate(n, o.opt("content"));
+                                } else {
+                                    context.accumulate(n, o);
+                                }
+                                return false;
+                            }
+                        }
+                    }
+                } else {
+                    throw x.syntaxError("Misshaped tag");
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Convert a well-formed (but not necessarily valid) XML string into a
+     * JSONObject. Some information may be lost in this transformation
+     * because JSON is a data format and XML is a document format. XML uses
+     * elements, attributes, and content text, while JSON uses unordered
+     * collections of name/value pairs and arrays of values. JSON does not
+     * does not like to distinguish between elements and attributes.
+     * Sequences of similar elements are represented as JSONArrays. Content
+     * text may be placed in a "content" member. Comments, prologs, DTDs, and
+     * <code>&lt;[ [ ]]></code> are ignored.
+     * @param string The source string.
+     * @return A JSONObject containing the structured data from the XML string.
+     * @throws JSONException
+     */
+    public static JSONObject toJSONObject(String string) throws JSONException {
+        JSONObject o = new JSONObject();
+        XMLTokener x = new XMLTokener(string);
+        while (x.more()) {
+            x.skipPast("<");
+            parse(x, o, null);
+        }
+        return o;
+    }
+
+
+    /**
+     * Convert a JSONObject into a well-formed, element-normal XML string.
+     * @param o A JSONObject.
+     * @return  A string.
+     * @throws  JSONException
+     */
+    public static String toString(Object o) throws JSONException {
+        return toString(o, null);
+    }
+
+
+    /**
+     * Convert a JSONObject into a well-formed, element-normal XML string.
+     * @param o A JSONObject.
+     * @param tagName The optional name of the enclosing tag.
+     * @return A string.
+     * @throws JSONException
+     */
+    public static String toString(Object o, String tagName)
+            throws JSONException {
+        StringBuffer b = new StringBuffer();
+        int          i;
+        JSONArray    ja;
+        JSONObject   jo;
+        String       k;
+        Iterator     keys;
+        int          len;
+        String       s;
+        Object       v;
+        if (o instanceof JSONObject) {
+
+// Emit <tagName>
+
+            if (tagName != null) {
+                b.append('<');
+                b.append(tagName);
+                b.append('>');
+            }
+
+// Loop thru the keys.
+
+            jo = (JSONObject)o;
+            keys = jo.keys();
+            while (keys.hasNext()) {
+                k = keys.next().toString();
+                v = jo.get(k);
+                if (v instanceof String) {
+                    s = (String)v;
+                } else {
+                    s = null;
+                }
+
+// Emit content in body
+
+                if (k.equals("content")) {
+                    if (v instanceof JSONArray) {
+                        ja = (JSONArray)v;
+                        len = ja.length();
+                        for (i = 0; i < len; i += 1) {
+                            if (i > 0) {
+                                b.append('\n');
+                            }
+                            b.append(escape(ja.get(i).toString()));
+                        }
+                    } else {
+                        b.append(escape(v.toString()));
+                    }
+
+// Emit an array of similar keys
+
+                } else if (v instanceof JSONArray) {
+                    ja = (JSONArray)v;
+                    len = ja.length();
+                    for (i = 0; i < len; i += 1) {
+                        b.append(toString(ja.get(i), k));
+                    }
+                } else if (v.equals("")) {
+                    b.append('<');
+                    b.append(k);
+                    b.append("/>");
+
+// Emit a new tag <k>
+
+                } else {
+                    b.append(toString(v, k));
+                }
+            }
+            if (tagName != null) {
+
+// Emit the </tagname> close tag
+
+                b.append("</");
+                b.append(tagName);
+                b.append('>');
+            }
+            return b.toString();
+
+// XML does not have good support for arrays. If an array appears in a place
+// where XML is lacking, synthesize an <array> element.
+
+        } else if (o instanceof JSONArray) {
+            ja = (JSONArray)o;
+            len = ja.length();
+            for (i = 0; i < len; ++i) {
+                b.append(toString(
+                    ja.opt(i), (tagName == null) ? "array" : tagName));
+            }
+            return b.toString();
+        } else {
+            s = (o == null) ? "null" : escape(o.toString());
+            return (tagName == null) ? "\"" + s + "\"" :
+                (s.length() == 0) ? "<" + tagName + "/>" :
+                "<" + tagName + ">" + s + "</" + tagName + ">";
+        }
+    }
+}
\ No newline at end of file

Added: incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XMLTokener.java
URL: http://svn.apache.org/viewvc/incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XMLTokener.java?rev=410216&view=auto
==============================================================================
--- incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XMLTokener.java (added)
+++ incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/json/XMLTokener.java Tue May 30 01:31:30 2006
@@ -0,0 +1,308 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.synapse.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+The Software shall be used for Good, not Evil.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+*/
+
+/**
+ * The XMLTokener extends the JSONTokener to provide additional methods
+ * for the parsing of XML texts.
+ * @author JSON.org
+ * @version 2
+ */
+public class XMLTokener extends JSONTokener {
+
+
+   /** The table of entity values. It initially contains Character values for
+    * amp, apos, gt, lt, quot.
+    */
+   public static final java.util.HashMap entity;
+
+   static {
+       entity = new java.util.HashMap(8);
+       entity.put("amp",  XML.AMP);
+       entity.put("apos", XML.APOS);
+       entity.put("gt",   XML.GT);
+       entity.put("lt",   XML.LT);
+       entity.put("quot", XML.QUOT);
+   }
+
+    /**
+     * Construct an XMLTokener from a string.
+     * @param s A source string.
+     */
+    public XMLTokener(String s) {
+        super(s);
+    }
+
+    /**
+     * Get the text in the CDATA block.
+     * @return The string up to the <code>]]&gt;</code>.
+     * @throws JSONException If the <code>]]&gt;</code> is not found.
+     */
+    public String nextCDATA() throws JSONException {
+        char         c;
+        int          i;
+        StringBuffer sb = new StringBuffer();
+        for (;;) {
+            c = next();
+            if (c == 0) {
+                throw syntaxError("Unclosed CDATA.");
+            }
+            sb.append(c);
+            i = sb.length() - 3;
+            if (i >= 0 && sb.charAt(i) == ']' &&
+                          sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
+                sb.setLength(i);
+                return sb.toString();
+            }
+        }
+    }
+
+
+    /**
+     * Get the next XML outer token, trimming whitespace. There are two kinds
+     * of tokens: the '<' character which begins a markup tag, and the content
+     * text between markup tags.
+     *
+     * @return  A string, or a '<' Character, or null if there is no more
+     * source text.
+     * @throws JSONException
+     */
+    public Object nextContent() throws JSONException {
+        char         c;
+        StringBuffer sb;
+        do {
+            c = next();
+        } while (Character.isWhitespace(c));
+        if (c == 0) {
+            return null;
+        }
+        if (c == '<') {
+            return XML.LT;
+        }
+        sb = new StringBuffer();
+        for (;;) {
+            if (c == '<' || c == 0) {
+                back();
+                return sb.toString().trim();
+            }
+            if (c == '&') {
+                sb.append(nextEntity(c));
+            } else {
+                sb.append(c);
+            }
+            c = next();
+        }
+    }
+
+
+    /**
+     * Return the next entity. These entities are translated to Characters:
+     *     <code>&amp;  &apos;  &gt;  &lt;  &quot;</code>.
+     * @param a An ampersand character.
+     * @return  A Character or an entity String if the entity is not recognized.
+     * @throws JSONException If missing ';' in XML entity.
+     */
+    public Object nextEntity(char a) throws JSONException {
+        StringBuffer sb = new StringBuffer();
+        for (;;) {
+            char c = next();
+            if (Character.isLetterOrDigit(c) || c == '#') {
+                sb.append(Character.toLowerCase(c));
+            } else if (c == ';') {
+                break;
+            } else {
+                throw syntaxError("Missing ';' in XML entity: &" + sb);
+            }
+        }
+        String s = sb.toString();
+        Object e = entity.get(s);
+        return e != null ? e : a + s + ";";
+    }
+
+
+    /**
+     * Returns the next XML meta token. This is used for skipping over <!...>
+     * and <?...?> structures.
+     * @return Syntax characters (<code>< > / = ! ?</code>) are returned as
+     *  Character, and strings and names are returned as Boolean. We don't care
+     *  what the values actually are.
+     * @throws JSONException If a string is not properly closed or if the XML
+     *  is badly structured.
+     */
+    public Object nextMeta() throws JSONException {
+        char c;
+        char q;
+        do {
+            c = next();
+        } while (Character.isWhitespace(c));
+        switch (c) {
+        case 0:
+            throw syntaxError("Misshaped meta tag.");
+        case '<':
+            return XML.LT;
+        case '>':
+            return XML.GT;
+        case '/':
+            return XML.SLASH;
+        case '=':
+            return XML.EQ;
+        case '!':
+            return XML.BANG;
+        case '?':
+            return XML.QUEST;
+        case '"':
+        case '\'':
+            q = c;
+            for (;;) {
+                c = next();
+                if (c == 0) {
+                    throw syntaxError("Unterminated string.");
+                }
+                if (c == q) {
+                    return Boolean.TRUE;
+                }
+            }
+        default:
+            for (;;) {
+                c = next();
+                if (Character.isWhitespace(c)) {
+                    return Boolean.TRUE;
+                }
+                switch (c) {
+                case 0:
+                case '<':
+                case '>':
+                case '/':
+                case '=':
+                case '!':
+                case '?':
+                case '"':
+                case '\'':
+                    back();
+                    return Boolean.TRUE;
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Get the next XML Token. These tokens are found inside of angle
+     * brackets. It may be one of these characters: <code>/ > = ! ?</code> or it
+     * may be a string wrapped in single quotes or double quotes, or it may be a
+     * name.
+     * @return a String or a Character.
+     * @throws JSONException If the XML is not well formed.
+     */
+    public Object nextToken() throws JSONException {
+        char c;
+        char q;
+        StringBuffer sb;
+        do {
+            c = next();
+        } while (Character.isWhitespace(c));
+        switch (c) {
+        case 0:
+            throw syntaxError("Misshaped element.");
+        case '<':
+            throw syntaxError("Misplaced '<'.");
+        case '>':
+            return XML.GT;
+        case '/':
+            return XML.SLASH;
+        case '=':
+            return XML.EQ;
+        case '!':
+            return XML.BANG;
+        case '?':
+            return XML.QUEST;
+
+// Quoted string
+
+        case '"':
+        case '\'':
+            q = c;
+            sb = new StringBuffer();
+            for (;;) {
+                c = next();
+                if (c == 0) {
+                    throw syntaxError("Unterminated string.");
+                }
+                if (c == q) {
+                    return sb.toString();
+                }
+                if (c == '&') {
+                    sb.append(nextEntity(c));
+                } else {
+                    sb.append(c);
+                }
+            }
+        default:
+
+// Name
+
+            sb = new StringBuffer();
+            for (;;) {
+                sb.append(c);
+                c = next();
+                if (Character.isWhitespace(c)) {
+                    return sb.toString();
+                }
+                switch (c) {
+                case 0:
+                case '>':
+                case '/':
+                case '=':
+                case '!':
+                case '?':
+                case '[':
+                case ']':
+                    back();
+                    return sb.toString();
+                case '<':
+                case '"':
+                case '\'':
+                    throw syntaxError("Bad character in a name.");
+                }
+            }
+        }
+    }
+}

Added: incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/mediators/ext/json/JsonMediator.java
URL: http://svn.apache.org/viewvc/incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/mediators/ext/json/JsonMediator.java?rev=410216&view=auto
==============================================================================
--- incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/mediators/ext/json/JsonMediator.java (added)
+++ incubator/synapse/trunk/java/modules/extensions/src/org/apache/synapse/mediators/ext/json/JsonMediator.java Tue May 30 01:31:30 2006
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.synapse.mediators.ext.json;
+
+import org.apache.synapse.api.Mediator;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.SynapseException;
+import org.apache.synapse.json.XML;
+import org.apache.synapse.json.JSONException;
+import org.apache.synapse.json.JSONObject;
+import org.apache.synapse.json.SynapseJsonSender;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.axis2.description.TransportOutDescription;
+
+import javax.xml.namespace.QName;
+
+public class JsonMediator implements Mediator {
+
+    private static final Log log = LogFactory.getLog(JsonMediator.class);
+
+    private String direction;
+
+    private static final String JTX = "JTX";
+    private static final String XJT = "XTJ";
+
+    public boolean mediate(MessageContext synMsgCtx) {
+
+        if (direction.equalsIgnoreCase(JTX)) {
+            // Json_To_Xml
+
+        } else if (direction.equalsIgnoreCase(XJT)) {
+            // Xml_To_Json
+            org.apache.axis2.context.MessageContext mc =
+                    ((Axis2MessageContext) synMsgCtx).getAxis2MessageContext();
+            JSONObject xmlToJSonObj = null;
+            try {
+                xmlToJSonObj =
+                        XML.toJSONObject(synMsgCtx.getEnvelope().toString());
+            } catch (JSONException e) {
+                log.error(e);
+                handleException(
+                        "JSON Encounterd an Error. Please see the logs");
+            }
+
+            mc.setProperty("JSONObject", xmlToJSonObj);
+
+            TransportOutDescription outDescription =
+                    new TransportOutDescription(new QName("http"));
+            SynapseJsonSender jsonSender = new SynapseJsonSender();
+            outDescription.setSender(jsonSender);
+
+            mc.setTransportOut(outDescription);
+
+            /*
+            Underline SOAP engine should be notified if the MessageContext Contain
+            Pure XML with a String as body.
+            */
+            mc.setDoingREST(true);
+
+        } else {
+            handleException(
+                    "'direction' contain a signal other than JTX or XJT");
+        }
+
+
+        return true;  //To change body of implemented methods use File | Settings | File Templates.
+    }
+
+    public String getType() {
+        return JsonMediator.class.getName();
+    }
+
+    public String getDirection() {
+        return direction;
+    }
+
+    public void setDirection(String direction) {
+        this.direction = direction;
+    }
+
+    private void handleException(String msg) {
+        log.error(msg);
+        throw new SynapseException(msg);
+    }
+
+
+
+
+}

Modified: incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/TestUtils.java
URL: http://svn.apache.org/viewvc/incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/TestUtils.java?rev=410216&r1=410215&r2=410216&view=diff
==============================================================================
--- incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/TestUtils.java (original)
+++ incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/TestUtils.java Tue May 30 01:31:30 2006
@@ -19,6 +19,10 @@
 import org.apache.axiom.om.OMAbstractFactory;
 import org.apache.axiom.om.OMDocument;
 import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.synapse.core.axis2.Axis2SynapseEnvironment;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+import org.apache.synapse.core.SynapseEnvironment;
+import org.apache.synapse.config.SynapseConfiguration;
 
 import javax.xml.stream.XMLStreamReader;
 import javax.xml.stream.XMLInputFactory;
@@ -44,5 +48,29 @@
 
         synCtx.setEnvelope(envelope);
         return synCtx;
+    }
+
+    public static MessageContext createLightweightSynapseMessageContext(
+            String paylod) throws Exception {
+        org.apache.axis2.context.MessageContext mc =
+                new org.apache.axis2.context.MessageContext();
+        SynapseConfiguration config = new SynapseConfiguration();
+        SynapseEnvironment env = new Axis2SynapseEnvironment();
+        MessageContext synMc = new Axis2MessageContext(mc,config,env);
+        SOAPEnvelope envelope =
+                OMAbstractFactory.getSOAP11Factory().getDefaultEnvelope();
+        OMDocument omDoc =
+                OMAbstractFactory.getSOAP11Factory().createOMDocument();
+        omDoc.addChild(envelope);
+
+        XMLStreamReader parser = XMLInputFactory.newInstance().
+                createXMLStreamReader(new StringReader(paylod));
+        StAXOMBuilder builder = new StAXOMBuilder(parser);
+
+        // set a dummy static message
+        envelope.getBody().addChild(builder.getDocumentElement());
+
+        synMc.setEnvelope(envelope);
+        return synMc;
     }
 }

Added: incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/json/JsonMediatorTest.java
URL: http://svn.apache.org/viewvc/incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/json/JsonMediatorTest.java?rev=410216&view=auto
==============================================================================
--- incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/json/JsonMediatorTest.java (added)
+++ incubator/synapse/trunk/java/modules/extensions/test/org/apache/synapse/json/JsonMediatorTest.java Tue May 30 01:31:30 2006
@@ -0,0 +1,50 @@
+package org.apache.synapse.json;
+
+import junit.framework.TestCase;
+import org.apache.synapse.mediators.ext.json.JsonMediator;
+import org.apache.synapse.MessageContext;
+import org.apache.synapse.TestUtils;
+import org.apache.synapse.core.axis2.Axis2MessageContext;
+/*
+ * Copyright 2004,2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+public class JsonMediatorTest extends TestCase {
+    private static final String ENV =
+            "<m:someOtherElement xmlns:m=\"http://someother\">" +
+            "<m0:CheckPriceRequest xmlns:m0=\"http://www.apache-synapse.org/test\">\n" +
+            "<m0:Code>String</m0:Code>\n" +
+            "</m0:CheckPriceRequest>" +
+            "</m:someOtherElement>";
+
+    private static final String JSON_OBJ =
+            "{\"soapenv:Envelope\":{\"soapenv:Body\":{\"m:someOtherElement\":{\"m0:CheckPriceRequest\":{\"xmlns:m0\":\"http://www.apache-synapse.org/test\",\"m0:Code\":\"String\"},\"xmlns:m\":\"http://someother\"}},\"xmlns:soapenv\":\"http://schemas.xmlsoap.org/soap/envelope/\",\"soapenv:Header\":{}}}";
+
+    private JsonMediator jsonMediator = null;
+    public void testJsonMediator() throws Exception{
+        jsonMediator = new JsonMediator();
+        jsonMediator.setDirection("XTJ");
+
+        // invoke transformation, with static enveope
+        MessageContext synCtx = TestUtils.createLightweightSynapseMessageContext(ENV);
+        jsonMediator.mediate(synCtx);
+        org.apache.axis2.context.MessageContext mc =
+                    ((Axis2MessageContext) synCtx).getAxis2MessageContext();
+        assertNotNull(mc.getProperty("JSONObject"));
+        String json_obj =mc.getProperty("JSONObject").toString();
+        assertEquals(json_obj,JSON_OBJ);
+
+    }
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: synapse-dev-unsubscribe@ws.apache.org
For additional commands, e-mail: synapse-dev-help@ws.apache.org