diff --git a/.gradle/6.1.1/executionHistory/executionHistory.lock b/.gradle/6.1.1/executionHistory/executionHistory.lock new file mode 100644 index 0000000..728cd6e Binary files /dev/null and b/.gradle/6.1.1/executionHistory/executionHistory.lock differ diff --git a/.gradle/6.1.1/fileChanges/last-build.bin b/.gradle/6.1.1/fileChanges/last-build.bin new file mode 100644 index 0000000..f76dd23 Binary files /dev/null and b/.gradle/6.1.1/fileChanges/last-build.bin differ diff --git a/.gradle/6.1.1/fileHashes/fileHashes.lock b/.gradle/6.1.1/fileHashes/fileHashes.lock new file mode 100644 index 0000000..61d3990 Binary files /dev/null and b/.gradle/6.1.1/fileHashes/fileHashes.lock differ diff --git a/.gradle/6.1.1/gc.properties b/.gradle/6.1.1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/.gradle/buildOutputCleanup/buildOutputCleanup.lock b/.gradle/buildOutputCleanup/buildOutputCleanup.lock new file mode 100644 index 0000000..4ff1ba3 Binary files /dev/null and b/.gradle/buildOutputCleanup/buildOutputCleanup.lock differ diff --git a/.gradle/buildOutputCleanup/cache.properties b/.gradle/buildOutputCleanup/cache.properties new file mode 100644 index 0000000..0d469dc --- /dev/null +++ b/.gradle/buildOutputCleanup/cache.properties @@ -0,0 +1,2 @@ +#Sat Aug 08 09:51:19 EEST 2020 +gradle.version=6.1.1 diff --git a/.gradle/checksums/checksums.lock b/.gradle/checksums/checksums.lock new file mode 100644 index 0000000..a899602 Binary files /dev/null and b/.gradle/checksums/checksums.lock differ diff --git a/.gradle/vcs-1/gc.properties b/.gradle/vcs-1/gc.properties new file mode 100644 index 0000000..e69de29 diff --git a/File b/File new file mode 100644 index 0000000..df9ef52 Binary files /dev/null and b/File differ diff --git a/File1 b/File1 new file mode 100644 index 0000000..7640e42 Binary files /dev/null and b/File1 differ diff --git a/Test b/Test new file mode 100644 index 0000000..eb86576 Binary files /dev/null and b/Test differ diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..495c503 --- /dev/null +++ b/build.gradle @@ -0,0 +1 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..f6b961f Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..6ea8d4f --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Aug 08 09:51:16 EEST 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..cccdd3d --- /dev/null +++ b/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/java-ipfs-http-client.iml b/java-ipfs-http-client.iml new file mode 100644 index 0000000..e91ffab --- /dev/null +++ b/java-ipfs-http-client.iml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/local.properties b/local.properties new file mode 100644 index 0000000..393d27c --- /dev/null +++ b/local.properties @@ -0,0 +1,8 @@ +## This file must *NOT* be checked into Version Control Systems, +# as it contains information specific to your local configuration. +# +# Location of the SDK. This is only used by Gradle. +# For customization when using a Version Control System, please read the +# header note. +#Sat Aug 08 09:51:06 EEST 2020 +sdk.dir=/home/christodoulos/Android/Sdk diff --git a/pom.xml b/pom.xml index 73ecd7e..6b84cc3 100644 --- a/pom.xml +++ b/pom.xml @@ -62,7 +62,13 @@ ${version.hamcrest} test - + + junit + junit + 4.12 + compile + + diff --git a/src/File b/src/File new file mode 100644 index 0000000..e69de29 diff --git a/src/File1 b/src/File1 new file mode 100644 index 0000000..e69de29 diff --git a/src/main/java/First_Application.java b/src/main/java/First_Application.java new file mode 100644 index 0000000..fd5fa08 --- /dev/null +++ b/src/main/java/First_Application.java @@ -0,0 +1,105 @@ +import io.ipfs.api.IPFS; +import io.ipfs.api.JSONParser; +import io.ipfs.api.MyIPFSClass; +import io.ipfs.api.Sub; +import io.ipfs.multiaddr.MultiAddress; +import io.ipfs.multihash.Multihash; +import sun.security.krb5.internal.PAData; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.stream.Collectors; +import java.util.stream.Stream; + + +class ThreadReceiver extends Thread{ + String Topic,_ID,Path; + Map> Peer_Responsibilities; + Map> Dealers; + List Responsibilities; + IPFS ipfs; + MyIPFSClass AuxilaryIpfs = new MyIPFSClass(); + + public ThreadReceiver(List responsibilities,String path){ + Path = path; + ipfs = new IPFS(path); + Topic = "New_Peer"; + Responsibilities = responsibilities; + } + + public ThreadReceiver(String topic, String my_id, Map> dealers, String path){ + Path = path; + ipfs = new IPFS(path); + Topic = topic; + Dealers = dealers; + _ID = my_id; + } + + public void process(String decodedString) throws UnsupportedEncodingException { + if(Topic == _ID){ + Map> Responsibility = AuxilaryIpfs.Unmarshall_Peer_Responsibilities(decodedString); + for (Map.Entry> me : Responsibility.entrySet()) { + Dealers.put(me.getKey(),me.getValue()); + } + } + else if(Topic == "New_Peer"){ + + } + else{ + + } + + } + + public void run() { + byte[] decodedBytes; + String decodedString = null; + Stream> sub = null; + boolean ok = true; + BlockingQueue queue = new LinkedBlockingQueue(); + Sub SUB = new Sub(Topic,Path,queue); + SUB.start(); + while(true){ + + try { + JSONObject json = (JSONObject) parser. parse(queue.take()); + JSONParser.parse(queue.take()).data; + //String encoded = (String) results.get(0).get("data"); + //decodedBytes = Base64.getUrlDecoder().decode(encoded); + //decodedString = new String(decodedBytes); + //System.out.println(decodedString); + + } + catch (Exception e) { + e.printStackTrace(); + } + + + } + } +} + +public class First_Application { + String my_id; + + public static void main(String[] args) throws InterruptedException, IOException { + List Respons = new ArrayList(); + MyIPFSClass ipfsClass = new MyIPFSClass(); + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/5001"); + Map> Dealers = new HashMap>(); + Respons.add(1); + Respons.add(2); + Respons.add(3); + Respons.add(4); + + ThreadReceiver boot_thread = new ThreadReceiver(Respons,"/ip4/127.0.0.1/tcp/5001"); + boot_thread.start(); + while (true){ + + } + + } +} diff --git a/src/main/java/io/ipfs/api/IPFS.java b/src/main/java/io/ipfs/api/IPFS.java index 8c638e3..e4430f4 100755 --- a/src/main/java/io/ipfs/api/IPFS.java +++ b/src/main/java/io/ipfs/api/IPFS.java @@ -248,6 +248,8 @@ public Object gc() throws IOException { } } + + public class Pubsub { public Object ls() throws IOException { return retrieveAndParse("pubsub/ls"); @@ -272,12 +274,18 @@ public Object pub(String topic, String data) throws Exception { return retrieveAndParse("pubsub/pub?arg="+topic + "&arg=" + data); } - public Stream> sub(String topic) throws Exception { - return sub(topic, ForkJoinPool.commonPool()); + public Object pub(String topic, Double[] data) throws Exception { + return retrieveAndParse("pubsub/pub?arg="+topic + "&arg=" + data); + } + + + + public Stream> sub(String topic,BlockingQueue queue) throws Exception { + return sub(topic, ForkJoinPool.commonPool(),queue); } - public Stream> sub(String topic, ForkJoinPool threadSupplier) throws Exception { - return retrieveAndParseStream("pubsub/sub?arg=" + topic, threadSupplier).map(obj -> (Map)obj); + public Stream> sub(String topic, ForkJoinPool threadSupplier,BlockingQueue queue) throws Exception { + return retrieveAndParseStream("pubsub/sub?arg=" + topic, threadSupplier,queue).map(obj -> (Map)obj); } /** @@ -638,7 +646,7 @@ private Object retrieveAndParse(String path) throws IOException { return JSONParser.parse(new String(res)); } - private Stream retrieveAndParseStream(String path, ForkJoinPool executor) throws IOException { + private Stream retrieveAndParseStream(String path, ForkJoinPool executor,BlockingQueue queue) throws IOException { BlockingQueue> results = new LinkedBlockingQueue<>(); InputStream in = retrieveStream(path); executor.submit(() -> getObjectStream(in, @@ -651,13 +659,23 @@ private Stream retrieveAndParseStream(String path, ForkJoinPool executor results.add(fut); }) ); + return Stream.generate(() -> { try { + while(true) { + String s = new String(results.take().get()); + queue.add(s); + if (s == null) { + break; + } + System.out.println(s); + } return JSONParser.parse(new String(results.take().get())); } catch (Exception e) { throw new RuntimeException(e); } }); + } /** @@ -672,14 +690,17 @@ private void retrieveAndParseStream(String path, Consumer results, Consu private byte[] retrieve(String path) throws IOException { URL target = new URL(protocol, host, port, version + path); + return IPFS.get(target, timeout); } private static byte[] get(URL target, int timeout) throws IOException { - HttpURLConnection conn = configureConnection(target, "GET", timeout); + + HttpURLConnection conn = configureConnection(target, "POST", timeout); try { InputStream in = conn.getInputStream(); + ByteArrayOutputStream resp = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; @@ -701,7 +722,6 @@ private static byte[] get(URL target, int timeout) throws IOException { private void getObjectStream(InputStream in, Consumer processor, Consumer error) { byte LINE_FEED = (byte)10; - try { ByteArrayOutputStream resp = new ByteArrayOutputStream(); @@ -712,8 +732,11 @@ private void getObjectStream(InputStream in, Consumer processor, Consume if (buf[r - 1] == LINE_FEED) { processor.accept(resp.toByteArray()); resp.reset(); + //break; } } + resp.flush(); + } catch (IOException e) { error.accept(e); } @@ -744,7 +767,7 @@ private InputStream retrieveStream(String path) throws IOException { } private static InputStream getStream(URL target, int timeout) throws IOException { - HttpURLConnection conn = configureConnection(target, "GET", timeout); + HttpURLConnection conn = configureConnection(target, "POST", timeout); return conn.getInputStream(); } @@ -790,6 +813,7 @@ private static HttpURLConnection configureConnection(URL target, String method, conn.setRequestMethod(method); conn.setRequestProperty("Content-Type", "application/json"); conn.setReadTimeout(timeout); + return conn; } } diff --git a/src/main/java/io/ipfs/api/MyIPFSClass.java b/src/main/java/io/ipfs/api/MyIPFSClass.java new file mode 100644 index 0000000..f6a1dea --- /dev/null +++ b/src/main/java/io/ipfs/api/MyIPFSClass.java @@ -0,0 +1,182 @@ +package io.ipfs.api; + +import io.ipfs.multihash.Multihash; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.nio.ByteBuffer; +import java.util.*; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class MyIPFSClass { + public static IPFS ipfsObj; + + public MyIPFSClass() { + ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + } + + public static void add_file(String Filename) throws IOException { + //IPFS ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + NamedStreamable.FileWrapper file = new NamedStreamable.FileWrapper(new File(Filename)); + List node = ipfsObj.add(file); + System.out.println(node.get(0).name.get() + " Uploaded " + node.get(0).hash.toString()); + } + + public static void read_file(String hash) throws IOException { + //IPFS ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + Multihash rhash = Multihash.fromBase58(hash); + System.out.println(new String(ipfsObj.cat(rhash))); + + } + + public static void get_content() throws IOException { + //IPFS ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + Map mp = ipfsObj.pin.ls(IPFS.PinType.all); + for (Map.Entry hash : mp.entrySet()) { + System.out.println(hash.getKey() + " , " + hash.getKey() + " , " + hash.getValue()); + } + + } + + public static KeyInfo create_key(String name) throws IOException { + //IPFS ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + KeyInfo key = ipfsObj.key.gen(name, Optional.empty(), Optional.empty()); + return key; + + } + + + public static void publish_key(String name) throws IOException { + KeyInfo key; + //IPFS ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + key = create_key(name); + System.out.println(ipfsObj.name.publish(key.id, Optional.of(key.name))); + + } + + // After we took the publish from a node we UnMarshall the String which is encoded in + // ISO , with the form [BUFF_SIZE (INT), GRADIENT (DOUBLE),...,GRADIENT] + public static double[] UnMarshall_Gradients(String returnVal) throws IOException, ClassNotFoundException { + int i, arr_len; + double d; + byte[] bytes_array = Base64.getUrlDecoder().decode(returnVal); + + + ByteBuffer rbuff = ByteBuffer.wrap(bytes_array); + + + arr_len = rbuff.getInt(0); + double[] Gradients = new double[arr_len]; + for (i = 0; i < arr_len; i++) { + d = rbuff.getDouble(i * Double.BYTES + Integer.BYTES); + Gradients[i] = d; + } + return Gradients; + } + + + //We form the double array into a String in order to publish it with the form + public static String Marshall_Gradients(double[] arr) throws IOException { + int i; + + ByteBuffer buff = ByteBuffer.allocate(Double.BYTES * arr.length + Integer.BYTES); + buff.putInt(0,arr.length); + for (i = 0; i < arr.length; i++) { + buff.putDouble(i * Double.BYTES + Integer.BYTES, arr[i]); + } + byte[] barr = new byte[buff.remaining()]; + buff.get(barr); + + + return Base64.getUrlEncoder().encodeToString(barr); + //System.out.println(new String(buff.array(),"ISO-8859-1")); + //return new String(buff.array(), "ISO-8859-1"); + } + + public static String Marshall_Peer_Responsibilities(int[] Responsibilities,String myId){ + int i; + ByteBuffer buff = ByteBuffer.allocate(Integer.BYTES * (Responsibilities.length + 1)); + buff.putInt(0, Responsibilities.length); + for(i = 0; i < Responsibilities.length; i++){ + buff.putInt((i+1)*Integer.BYTES ,Responsibilities[i]); + } + + + byte[] barr = new byte[buff.remaining()]; + byte[] idBytes = myId.getBytes(); + buff.get(barr); + byte[] finalbarr = new byte[barr.length + myId.length()]; + for(i = 0; i < barr.length; i++){ + finalbarr[i] = barr[i]; + } + for (i= barr.length; i < finalbarr.length; i++){ + finalbarr[i] = idBytes[i- barr.length]; + } + + return Base64.getUrlEncoder().encodeToString(finalbarr); + } + + + + public static Map> Unmarshall_Peer_Responsibilities(String returnval) throws UnsupportedEncodingException { + int i, arr_len; + byte[] bytes_array = Base64.getUrlDecoder().decode(returnval); + List Responsibilities = new ArrayList(); + Map> rval = new HashMap>(); + ByteBuffer rbuff = ByteBuffer.wrap(bytes_array); + + arr_len = rbuff.getInt(0); + byte[] Id_array = new byte[bytes_array.length - (arr_len+1)*Integer.BYTES]; + for (i = 0; i < arr_len; i++) { + Responsibilities.add(rbuff.getInt((i+1)*Integer.BYTES)); + } + for(i = (arr_len+1)*Integer.BYTES; i < bytes_array.length; i++){ + Id_array[i-(arr_len+1)*Integer.BYTES] = bytes_array[i]; + } + String ID = returnval.substring((arr_len+1)*Integer.BYTES); + + rval.put(new String(Id_array),Responsibilities); + + return rval; + + } + + + + /* + // Here we wait for a publish from a specific topic to get gradients + public double[] recv(IPFS ipfs,String topic) throws Exception { + + byte[] decodedBytes; + String decodedString = null; + Stream> sub = ipfs.pubsub.sub(topic); + System.out.println("OK"); + List results = sub.limit(1).collect(Collectors.toList()); + String encoded = (String) results.get(0).get("data"); + System.out.println(results); + decodedBytes = Base64.getUrlDecoder().decode(encoded); + decodedString = new String(decodedBytes); + //System.out.println(Arrays.toString(UnMarshall_Gradients(decodedString))); + System.out.println("Received"); + + sub.close(); + + return UnMarshall_Gradients(decodedString); + } + + //In this function we publish the gradients + public static void publish_gradients(String topic, double[] gradients) throws Exception { + IPFS ipfs = new IPFS("/ip4/127.0.0.1/tcp/5001"); + String data = Marshall_Gradients(gradients); + System.out.println(data); + //System.out.println(data.toCharArray()); + Object pub = ipfs.pubsub.pub(topic,data); + + } + + */ +} diff --git a/src/main/java/io/ipfs/api/Sub.java b/src/main/java/io/ipfs/api/Sub.java new file mode 100644 index 0000000..f5de25e --- /dev/null +++ b/src/main/java/io/ipfs/api/Sub.java @@ -0,0 +1,30 @@ +package io.ipfs.api; + +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class Sub extends Thread { + String Topic; + String Path; + BlockingQueue Queue; + + public Sub(String topic, String path, BlockingQueue queue) { + Queue = queue; + Topic = topic; + Path = path; + } + + public void run() { + IPFS ipfs = new IPFS(Path); + try { + Stream> sub = ipfs.pubsub.sub(Topic, Queue); + sub.limit(1).collect(Collectors.toList()); + } catch (Exception e) { + e.printStackTrace(); + } + + } +} diff --git a/src/main/java/io/ipfs/api/cbor/CborConstants.java b/src/main/java/io/ipfs/api/cbor/CborConstants.java deleted file mode 100644 index 3494dde..0000000 --- a/src/main/java/io/ipfs/api/cbor/CborConstants.java +++ /dev/null @@ -1,90 +0,0 @@ -package io.ipfs.api.cbor; - -/* - * JACOB - CBOR implementation in Java. - * - * (C) Copyright - 2013 - J.W. Janssen - * - * Licensed under Apache License v2.0. - */ - -/** - * Constant values used by the CBOR format. - */ -public interface CborConstants { - /** Major type 0: unsigned integers. */ - int TYPE_UNSIGNED_INTEGER = 0x00; - /** Major type 1: negative integers. */ - int TYPE_NEGATIVE_INTEGER = 0x01; - /** Major type 2: byte string. */ - int TYPE_BYTE_STRING = 0x02; - /** Major type 3: text/UTF8 string. */ - int TYPE_TEXT_STRING = 0x03; - /** Major type 4: array of items. */ - int TYPE_ARRAY = 0x04; - /** Major type 5: map of pairs. */ - int TYPE_MAP = 0x05; - /** Major type 6: semantic tags. */ - int TYPE_TAG = 0x06; - /** Major type 7: floating point, simple data types. */ - int TYPE_FLOAT_SIMPLE = 0x07; - - /** Denotes a one-byte value (uint8). */ - int ONE_BYTE = 0x18; - /** Denotes a two-byte value (uint16). */ - int TWO_BYTES = 0x19; - /** Denotes a four-byte value (uint32). */ - int FOUR_BYTES = 0x1a; - /** Denotes a eight-byte value (uint64). */ - int EIGHT_BYTES = 0x1b; - - /** The CBOR-encoded boolean false value (encoded as "simple value": {@link #MT_SIMPLE}). */ - int FALSE = 0x14; - /** The CBOR-encoded boolean true value (encoded as "simple value": {@link #MT_SIMPLE}). */ - int TRUE = 0x15; - /** The CBOR-encoded null value (encoded as "simple value": {@link #MT_SIMPLE}). */ - int NULL = 0x16; - /** The CBOR-encoded "undefined" value (encoded as "simple value": {@link #MT_SIMPLE}). */ - int UNDEFINED = 0x17; - /** Denotes a half-precision float (two-byte IEEE 754, see {@link #MT_FLOAT}). */ - int HALF_PRECISION_FLOAT = 0x19; - /** Denotes a single-precision float (four-byte IEEE 754, see {@link #MT_FLOAT}). */ - int SINGLE_PRECISION_FLOAT = 0x1a; - /** Denotes a double-precision float (eight-byte IEEE 754, see {@link #MT_FLOAT}). */ - int DOUBLE_PRECISION_FLOAT = 0x1b; - /** The CBOR-encoded "break" stop code for unlimited arrays/maps. */ - int BREAK = 0x1f; - - /** Semantic tag value describing date/time values in the standard format (UTF8 string, RFC3339). */ - int TAG_STANDARD_DATE_TIME = 0; - /** Semantic tag value describing date/time values as Epoch timestamp (numeric, RFC3339). */ - int TAG_EPOCH_DATE_TIME = 1; - /** Semantic tag value describing a positive big integer value (byte string). */ - int TAG_POSITIVE_BIGINT = 2; - /** Semantic tag value describing a negative big integer value (byte string). */ - int TAG_NEGATIVE_BIGINT = 3; - /** Semantic tag value describing a decimal fraction value (two-element array, base 10). */ - int TAG_DECIMAL_FRACTION = 4; - /** Semantic tag value describing a big decimal value (two-element array, base 2). */ - int TAG_BIGDECIMAL = 5; - /** Semantic tag value describing an expected conversion to base64url encoding. */ - int TAG_EXPECTED_BASE64_URL_ENCODED = 21; - /** Semantic tag value describing an expected conversion to base64 encoding. */ - int TAG_EXPECTED_BASE64_ENCODED = 22; - /** Semantic tag value describing an expected conversion to base16 encoding. */ - int TAG_EXPECTED_BASE16_ENCODED = 23; - /** Semantic tag value describing an encoded CBOR data item (byte string). */ - int TAG_CBOR_ENCODED = 24; - /** Semantic tag value describing an URL (UTF8 string). */ - int TAG_URI = 32; - /** Semantic tag value describing a base64url encoded string (UTF8 string). */ - int TAG_BASE64_URL_ENCODED = 33; - /** Semantic tag value describing a base64 encoded string (UTF8 string). */ - int TAG_BASE64_ENCODED = 34; - /** Semantic tag value describing a regular expression string (UTF8 string, PCRE). */ - int TAG_REGEXP = 35; - /** Semantic tag value describing a MIME message (UTF8 string, RFC2045). */ - int TAG_MIME_MESSAGE = 36; - /** Semantic tag value describing CBOR content. */ - int TAG_CBOR_MARKER = 55799; -} diff --git a/src/main/java/io/ipfs/api/cbor/CborDecoder.java b/src/main/java/io/ipfs/api/cbor/CborDecoder.java deleted file mode 100644 index 1229ccf..0000000 --- a/src/main/java/io/ipfs/api/cbor/CborDecoder.java +++ /dev/null @@ -1,496 +0,0 @@ -package io.ipfs.api.cbor; - -/* - * JACOB - CBOR implementation in Java. - * - * (C) Copyright - 2013 - J.W. Janssen - */ - -import java.io.*; - -import static io.ipfs.api.cbor.CborConstants.*; -import static io.ipfs.api.cbor.CborType.*; - -/** - * Provides a decoder capable of handling CBOR encoded data from a {@link InputStream}. - */ -public class CborDecoder { - protected final PushbackInputStream m_is; - - /** - * Creates a new {@link CborDecoder} instance. - * - * @param is the actual input stream to read the CBOR-encoded data from, cannot be null. - */ - public CborDecoder(InputStream is) { - if (is == null) { - throw new IllegalArgumentException("InputStream cannot be null!"); - } - m_is = (is instanceof PushbackInputStream) ? (PushbackInputStream) is : new PushbackInputStream(is); - } - - private static void fail(String msg, Object... args) throws IOException { - throw new IOException(msg + args); - } - - private static String lengthToString(int len) { - return (len < 0) ? "no payload" : (len == ONE_BYTE) ? "one byte" : (len == TWO_BYTES) ? "two bytes" - : (len == FOUR_BYTES) ? "four bytes" : (len == EIGHT_BYTES) ? "eight bytes" : "(unknown)"; - } - - /** - * Peeks in the input stream for the upcoming type. - * - * @return the upcoming type in the stream, or null in case of an end-of-stream. - * @throws IOException in case of I/O problems reading the CBOR-type from the underlying input stream. - */ - public CborType peekType() throws IOException { - int p = m_is.read(); - if (p < 0) { - // EOF, nothing to peek at... - return null; - } - m_is.unread(p); - return valueOf(p); - } - - /** - * Prolog to reading an array value in CBOR format. - * - * @return the number of elements in the array to read, or -1 in case of infinite-length arrays. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public long readArrayLength() throws IOException { - return readMajorTypeWithSize(TYPE_ARRAY); - } - - /** - * Reads a boolean value in CBOR format. - * - * @return the read boolean. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public boolean readBoolean() throws IOException { - int b = readMajorType(TYPE_FLOAT_SIMPLE); - if (b != FALSE && b != TRUE) { - fail("Unexpected boolean value: %d!", b); - } - return b == TRUE; - } - - /** - * Reads a "break"/stop value in CBOR format. - * - * @return always null. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public Object readBreak() throws IOException { - readMajorTypeExact(TYPE_FLOAT_SIMPLE, BREAK); - - return null; - } - - /** - * Reads a byte string value in CBOR format. - * - * @return the read byte string, never null. In case the encoded string has a length of 0, an empty string is returned. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public byte[] readByteString() throws IOException { - long len = readMajorTypeWithSize(TYPE_BYTE_STRING); - if (len < 0) { - fail("Infinite-length byte strings not supported!"); - } - if (len > Integer.MAX_VALUE) { - fail("String length too long!"); - } - return readFully(new byte[(int) len]); - } - - /** - * Prolog to reading a byte string value in CBOR format. - * - * @return the number of bytes in the string to read, or -1 in case of infinite-length strings. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public long readByteStringLength() throws IOException { - return readMajorTypeWithSize(TYPE_BYTE_STRING); - } - - /** - * Reads a double-precision float value in CBOR format. - * - * @return the read double value, values from {@link Float#MIN_VALUE} to {@link Float#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public double readDouble() throws IOException { - readMajorTypeExact(TYPE_FLOAT_SIMPLE, DOUBLE_PRECISION_FLOAT); - - return Double.longBitsToDouble(readUInt64()); - } - - /** - * Reads a single-precision float value in CBOR format. - * - * @return the read float value, values from {@link Float#MIN_VALUE} to {@link Float#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public float readFloat() throws IOException { - readMajorTypeExact(TYPE_FLOAT_SIMPLE, SINGLE_PRECISION_FLOAT); - - return Float.intBitsToFloat((int) readUInt32()); - } - - /** - * Reads a half-precision float value in CBOR format. - * - * @return the read half-precision float value, values from {@link Float#MIN_VALUE} to {@link Float#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public double readHalfPrecisionFloat() throws IOException { - readMajorTypeExact(TYPE_FLOAT_SIMPLE, HALF_PRECISION_FLOAT); - - int half = readUInt16(); - int exp = (half >> 10) & 0x1f; - int mant = half & 0x3ff; - - double val; - if (exp == 0) { - val = mant * Math.pow(2, -24); - } else if (exp != 31) { - val = (mant + 1024) * Math.pow(2, exp - 25); - } else if (mant != 0) { - val = Double.NaN; - } else { - val = Double.POSITIVE_INFINITY; - } - - return ((half & 0x8000) == 0) ? val : -val; - } - - /** - * Reads a signed or unsigned integer value in CBOR format. - * - * @return the read integer value, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public long readInt() throws IOException { - int ib = m_is.read(); - - // in case of negative integers, extends the sign to all bits; otherwise zero... - long ui = expectIntegerType(ib); - // in case of negative integers does a ones complement - return ui ^ readUInt(ib & 0x1f, false /* breakAllowed */); - } - - /** - * Reads a signed or unsigned 16-bit integer value in CBOR format. - * - * @read the small integer value, values from [-65536..65535] are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying output stream. - */ - public int readInt16() throws IOException { - int ib = m_is.read(); - - // in case of negative integers, extends the sign to all bits; otherwise zero... - long ui = expectIntegerType(ib); - // in case of negative integers does a ones complement - return (int) (ui ^ readUIntExact(TWO_BYTES, ib & 0x1f)); - } - - /** - * Reads a signed or unsigned 32-bit integer value in CBOR format. - * - * @read the small integer value, values in the range [-4294967296..4294967295] are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying output stream. - */ - public long readInt32() throws IOException { - int ib = m_is.read(); - - // in case of negative integers, extends the sign to all bits; otherwise zero... - long ui = expectIntegerType(ib); - // in case of negative integers does a ones complement - return ui ^ readUIntExact(FOUR_BYTES, ib & 0x1f); - } - - /** - * Reads a signed or unsigned 64-bit integer value in CBOR format. - * - * @read the small integer value, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying output stream. - */ - public long readInt64() throws IOException { - int ib = m_is.read(); - - // in case of negative integers, extends the sign to all bits; otherwise zero... - long ui = expectIntegerType(ib); - // in case of negative integers does a ones complement - return ui ^ readUIntExact(EIGHT_BYTES, ib & 0x1f); - } - - /** - * Reads a signed or unsigned 8-bit integer value in CBOR format. - * - * @read the small integer value, values in the range [-256..255] are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying output stream. - */ - public int readInt8() throws IOException { - int ib = m_is.read(); - - // in case of negative integers, extends the sign to all bits; otherwise zero... - long ui = expectIntegerType(ib); - // in case of negative integers does a ones complement - return (int) (ui ^ readUIntExact(ONE_BYTE, ib & 0x1f)); - } - - /** - * Prolog to reading a map of key-value pairs in CBOR format. - * - * @return the number of entries in the map, >= 0. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public long readMapLength() throws IOException { - return readMajorTypeWithSize(TYPE_MAP); - } - - /** - * Reads a null-value in CBOR format. - * - * @return always null. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public Object readNull() throws IOException { - readMajorTypeExact(TYPE_FLOAT_SIMPLE, NULL); - return null; - } - - /** - * Reads a single byte value in CBOR format. - * - * @return the read byte value. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public byte readSimpleValue() throws IOException { - readMajorTypeExact(TYPE_FLOAT_SIMPLE, ONE_BYTE); - return (byte) readUInt8(); - } - - /** - * Reads a signed or unsigned small (<= 23) integer value in CBOR format. - * - * @read the small integer value, values in the range [-24..23] are supported. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying output stream. - */ - public int readSmallInt() throws IOException { - int ib = m_is.read(); - - // in case of negative integers, extends the sign to all bits; otherwise zero... - long ui = expectIntegerType(ib); - // in case of negative integers does a ones complement - return (int) (ui ^ readUIntExact(-1, ib & 0x1f)); - } - - /** - * Reads a semantic tag value in CBOR format. - * - * @return the read tag value. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public long readTag() throws IOException { - return readUInt(readMajorType(TYPE_TAG), false /* breakAllowed */); - } - - /** - * Reads an UTF-8 encoded string value in CBOR format. - * - * @return the read UTF-8 encoded string, never null. In case the encoded string has a length of 0, an empty string is returned. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public String readTextString() throws IOException { - long len = readMajorTypeWithSize(TYPE_TEXT_STRING); - if (len < 0) { - fail("Infinite-length text strings not supported!"); - } - if (len > Integer.MAX_VALUE) { - fail("String length too long!"); - } - return new String(readFully(new byte[(int) len]), "UTF-8"); - } - - /** - * Prolog to reading an UTF-8 encoded string value in CBOR format. - * - * @return the length of the string to read, or -1 in case of infinite-length strings. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public long readTextStringLength() throws IOException { - return readMajorTypeWithSize(TYPE_TEXT_STRING); - } - - /** - * Reads an undefined value in CBOR format. - * - * @return always null. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - public Object readUndefined() throws IOException { - readMajorTypeExact(TYPE_FLOAT_SIMPLE, UNDEFINED); - return null; - } - - /** - * Reads the next major type from the underlying input stream, and verifies whether it matches the given expectation. - * - * @param majorType the expected major type, cannot be null (unchecked). - * @return either -1 if the major type was an signed integer, or 0 otherwise. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - protected long expectIntegerType(int ib) throws IOException { - int majorType = ((ib & 0xFF) >>> 5); - if ((majorType != TYPE_UNSIGNED_INTEGER) && (majorType != TYPE_NEGATIVE_INTEGER)) { - fail("Unexpected type: %s, expected type %s or %s!", getName(majorType), getName(TYPE_UNSIGNED_INTEGER), - getName(TYPE_NEGATIVE_INTEGER)); - } - return -majorType; - } - - /** - * Reads the next major type from the underlying input stream, and verifies whether it matches the given expectation. - * - * @param majorType the expected major type, cannot be null (unchecked). - * @return the read subtype, or payload, of the read major type. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - protected int readMajorType(int majorType) throws IOException { - int ib = m_is.read(); - if (majorType != ((ib >>> 5) & 0x07)) { - fail("Unexpected type: %s, expected: %s!", getName(ib), getName(majorType)); - } - return ib & 0x1F; - } - - /** - * Reads the next major type from the underlying input stream, and verifies whether it matches the given expectations. - * - * @param majorType the expected major type, cannot be null (unchecked); - * @param subtype the expected subtype. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - protected void readMajorTypeExact(int majorType, int subtype) throws IOException { - int st = readMajorType(majorType); - if ((st ^ subtype) != 0) { - fail("Unexpected subtype: %d, expected: %d!", st, subtype); - } - } - - /** - * Reads the next major type from the underlying input stream, verifies whether it matches the given expectation, and decodes the payload into a size. - * - * @param majorType the expected major type, cannot be null (unchecked). - * @return the number of succeeding bytes, >= 0, or -1 if an infinite-length type is read. - * @throws IOException in case of I/O problems reading the CBOR-encoded value from the underlying input stream. - */ - protected long readMajorTypeWithSize(int majorType) throws IOException { - return readUInt(readMajorType(majorType), true /* breakAllowed */); - } - - /** - * Reads an unsigned integer with a given length-indicator. - * - * @param length the length indicator to use; - * @return the read unsigned integer, as long value. - * @throws IOException in case of I/O problems reading the unsigned integer from the underlying input stream. - */ - protected long readUInt(int length, boolean breakAllowed) throws IOException { - long result = -1; - if (length < ONE_BYTE) { - result = length; - } else if (length == ONE_BYTE) { - result = readUInt8(); - } else if (length == TWO_BYTES) { - result = readUInt16(); - } else if (length == FOUR_BYTES) { - result = readUInt32(); - } else if (length == EIGHT_BYTES) { - result = readUInt64(); - } else if (breakAllowed && length == BREAK) { - return -1; - } - if (result < 0) { - fail("Not well-formed CBOR integer found, invalid length: %d!", result); - } - return result; - } - - /** - * Reads an unsigned 16-bit integer value - * - * @return value the read value, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected int readUInt16() throws IOException { - byte[] buf = readFully(new byte[2]); - return (buf[0] & 0xFF) << 8 | (buf[1] & 0xFF); - } - - /** - * Reads an unsigned 32-bit integer value - * - * @return value the read value, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected long readUInt32() throws IOException { - byte[] buf = readFully(new byte[4]); - return ((buf[0] & 0xFF) << 24 | (buf[1] & 0xFF) << 16 | (buf[2] & 0xFF) << 8 | (buf[3] & 0xFF)) & 0xffffffffL; - } - - /** - * Reads an unsigned 64-bit integer value - * - * @return value the read value, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected long readUInt64() throws IOException { - byte[] buf = readFully(new byte[8]); - return (buf[0] & 0xFFL) << 56 | (buf[1] & 0xFFL) << 48 | (buf[2] & 0xFFL) << 40 | (buf[3] & 0xFFL) << 32 | // - (buf[4] & 0xFFL) << 24 | (buf[5] & 0xFFL) << 16 | (buf[6] & 0xFFL) << 8 | (buf[7] & 0xFFL); - } - - /** - * Reads an unsigned 8-bit integer value - * - * @return value the read value, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected int readUInt8() throws IOException { - return m_is.read() & 0xff; - } - - /** - * Reads an unsigned integer with a given length-indicator. - * - * @param length the length indicator to use; - * @return the read unsigned integer, as long value. - * @throws IOException in case of I/O problems reading the unsigned integer from the underlying input stream. - */ - protected long readUIntExact(int expectedLength, int length) throws IOException { - if (((expectedLength == -1) && (length >= ONE_BYTE)) || ((expectedLength >= 0) && (length != expectedLength))) { - fail("Unexpected payload/length! Expected %s, but got %s.", lengthToString(expectedLength), - lengthToString(length)); - } - return readUInt(length, false /* breakAllowed */); - } - - private byte[] readFully(byte[] buf) throws IOException { - int len = buf.length; - int n = 0, off = 0; - while (n < len) { - int count = m_is.read(buf, off + n, len - n); - if (count < 0) { - throw new EOFException(); - } - n += count; - } - return buf; - } -} \ No newline at end of file diff --git a/src/main/java/io/ipfs/api/cbor/CborEncoder.java b/src/main/java/io/ipfs/api/cbor/CborEncoder.java deleted file mode 100644 index fd57b21..0000000 --- a/src/main/java/io/ipfs/api/cbor/CborEncoder.java +++ /dev/null @@ -1,488 +0,0 @@ -package io.ipfs.api.cbor; - -/* - * JACOB - CBOR implementation in Java. - * - * (C) Copyright - 2013 - J.W. Janssen - * - * Licensed under Apache License v2.0. - */ - -import java.io.*; - -import static io.ipfs.api.cbor.CborConstants.*; - -/** - * Provides an encoder capable of encoding data into CBOR format to a given {@link OutputStream}. - */ -public class CborEncoder { - private static final int NEG_INT_MASK = TYPE_NEGATIVE_INTEGER << 5; - - private final OutputStream m_os; - - /** - * Creates a new {@link CborEncoder} instance. - * - * @param os the actual output stream to write the CBOR-encoded data to, cannot be null. - */ - public CborEncoder(OutputStream os) { - if (os == null) { - throw new IllegalArgumentException("OutputStream cannot be null!"); - } - m_os = os; - } - - /** - * Interprets a given float-value as a half-precision float value and - * converts it to its raw integer form, as defined in IEEE 754. - *

