Browse Source

new endpoint /send posts "body" parameter as body

Martin Kunz 5 years ago
parent
commit
d45cffb55f

+ 5 - 1
src/main/java/com/acdp/transceivr/LoadTools.java

@@ -4,6 +4,7 @@ import okhttp3.*;
 import okio.BufferedSink;
 import org.slf4j.LoggerFactory;
 
+import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 
@@ -143,6 +144,9 @@ public class LoadTools {
                 }
             }
         };
-        download(t, progressListener);
+        if(t.body!=null)
+            upload(t, new ByteArrayInputStream(t.body.getBytes()));
+        else
+            download(t, progressListener);
     }
 }

+ 10 - 16
src/main/java/com/acdp/transceivr/Transfer.java

@@ -4,13 +4,6 @@ import com.eclipsesource.json.JsonObject;
 import okhttp3.Call;
 
 public class Transfer {
-
-
-
-    public Transfer(int id) {
-        this.id = id;
-        startTS=System.currentTimeMillis();
-    }
     public Call call;
     public long bytesRead;
     public long contentLength;
@@ -23,13 +16,13 @@ public class Transfer {
     public int downloadCode;
     public String downloadError;
     public boolean uploadDone = false;
-    public boolean canceled=false;
+    public boolean canceled = false;
     public long startTS;
     public long currentTS;
     public String cpeeCallback;
     public String cpeeCallbackId;
     public String cpeeInstanceURL;
-    public boolean doCpeeCallback=false;
+    public boolean doCpeeCallback = false;
     public String cpeeCallbackResult;
     public int cpeeCallbackCode;
     public String cpeeCallbackMessage;
@@ -37,7 +30,12 @@ public class Transfer {
     public boolean finished;
     public long finishedAT;
     public String toMethod;
+    public String body;
     int id;
+    public Transfer(int id) {
+        this.id = id;
+        startTS = System.currentTimeMillis();
+    }
 
     public JsonObject toJSON() {
         JsonObject js = new JsonObject();
@@ -50,7 +48,7 @@ public class Transfer {
         js.add("uploadCode", uploadCode);
         js.add("uploadResponseBody", uploadResponseBody);
         js.add("uploadDone", uploadDone);
-        js.add("progress", contentLength>0?((100 * bytesRead) / contentLength):0);
+        js.add("progress", contentLength > 0 ? ((100 * bytesRead) / contentLength) : 0);
         js.add("downloadDone", downloadDone);
         js.add("downloadCode", downloadCode);
         js.add("downloadError", downloadError);
@@ -63,12 +61,8 @@ public class Transfer {
         js.add("toMethod", toMethod);
 
 
-
-
-
-
-        var diff=currentTS-startTS;
-        js.add("rate",  diff>0?(bytesRead/diff):0);
+        var diff = currentTS - startTS;
+        js.add("rate", diff > 0 ? (bytesRead / diff) : 0);
         return js;
     }
 }

+ 44 - 37
src/main/java/com/acdp/transceivr/WebServer.java

@@ -3,9 +3,9 @@ package com.acdp.transceivr;
 import com.eclipsesource.json.JsonArray;
 import info.faljse.SDNotify.SDNotify;
 import org.slf4j.LoggerFactory;
+import spark.Request;
+import spark.Response;
 
-import java.util.Iterator;
-import java.util.Map;
 import java.util.Timer;
 import java.util.TimerTask;
 import java.util.concurrent.ConcurrentHashMap;
@@ -15,11 +15,11 @@ import static spark.Spark.*;
 
 public class WebServer {
     private final static org.slf4j.Logger logger = LoggerFactory.getLogger(WebServer.class);
+    private final static int BS = 2014;
     private final Params params;
     private int nextID = 1;
     private ConcurrentHashMap<Integer, Transfer> uploads = new ConcurrentHashMap<>();
-    private Timer t=new Timer("cleanup",true);
-    private final static int BS=2014;
+    private Timer t = new Timer("cleanup", true);
 
     public WebServer(Params params) {
         this.params = params;
@@ -27,22 +27,21 @@ public class WebServer {
 
     public void start() {
         port(params.port);
-        if(!params.webroot.isEmpty())
+        if (!params.webroot.isEmpty())
             staticFileLocation(params.webroot);
         else
             staticFiles.location("/webroot");
         get("/zero", (req, res) -> {
             var os = res.raw().getOutputStream();
             var ba = new byte[BS];
-            var lengthParam=req.queryParams("length");
-            if(lengthParam!=null) {
-                res.header("Content-Length",lengthParam);
-                int length=Integer.parseInt(lengthParam);
-                for(;length>BS;length-=BS)
+            var lengthParam = req.queryParams("length");
+            if (lengthParam != null) {
+                res.header("Content-Length", lengthParam);
+                int length = Integer.parseInt(lengthParam);
+                for (; length > BS; length -= BS)
                     os.write(ba);
-                os.write(ba,0,length);
-            }
-            else {
+                os.write(ba, 0, length);
+            } else {
                 while (true)
                     os.write(ba);
             }
@@ -51,14 +50,14 @@ public class WebServer {
         post("/null", (req, res) -> {
             var is = req.raw().getInputStream();
             var ba = new byte[BS];
-            while (is.read(ba)!=-1);
+            while (is.read(ba) != -1) ;
             res.status(200);
             return "";
         });
         put("/null", (req, res) -> {
             var is = req.raw().getInputStream();
             var ba = new byte[BS];
-            while (is.read(ba)!=-1);
+            while (is.read(ba) != -1) ;
             res.status(200);
             return "";
         });
@@ -78,41 +77,49 @@ public class WebServer {
             return ja.toString();
         });
         post("/xfer", (req, res) -> {
-            try {
-                Transfer t = new Transfer(nextID++);
-                t.from = req.queryParams("from");
-                t.to = req.queryParams("to");
-                t.toMethod=req.queryParamOrDefault("toMethod","POST");
-                t.cpeeCallback = req.headers("CPEE-CALLBACK");
-                t.cpeeCallbackId = req.headers("CPEE-CALLBACK-ID");
-                t.cpeeInstanceURL = req.headers("CPEE-INSTANCE-URL");
-                if (Boolean.valueOf(req.queryParams("callback"))) {
-                    res.header("CPEE-CALLBACK", "true");
-                    t.doCpeeCallback = true;
-                }
-                LoadTools.startTransfer(t);
-                uploads.put(t.id, t);
-                res.status(200);
-                return "OK: " + t.id;
-            } catch (Exception e) {
-                return "FAILED: " + e.toString();
-            }
+            return sendBody(req, res, null);
+        });
+        post("/send", (req, res) -> {
+           return sendBody(req, res, req.queryParams("body"));
         });
         awaitInitialization();
         t.scheduleAtFixedRate(new TimerTask() {
             @Override
             public void run() {
-                for (var i = uploads.entrySet().iterator(); i.hasNext();) {
+                for (var i = uploads.entrySet().iterator(); i.hasNext(); ) {
                     var e = i.next();
-                    if(e.getValue().finished&&(e.getValue().finishedAT+30000<System.currentTimeMillis())){
+                    if (e.getValue().finished && (e.getValue().finishedAT + 30000 < System.currentTimeMillis())) {
                         i.remove();
                         logger.info("Removed finished transfer {}", e.getValue().id);
                     }
                 }
             }
-        },1000,1000);
+        }, 1000, 1000);
 
         SDNotify.sendNotify(); //notify: ready
         logger.info("Running");
     }
+
+    private String sendBody(Request req, Response res, String body) {
+        try {
+            Transfer t = new Transfer(nextID++);
+            t.body=body;
+            t.from = req.queryParams("from");
+            t.to = req.queryParams("to");
+            t.toMethod = req.queryParamOrDefault("toMethod", "POST");
+            t.cpeeCallback = req.headers("CPEE-CALLBACK");
+            t.cpeeCallbackId = req.headers("CPEE-CALLBACK-ID");
+            t.cpeeInstanceURL = req.headers("CPEE-INSTANCE-URL");
+            if (Boolean.valueOf(req.queryParams("callback"))) {
+                res.header("CPEE-CALLBACK", "true");
+                t.doCpeeCallback = true;
+            }
+            LoadTools.startTransfer(t);
+            uploads.put(t.id, t);
+            res.status(200);
+            return "OK: " + t.id;
+        } catch (Exception e) {
+            return "FAILED: " + e.toString();
+        }
+    }
 }

+ 12 - 4
src/main/resources/webroot/index.html

@@ -5,7 +5,6 @@
         width: 100%;
         background-color: #ddd;
     }
-
     #myBar {
         width: 1%;
         height: 30px;
@@ -20,8 +19,14 @@
 </head>
 <body>
 <div id="app">
-    <input v-model="from" placeholder="from" size="80"><br>
+    <input v-model="from" placeholder="from" size="80" v-if="type == 'xfer'">
+    <textarea v-model="body" placeholder="{[]}" v-if="type == 'send'"></textarea>
+    <br>
     <input v-model="to" placeholder="to" size="80"><br>
+    <select v-model="type">
+        <option value="xfer">xfer</option>
+        <option value="send">send</option>
+    </select>
     <select v-model="toMethod">
         <option value="POST">POST</option>
         <option value="PUT">PUT</option>
@@ -81,7 +86,8 @@ cpeeCallbackError: {{ item.cpeeCallbackError}}
             transfers: [],
             from: '',
             to: '',
-            toMethod: 'POST'
+            toMethod: 'POST',
+            type: 'xfer'
         },
         created: function () {
             setInterval(this.update, 330);
@@ -101,7 +107,9 @@ cpeeCallbackError: {{ item.cpeeCallbackError}}
                 data.append('from', this.from);
                 data.append('to', this.to);
                 data.append('toMethod', this.toMethod);
-                fetch('/xfer', {
+                data.append('body', this.body);
+                ep=this.$data.type;
+                fetch('/' + ep, {
                     method: "POST",
                     body: data
                 }).then(response => {