[mashup-dev] svn commit r1751 - trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file

svn at wso2.org svn at wso2.org
Wed Apr 4 07:44:58 PDT 2007


Author: thilina
Date: Wed Apr  4 07:44:48 2007
New Revision: 1751

Added:
   trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/JavaScriptTextFileObject.java
   trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/WSRequestCallBack.java
   trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/WSRequestHostImpl.java
Log:
Host objects for WSRequest & TextFile support

Added: trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/JavaScriptTextFileObject.java
==============================================================================
--- (empty file)
+++ trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/JavaScriptTextFileObject.java	Wed Apr  4 07:44:48 2007
@@ -0,0 +1,130 @@
+package org.wso2.mashup.hostobjects.file;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.LineNumberReader;
+import java.io.Reader;
+import java.io.Writer;
+import java.util.Date;
+
+import org.mozilla.javascript.Context;
+
+public class JavaScriptTextFileObject extends JavaScriptFileObject {
+    private BufferedWriter writer;
+
+    private BufferedReader reader;
+
+    public void jsConstructor(String filename) {
+        file = new File(filename);
+        if (file.isDirectory())
+            throw Context.reportRuntimeError("Given path is not a Text File.");
+        if (!file.exists()) {
+            try {
+                File parentFile = file.getParentFile();
+                if (parentFile != null) {
+                    parentFile.mkdirs();
+                }
+                file.createNewFile();
+            } catch (IOException e) {
+                Context.reportRuntimeError(e.toString());
+            }
+        }
+    }
+
+    public String getClassName() {
+        return "TextFile";
+    }
+
+    public void jsFunction_write(Object object) throws IOException {
+        jsFunction_getWriter();
+        writer.write(Context.toString(object));
+        writer.flush();
+    }
+
+    public String jsFunction_readLine() throws IOException {
+        jsFunction_getReader();
+        return ((LineNumberReader) reader).readLine();
+    }
+
+    public Writer jsFunction_getWriter() throws IOException {
+
+        if (reader != null)
+            throw Context
+                    .reportRuntimeError("Cannot write to the already reading file. Please close the reader by calling finishReading().");
+        if (writer == null) {
+            writer = new BufferedWriter(new FileWriter(file));
+        }
+        return writer;
+    }
+
+    public BufferedReader jsFunction_getReader() throws FileNotFoundException {
+        if (writer != null)
+            throw Context
+                    .reportRuntimeError("Cannot read from the already writing file. Please close the writer by calling finishWriting().");
+        if (reader == null) {
+            reader = new BufferedReader(new FileReader(file));
+        }
+        return reader;
+    }
+
+    public void jsFunction_finishReading() throws IOException {
+        if (reader != null) {
+            reader.close();
+            reader = null;
+        }
+    }
+
+    public void jsFunction_finishWriting() throws IOException {
+        if (writer != null) {
+            writer.close();
+            writer = null;
+        }
+    }
+
+    public String jsFunction_toString() throws IOException {
+        StringBuffer stringBuffer = new StringBuffer();
+        BufferedReader reader = new BufferedReader(new FileReader(file));
+        ;
+        String lineText;
+        while ((lineText = reader.readLine()) != null) {
+            stringBuffer.append(lineText);
+        }
+        return stringBuffer.toString();
+    }
+
+    public boolean jsFunction_move(String fileName) {
+        File movedFile = new File(fileName);
+        boolean result = file.renameTo(movedFile);
+        file = movedFile;
+        return result;
+    }
+
+    public void jsFunction_deleteFile() {
+        file.delete();
+    }
+
+    /**
+     * @return the length of the file in bytes
+     */
+    public long jsFunction_length() {
+        return file.length();
+    }
+
+    public String jsFunction_lastModified() {
+        Date date = new Date(file.lastModified());
+        return date.toString();
+    }
+
+    public String jsGet_path() {
+        return file.getPath();
+    }
+    
+    public String jsGet_name() {
+        return file.getName();
+    }
+}

Added: trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/WSRequestCallBack.java
==============================================================================
--- (empty file)
+++ trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/WSRequestCallBack.java	Wed Apr  4 07:44:48 2007
@@ -0,0 +1,33 @@
+package org.wso2.mashup.hostobjects.file;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axis2.client.async.AsyncResult;
+import org.apache.axis2.client.async.Callback;
+import org.mozilla.javascript.Context;
+
+public class WSRequestCallBack extends Callback {
+
+    WSRequestHostImpl wsrequest;
+    
+    public WSRequestCallBack(WSRequestHostImpl wsrequest) {
+        super();
+        this.wsrequest = wsrequest;
+    }
+
+    public void onComplete(AsyncResult result) {
+        OMElement response = result.getResponseEnvelope().getBody().getFirstElement();
+//        this.wsrequest.responseText = response.toString();
+        this.wsrequest.responseXML = response;
+        this.wsrequest.readyState = 4;
+        if (this.wsrequest.onReadyStateChangeFunction!=null)
+        {
+            Context cx =  Context.getCurrentContext();
+            this.wsrequest.onReadyStateChangeFunction.call(cx, wsrequest, wsrequest, new Object[0]);
+        }
+
+    }
+
+    public void onError(Exception e) {
+        Context.reportWarning(e.toString());
+    }
+}