- * Taken from: this Stack Overflow answer. - *

- * - * @param fval the value to convert. - * @return the raw integer representation of the given float value. - */ - static int halfPrecisionToRawIntBits(float fval) { - int fbits = Float.floatToIntBits(fval); - int sign = (fbits >>> 16) & 0x8000; - int val = (fbits & 0x7fffffff) + 0x1000; - - // might be or become NaN/Inf - if (val >= 0x47800000) { - if ((fbits & 0x7fffffff) >= 0x47800000) { // is or must become NaN/Inf - if (val < 0x7f800000) { - // was value but too large, make it +/-Inf - return sign | 0x7c00; - } - return sign | 0x7c00 | (fbits & 0x007fffff) >>> 13; // keep NaN (and Inf) bits - } - return sign | 0x7bff; // unrounded not quite Inf - } - if (val >= 0x38800000) { - // remains normalized value - return sign | val - 0x38000000 >>> 13; // exp - 127 + 15 - } - if (val < 0x33000000) { - // too small for subnormal - return sign; // becomes +/-0 - } - - val = (fbits & 0x7fffffff) >>> 23; - // add subnormal bit, round depending on cut off and div by 2^(1-(exp-127+15)) and >> 13 | exp=0 - return sign | ((fbits & 0x7fffff | 0x800000) + (0x800000 >>> val - 102) >>> 126 - val); - } - - /** - * Writes the start of an indefinite-length array. - *

- * After calling this method, one is expected to write the given number of array elements, which can be of any type. No length checks are performed.
- * After all array elements are written, one should write a single break value to end the array, see {@link #writeBreak()}. - *

- * - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeArrayStart() throws IOException { - writeSimpleType(TYPE_ARRAY, BREAK); - } - - /** - * Writes the start of a definite-length array. - *

- * After calling this method, one is expected to write the given number of array elements, which can be of any type. No length checks are performed. - *

- * - * @param length the number of array elements to write, should >= 0. - * @throws IllegalArgumentException in case the given length was negative; - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeArrayStart(int length) throws IOException { - if (length < 0) { - throw new IllegalArgumentException("Invalid array-length!"); - } - writeType(TYPE_ARRAY, length); - } - - /** - * Writes a boolean value in canonical CBOR format. - * - * @param value the boolean to write. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeBoolean(boolean value) throws IOException { - writeSimpleType(TYPE_FLOAT_SIMPLE, value ? TRUE : FALSE); - } - - /** - * Writes a "break" stop-value in canonical CBOR format. - * - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeBreak() throws IOException { - writeSimpleType(TYPE_FLOAT_SIMPLE, BREAK); - } - - /** - * Writes a byte string in canonical CBOR-format. - * - * @param bytes the byte string to write, can be null in which case a byte-string of length 0 is written. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeByteString(byte[] bytes) throws IOException { - writeString(TYPE_BYTE_STRING, bytes); - } - - /** - * Writes the start of an indefinite-length byte string. - *

- * After calling this method, one is expected to write the given number of string parts. No length checks are performed.
- * After all string parts are written, one should write a single break value to end the string, see {@link #writeBreak()}. - *

- * - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeByteStringStart() throws IOException { - writeSimpleType(TYPE_BYTE_STRING, BREAK); - } - - /** - * Writes a double-precision float value in canonical CBOR format. - * - * @param value the value to write, values from {@link Double#MIN_VALUE} to {@link Double#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeDouble(double value) throws IOException { - writeUInt64(TYPE_FLOAT_SIMPLE << 5, Double.doubleToRawLongBits(value)); - } - - /** - * Writes a single-precision float value in canonical CBOR format. - * - * @param value the value to write, values from {@link Float#MIN_VALUE} to {@link Float#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeFloat(float value) throws IOException { - writeUInt32(TYPE_FLOAT_SIMPLE << 5, Float.floatToRawIntBits(value)); - } - - /** - * Writes a half-precision float value in canonical CBOR format. - * - * @param value the value to write, values from {@link Float#MIN_VALUE} to {@link Float#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeHalfPrecisionFloat(float value) throws IOException { - writeUInt16(TYPE_FLOAT_SIMPLE << 5, halfPrecisionToRawIntBits(value)); - } - - /** - * Writes a signed or unsigned integer value in canonical CBOR format, that is, tries to encode it in a little bytes as possible.. - * - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeInt(long value) throws IOException { - // extends the sign over all bits... - long sign = value >> 63; - // in case value is negative, this bit should be set... - int mt = (int) (sign & NEG_INT_MASK); - // complement negative value... - value = (sign ^ value); - - writeUInt(mt, value); - } - - /** - * Writes a signed or unsigned 16-bit integer value in CBOR format. - * - * @param value the value to write, values from [-65536..65535] are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeInt16(int value) throws IOException { - // extends the sign over all bits... - int sign = value >> 31; - // in case value is negative, this bit should be set... - int mt = (int) (sign & NEG_INT_MASK); - // complement negative value... - writeUInt16(mt, (sign ^ value) & 0xffff); - } - - /** - * Writes a signed or unsigned 32-bit integer value in CBOR format. - * - * @param value the value to write, values in the range [-4294967296..4294967295] are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeInt32(long value) throws IOException { - // extends the sign over all bits... - long sign = value >> 63; - // in case value is negative, this bit should be set... - int mt = (int) (sign & NEG_INT_MASK); - // complement negative value... - writeUInt32(mt, (int) ((sign ^ value) & 0xffffffffL)); - } - - /** - * Writes a signed or unsigned 64-bit integer value in CBOR format. - * - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeInt64(long value) throws IOException { - // extends the sign over all bits... - long sign = value >> 63; - // in case value is negative, this bit should be set... - int mt = (int) (sign & NEG_INT_MASK); - // complement negative value... - writeUInt64(mt, sign ^ value); - } - - /** - * Writes a signed or unsigned 8-bit integer value in CBOR format. - * - * @param value the value to write, values in the range [-256..255] are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeInt8(int value) throws IOException { - // extends the sign over all bits... - int sign = value >> 31; - // in case value is negative, this bit should be set... - int mt = (int) (sign & NEG_INT_MASK); - // complement negative value... - writeUInt8(mt, (sign ^ value) & 0xff); - } - - /** - * Writes the start of an indefinite-length map. - *

- * After calling this method, one is expected to write any number of map entries, as separate key and value. Keys and values can both be of any type. No length checks are performed.
- * After all map entries are written, one should write a single break value to end the map, see {@link #writeBreak()}. - *

- * - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeMapStart() throws IOException { - writeSimpleType(TYPE_MAP, BREAK); - } - - /** - * Writes the start of a finite-length map. - *

- * After calling this method, one is expected to write any number of map entries, as separate key and value. Keys and values can both be of any type. No length checks are performed. - *

- * - * @param length the number of map entries to write, should >= 0. - * @throws IllegalArgumentException in case the given length was negative; - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeMapStart(int length) throws IOException { - if (length < 0) { - throw new IllegalArgumentException("Invalid length of map!"); - } - writeType(TYPE_MAP, length); - } - - /** - * Writes a null value in canonical CBOR format. - * - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeNull() throws IOException { - writeSimpleType(TYPE_FLOAT_SIMPLE, NULL); - } - - /** - * Writes a simple value, i.e., an "atom" or "constant" value in canonical CBOR format. - * - * @param simpleValue the (unsigned byte) value to write, values from 32 to 255 are supported (though not enforced). - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeSimpleValue(byte simpleValue) throws IOException { - // convert to unsigned value... - int value = (simpleValue & 0xff); - writeType(TYPE_FLOAT_SIMPLE, value); - } - - /** - * Writes a signed or unsigned small (<= 23) integer value in CBOR format. - * - * @param value the value to write, values in the range [-24..23] are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeSmallInt(int value) throws IOException { - // extends the sign over all bits... - int sign = value >> 31; - // in case value is negative, this bit should be set... - int mt = (int) (sign & NEG_INT_MASK); - // complement negative value... - value = Math.min(0x17, (sign ^ value)); - - m_os.write((int) (mt | value)); - } - - /** - * Writes a semantic tag in canonical CBOR format. - * - * @param tag the tag to write, should >= 0. - * @throws IllegalArgumentException in case the given tag was negative; - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeTag(long tag) throws IOException { - if (tag < 0) { - throw new IllegalArgumentException("Invalid tag specification, cannot be negative!"); - } - writeType(TYPE_TAG, tag); - } - - /** - * Writes an UTF-8 string in canonical CBOR-format. - *

- * Note that this method is platform specific, as the given string value will be encoded in a byte array - * using the platform encoding! This means that the encoding must be standardized and known. - *

- * - * @param value the UTF-8 string to write, can be null in which case an UTF-8 string of length 0 is written. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeTextString(String value) throws IOException { - writeString(TYPE_TEXT_STRING, value == null ? null : value.getBytes("UTF-8")); - } - - /** - * Writes the start of an indefinite-length UTF-8 string. - *

- * After calling this method, one is expected to write the given number of string parts. No length checks are performed.
- * After all string parts are written, one should write a single break value to end the string, see {@link #writeBreak()}. - *

- * - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeTextStringStart() throws IOException { - writeSimpleType(TYPE_TEXT_STRING, BREAK); - } - - /** - * Writes an "undefined" value in canonical CBOR format. - * - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - public void writeUndefined() throws IOException { - writeSimpleType(TYPE_FLOAT_SIMPLE, UNDEFINED); - } - - /** - * Encodes and writes the major type and value as a simple type. - * - * @param majorType the major type of the value to write, denotes what semantics the written value has; - * @param value the value to write, values from [0..31] are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeSimpleType(int majorType, int value) throws IOException { - m_os.write((majorType << 5) | (value & 0x1f)); - } - - /** - * Writes a byte string in canonical CBOR-format. - * - * @param majorType the major type of the string, should be either 0x40 or 0x60; - * @param bytes the byte string to write, can be null in which case a byte-string of length 0 is written. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeString(int majorType, byte[] bytes) throws IOException { - int len = (bytes == null) ? 0 : bytes.length; - writeType(majorType, len); - for (int i = 0; i < len; i++) { - m_os.write(bytes[i]); - } - } - - /** - * Encodes and writes the major type indicator with a given payload (length). - * - * @param majorType the major type of the value to write, denotes what semantics the written value has; - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeType(int majorType, long value) throws IOException { - writeUInt((majorType << 5), value); - } - - /** - * Encodes and writes an unsigned integer value, that is, tries to encode it in a little bytes as possible. - * - * @param mt the major type of the value to write, denotes what semantics the written value has; - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeUInt(int mt, long value) throws IOException { - if (value < 0x18L) { - m_os.write((int) (mt | value)); - } else if (value < 0x100L) { - writeUInt8(mt, (int) value); - } else if (value < 0x10000L) { - writeUInt16(mt, (int) value); - } else if (value < 0x100000000L) { - writeUInt32(mt, (int) value); - } else { - writeUInt64(mt, value); - } - } - - /** - * Encodes and writes an unsigned 16-bit integer value - * - * @param mt the major type of the value to write, denotes what semantics the written value has; - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeUInt16(int mt, int value) throws IOException { - m_os.write(mt | TWO_BYTES); - m_os.write(value >> 8); - m_os.write(value & 0xFF); - } - - /** - * Encodes and writes an unsigned 32-bit integer value - * - * @param mt the major type of the value to write, denotes what semantics the written value has; - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeUInt32(int mt, int value) throws IOException { - m_os.write(mt | FOUR_BYTES); - m_os.write(value >> 24); - m_os.write(value >> 16); - m_os.write(value >> 8); - m_os.write(value & 0xFF); - } - - /** - * Encodes and writes an unsigned 64-bit integer value - * - * @param mt the major type of the value to write, denotes what semantics the written value has; - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeUInt64(int mt, long value) throws IOException { - m_os.write(mt | EIGHT_BYTES); - m_os.write((int) (value >> 56)); - m_os.write((int) (value >> 48)); - m_os.write((int) (value >> 40)); - m_os.write((int) (value >> 32)); - m_os.write((int) (value >> 24)); - m_os.write((int) (value >> 16)); - m_os.write((int) (value >> 8)); - m_os.write((int) (value & 0xFF)); - } - - /** - * Encodes and writes an unsigned 8-bit integer value - * - * @param mt the major type of the value to write, denotes what semantics the written value has; - * @param value the value to write, values from {@link Long#MIN_VALUE} to {@link Long#MAX_VALUE} are supported. - * @throws IOException in case of I/O problems writing the CBOR-encoded value to the underlying output stream. - */ - protected void writeUInt8(int mt, int value) throws IOException { - m_os.write(mt | ONE_BYTE); - m_os.write(value & 0xFF); - } -} \ No newline at end of file diff --git a/src/main/java/io/ipfs/api/cbor/CborObject.java b/src/main/java/io/ipfs/api/cbor/CborObject.java deleted file mode 100644 index e2a34c9..0000000 --- a/src/main/java/io/ipfs/api/cbor/CborObject.java +++ /dev/null @@ -1,427 +0,0 @@ -package io.ipfs.api.cbor; - -import io.ipfs.cid.*; -import io.ipfs.multiaddr.*; -import io.ipfs.multihash.*; - -import java.io.*; -import java.util.*; -import java.util.stream.*; - -public interface CborObject { - - void serialize(CborEncoder encoder); - - default byte[] toByteArray() { - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - CborEncoder encoder = new CborEncoder(bout); - serialize(encoder); - return bout.toByteArray(); - } - - int LINK_TAG = 42; - - static CborObject fromByteArray(byte[] cbor) { - return deserialize(new CborDecoder(new ByteArrayInputStream(cbor))); - } - - static CborObject deserialize(CborDecoder decoder) { - try { - CborType type = decoder.peekType(); - switch (type.getMajorType()) { - case CborConstants.TYPE_TEXT_STRING: - return new CborString(decoder.readTextString()); - case CborConstants.TYPE_BYTE_STRING: - return new CborByteArray(decoder.readByteString()); - case CborConstants.TYPE_UNSIGNED_INTEGER: - return new CborLong(decoder.readInt()); - case CborConstants.TYPE_NEGATIVE_INTEGER: - return new CborLong(decoder.readInt()); - case CborConstants.TYPE_FLOAT_SIMPLE: - if (type.getAdditionalInfo() == CborConstants.NULL) { - decoder.readNull(); - return new CborNull(); - } - if (type.getAdditionalInfo() == CborConstants.TRUE) { - decoder.readBoolean(); - return new CborBoolean(true); - } - if (type.getAdditionalInfo() == CborConstants.FALSE) { - decoder.readBoolean(); - return new CborBoolean(false); - } - throw new IllegalStateException("Unimplemented simple type! " + type.getAdditionalInfo()); - case CborConstants.TYPE_MAP: { - long nValues = decoder.readMapLength(); - SortedMap result = new TreeMap<>(); - for (long i=0; i < nValues; i++) { - CborObject key = deserialize(decoder); - CborObject value = deserialize(decoder); - result.put(key, value); - } - return new CborMap(result); - } - case CborConstants.TYPE_ARRAY: - long nItems = decoder.readArrayLength(); - List res = new ArrayList<>((int) nItems); - for (long i=0; i < nItems; i++) - res.add(deserialize(decoder)); - return new CborList(res); - case CborConstants.TYPE_TAG: - long tag = decoder.readTag(); - if (tag == LINK_TAG) { - CborObject value = deserialize(decoder); - if (value instanceof CborString) - return new CborMerkleLink(Cid.decode(((CborString) value).value)); - if (value instanceof CborByteArray) { - byte[] bytes = ((CborByteArray) value).value; - if (bytes[0] == 0) // multibase for binary - return new CborMerkleLink(Cid.cast(Arrays.copyOfRange(bytes, 1, bytes.length))); - throw new IllegalStateException("Unknown Multibase decoding Merkle link: " + bytes[0]); - } - throw new IllegalStateException("Invalid type for merkle link: " + value); - } - throw new IllegalStateException("Unknown TAG in CBOR: " + type.getAdditionalInfo()); - default: - throw new IllegalStateException("Unimplemented cbor type: " + type); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - final class CborMap implements CborObject { - public final SortedMap values; - - public CborMap(SortedMap values) { - this.values = values; - } - - public static CborMap build(Map values) { - SortedMap transformed = values.entrySet() - .stream() - .collect(Collectors.toMap( - e -> new CborString(e.getKey()), - e -> e.getValue(), - (a, b) -> a, TreeMap::new)); - return new CborMap(transformed); - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeMapStart(values.size()); - for (Map.Entry entry : values.entrySet()) { - entry.getKey().serialize(encoder); - entry.getValue().serialize(encoder); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CborMap cborMap = (CborMap) o; - - return values != null ? values.equals(cborMap.values) : cborMap.values == null; - - } - - @Override - public int hashCode() { - return values != null ? values.hashCode() : 0; - } - } - - final class CborMerkleLink implements CborObject { - public final Multihash target; - - public CborMerkleLink(Multihash target) { - this.target = target; - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeTag(LINK_TAG); - byte[] cid = target.toBytes(); - byte[] withMultibaseHeader = new byte[cid.length + 1]; - System.arraycopy(cid, 0, withMultibaseHeader, 1, cid.length); - encoder.writeByteString(withMultibaseHeader); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CborMerkleLink that = (CborMerkleLink) o; - - return target != null ? target.equals(that.target) : that.target == null; - - } - - @Override - public int hashCode() { - return target != null ? target.hashCode() : 0; - } - } - - final class CborList implements CborObject { - public final List value; - - public CborList(List value) { - this.value = value; - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeArrayStart(value.size()); - for (CborObject object : value) { - object.serialize(encoder); - } - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CborList cborList = (CborList) o; - - return value != null ? value.equals(cborList.value) : cborList.value == null; - } - - @Override - public int hashCode() { - return value != null ? value.hashCode() : 0; - } - } - - final class CborBoolean implements CborObject { - public final boolean value; - - public CborBoolean(boolean value) { - this.value = value; - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeBoolean(value); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CborBoolean that = (CborBoolean) o; - - return value == that.value; - - } - - @Override - public int hashCode() { - return (value ? 1 : 0); - } - - @Override - public String toString() { - return "CborBoolean{" + - value + - '}'; - } - } - - final class CborByteArray implements CborObject, Comparable { - public final byte[] value; - - public CborByteArray(byte[] value) { - this.value = value; - } - - @Override - public int compareTo(CborByteArray other) { - return compare(value, other.value); - } - - public static int compare(byte[] a, byte[] b) - { - for (int i=0; i < Math.min(a.length, b.length); i++) - if (a[i] != b[i]) - return a[i] & 0xff - b[i] & 0xff; - return 0; - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeByteString(value); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CborByteArray that = (CborByteArray) o; - - return Arrays.equals(value, that.value); - - } - - @Override - public int hashCode() { - return Arrays.hashCode(value); - } - } - - final class CborString implements CborObject, Comparable { - - public final String value; - - public CborString(String value) { - this.value = value; - } - - @Override - public int compareTo(CborString cborString) { - int lenDiff = value.length() - cborString.value.length(); - if (lenDiff != 0) - return lenDiff; - return value.compareTo(cborString.value); - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeTextString(value); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CborString that = (CborString) o; - - return value.equals(that.value); - - } - - @Override - public int hashCode() { - return value.hashCode(); - } - - @Override - public String toString() { - return "CborString{\"" + - value + - "\"}"; - } - } - - final class CborLong implements CborObject, Comparable { - public final long value; - - public CborLong(long value) { - this.value = value; - } - - @Override - public int compareTo(CborLong other) { - return Long.compare(value, other.value); - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeInt(value); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - CborLong cborLong = (CborLong) o; - - return value == cborLong.value; - - } - - @Override - public int hashCode() { - return (int) (value ^ (value >>> 32)); - } - - @Override - public String toString() { - return "CborLong{" + - value + - '}'; - } - } - - final class CborNull implements CborObject, Comparable { - public CborNull() {} - - @Override - public int compareTo(CborNull cborNull) { - return 0; - } - - @Override - public void serialize(CborEncoder encoder) { - try { - encoder.writeNull(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - return true; - } - - @Override - public int hashCode() { - return 0; - } - - @Override - public String toString() { - return "CborNull{}"; - } - } -} diff --git a/src/main/java/io/ipfs/api/cbor/CborType.java b/src/main/java/io/ipfs/api/cbor/CborType.java deleted file mode 100644 index 68b325c..0000000 --- a/src/main/java/io/ipfs/api/cbor/CborType.java +++ /dev/null @@ -1,143 +0,0 @@ -package io.ipfs.api.cbor; - -/* - * JACOB - CBOR implementation in Java. - * - * (C) Copyright - 2013 - J.W. Janssen - * - * Licensed under Apache License v2.0. - */ - -import static io.ipfs.api.cbor.CborConstants.*; - -/** - * Represents the various major types in CBOR, along with their . - *

- * The major type is encoded in the upper three bits of each initial byte. The lower 5 bytes represent any additional information. - *

- */ -public class CborType { - private final int m_major; - private final int m_additional; - - private CborType(int major, int additional) { - m_major = major; - m_additional = additional; - } - - /** - * Returns a descriptive string for the given major type. - * - * @param mt the major type to return as string, values from [0..7] are supported. - * @return the name of the given major type, as String, never null. - * @throws IllegalArgumentException in case the given major type is not supported. - */ - public static String getName(int mt) { - switch (mt) { - case TYPE_ARRAY: - return "array"; - case TYPE_BYTE_STRING: - return "byte string"; - case TYPE_FLOAT_SIMPLE: - return "float/simple value"; - case TYPE_MAP: - return "map"; - case TYPE_NEGATIVE_INTEGER: - return "negative integer"; - case TYPE_TAG: - return "tag"; - case TYPE_TEXT_STRING: - return "text string"; - case TYPE_UNSIGNED_INTEGER: - return "unsigned integer"; - default: - throw new IllegalArgumentException("Invalid major type: " + mt); - } - } - - /** - * Decodes a given byte value to a {@link CborType} value. - * - * @param i the input byte (8-bit) to decode into a {@link CborType} instance. - * @return a {@link CborType} instance, never null. - */ - public static CborType valueOf(int i) { - return new CborType((i & 0xff) >>> 5, i & 0x1f); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null || getClass() != obj.getClass()) { - return false; - } - - CborType other = (CborType) obj; - return (m_major == other.m_major) && (m_additional == other.m_additional); - } - - /** - * @return the additional information of this type, as integer value from [0..31]. - */ - public int getAdditionalInfo() { - return m_additional; - } - - /** - * @return the major type, as integer value from [0..7]. - */ - public int getMajorType() { - return m_major; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + m_additional; - result = prime * result + m_major; - return result; - } - - /** - * @return true if this type allows for an infinite-length payload, - * false if only definite-length payloads are allowed. - */ - public boolean isBreakAllowed() { - return m_major == TYPE_ARRAY || m_major == TYPE_BYTE_STRING || m_major == TYPE_MAP - || m_major == TYPE_TEXT_STRING; - } - - /** - * Determines whether the major type of a given {@link CborType} equals the major type of this {@link CborType}. - * - * @param other the {@link CborType} to compare against, cannot be null. - * @return true if the given {@link CborType} is of the same major type as this {@link CborType}, false otherwise. - * @throws IllegalArgumentException in case the given argument was null. - */ - public boolean isEqualType(CborType other) { - if (other == null) { - throw new IllegalArgumentException("Parameter cannot be null!"); - } - return m_major == other.m_major; - } - - /** - * Determines whether the major type of a given byte value (representing an encoded {@link CborType}) equals the major type of this {@link CborType}. - * - * @param encoded the encoded CBOR type to compare. - * @return true if the given byte value represents the same major type as this {@link CborType}, false otherwise. - */ - public boolean isEqualType(int encoded) { - return m_major == ((encoded & 0xff) >>> 5); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append(getName(m_major)).append('(').append(m_additional).append(')'); - return sb.toString(); - } -} \ No newline at end of file diff --git a/src/main/java/io/ipfs/api/cbor/Cborable.java b/src/main/java/io/ipfs/api/cbor/Cborable.java deleted file mode 100644 index 2025e72..0000000 --- a/src/main/java/io/ipfs/api/cbor/Cborable.java +++ /dev/null @@ -1,10 +0,0 @@ -package io.ipfs.api.cbor; - -public interface Cborable { - - CborObject toCbor(); - - default byte[] serialize() { - return toCbor().toByteArray(); - } -} diff --git a/src/main/java/io/ipfs/api/ipfsTest.java b/src/main/java/io/ipfs/api/ipfsTest.java new file mode 100644 index 0000000..d6d4486 --- /dev/null +++ b/src/main/java/io/ipfs/api/ipfsTest.java @@ -0,0 +1,111 @@ +package io.ipfs.api; + +import io.ipfs.api.IPFS; +import io.ipfs.api.NamedStreamable; + +import java.io.*; +import java.lang.reflect.Array; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.stream.Stream; +import java.util.stream.Collectors; + + +import io.ipfs.api.cbor.*; +import io.ipfs.cid.*; +import io.ipfs.multihash.Multihash; +import io.ipfs.multiaddr.MultiAddress; + + +public class ipfsTest{ + public static class Node1 extends Thread{ + MyIPFSClass ipfs = new MyIPFSClass(); + + public void run(){ + double [] arr = {1,2,3,4}; + int i = 0; + List results; + IPFS ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + try { + while(true) { + i++; + //System.out.println(Arrays.toString(ipfs.recv(ipfsObj,"12"))); + System.out.println(i); + } + /* + while(true){ + Stream> sub = ipfsObj.pubsub.sub("12"); + System.out.println("SUB STREAM INIT COMPLETED"); + byte[] decodedBytes; + String decodedString = null; + + System.out.println("WAITTING TO COLLECT"); + + results = sub.limit(1).collect(Collectors.toList()); + System.out.println("COLLECTED!!!!"); + + String encoded = (String) results.get(0).get("data"); + decodedBytes = Base64.getDecoder().decode(encoded); + decodedString = new String(decodedBytes); + //System.out.println(Arrays.toString(ipfs.UnMarshall_Gradients(decodedString))); + sub.close(); + + } + + */ + + + } + catch (Exception e) { + System.out.println("error"); + e.printStackTrace(); + } + } + } + + + public static void main(String args[]) throws Exception { + + Node1 t1 = new Node1(); + + t1.start(); + + double [] arr = {4,3,2,1}; + int i; + MyIPFSClass ipfs = new MyIPFSClass(); + IPFS ipfsObj = new IPFS("/ip4/127.0.0.1/tcp/5001"); + + while(true){ + for(i = 0; i < 4; i++){ + arr[i]++; + } + try { + //System.out.println("SENDER : Going to sleep"); + Thread.sleep(500); + //System.out.println("SENDER : Woke"); + + } catch (InterruptedException e) { + e.printStackTrace(); + } + //System.out.println("SENDER : Publishing"); + try { + String data = ipfs.Marshall_Gradients(arr); + System.out.println(data); + //System.out.println(data.toCharArray()); + Object pub = ipfsObj.pubsub.pub("12",data); + + } catch (Exception e) { + System.out.println("Error"); + e.printStackTrace(); + } + + + } + + + + } +} diff --git a/src/main/java/testcode.java b/src/main/java/testcode.java new file mode 100644 index 0000000..db20efe --- /dev/null +++ b/src/main/java/testcode.java @@ -0,0 +1,79 @@ +//package io.ipfs.api; + +import io.ipfs.api.cbor.*; +import io.ipfs.cid.*; +import io.ipfs.multihash.Multihash; +import io.ipfs.multiaddr.MultiAddress; + +/* +class FileH{ + public static void FileH(){ + System.out.println("ok"); + } + public void test() throws IOException { + char[] data = new char[2]; + File fd = new File("File.txt"); + FileWriter writter = new FileWriter(fd,true); + FileReader reader = new FileReader(fd); + if(fd.createNewFile()){ + System.out.println("Created Succesfully"); + } + writter.write("Hello world"); + writter.flush(); + reader.skip(2); + reader.read(data,1,1); + System.out.println(data); + reader.read(data,1,1); + System.out.println(data); + + + } +} + +class dataset implements java.io.Serializable { + int num1; + int num2; + public void dataset(int num1,int num2){ + this.num1 = num1; + this.num2 = num2; + } + public int add(){ + return num1 + num2; + } +} +*/ +/* +class FileH{ + public static void main(String[] args) throws IOException { + String s = "1d"; + int a = 1; + int b = 2; + ByteBuffer buff = ByteBuffer.allocate(10); + buff.putInt(a); + buff.putInt(b); + buff.put(s.getBytes()); + System.out.println(buff.toString()); + FileOutputStream out = new FileOutputStream("Test"); + FileInputStream in = new FileInputStream("Test"); + byte [] writeData = buff.array(); + out.write(writeData); + out.close(); + byte[] instream = new byte[10]; + in.read(instream); + in.close(); + System.out.println(instream); + ByteBuffer nbuff = ByteBuffer.wrap(instream); + + int na,nb; + byte[] nstr = new byte[2]; + na = nbuff.getInt(); + nb = nbuff.getInt(); + nbuff.get(nstr); + System.out.println(na); + System.out.println(nb); + System.out.println(new String(nstr)); + + } + +} +*/ \ No newline at end of file diff --git a/src/test/java/io/ipfs/api/APITest.java b/src/test/java/io/ipfs/api/APITest.java index 0435dd2..cb24345 100755 --- a/src/test/java/io/ipfs/api/APITest.java +++ b/src/test/java/io/ipfs/api/APITest.java @@ -429,6 +429,7 @@ public void pubsubSynchronous() throws Exception { Assert.assertTrue("Fast synchronous pub-sub", duration < 1000); } + /* @Test public void pubsub() throws Exception { String topic = "topic" + System.nanoTime(); @@ -439,7 +440,7 @@ public void pubsub() throws Exception { List results = sub.limit(2).collect(Collectors.toList()); Assert.assertTrue( ! results.get(0).equals(Collections.emptyMap())); } - +*/ private static String toEscapedHex(byte[] in) throws IOException { StringBuilder res = new StringBuilder(); for (byte b : in) {