Added: trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/WSRequestHostImpl.java
==============================================================================
--- (empty file)
+++ trunk/mashup/java/modules/hostobjects/src/org/wso2/mashup/hostobjects/file/WSRequestHostImpl.java	Wed Apr  4 07:44:48 2007
@@ -0,0 +1,269 @@
+package org.wso2.mashup.hostobjects.file;
+
+import java.io.StringReader;
+
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+
+import org.apache.axiom.om.OMElement;
+import org.apache.axiom.om.OMNode;
+import org.apache.axiom.om.impl.builder.StAXOMBuilder;
+import org.apache.axis2.AxisFault;
+import org.apache.axis2.Constants;
+import org.apache.axis2.addressing.EndpointReference;
+import org.apache.axis2.client.Options;
+import org.apache.axis2.client.ServiceClient;
+import org.apache.axis2.client.async.Callback;
+import org.apache.axis2.transport.http.HTTPConstants;
+import org.apache.axis2.transport.http.HttpTransportProperties;
+import org.apache.axis2.transport.http.HttpTransportProperties.Authenticator;
+import org.mozilla.javascript.Context;
+import org.mozilla.javascript.Function;
+import org.mozilla.javascript.Scriptable;
+import org.mozilla.javascript.ScriptableObject;
+import org.mozilla.javascript.xmlimpl.XML;
+
+/**
+ * TODO: DOM Support
+ * TODO: Options array
+ *
+ */
+public class WSRequestHostImpl extends ScriptableObject {
+    // public variable responseText
+    String responseText = null;
+    // public variable responseXML
+    OMNode responseXML = null;
+    // public variable readyState
+    int readyState = 0;
+    // Call back function
+    Function onReadyStateChangeFunction;
+
+    // other private variables
+    boolean async = true;
+    ServiceClient sender = null;
+    //Event optionArr = null;
+    String httpMethod = null;
+    String url = null;
+    String username = null;
+    String passwd = null;
+   /**
+    * Constructor for the use by Rhino 
+    */
+   public WSRequestHostImpl() {
+   }
+
+   /**
+    * Constructor the user will be using inside javaScript
+    */
+   public void jsConstructor()
+   {
+   }
+
+   /**
+    * Returns the name to be used for this JavaScript Object.
+    */
+   public String getClassName() {
+       return "WSRequest";
+   }
+
+   public static void jsFunction_open(Context cx, Scriptable thisObj,
+           Object[] arguments, Function funObj) throws AxisFault
+   {
+       WSRequestHostImpl wsRequest = checkInstance(thisObj);
+      
+       if (wsRequest.readyState > 0 && wsRequest.readyState < 4) { // readyState can either be 1, 2 or 4
+           throw new Error("INVALID_STATE_EXCEPTION");
+       } else if (wsRequest.readyState == 4) { // reset private variables if readyState equals 4
+           wsRequest.reset();
+       }
+      
+       switch (arguments.length)
+       {
+       case 0:throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+       case 1:throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+       case 5: 
+           if (arguments[4] instanceof String)
+               wsRequest.passwd = (String)arguments[4];
+           else throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+           if (arguments[3] instanceof String)
+               wsRequest.username = (String)arguments[3];
+           else throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+           break;
+       case 4:
+           if (arguments[2] instanceof String){
+               wsRequest.username = (String)arguments[2];
+               if (arguments[3] instanceof String)
+                   wsRequest.passwd = (String)arguments[3];
+               else throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+           }
+           else if (arguments[2] instanceof Boolean){
+               wsRequest.async = ((Boolean)arguments[2]).booleanValue();
+               if (arguments[3] instanceof String)
+                   wsRequest.username = (String)arguments[3];
+               else throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+           }
+           else throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+           break;
+       case 3:
+           if (arguments[2] instanceof Boolean)
+               wsRequest.async = ((Boolean)arguments[2]).booleanValue();
+           else if (arguments[2] instanceof String){
+               wsRequest.username = (String)arguments[2];
+           }
+           break;
+       }
+           if (arguments[0] instanceof String)
+               wsRequest.httpMethod = (String)arguments[0];
+//          TODO: Handle the options bag
+           else throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+           if (arguments[1] instanceof String)
+               wsRequest.url = (String)arguments[1];
+           else
+            throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+
+        wsRequest.open();
+        wsRequest.responseText = null;
+        wsRequest.responseXML = null;
+        wsRequest.readyState = 1;
+       //Calling onreadystatechange function
+       if (wsRequest.onReadyStateChangeFunction!=null)
+       {
+           wsRequest.onReadyStateChangeFunction.call(cx, wsRequest, wsRequest, new Object[0]);
+       }
+   }
+   
+   private void open() throws AxisFault
+   {
+       Options options = new Options();
+       sender = new ServiceClient();
+       sender.setOptions(options);
+
+       options.setProperty(HTTPConstants.CHUNKED, Boolean.FALSE);
+       
+       EndpointReference targetEPR = new EndpointReference(url);
+       options.setTo(targetEPR);
+
+       // handle basic authentication
+       if (username != null) { // set username if not null
+           Authenticator authenticator = new HttpTransportProperties.Authenticator();
+           authenticator.setUsername(username);
+           if (passwd != null) { // set password if present
+               authenticator.setPassword(passwd);
+           }
+           authenticator.setPreemptiveAuthentication(true);
+           options.setProperty(HTTPConstants.AUTHENTICATE,
+                   authenticator);
+       }
+
+       if (httpMethod != null) {
+           if (httpMethod.equalsIgnoreCase("get")) {
+               options.setProperty(Constants.Configuration.HTTP_METHOD,
+                       Constants.Configuration.HTTP_METHOD_GET);
+               options.setProperty(Constants.Configuration.ENABLE_REST, Constants.VALUE_TRUE);
+           } else if (httpMethod.equalsIgnoreCase("post")) {
+               options.setProperty(Constants.Configuration.HTTP_METHOD,
+                       Constants.Configuration.HTTP_METHOD_POST);
+           } else {
+               throw Context.reportRuntimeError("INVALID_SYNTAX_EXCEPTION");
+           }
+       }
+   }
+   
+   public void jsFunction_send(Object payload)
+   {
+       OMElement payloadElement= null;
+       if (this.readyState != 1) throw new Error("INVALID_STATE_EXCEPTION");
+       if (payload instanceof String) {
+           try {
+               XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(
+                       new StringReader((String)payload));
+               StAXOMBuilder builder = new StAXOMBuilder(parser);
+               payloadElement = builder.getDocumentElement();
+           } catch(Exception e) {
+               throw new Error("INVALID_INPUT_EXCEPTION");
+           }
+       } else if (payload instanceof XML) {
+           try {
+               payload = ((XML)payload).getAxiomFromXML();
+           } catch(Exception e) {
+               throw new Error("INVALID_INPUT_EXCEPTION");
+           }
+       }
+//       else if (typeof(payload) == "object") {
+//           // set DOOMRequired to true
+//           DocumentBuilderFactoryImpl.setDOOMRequired(true);
+//           try {
+//               payload = payload.getFirstChild();
+//           } catch(Exception e) {
+//               throw new Error("INVALID_INPUT_EXCEPTION");
+//           }
+//       } 
+//       else if (payload == undefined) {
+//           payload = null;
+//       } 
+
+       try {
+           if (async) { // asynchronous call to send()
+               Callback callback = new WSRequestCallBack(this);
+               sender.sendReceiveNonBlocking(payloadElement, callback);
+               this.readyState = 2;
+           } else { // synchronous call to send()
+               this.readyState = 2;
+               // TODO do we need to call onreadystatechange here too
+               this.responseXML = sender.sendReceive(payloadElement);
+               this.readyState = 4;
+           }
+           //Calling onreadystatechange function
+           if (this.onReadyStateChangeFunction!=null)
+           {
+               Context cx =  Context.getCurrentContext();
+               this.onReadyStateChangeFunction.call(cx, this, this, new Object[0]);
+           }
+       } catch(Exception e) {
+           throw Context.reportRuntimeError(e.toString());
+       }
+   }
+   
+   /* 
+    *  resets private variables
+    */
+    private void reset() {
+        async = true;
+        sender = null;
+  //      optionArr = null
+        httpMethod = null;
+        url = null;
+        username = null;
+        passwd = null;
+        this.readyState = 0;
+    }
+
+   private static WSRequestHostImpl checkInstance(Scriptable obj) {
+       if (obj == null || !(obj instanceof WSRequestHostImpl)) {
+           throw Context.reportRuntimeError("called on incompatible object");
+       }
+       return (WSRequestHostImpl) obj;
+   }
+   
+   public String jsGet_responseText()
+   {
+       if (responseText==null && responseXML!=null)
+       {
+           responseText = responseXML.toString();
+       }
+       return responseText;
+   }
+   
+   //TODO change to e4x XML
+   public OMNode jsGet_responseE4XXML()
+   {
+       return responseXML;
+   }
+   
+   //TODO change to Doom
+   public OMNode jsGet_responseXML()
+   {
+       return responseXML;
+   }
+}
+




More information about the Mashup-dev mailing list