getExtraCharSequenceSetParameter(CharSequence key) throws IOException, SharkException {
- return this.getExtraData().getExtraCharSequenceSetParameter(key);
- }
-
- @Override
- public String getExtraString(CharSequence key) throws IOException, SharkException {
- return this.getExtraData().getExtraString(key);
- }
-
- @Override
- public void removeAll() throws IOException, SharkException {
- this.getExtraData().removeAll();
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPInternalStorage.java b/src/main/java/net/sharksystem/asap/engine/ASAPInternalStorage.java
deleted file mode 100644
index 307a68d..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPInternalStorage.java
+++ /dev/null
@@ -1,172 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.*;
-import net.sharksystem.asap.listenermanager.management.ASAPManagementStorage;
-
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Set;
-
-/**
- *
- * Break down of a communication channel in ad-hoc networks is normal and barely failure.
- * That chunk storage is meant to keep messages which are produced by an
- * app for later transmission.
- *
- * Messages which cannot be sent to their recipients can be stored in ASAP chunks.
- * Each chunk is addressed with an URI (comparable to URIs e.g. in Android
- * Content Provider)
- *
- * Applications can easily store their messages by calling add(URI, message).
- * That message is stored in a chunk addressed by the URI.
- *
- * Each chunk has a recipient list which can be changed anytime. The ASAPEngine
- * uses those information for sending such stored messages whenever a peer
- * establishes a connection.
- *
- * It is recommended to use ASAPEngineFS to set up that framework.
- * Create a ASAPEngine like this
- *
- *
- * AASPReader reader = ...;
- * ASAPStorage myStorage = ASAPEngineFS.getASAPEngine("EngineName", "ChunkStorageRootFolder", reader);
- *
- *
- * An ASAPReader must be implemented prior using that framework. Objects of
- * that class are called whenever another peer transmits messages to the
- * local peer. @see AASPReader
- *
- * Chunks are structured by eras. In most cases, application developers don't
- * have to care about era management at all. If so, take care. Eras are usually
- * changed by the ASAPEngine whenever a peer (re-) connects. In that case, the
- * current era is declared to be finished and an new era is opened.
- * Any new message is now tagged as message from that new era. The ASAPEngine
- * transmits all message to the peer which are stored after the final
- * encounter. If no encounter ever happened - all available messages are
- * transmitted.
- *
- * @see ASAPEngine
- *
- * @author thsc
- */
-public interface ASAPInternalStorage extends ASAPStorage {
- /**
- * Creates a channel with named recipients - we call it a closed channel in opposite
- * to an open channel.
- *
- * Peers must not forward messages from a closed to other peers than those in recipient list.
- *
- * @param uri
- * @param recipients
- * @throws IOException
- */
- void createChannel(CharSequence uri, Collection recipients) throws IOException, ASAPException;
-
- /**
- * Create channel (owner can differ from local peer owing this asap engine)
- * @param owner
- * @param uri
- * @param recipients
- * @throws IOException
- * @throws ASAPException
- */
- void createChannel(CharSequence owner, CharSequence uri, Collection recipients) throws IOException, ASAPException;
-
- /**
- * Create a channel with only two members - creator and recipient
- * @param urlTarget
- * @param recipient
- * @throws IOException
- */
- void createChannel(CharSequence urlTarget, CharSequence recipient) throws IOException, ASAPException;
-
- /**
- * Create open channel
- * @param urlTarget
- * @throws IOException
- * @throws ASAPException
- */
- void createChannel(CharSequence urlTarget) throws IOException, ASAPException;
-
- /**
- * Chunks are delivered when seeing other peers. This flag allows to decide whether delivered chunks
- * are to be deleted.
- * @param drop
- */
-// void setDropDeliveredChunks(boolean drop) throws IOException;
-
- /**
- * Chunks are delivered when seeing other peers. Default behaviour is to send only message which
- * are in local peers own storage. A peer can also have received messages in an incoming storage.
- * This flag allows to force even delivery of received messages from incoming storages. Basis of
- * multihop communication.
- *
- * @param drop
- */
-// void setSendReceivedChunks(boolean drop) throws IOException;
-
- /**
- /**
- * returns recipient list
- *
- * @param urlTarget chunk address
- * @throws IOException
- * @return
- */
- Set getRecipients(CharSequence urlTarget) throws IOException;
-
- void addRecipient(CharSequence urlTarget, CharSequence recipient) throws IOException;
- void removeRecipient(CharSequence urlTarget, CharSequence recipient) throws IOException;
-
- /**
- * Add a message to that chunk.
- * @param uri message topic
- * @param message Message to be kept for later transmission
- * @throws IOException
- */
- void add(CharSequence uri, CharSequence message) throws IOException;
-
- void attachASAPMessageAddListener(ASAPOnlineMessageSender asapOnlineMessageSender);
-
- void detachASAPMessageAddListener();
-
- void setASAPManagementStorage(ASAPManagementStorage asapManagementStorage);
-
- boolean isASAPManagementStorageSet();
-
- /**
- * Create a new era
- */
- public void newEra();
-
- /**
- * Default behaviour of ASAPEngine: Each peer / communication partner
- * gets its own chunk storage. That storage is filled during asap
- * synchronization. That storage can be retrieved with this command.
- *
- * @param sender
- * @return
- */
- ASAPChunkStorage getReceivedChunksStorage(CharSequence sender);
-
- ASAPMessages getChunkChain(int uriPosition) throws IOException, ASAPException;
-
- ASAPMessages getChunkChain(int uriPosition, int toEra) throws IOException, ASAPException;
-
- ASAPMessages getChunkChain(CharSequence uri, int toEra) throws IOException;
-
- ASAPMessages getChunkChain(CharSequence uri) throws IOException;
-
- /**
- * Refresh with external system - re-read files, or whatever.
- * @return refreshed object
- */
- ASAPInternalStorage refresh() throws IOException, ASAPException;
-
- /**
- * Get (and probably create a chunk - set era to this new era
- * @param uri
- * @param newEra
- */
- ASAPInternalChunk createNewChunk(String uri, int newEra) throws IOException;
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPMemento.java b/src/main/java/net/sharksystem/asap/engine/ASAPMemento.java
deleted file mode 100644
index 4cac349..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPMemento.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import java.io.IOException;
-
-/**
- * The memento for the engine.
- *
- * @author thsc
- */
-interface ASAPMemento {
- public void save(ASAPEngine engine) throws IOException;
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPMementoFS.java b/src/main/java/net/sharksystem/asap/engine/ASAPMementoFS.java
deleted file mode 100644
index 27208c1..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPMementoFS.java
+++ /dev/null
@@ -1,209 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.protocol.ASAP_1_0;
-import net.sharksystem.utils.Log;
-
-import java.io.*;
-import java.util.HashMap;
-
-/**
- * Engine memento implementation in filesystem.
- *
- * @author local
- */
-class ASAPMementoFS implements ASAPMemento {
- private final File rootDirectory;
- private String owner;
- private String format;
- private int era;
- private int oldestEra;
- private boolean contentChanged;
- private boolean dropDeliveredChunks;
- private boolean sendReceivedChunks;
- private HashMap lastSeen;
- public long lastMementoWritten;
-
- public ASAPMementoFS(File rootDirectory) {
- this.rootDirectory = rootDirectory;
- }
-
- @Override
- public void save(ASAPEngine engine) throws IOException {
- /*
- Log.writeLog(this, "\n" +
- ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>save memento<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n" +
- ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>save memento<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
- */
- String fName = this.getMementoFileName();
-
- File file = new File(fName);
- if(!file.exists()) {
- if(!file.createNewFile()) {
- throw new IOException("could not create file (problems with directory?): " + fName);
- }
- }
-
- DataOutputStream dos = new DataOutputStream(new FileOutputStream(fName));
-
- long now = System.currentTimeMillis();
-
- engine.lastMementoWritten = now;
- this.lastMementoWritten = engine.lastMementoWritten;
- dos.writeLong(now);
- dos.writeUTF(engine.owner);
- dos.writeUTF(engine.format);
- dos.writeInt(engine.era);
- dos.writeInt(engine.oldestEra);
- dos.writeBoolean(engine.contentChanged);
- this.contentChanged = engine.contentChanged;
- dos.writeBoolean(engine.dropDeliveredChunks);
- dos.writeBoolean(engine.routingAllowed);
-
- // write lastSeen hash map
- if(engine.lastSeen != null && !engine.lastSeen.isEmpty()) {
- for(String key : engine.lastSeen.keySet()) {
- Integer era = engine.lastSeen.get(key);
-
- // write peer and era
- dos.writeUTF(key);
- dos.writeInt(era);
- }
- }
-
- //Log.writeLog(this, "saved: " + this);
- }
-
- private void setDefaults(ASAPEngine engine) {
- // set defaults
- engine.owner = ASAPEngine.DEFAULT_OWNER;
- engine.format = ASAP_1_0.ANY_FORMAT.toString();
- engine.era = ASAPEngine.DEFAULT_INIT_ERA;
- engine.oldestEra = ASAPEngine.DEFAULT_INIT_ERA;
- engine.lastSeen = new HashMap<>();
- engine.dropDeliveredChunks = false;
- engine.routingAllowed = true;
- }
-
- public void read() throws IOException {
- String fName = this.getMementoFileName();
-
- File file = new File(fName);
- if(!file.exists()) {
- return;
- }
-
- DataInputStream dis = new DataInputStream(
- new FileInputStream(file));
-
- try {
- this.lastMementoWritten = dis.readLong();
- this.owner = dis.readUTF();
- this.format = dis.readUTF();
- this.era = dis.readInt();
- this.oldestEra = dis.readInt();
- this.contentChanged = dis.readBoolean();
- this.dropDeliveredChunks = dis.readBoolean();
- this.sendReceivedChunks = dis.readBoolean();
- }
- catch(EOFException e) {
- // ignore and work with set defaults
- return; // reached end of file - nothing to do here
- }
-
- // try to read lastSeen list
- boolean first = true;
- try {
- for(;;) { // escapes from that loop via ioexception
- String peer = dis.readUTF();
- // got one
- if(first) {
- // init empty list
- this.lastSeen = new HashMap<>();
- first = false;
- }
-
- Integer era = dis.readInt();
-
- // remember
- this.lastSeen.put(peer, era);
- }
- }
- catch(IOException ioe) {
- // ok no more data
- }
- dis.close();
- }
-
- public void restore(ASAPEngine engine) throws IOException {
- String fName = this.getMementoFileName();
-
- File file = new File(fName);
- if(!file.exists()) {
- this.setDefaults(engine);
- return;
- }
-
- DataInputStream dis = new DataInputStream(
- new FileInputStream(file));
-
- try {
- engine.lastMementoWritten = dis.readLong();
- this.lastMementoWritten = engine.lastMementoWritten;
- engine.owner = dis.readUTF();
- engine.format = dis.readUTF();
- engine.era = dis.readInt();
- engine.oldestEra = dis.readInt();
- engine.contentChanged = dis.readBoolean();
- this.contentChanged = engine.contentChanged;
- engine.dropDeliveredChunks = dis.readBoolean();
- engine.routingAllowed = dis.readBoolean();
- }
- catch(EOFException e) {
- // ignore and work with set defaults
- return; // reached end of file - nothing to do here
- }
-
- // try to read lastSeen list
- boolean first = true;
- try {
- for(;;) { // escapes from that loop via ioexception
- String peer = dis.readUTF();
- // got one
- if(first) {
- // init empty list
- engine.lastSeen = new HashMap<>();
- first = false;
- }
-
- Integer era = dis.readInt();
-
- // remember
- engine.lastSeen.put(peer, era);
- }
- }
- catch(IOException ioe) {
- // ok no more data
- }
- dis.close();
-
- //Log.writeLog(this, "restored: " + this);
- }
-
- private String getMementoFileName() {
- return this.rootDirectory + "/" + ASAPEngineFS.MEMENTO_FILENAME;
- }
-
- public String getFormat() {
- return this.format;
- }
-
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("changed == ");
- sb.append(this.contentChanged);
- sb.append(" | written == ");
- sb.append(this.lastMementoWritten);
-
- return sb.toString();
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPMessagesMerger.java b/src/main/java/net/sharksystem/asap/engine/ASAPMessagesMerger.java
deleted file mode 100644
index f37e0c3..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPMessagesMerger.java
+++ /dev/null
@@ -1,399 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.ASAPChunk;
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.ASAPMessageCompare;
-import net.sharksystem.asap.ASAPMessages;
-import net.sharksystem.asap.utils.PeerIDHelper;
-
-import javax.xml.transform.Source;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-public class ASAPMessagesMerger implements ASAPMessages {
- private final ASAPMessageCompare messageCompare;
- private CharSequence format;
- private CharSequence uri;
- private int size;
-
- private final ASAPMessages[] messageSources;
- private List newFirstPositionList = new ArrayList<>();
- private List oldFirstPositionList = new ArrayList<>();
-
- private class SourceIndex {
- public int wantedPosition; // overall position
- public int sourceIndex; // which had fitting message
- public int positionInSource; // position in source where to find message.
-
- public SourceIndex(int wantedPosition, int sourceIndex, int positionInSource) {
- this.wantedPosition = wantedPosition;
- this.sourceIndex = sourceIndex;
- this.positionInSource = positionInSource;
- }
- }
-
- ASAPMessagesMerger(List messageSources, ASAPMessageCompare messageCompare)
- throws ASAPException, IOException {
- if(messageSources == null || messageSources.isEmpty())
- throw new ASAPException("message source must not be null or empty");
-
- this.messageCompare = messageCompare;
- this.size = 0; // init;
-
- // check integrity and find empty sources
- this.format = null;
- this.uri = null;
- int notEmpty = 0;
- for(ASAPMessages source : messageSources) {
- CharSequence currentFormat = source.getFormat();
- if(this.format != null && !PeerIDHelper.sameFormat(currentFormat, this.format)) {
- throw new ASAPException("message source must not have different formats: " + this.format
- + " != " + currentFormat);
- }
- // else
- this.format = currentFormat;
-
- CharSequence currentUri = source.getURI();
- if(this.uri != null && !PeerIDHelper.sameFormat(currentUri, this.uri)) {
- throw new ASAPException("message source must not have different uris: " + this.uri
- + " != " + currentUri);
- }
-
- // else
- this.uri = currentUri;
- this.size += source.size();
-
- if(source.size() > 0) notEmpty++;
- }
-
- // remember no empty sources
- this.messageSources = new ASAPMessages[notEmpty];
- int i = 0;
- for(ASAPMessages source : messageSources) {
- if(source.size() > 0) this.messageSources[i++] = source;
- }
-
- if(this.messageCompare == null) {
- // source will be returned in their order
- int globalIndex = 0;
- for(int sIndex = 0; sIndex < this.messageSources.length; sIndex++) {
- SourceIndex index = new SourceIndex(globalIndex, sIndex, 0);
- this.oldFirstPositionList.add(index);
- this.newFirstPositionList.add(index);
- globalIndex += this.messageSources[sIndex].size();
- }
- // last entry
- int lastSourceI = this.messageSources.length-1;
- SourceIndex lastSourceIndex = new SourceIndex(
- globalIndex-1, // last index
- lastSourceI, // last source
- this.messageSources[lastSourceI].size()-1);
- this.oldFirstPositionList.add(lastSourceIndex);
- this.newFirstPositionList.add(lastSourceIndex);
- }
- }
-
- @Override
- public int size() throws IOException {
- return this.size;
- }
-
- @Override
- public CharSequence getURI() {
- return this.uri;
- }
-
- @Override
- public CharSequence getFormat() {
- return this.format;
- }
-
- @Override
- public Iterator getMessagesAsCharSequence() throws IOException {
- return new MessageMergerCharSequenceIterator(new MessageMergerIterator(true));
- }
-
- private class MessageMergerCharSequenceIterator implements Iterator {
- private final MessageMergerIterator iter;
-
- MessageMergerCharSequenceIterator(MessageMergerIterator iter) {
- this.iter = iter;
- }
-
- @Override
- public boolean hasNext() {
- return this.iter.hasNext();
- }
-
- @Override
- public CharSequence next() {
- return new String(this.iter.next());
- }
- }
-
- @Override
- public Iterator getMessages() throws IOException {
- return new MessageMergerIterator(true);
- }
-
- private class MessageMergerIterator implements Iterator {
- private final boolean chronologically;
- private int currentPosition;
- private byte[] lookAheadMessage = null;
-
- MessageMergerIterator(boolean chronologically) {
- this.chronologically = chronologically;
-
- }
-
- @Override
- public boolean hasNext() {
- if(lookAheadMessage == null) {
- // try
- try {
- this.lookAheadMessage = ASAPMessagesMerger.this.getMessage(currentPosition++, chronologically);
- } catch (ASAPException | IOException e) {
- return false;
- }
- }
- return (this.lookAheadMessage != null);
- }
-
- @Override
- public byte[] next() {
- if (this.lookAheadMessage != null) {
- if (this.hasNext()) {
- byte[] temp = this.lookAheadMessage;
- this.lookAheadMessage = null;
- return temp;
- }
- }
-
- throw new NoSuchElementException("no more messages");
- }
- }
-
- @Override
- public CharSequence getMessageAsCharSequence(int position, boolean chronologically) throws ASAPException, IOException {
- return new String(this.getMessage(position, chronologically));
- }
-
- /**
- The list is organized like this: Each entry describes a position of the merged sources: wantedPosition.
- It also describes source (actually the index of the source: sourceIndex) and position of the message
- in the source (positionInSource). There is not necessarily and entry for each wantedPosition - to keep
- that list short.
-
- A entry is made if the list was empty. There will always be an entry for wantedPosition == 0. Another entry
- will only added if source has changed. Assumed we would have two sources (A and B), first messages come from
- A, follow by B again and so forth, list would look like this: (wantedPosition: 0, A, 0) Both positions will be
- 0 in the first entry. Next entry could be: (4, B, 0). Message for position comes from source B index 0. But
- where come message at 1, 2 and 3? From A. There was no change of source, no entry was made. We avoid a series of
- entries like: (1, A, 1), (2, A, 2), (3, A, 3). They can easily be calculated.
- */
- private SourceIndex getSourceIndex(int position, List indexList) {
- if(indexList.isEmpty()) return null; // not yet initialized?
- SourceIndex previousIndexEntry = null;
- int i = 0;
- do {
- if(indexList.size() <= i) return null;
- SourceIndex indexEntry = indexList.get(i++);
-
- if(indexEntry.wantedPosition == position) return indexEntry; // found match
-
- if(previousIndexEntry != null
- && previousIndexEntry.wantedPosition < position
- && position < indexEntry.wantedPosition) {
- // we are within a range.
- int offsetIndex = previousIndexEntry.wantedPosition;
- int steps = position - offsetIndex;
- return new SourceIndex(position,
- previousIndexEntry.sourceIndex,
- previousIndexEntry.positionInSource + steps);
- }
-
- previousIndexEntry = indexEntry;
- } while(previousIndexEntry.wantedPosition < position); // we have still a chance to find anything
-
- return null; // there is no entry
- }
-
- private static final int FALSE = 0;
- private static final int TRUE = 1;
- private byte[][][] lookAheadMessages = new byte[2][][]; // actual look ahead message
- private SourceIndex[][] lookAheadSourceIndex = new SourceIndex[2][]; // describes position etc. of previous
-
- private byte[][] getLookAheadMessages(boolean chronologically) {
- byte[][] a = chronologically ? this.lookAheadMessages[TRUE] : this.lookAheadMessages[FALSE];
-
- if(a == null) { // not yet initialized
- a = new byte[this.messageSources.length][];
- if(chronologically) this.lookAheadMessages[TRUE] = a;
- else this.lookAheadMessages[FALSE] = a;
- }
-
- return a;
- }
-
- private SourceIndex[] getLookAheadSourceIndex(boolean chronologically) {
- SourceIndex[] s = chronologically ? this.lookAheadSourceIndex[TRUE] : this.lookAheadSourceIndex[FALSE];
-
- if(s == null) { // not yet initialized
- s = new SourceIndex[this.messageSources.length];
- if(chronologically) this.lookAheadSourceIndex[TRUE] = s;
- else this.lookAheadSourceIndex[FALSE] = s;
- }
-
- return s;
- }
-
- private boolean lookAheadSettedUp = false;
- private SourceIndex lookAhead(int position, List indexList, boolean chronologically)
- throws ASAPException, IOException {
-
- int wantedLookAheadPosition = 0;
-
- if(!indexList.isEmpty()) { // we already made a look ahead
- // get last entry
- SourceIndex sourceIndex = indexList.get(indexList.size() - 1);
-
- // check for your own stupidity - last position is before our wanted position - we would not be here otherwise
- if (sourceIndex != null && sourceIndex.wantedPosition >= position)
- throw new ASAPException("internal error - look ahead algorithm buggy");
-
- wantedLookAheadPosition = sourceIndex.wantedPosition + 1;
- }
-
- byte[][] lookAheadMessages = this.getLookAheadMessages(chronologically);
- SourceIndex[] lookAheadSourceIndexArray = this.getLookAheadSourceIndex(chronologically);
-
- if(!this.lookAheadSettedUp) { // setup
- // set it up - read first message from each non empty source
- this.lookAheadSettedUp = true;
- for (int i = 0; i < this.messageSources.length; i++) {
- lookAheadMessages[i] = this.messageSources[i].getMessage(0, chronologically);
- lookAheadSourceIndexArray[i] = new SourceIndex(-1, i, 0);
- }
- }
-
- // find message for next position.
- SourceIndex previousSourceIndex = null;
- SourceIndex foundSourceIndex = null;
-
- boolean lastSourceIndexAdded;
- do {
- int bestSourceIndex = -1; // init source index 0 wins?
- lastSourceIndexAdded = false; // not yet at least
-
- for (int i = 0; i < this.messageSources.length; i++) {
- if(lookAheadMessages[i] == null) continue; // nothing to do in this round
- if(bestSourceIndex == -1) {
- // guess we have a winner without opponent
- bestSourceIndex = i;
- continue;
- }
-
- boolean previousEarlier =
- this.messageCompare.earlier(lookAheadMessages[bestSourceIndex], lookAheadMessages[i]);
-
- /*
- previous earlier | chronologically | what wins?
- -----------------------------------------------
- true true no change
- false true i is better
- true false i is better
- false false no change
- */
-
- if (previousEarlier != chronologically) { bestSourceIndex = i; }
- }
-
- if(bestSourceIndex == -1) // failure in algorithm - should not happen due to test of size()..
- throw new ASAPException("no more message - cannot look ahead");
-
- // we have a winner
- foundSourceIndex = lookAheadSourceIndexArray[bestSourceIndex];
-
- // now we can tell at what overall position this message is
- foundSourceIndex.wantedPosition = wantedLookAheadPosition;
-
- if(previousSourceIndex != null) {
- if(previousSourceIndex.sourceIndex != foundSourceIndex.sourceIndex) {
- // remember previous - we have a change in sources
- indexList.add(foundSourceIndex);
- lastSourceIndexAdded = true;
- }
- } else {
- indexList.add(foundSourceIndex);
- lastSourceIndexAdded = true;
- }
-
- // prepare next round
- previousSourceIndex = foundSourceIndex;
-
- // read ahead - if possible
- lookAheadSourceIndexArray[bestSourceIndex] = null;
- lookAheadMessages[bestSourceIndex] = null;
- int nextPositionInSource = foundSourceIndex.positionInSource + 1;
- try {
- lookAheadMessages[bestSourceIndex] =
- messageSources[bestSourceIndex].getMessage(nextPositionInSource, chronologically);
-
- // remember read ahead
- lookAheadSourceIndexArray[bestSourceIndex] =
- new SourceIndex(-1, // we cannot tell yet
- bestSourceIndex, nextPositionInSource); // we know where it comes from
- }
- catch(Exception e) {
- // no more messages
- }
- } while(position > wantedLookAheadPosition++);
-
- // remember this in any case
- if(!lastSourceIndexAdded) indexList.add(foundSourceIndex);
-
- return foundSourceIndex;
- }
-
- private List getIndexList(boolean chronologically) {
- return chronologically ? oldFirstPositionList : newFirstPositionList;
- }
-
- private SourceIndex getSourceIndex(int position, boolean chronologically) throws ASAPException, IOException {
- if(position >= this.size)
- throw new ASAPException("position index must not exceed total number of messages: "
- + position + " >= " + this.size);
-
- SourceIndex sourceIndex;
- List usedList = this.getIndexList(chronologically);
-
- sourceIndex = this.getSourceIndex(position, usedList);
-
- if(sourceIndex == null) {
- // cache miss
- sourceIndex = this.lookAhead(position, usedList, chronologically);
- }
- if(sourceIndex == null) {
- // still nothing
- throw new ASAPException("no message at position: " + position);
- }
-
- return sourceIndex;
- }
-
- @Override
- public byte[] getMessage(int position, boolean chronologically) throws ASAPException, IOException {
- SourceIndex sourceIndex = this.getSourceIndex(position, chronologically);
- return this.messageSources[sourceIndex.sourceIndex].getMessage(
- sourceIndex.positionInSource, chronologically);
- }
-
- @Override
- public ASAPChunk getChunk(int position, boolean chronologically) throws IOException, ASAPException {
- SourceIndex sourceIndex = this.getSourceIndex(position, chronologically);
- return this.messageSources[sourceIndex.sourceIndex].getChunk(sourceIndex.positionInSource, chronologically);
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSender.java b/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSender.java
deleted file mode 100644
index 7b21127..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSender.java
+++ /dev/null
@@ -1,20 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.ASAPException;
-
-import java.io.IOException;
-import java.util.Set;
-
-public interface ASAPOnlineMessageSender {
- void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, Set recipients,
- byte[] messageAsBytes, int era) throws IOException, ASAPException;
-
- void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, CharSequence recipient,
- byte[] messageAsBytes, int era) throws IOException, ASAPException;
-
- void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, byte[] messageAsBytes, int era)
- throws IOException, ASAPException;
-
- void sendASAPAssimilateMessage(CharSequence format, CharSequence urlTarget, byte[] messageAsBytes)
- throws IOException, ASAPException;
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSenderEngineSide.java b/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSenderEngineSide.java
deleted file mode 100644
index b7d3546..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPOnlineMessageSenderEngineSide.java
+++ /dev/null
@@ -1,142 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.ASAP;
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.protocol.ASAPConnection;
-import net.sharksystem.asap.protocol.ASAPOnlineMessageSource;
-import net.sharksystem.asap.protocol.ASAP_1_0;
-import net.sharksystem.asap.protocol.ASAP_Modem_Impl;
-import net.sharksystem.utils.Log;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.*;
-
-public class ASAPOnlineMessageSenderEngineSide extends ASAPAbstractOnlineMessageSender
- implements ASAPOnlineMessageSource, ASAPOnlineMessageSender {
-
- private final ASAPInternalPeer multiEngine;
- private final ASAP_1_0 protocol = new ASAP_Modem_Impl();
-
- // connections and their remote peer (recipients)
- private Map connectionPeers = new HashMap<>();
-
- // message for recipients
- private Map> messages = new HashMap<>();
-
- public ASAPOnlineMessageSenderEngineSide(ASAPInternalPeer multiEngine) {
- this.multiEngine = multiEngine;
- }
-
- public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes)
- throws IOException, ASAPException {
- this.sendASAPAssimilateMessage(format, uri, messageAsBytes, ASAPEngineFS.DEFAULT_INIT_ERA);
- }
-
- public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes, int era)
- throws IOException, ASAPException {
-
- Set onlinePeers = this.multiEngine.getOnlinePeers();
- if(onlinePeers == null || onlinePeers.size() < 1) {
- Log.writeLog(this, "no online peers");
- throw new ASAPException("no online peers");
- }
-
- Set onlinePeerList = new HashSet<>();
- for(CharSequence peerName : onlinePeers) {
- onlinePeerList.add(peerName);
- Log.writeLog(this, peerName + " is online");
- }
-
- this.sendASAPAssimilateMessage(format, uri, onlinePeerList, messageAsBytes, era);
- }
-
- public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, Set receiver,
- byte[] messageAsBytes, int era) throws IOException, ASAPException {
-
- if(receiver == null || receiver.size() < 1) {
- // replace empty recipient list with list of online peers.
- this.sendASAPAssimilateMessage(format, uri, messageAsBytes, era);
- return;
- }
-
- StringBuilder sb = Log.startLog(this);
- sb.append("sendASAPAssimilate(format: ");
- sb.append(format);
- sb.append("| uri: ");
- sb.append(uri);
- sb.append("| era: ");
- if(era != ASAP.TRANSIENT_ERA) sb.append(era);
- else sb.append("transient");
- sb.append("| #receiver: ");
- if(receiver != null) sb.append(receiver.size());
- else sb.append("null");
- sb.append("| length: ");
- sb.append(messageAsBytes.length);
- sb.append(")");
- Log.writeLog(this, sb.toString());
-
- // each message can have multiple receiver. Iterate
-
- // is there an open connection to each of the receiver.
- boolean foundAll = true; // optimism captain :)
- for(CharSequence recipient : receiver) {
- sb = Log.startLog(this);
- sb.append("try to find connection for recipient: ");
- sb.append(recipient);
- Log.writeLog(this, sb.toString());
- if(multiEngine.existASAPConnection(recipient)) {
- ASAPConnection asapConnection = multiEngine.getASAPConnection(recipient);
- sb = Log.startLog(this);
- sb.append("got asap connection, subscribe and store message");
- Log.writeLog(this, sb.toString());
-
- // serialize message for this recipient
- ByteArrayOutputStream asapPDUBytes = new ByteArrayOutputStream();
- this.protocol.assimilate(this.multiEngine.getOwner(), recipient, format, uri, era, null, // no offsets
- null, messageAsBytes, asapPDUBytes, asapConnection.isSigned());
-
- // I guess maps are synchronized
- List messageList = this.messages.get(recipient);
- if(messageList == null) {
- messageList = new ArrayList<>();
- this.messages.put(recipient, messageList);
- }
-
- messageList.add(asapPDUBytes.toByteArray());
-
- // subscribe and remember it
- asapConnection.addOnlineMessageSource(this);
- this.connectionPeers.put(asapConnection, recipient);
- } else {
- sb = Log.startLog(this);
- sb.append("no connection found");
- Log.writeLog(this, sb.toString());
- foundAll = false; // at least to one recipient is not open line
- }
- }
- }
-
- private String getLogStart() {
- return this.getClass().getSimpleName() + ": ";
- }
-
- @Override
- public void sendStoredMessages(ASAPConnection asapConnection, OutputStream os) throws IOException {
- CharSequence recipient = this.connectionPeers.get(asapConnection);
-
- List messageList = this.messages.get(recipient);
- Log.writeLog(this, this.getLogStart() + "send message(s) to " + recipient + " via: "
- + os.getClass().getSimpleName());
- while(!messageList.isEmpty()) {
- byte[] messageBytes = messageList.remove(0);
- os.write(messageBytes);
- Log.writeLog(this, "wrote pure bytes: " + messageBytes.length);
- }
-
- this.messages.remove(recipient);
- asapConnection.removeOnlineMessageSource(this);
- this.connectionPeers.remove(asapConnection);
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPProtocolEngine.java b/src/main/java/net/sharksystem/asap/engine/ASAPProtocolEngine.java
deleted file mode 100644
index a1a0569..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPProtocolEngine.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.ASAPEncounterConnectionType;
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.protocol.ASAP_1_0;
-import net.sharksystem.asap.protocol.ASAP_AssimilationPDU_1_0;
-import net.sharksystem.asap.protocol.ASAP_Interest_PDU_1_0;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * @author thsc
- */
-public interface ASAPProtocolEngine {
- void handleASAPInterest(ASAP_Interest_PDU_1_0 asapInterest, ASAP_1_0 protocol,
- String encounteredPeer, OutputStream os, ASAPEncounterConnectionType connectionType)
- throws ASAPException, IOException;
-
- void handleASAPAssimilate(ASAP_AssimilationPDU_1_0 asapAssimilationPDU, ASAP_1_0 protocolModem,
- String encounteredPeer, InputStream is, OutputStream os,
- ASAPEncounterConnectionType connectionType,
- ASAPChunkAssimilatedListener listener)
- throws ASAPException, IOException;
-
- /**
- * Chunks are (tried to be) delivered to their recipients during each encounter
- * with another peer. After successful delivery, recipient is withdrawn from recipient
- * list to prevent multiple delivery.
- *
- * If this flag is set, chunk are removed permanently if their are delivered
- * to all their recipients. There are kept in local storage otherwise.
- * @param drop
- */
- void setBehaviourDropDeliveredChunks(boolean drop) throws IOException;
-
- /**
- * engine can deliver local message but also received messages - default false - send no received messages
- * @param on
- */
- void setBehaviourAllowRouting(boolean on) throws IOException;
-
- boolean routingAllowed();
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPSingleProcessOnlineMessageSender.java b/src/main/java/net/sharksystem/asap/engine/ASAPSingleProcessOnlineMessageSender.java
deleted file mode 100644
index 4e9c8f0..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPSingleProcessOnlineMessageSender.java
+++ /dev/null
@@ -1,45 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.protocol.ASAPConnection;
-import net.sharksystem.asap.protocol.ASAPOnlineMessageSource;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.Set;
-
-public class ASAPSingleProcessOnlineMessageSender
- extends ASAPAbstractOnlineMessageSender implements ASAPOnlineMessageSource {
-
- private final ASAPOnlineMessageSenderEngineSide asapOnlineMessageSenderEngineSide;
-
- public ASAPSingleProcessOnlineMessageSender(ASAPInternalPeer multiEngine, ASAPInternalStorage source) {
- this.attachToSource(source);
- this.asapOnlineMessageSenderEngineSide = new ASAPOnlineMessageSenderEngineSide(multiEngine);
- }
-
- @Override
- public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, Set recipients,
- byte[] messageAsBytes, int era) throws IOException, ASAPException {
-
- this.asapOnlineMessageSenderEngineSide.sendASAPAssimilateMessage(
- format, uri, recipients, messageAsBytes, era);
- }
-
- public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes)
- throws IOException, ASAPException {
- this.sendASAPAssimilateMessage(format, uri, messageAsBytes, ASAPEngineFS.DEFAULT_INIT_ERA);
- }
-
- @Override
- public void sendASAPAssimilateMessage(CharSequence format, CharSequence uri, byte[] messageAsBytes, int era)
- throws IOException, ASAPException {
-
- this.asapOnlineMessageSenderEngineSide.sendASAPAssimilateMessage(format, uri, messageAsBytes, era);
- }
-
- @Override
- public void sendStoredMessages(ASAPConnection asapConnection, OutputStream os) throws IOException {
- this.asapOnlineMessageSenderEngineSide.sendStoredMessages(asapConnection, os);
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPStorageImpl.java b/src/main/java/net/sharksystem/asap/engine/ASAPStorageImpl.java
deleted file mode 100644
index fcd7fd4..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPStorageImpl.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.ASAPChunkStorage;
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.protocol.ASAP_1_0;
-
-import java.io.IOException;
-
-public abstract class ASAPStorageImpl implements ASAPInternalStorage {
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/ASAPUndecryptableMessageHandler.java b/src/main/java/net/sharksystem/asap/engine/ASAPUndecryptableMessageHandler.java
deleted file mode 100644
index c85fb1f..0000000
--- a/src/main/java/net/sharksystem/asap/engine/ASAPUndecryptableMessageHandler.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.crypto.ASAPCryptoAlgorithms;
-
-public interface ASAPUndecryptableMessageHandler {
- String FORMAT_UNDECRYPTABLE_MESSAGES = "asap/undecryptable";
- String URI_UNDECRYPTABLE_MESSAGES = "asap://undecryptable";
- /**
- * Peer can (and should) receive encrypted messages without being receiver. A peer is not able
- * to encrypt that message but could store and forward. That is what ASAP is about.
- */
- void handleUndecryptableMessage(ASAPCryptoAlgorithms.EncryptedMessagePackage encryptedMessage, CharSequence receiver);
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/CryptoControl.java b/src/main/java/net/sharksystem/asap/engine/CryptoControl.java
deleted file mode 100644
index 2b9021b..0000000
--- a/src/main/java/net/sharksystem/asap/engine/CryptoControl.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.protocol.ASAP_PDU_1_0;
-
-public interface CryptoControl {
- boolean allowed2Process(ASAP_PDU_1_0 pdu);
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/DefaultSecurityAdministrator.java b/src/main/java/net/sharksystem/asap/engine/DefaultSecurityAdministrator.java
deleted file mode 100644
index 3c024d1..0000000
--- a/src/main/java/net/sharksystem/asap/engine/DefaultSecurityAdministrator.java
+++ /dev/null
@@ -1,110 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.protocol.ASAP_AssimilationPDU_1_0;
-import net.sharksystem.asap.protocol.ASAP_PDU_1_0;
-import net.sharksystem.asap.crypto.ASAPPoint2PointCryptoSettings;
-import net.sharksystem.utils.Log;
-
-import java.io.IOException;
-
-public class DefaultSecurityAdministrator implements ASAPCommunicationSetting,
- ASAPEnginePermissionSettings, CryptoControl, ASAPPoint2PointCryptoSettings {
-
- private boolean receivedMessageMustBeEncrypted = false;
- private boolean receivedMessagesMustBeSigned = false;
- private boolean sendEncrypted = false;
- private boolean sendSigned;
-
- @Override
- public void setRememberEncounteredPeers(boolean on) throws IOException {
-
- }
-
- @Override
- public void setReceivedMessagesMustBeEncrypted(boolean on) throws IOException {
- this.receivedMessageMustBeEncrypted = on;
- }
-
- @Override
- public void setReceivedMessagesMustBeSigned(boolean on) throws IOException {
- this.receivedMessagesMustBeSigned = on;
- }
-
- @Override
- public void setSetAllowedRemotePeers(AllowedRemotePeers safetyLevel) {
-
- }
-
- @Override
- public boolean setRevealEngineFormat(String peerName) {
- return false;
- }
-
- @Override
- public boolean setSendOpenMessages(String peerName) {
- return false;
- }
-
- @Override
- public boolean allowedToCreateChannel(ASAP_AssimilationPDU_1_0 asapAssimilationPDU) {
- return true; // it is a dummy
- }
-
- @Override
- public void setSendEncryptedMessages(boolean on) {
- this.sendEncrypted = on;
- }
-
- @Override
- public void setSendSignedMessages(boolean on) {
- this.sendSigned = on;
- }
-
- @Override
- public boolean allowed2Process(ASAP_PDU_1_0 pdu) {
- if(this.receivedMessagesMustBeSigned && !pdu.signed()) {
- Log.writeLog(this, "checked: " + pdu);
- Log.writeLog(this, "not signed");
- return false;
- }
- if(this.receivedMessageMustBeEncrypted && !pdu.encrypted()) {
- Log.writeLog(this, "checked: " + pdu);
- Log.writeLog(this, "not encrypted");
- return false;
- }
-
- Log.writeLog(this, "ok");
- return true;
- }
-
- private String getLogStart() {
- return this.getClass().getSimpleName() + ": ";
- }
-
- @Override
- public boolean mustEncrypt() {
- return this.sendEncrypted;
- }
-
- @Override
- public boolean mustSign() {
- return this.sendSigned;
- }
-
- /*
- private boolean encryptedMessagesOnly = false;
- private boolean signedMessagesOnly = false;
- private boolean sendEncrypted = false;
- private boolean sendSigned;
-
- */
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(this.getLogStart());
- sb.append("recEncrypted: " + this.receivedMessageMustBeEncrypted);
- sb.append(" | recSigned: " + this.receivedMessagesMustBeSigned);
- sb.append(" | sendEncrypted: " + this.sendEncrypted);
- sb.append(" | sendSigned: " + this.sendSigned);
- return sb.toString();
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/EngineSetting.java b/src/main/java/net/sharksystem/asap/engine/EngineSetting.java
deleted file mode 100644
index 8316c27..0000000
--- a/src/main/java/net/sharksystem/asap/engine/EngineSetting.java
+++ /dev/null
@@ -1,16 +0,0 @@
-package net.sharksystem.asap.engine;
-
-public class EngineSetting {
- public final CharSequence folder;
- public ASAPChunkAssimilatedListener listener;
- public ASAPEngine engine;
-
- EngineSetting(CharSequence folder, ASAPChunkAssimilatedListener listener) {
- this.folder = folder;
- this.listener = listener;
- }
-
- void setASAPEngine(ASAPEngine engine) {
- this.engine = engine;
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/MessageIter.java b/src/main/java/net/sharksystem/asap/engine/MessageIter.java
deleted file mode 100644
index 82eba0a..0000000
--- a/src/main/java/net/sharksystem/asap/engine/MessageIter.java
+++ /dev/null
@@ -1,32 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import java.io.FileNotFoundException;
-import java.util.Iterator;
-import java.util.List;
-import java.util.NoSuchElementException;
-
-public class MessageIter implements Iterator {
- private final List byteMessages;
- private int nextIndex;
- private String nextString;
-
-
- public MessageIter(List byteMessages) throws FileNotFoundException {
- this.byteMessages = byteMessages;
- this.nextIndex = 0;
- }
-
- @Override
- public boolean hasNext() {
- return this.byteMessages.size() > nextIndex;
- }
-
- @Override
- public String next() {
- if (!this.hasNext()) {
- throw new NoSuchElementException("no more messages");
- }
-
- return new String(this.byteMessages.get(nextIndex++));
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/engine/MessagesContainer.java b/src/main/java/net/sharksystem/asap/engine/MessagesContainer.java
deleted file mode 100644
index 1e0f90e..0000000
--- a/src/main/java/net/sharksystem/asap/engine/MessagesContainer.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package net.sharksystem.asap.engine;
-
-import net.sharksystem.asap.ASAPHop;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.List;
-
-public interface MessagesContainer {
- void addMessage(InputStream is, long length) throws IOException;
- void setASAPHopList(List asapHopList) throws IOException;
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/ASAPChannelContentChangedListenerManager.java b/src/main/java/net/sharksystem/asap/listenermanager/ASAPChannelContentChangedListenerManager.java
deleted file mode 100644
index 00beaa7..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/ASAPChannelContentChangedListenerManager.java
+++ /dev/null
@@ -1,71 +0,0 @@
-package net.sharksystem.asap.listenermanager;
-
-import net.sharksystem.asap.*;
-
-import java.util.HashMap;
-
-public class ASAPChannelContentChangedListenerManager implements ASAPChannelContentChangedListenerManagement {
- private HashMap> listenerMap =
- new HashMap();
-
- @Override
- public void addASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener) {
- GenericListenerImplementation listenerList = this.listenerMap.get(format);
- if(listenerList == null) {
- listenerList = new GenericListenerImplementation();
- this.listenerMap.put(format, listenerList);
- }
-
- listenerList.addListener(listener);
- }
-
- @Override
- public void removeASAPChannelContentChangedListener(CharSequence format, ASAPChannelContentChangedListener listener) {
- GenericListenerImplementation listenerList = this.listenerMap.get(format);
- if(listenerList != null) {
- listenerList.removeListener(listener);
- }
- }
-
- public int getNumberListener() {
- if(this.listenerMap == null) return 0;
- return this.listenerMap.size();
- }
-
- public void removeAllListeners() {
- // reset
- this.listenerMap = new HashMap();
- }
-
- public void notifyChanged(CharSequence format, CharSequence uri, int era) {
-
- this.notifyChanged(format, uri, era, false);
- }
-
- public void notifyChanged(CharSequence format, CharSequence uri, int era, boolean useThreads) {
-
- GenericListenerImplementation listenerList = this.listenerMap.get(format);
- if(listenerList != null) {
- ASAPChannelContentChangedListenerManager.ASAPChannelContentChangedNotifier notifier
- = new ASAPChannelContentChangedListenerManager.ASAPChannelContentChangedNotifier(format, uri, era);
-
- listenerList.notifyAll(notifier, useThreads);
- }
- }
-
- public class ASAPChannelContentChangedNotifier implements GenericNotifier {
- private CharSequence format;
- private CharSequence uri;
- private int era;
-
- ASAPChannelContentChangedNotifier(CharSequence format, CharSequence uri, int era) {
- this.format = format;
- this.uri = uri;
- this.era = era;
- }
-
- public void doNotify(ASAPChannelContentChangedListener listener) {
- listener.asapChannelContentChanged(this.format, this.uri, this.era);
- }
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/ASAPEnvironmentChangesListenerManager.java b/src/main/java/net/sharksystem/asap/listenermanager/ASAPEnvironmentChangesListenerManager.java
deleted file mode 100644
index 6d54f61..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/ASAPEnvironmentChangesListenerManager.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package net.sharksystem.asap.listenermanager;
-
-import net.sharksystem.asap.ASAPEnvironmentChangesListener;
-import net.sharksystem.asap.ASAPEnvironmentChangesListenerManagement;
-import net.sharksystem.utils.Log;
-
-import java.util.HashSet;
-import java.util.Set;
-
-public class ASAPEnvironmentChangesListenerManager
- extends GenericListenerImplementation
- implements ASAPEnvironmentChangesListenerManagement {
-
- @Override
- public void addASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener) {
- this.addListener(changesListener);
- }
-
- @Override
- public void removeASAPEnvironmentChangesListener(ASAPEnvironmentChangesListener changesListener) {
- this.removeListener(changesListener);
- }
-
- public void notifyListeners(Set peerList) {
- if(peerList == null) peerList = new HashSet<>();
-
- if(this.listenerList == null || this.listenerList.isEmpty()) return;
-
- // make a copy of that list
- for(ASAPEnvironmentChangesListener listener : this.listenerList) {
- if(listener != null) listener.onlinePeersChanged(new HashSet<>(peerList));
- }
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/ASAPMessageReceivedListenerManager.java b/src/main/java/net/sharksystem/asap/listenermanager/ASAPMessageReceivedListenerManager.java
deleted file mode 100644
index 41de9d0..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/ASAPMessageReceivedListenerManager.java
+++ /dev/null
@@ -1,87 +0,0 @@
-package net.sharksystem.asap.listenermanager;
-
-import net.sharksystem.asap.*;
-import net.sharksystem.utils.Log;
-
-import java.io.IOException;
-import java.util.HashMap;
-import java.util.List;
-
-public class ASAPMessageReceivedListenerManager implements ASAPMessageReceivedListenerManagement {
- private HashMap> listenerMap =
- new HashMap();
-
- @Override
- public void addASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener) {
- GenericListenerImplementation listenerList = this.listenerMap.get(format);
- if(listenerList == null) {
- listenerList = new GenericListenerImplementation();
- this.listenerMap.put(format, listenerList);
- }
-
- listenerList.addListener(listener);
- }
-
- @Override
- public void removeASAPMessageReceivedListener(CharSequence format, ASAPMessageReceivedListener listener) {
- GenericListenerImplementation listenerList = this.listenerMap.get(format);
- if(listenerList != null) {
- listenerList.removeListener(listener);
- }
- }
-
- @Override
- public int getNumberListener() {
- if(this.listenerMap == null) return 0;
- return this.listenerMap.size();
- }
-
- public void removeAllListeners() {
- // reset
- this.listenerMap = new HashMap();
- }
-
- public void notifyReceived(CharSequence format, ASAPMessages asapMessage,
- String senderE2E, // E2E part
- List asapHopList) {
-
- this.notifyReceived(format, asapMessage, false, senderE2E, asapHopList);
- }
-
- public void notifyReceived(CharSequence format, ASAPMessages asapMessage, boolean useThreads,
- String senderE2E, List asapHopList) {
-
- GenericListenerImplementation listenerList = this.listenerMap.get(format);
- if(listenerList != null) {
- ASAPMessageReceivedNotifier asapMessageReceivedNotifier
- = new ASAPMessageReceivedNotifier(asapMessage, senderE2E, asapHopList);
-
- listenerList.notifyAll(asapMessageReceivedNotifier, useThreads);
- }
- }
-
- public class ASAPMessageReceivedNotifier implements GenericNotifier {
- private final ASAPMessages asapMessage;
- private final String senderE2E;
- private List asapHopList;
-
- ASAPMessageReceivedNotifier(ASAPMessages asapMessage,
- String senderE2E,
- List asapHopList) {
-
- this.asapMessage = asapMessage;
- this.senderE2E = senderE2E;
- this.asapHopList = asapHopList;
- }
-
- public void doNotify(ASAPMessageReceivedListener listener) {
- try {
- //Log.writeLog(this, "notify: " + listener.getClass().getSimpleName());
- listener.asapMessagesReceived(this.asapMessage, this.senderE2E, this.asapHopList);
- } catch (IOException e) {
- System.err.println("error when notifying about received asap message: "
- + e.getLocalizedMessage());
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/GenericListenerImplementation.java b/src/main/java/net/sharksystem/asap/listenermanager/GenericListenerImplementation.java
deleted file mode 100644
index e2d4507..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/GenericListenerImplementation.java
+++ /dev/null
@@ -1,47 +0,0 @@
-package net.sharksystem.asap.listenermanager;
-
-import net.sharksystem.utils.Log;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class GenericListenerImplementation {
- protected List listenerList = new ArrayList();
-
- protected void addListener(L listener) {
- if(!this.listenerList.contains(listener)) {
- this.listenerList.add(listener);
- }
- }
-
- protected void removeListener(L listener) {
- this.listenerList.remove(listener);
- }
-
- public void removeAllListeners() {
- this.listenerList = new ArrayList();
- }
-
- public void notifyAll(GenericNotifier notifier, boolean useThreads) {
- for(L listener : this.listenerList) {
- if(useThreads) {
- new Thread (new Runnable() {
- @Override
- public void run() { notifier.doNotify(listener); }
- }).start();
- } else { // no threads
- notifier.doNotify(listener);
- }
- }
- }
-
- protected void log(String msg) {
- StringBuilder sb = new StringBuilder();
- sb.append(Log.startLog(this));
- sb.append(": ");
- sb.append(msg);
-
- Log.writeLog(this, sb.toString());
- }
-
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/GenericNotifier.java b/src/main/java/net/sharksystem/asap/listenermanager/GenericNotifier.java
deleted file mode 100644
index 9bd2fa5..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/GenericNotifier.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package net.sharksystem.asap.listenermanager;
-
-public interface GenericNotifier {
- /**
- * run specific notification
- */
- void doNotify(L listener);
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementCreateASAPStorageMessage.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementCreateASAPStorageMessage.java
deleted file mode 100644
index 2e813ae..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementCreateASAPStorageMessage.java
+++ /dev/null
@@ -1,23 +0,0 @@
-package net.sharksystem.asap.listenermanager.management;
-
-import java.util.Set;
-
-public interface ASAPManagementCreateASAPStorageMessage {
- /**
- * @return list of recipients of this storage/channel
- */
- Set getRecipients();
-
- /**
- * @return channel uri
- */
- CharSequence getChannelUri();
-
- /**
- *
- * @return storage/channel owner
- */
- CharSequence getOwner();
-
- CharSequence getAppName();
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessage.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessage.java
deleted file mode 100644
index 8bef338..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessage.java
+++ /dev/null
@@ -1,100 +0,0 @@
-package net.sharksystem.asap.listenermanager.management;
-
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.protocol.ASAP_1_0;
-import net.sharksystem.asap.protocol.ASAP_PDU_1_0;
-
-import java.io.*;
-import java.util.*;
-
-public class ASAPManagementMessage {
- public static byte[] getCreateClosedASAPChannelMessage(
- CharSequence owner, CharSequence appName, CharSequence channelUri,
- Collection recipients) throws ASAPException, IOException {
-
- if(recipients == null || recipients.size() < 1) {
- throw new ASAPException("recipients in storage/channelUri must not be null or empty: ");
- }
-
- // we have to put format and recipients into an assimilate message.
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- DataOutputStream dos = new DataOutputStream(baos);
-
- // put owner
- dos.writeUTF(owner.toString());
-
- // put appName uri
- dos.writeUTF(appName.toString());
-
- // put channelUri uri
- dos.writeUTF(channelUri.toString());
-
- // put recipients
- for(CharSequence recipient : recipients) {
- dos.writeUTF(recipient.toString());
- }
-
- return baos.toByteArray();
- }
-
- public static ASAPManagementCreateASAPStorageMessage parseASAPManagementMessage(byte[] message)
- throws IOException {
-
- return new CreateASAPStorageMessage(message);
- }
-
- private static boolean isASAPManagementMessage(ASAP_PDU_1_0 asapPDU) {
- return asapPDU.getFormat().equalsIgnoreCase(ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
- }
-
- private static class CreateASAPStorageMessage implements ASAPManagementCreateASAPStorageMessage {
- private final Set recipients;
- private final CharSequence channelUri;
- private final CharSequence appName;
- private final CharSequence owner;
-
- CreateASAPStorageMessage(byte[] message) throws IOException {
-
- // convert to string
- DataInputStream dis = new DataInputStream(new ByteArrayInputStream(message));
- this.owner = dis.readUTF();
- this.appName = dis.readUTF();
- this.channelUri = dis.readUTF();
-
- // there must be at least one recipient
- this.recipients = new HashSet<>();
- this.recipients.add(dis.readUTF());
-
- // and maybe some more
- try {
- for(;;) {
- this.recipients.add(dis.readUTF());
- }
- }
- catch(Throwable t) {
- // reach end - ok
- }
- }
-
- @Override
- public Set getRecipients() {
- return this.recipients;
- }
-
- @Override
- public CharSequence getChannelUri() {
- return this.channelUri;
- }
-
- @Override
- public CharSequence getOwner() {
- return this.owner;
- }
-
- @Override
- public CharSequence getAppName() {
- return this.appName;
- }
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessageHandler.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessageHandler.java
deleted file mode 100644
index fa91269..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementMessageHandler.java
+++ /dev/null
@@ -1,167 +0,0 @@
-package net.sharksystem.asap.listenermanager.management;
-
-import net.sharksystem.asap.ASAPHop;
-import net.sharksystem.asap.ASAPMessages;
-import net.sharksystem.asap.engine.ASAPInternalChunk;
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.engine.ASAPInternalStorage;
-import net.sharksystem.asap.ASAPChunkStorage;
-import net.sharksystem.asap.engine.*;
-import net.sharksystem.asap.protocol.ASAP_1_0;
-import net.sharksystem.utils.Log;
-
-import java.io.IOException;
-import java.util.*;
-
-public class ASAPManagementMessageHandler implements ASAPChunkAssimilatedListener {
- private final ASAPInternalPeer multiASAPEngine;
-
- public ASAPManagementMessageHandler(ASAPInternalPeer multiASAPEngine) throws IOException, ASAPException {
- this.multiASAPEngine = multiASAPEngine;
- }
-
- ///////////////////////////////////////////////////////////////////////////////////////////////////////
- // chunk received listener for asap management engine //
- ///////////////////////////////////////////////////////////////////////////////////////////////////////
-
- private HashMap, CharSequence> recipientUris = new HashMap<>();
-
- public static CharSequence createUniqueUri() {
- return "sn2://asapManagement://" + Long.toString(System.currentTimeMillis());
- }
-
- CharSequence getURI(Set recipients) throws IOException, ASAPException {
- // find entry with all recipients - and only those recipients
-
- for(Set rSet : recipientUris.keySet()) {
- // are recipients fully inside rSet?
- if(rSet.containsAll(recipients) && recipients.containsAll(rSet)) {
- return recipientUris.get(rSet);
- }
- }
-
- return null;
- }
-
- @Override
- public void chunkStored(String format, String senderE2E, String uri, int era,
- List asapHop) throws IOException {
-
- Log.writeLog(this,
- "handle received chunk (format|senderE2E|uri|era) " + format + senderE2E + "|" + uri + "|" + era);
- try {
- ASAPEngine asapManagementEngine = multiASAPEngine.getEngineByFormat(ASAP_1_0.ASAP_MANAGEMENT_FORMAT);
-
- ASAPChunkStorage incomingChunkStorage = asapManagementEngine.getReceivedChunksStorage(senderE2E);
- ASAPInternalChunk chunk = incomingChunkStorage.getChunk(uri, era);
- Iterator messageIter = chunk.getMessages();
- Log.writeLog(this, "iterate management messages");
- while(messageIter.hasNext()) {
- byte[] message = messageIter.next();
- Set recipients = this.handleASAPManagementMessage(message);
-
- // add message without changes - could be signed
- CharSequence sendUri = this.getURI(recipients);
- boolean setUpRecipients = (sendUri == null);
- if(setUpRecipients) {
- sendUri = createUniqueUri();
- }
- // write message
- Log.writeLog(this, "add received message locally: ");
- asapManagementEngine.add(sendUri, message);
-
- if(setUpRecipients) {
- asapManagementEngine.setRecipients(sendUri, recipients);
- this.recipientUris.put(recipients, sendUri);
- }
- }
- Log.writeLog(this, "done iterating management messages");
- // remove incoming messages - handled
- asapManagementEngine.getReceivedChunksStorage(senderE2E).dropChunks(era);
- Log.writeLog(this, "incoming asap management messages dropped");
- } catch (ASAPException | IOException e) {
- Log.writeLog(this, "could get asap management engine but received chunk - looks like a bug");
- }
- }
-
- @Override
- public void transientMessagesReceived(ASAPMessages transientMessages, ASAPHop asapHop) throws IOException {
- Log.writeLogErr(this, "transientChunkReceived not yet implement");
- }
-
- private Set handleASAPManagementMessage(byte[] message) throws ASAPException, IOException {
- StringBuilder b = new StringBuilder();
- b.append(this.getLogStart());
- b.append("start processing asap management pdu");
- Log.writeLog(this, b.toString());
-
- ASAPManagementCreateASAPStorageMessage asapManagementCreateASAPStorageMessage =
- ASAPManagementMessage.parseASAPManagementMessage(message);
-
- CharSequence owner = asapManagementCreateASAPStorageMessage.getOwner();
- CharSequence channelUri = asapManagementCreateASAPStorageMessage.getChannelUri();
- CharSequence format = asapManagementCreateASAPStorageMessage.getAppName();
- Set receivedRecipients = asapManagementCreateASAPStorageMessage.getRecipients();
-
- // add owner to this list
- Set recipients = new HashSet<>();
-
- // add owner
- recipients.add(owner);
-
- // add rest
- for(CharSequence r : receivedRecipients) {
- recipients.add(r);
- }
-
- b = new StringBuilder();
- b.append(this.getLogStart());
- b.append("owner: ");
- b.append(owner);
- b.append(" | format: ");
- b.append(format);
- b.append(" | channelUri: ");
- b.append(channelUri);
- b.append(" | #recipients: ");
- b.append(recipients.size());
-
- // find storage / app - can throw an exception - that's ok
- ASAPInternalStorage asapStorage = this.multiASAPEngine.getEngineByFormat(format);
-
- if(asapStorage.channelExists(channelUri)) {
- Set existingChannelRecipientsList = asapStorage.getRecipients(channelUri);
- if(existingChannelRecipientsList.size() == recipients.size()) {
- // could be the same - same recipients?
-
- // iterate all recipient and check whether they are also in local recipient list
- for(CharSequence recipient : recipients) {
- boolean found = false;
- for(CharSequence existingRecipient : existingChannelRecipientsList) {
- if(existingRecipient.toString().equalsIgnoreCase(recipient.toString())) {
- // got it
- found = true;
- break; // leave loop and test next
- }
- }
- if(!found) {
- throw new ASAPException("channel already exists but with different recipients: " + b.toString());
- }
- }
- // ok it the same
- return receivedRecipients;
- } else {
- throw new ASAPException("channel already exists but with different settings: " + b.toString());
- }
- }
-
- // else - channel does not exist - create by setting recipients
- Log.writeLog(this, "create channel: " + b.toString());
- asapStorage.createChannel(owner, channelUri, recipients);
-
- return receivedRecipients;
- }
-
- private String getLogStart() {
- return this.getClass().getSimpleName() + "(" + this.multiASAPEngine.getOwner() + "): ";
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorage.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorage.java
deleted file mode 100644
index 93cf6a6..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorage.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package net.sharksystem.asap.listenermanager.management;
-
-import net.sharksystem.asap.ASAPException;
-
-import java.io.IOException;
-import java.util.Collection;
-
-public interface ASAPManagementStorage {
- CharSequence ASAP_CREATE_CHANNEL = "asap://createChannel";
-
- void notifyChannelCreated(CharSequence appName, CharSequence channelUri,
- CharSequence uri, Collection storageRecipients) throws ASAPException, IOException;
-}
diff --git a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorageImpl.java b/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorageImpl.java
deleted file mode 100644
index 17c8408..0000000
--- a/src/main/java/net/sharksystem/asap/listenermanager/management/ASAPManagementStorageImpl.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package net.sharksystem.asap.listenermanager.management;
-
-import net.sharksystem.asap.engine.ASAPEngine;
-import net.sharksystem.asap.ASAPException;
-
-import java.io.IOException;
-import java.util.Collection;
-
-public class ASAPManagementStorageImpl implements ASAPManagementStorage {
- private final ASAPEngine asapEngine;
-
- public ASAPManagementStorageImpl(ASAPEngine asapEngine) {
- this.asapEngine = asapEngine;
- }
-
- @Override
- public void notifyChannelCreated(CharSequence appName, CharSequence channelUri, CharSequence uri,
- Collection recipients) throws ASAPException, IOException {
-
- byte[] createClosedASAPChannelMessage = ASAPManagementMessage.getCreateClosedASAPChannelMessage(
- this.asapEngine.getOwner(),
- appName,
- uri,
- recipients);
-
- // put into a channel
- CharSequence newUri = ASAPManagementMessageHandler.createUniqueUri();
- this.asapEngine.add(newUri, createClosedASAPChannelMessage);
- this.asapEngine.setRecipients(newUri, recipients);
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPConnection.java b/src/main/java/net/sharksystem/asap/protocol/ASAPConnection.java
deleted file mode 100644
index 8f66e66..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPConnection.java
+++ /dev/null
@@ -1,21 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import net.sharksystem.asap.ASAPEncounterConnectionType;
-
-public interface ASAPConnection {
- CharSequence getEncounteredPeer();
-
- void addOnlineMessageSource(ASAPOnlineMessageSource source);
- void removeOnlineMessageSource(ASAPOnlineMessageSource source);
-
- void addASAPConnectionListener(ASAPConnectionListener asapConnectionListener);
-
- void removeASAPConnectionListener(ASAPConnectionListener asapConnectionListener);
-
- boolean isSigned();
-
- ASAPEncounterConnectionType getASAPEncounterConnectionType();
-
- // terminate that connection - does not effect the underlying connections established e.g. with Bluetooth
- void kill();
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPConnectionListener.java b/src/main/java/net/sharksystem/asap/protocol/ASAPConnectionListener.java
deleted file mode 100644
index f7abfc5..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPConnectionListener.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-public interface ASAPConnectionListener {
- /**
- * Called when first message was read from remote peer.
- * The session started.
- */
- void asapConnectionStarted(String remotePeerName, ASAPConnection connection);
-
- void asapConnectionTerminated(Exception terminatingException, ASAPConnection connection);
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPCryptoMessage.java b/src/main/java/net/sharksystem/asap/protocol/ASAPCryptoMessage.java
deleted file mode 100644
index de76424..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPCryptoMessage.java
+++ /dev/null
@@ -1,228 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.ASAPSecurityException;
-import net.sharksystem.asap.crypto.ASAPKeyStore;
-import net.sharksystem.asap.crypto.ASAPCryptoAlgorithms;
-import net.sharksystem.asap.utils.ASAPSerialization;
-import net.sharksystem.utils.Log;
-
-import java.io.*;
-
-class ASAPCryptoMessage {
- private boolean encrypted;
- private boolean sign;
- private CharSequence recipient;
- private ASAPKeyStore ASAPKeyStore;
- private byte cmd;
-
- private OutputStream effectiveOS;
- private OutputStream realOS;
- private ByteArrayOutputStream outputStreamCopy;
- private InputStreamCopy inputStreamCopy;
- private ASAPCryptoAlgorithms.EncryptedMessagePackage encryptedMessagePackage;
-
- ASAPCryptoMessage(ASAPKeyStore ASAPKeyStore) {
- this.ASAPKeyStore = ASAPKeyStore;
- }
-
- ASAPCryptoMessage(byte cmd, OutputStream os, boolean sign, boolean encrypted,
- CharSequence recipient,
- ASAPKeyStore ASAPKeyStore)
- throws ASAPSecurityException {
-
- this.cmd = cmd;
- this.realOS = os;
- this.effectiveOS = os; // still this one
- this.ASAPKeyStore = ASAPKeyStore;
- this.recipient = recipient;
- this.encrypted = encrypted;
- this.sign = sign;
-
- if(encrypted || sign) {
- // we need some basic crypto parameters
- if(ASAPKeyStore == null) {
- throw new ASAPSecurityException("cannot encrypt or sign without cryptp parameters / key store");
- }
- this.setupCopyOutputStream();
- }
-
- if(encrypted) {
- // mark encryption in command - rest will be encrypted
- this.cmd += ASAP_1_0.ENCRYPTED_CMD;
- if(this.recipient == null) {
- throw new ASAPSecurityException("cannot encrypt message with no specified receiver - fatal, give up");
- }
- }
-
- if(sign) {
- // signing needs a private key - check of available
- if(ASAPKeyStore.getPrivateKey() == null) {
- throw new ASAPSecurityException("asap message is to be signed but no private key - fatal, give up");
- }
- }
- }
-
- private void setupCopyOutputStream() {
- if(this.outputStreamCopy == null) {
- this.outputStreamCopy = new ByteArrayOutputStream();
- // pud will make a detour
- this.effectiveOS = this.outputStreamCopy;
- }
- }
-
- public void sendCmd() throws IOException {
- // send cmd in clear
- PDU_Impl.sendCmd(this.cmd, this.realOS);
- }
-
- public OutputStream getOutputStream() {
- return this.effectiveOS;
- }
-
- public void finish() throws ASAPSecurityException {
- if(this.sign) {
- try {
- // get message as bytes
- byte[] asapMessageAsBytes = this.outputStreamCopy.toByteArray();
- // produce signature
- byte[] signatureBytes = ASAPCryptoAlgorithms.sign(asapMessageAsBytes, this.ASAPKeyStore);
-
- if(this.encrypted) {
- // have to store it - message and signature will be encrypted
- ASAPSerialization.writeByteArray(signatureBytes, this.outputStreamCopy);
- } else {
- // no encryption planned - write clear to stream
- this.realOS.write(asapMessageAsBytes);
- ASAPSerialization.writeByteArray(signatureBytes, this.realOS);
- }
- } catch (IOException e) {
- throw new ASAPSecurityException(this.getLogStart(), e);
- }
- }
-
- if(this.encrypted) {
- // get maybe signed asap message
- byte[] asapMessageAsBytes = this.outputStreamCopy.toByteArray();
-
- ASAPCryptoAlgorithms.writeEncryptedMessagePackage(
- asapMessageAsBytes, this.recipient, this.ASAPKeyStore, this.realOS);
- }
- }
-
- public CharSequence getReceiver() {
- return this.recipient;
- }
-
- ////////////////////////////////// verify
- private class InputStreamCopy extends InputStream {
- private final InputStream is;
- ByteArrayOutputStream copy = new ByteArrayOutputStream();
-
- InputStreamCopy(byte[] bytes, InputStream is) throws IOException {
- // add byte if any
- if(bytes != null && bytes.length > 0) {
- copy.write(bytes);
- }
-
- this.is = is;
- }
-
- @Override
- public int read() throws IOException {
- int read = is.read();
- copy.write(read);
- return read;
- }
-
- byte[] getCopy() {
- return copy.toByteArray();
- }
- }
-
- public InputStream setupCopyInputStream(int flags, InputStream is)
- throws IOException {
-
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-// if(writeInt) {
-// PDU_Impl.sendFlags(flags, baos);
-// }
-
- PDU_Impl.sendFlags(flags, baos);
- //baos.write(flags);
-
- this.inputStreamCopy = new InputStreamCopy(baos.toByteArray(), is);
- return this.inputStreamCopy;
- }
-
- public boolean verify(String sender, InputStream is) throws IOException, ASAPException {
- // try to get senders' public key
- byte[] signedData = this.inputStreamCopy.getCopy();
- byte[] signatureBytes = ASAPSerialization.readByteArray(is);
- // debug break
- boolean wasVerified =
- ASAPCryptoAlgorithms.verify(signedData, signatureBytes, sender, this.ASAPKeyStore);
-
- return wasVerified;
- }
-
- ////////////////////////////////// decrypt
-
- /**
- * Simple idea: We read anything from stream and keep a copy. Later, we figure out
- * if we can encrypt that message or not. Either way, we can keep and redistribute a copy.
- *
- *
- * @param cmd
- * @param is
- * @return
- * @throws IOException
- * @throws ASAPException
- */
- public boolean initDecryption(byte cmd, InputStream is) throws IOException, ASAPException {
- // make a copy of encrypted message - it is redundant. Same data in encryptedMessagePackage
- //InputStream copyStream = this.setupCopyInputStream(cmd, is);
-
- this.encryptedMessagePackage =
- ASAPCryptoAlgorithms.parseEncryptedMessagePackage(is);
- // ASAPCryptoAlgorithms.parseEncryptedMessagePackage(copyStream);
-
- if(this.ASAPKeyStore == null) {
- Log.writeLog(this, "no keystore set: cannot handle encrypted messages");
- return false;
- }
-
- if(this.ASAPKeyStore.isOwner(this.encryptedMessagePackage.getReceiver())) {
- return true;
- }
-
- return false;
- }
-
- ASAPCryptoAlgorithms.EncryptedMessagePackage getEncryptedMessage() throws ASAPSecurityException {
- return this.encryptedMessagePackage;
- /*
- if(this.inputStreamCopy == null) {
- throw new ASAPSecurityException(
- this.getLogStart() + "no copy made, maybe forgot to initialize decryption?");
- }
-
- return this.inputStreamCopy.getCopy();
- */
- }
-
- public InputStream doDecryption() throws ASAPSecurityException {
- if(this.encryptedMessagePackage == null) {
- throw new ASAPSecurityException("forgot to initialize decryption? There are no data");
- }
-
- byte[] decryptedBytes =
- ASAPCryptoAlgorithms.decryptPackage(this.encryptedMessagePackage, this.ASAPKeyStore);
-
- return new ByteArrayInputStream(decryptedBytes);
- }
-
- private String getLogStart() {
- return this.getClass().getSimpleName() + ": ";
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPEncounterList.java b/src/main/java/net/sharksystem/asap/protocol/ASAPEncounterList.java
deleted file mode 100644
index 2729637..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPEncounterList.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import net.sharksystem.asap.ASAPException;
-
-import java.io.IOException;
-import java.util.Set;
-
-public interface ASAPEncounterList {
- /**
- * Provides a set of peer id. There is record of a previous encounter with those peers.
- * @return
- */
- Set getEncounteredPeers();
-
- /**
- * Provide era of last encounter with a peer. The local era, the counting of this peer is returned.
- * @param peerID
- * @return
- * @throws ASAPException There is not such peerID
- */
- int getLocalMostRecentEra(CharSequence peerID) throws ASAPException;
-
- /**
- * Provide the most era from a most recent chunk received by this peer.
- * @param peerID
- * @return
- * @throws ASAPException There is not such peerID
- */
- int getTheirMostRecentEra(CharSequence peerID) throws ASAPException, IOException;
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPExecTimeExceededException.java b/src/main/java/net/sharksystem/asap/protocol/ASAPExecTimeExceededException.java
deleted file mode 100644
index f9b0ebb..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPExecTimeExceededException.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import net.sharksystem.asap.ASAPException;
-
-public class ASAPExecTimeExceededException extends ASAPException {
- public ASAPExecTimeExceededException() {
- super();
- }
-
- public ASAPExecTimeExceededException(String message) {
- super(message);
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java b/src/main/java/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java
deleted file mode 100644
index d5c9a5f..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPOnlineMessageSource.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-public interface ASAPOnlineMessageSource {
- void sendStoredMessages(ASAPConnection asapConnection, OutputStream os) throws IOException;
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPProtocolEngine.java b/src/main/java/net/sharksystem/asap/protocol/ASAPProtocolEngine.java
deleted file mode 100644
index 35166f1..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPProtocolEngine.java
+++ /dev/null
@@ -1,66 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import net.sharksystem.asap.engine.ASAPUndecryptableMessageHandler;
-import net.sharksystem.asap.crypto.ASAPKeyStore;
-import net.sharksystem.utils.Log;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-public abstract class ASAPProtocolEngine {
- protected final ASAP_1_0 protocol;
- protected final InputStream is;
- protected final OutputStream os;
- protected final ASAPUndecryptableMessageHandler undecryptableMessageHandler;
- protected final ASAPKeyStore ASAPKeyStore;
-
- public ASAPProtocolEngine(InputStream is, OutputStream os, ASAP_1_0 protocol,
- ASAPUndecryptableMessageHandler undecryptableMessageHandler,
- ASAPKeyStore ASAPKeyStore) {
- /*
- this.is = new ISWrapper(is);
- this.os = new OSWrapper(os);
- */
- this.is = is;
- this.os = os;
- this.protocol = protocol;
- this.undecryptableMessageHandler = undecryptableMessageHandler;
- this.ASAPKeyStore = ASAPKeyStore;
-
- Log.writeLog(this, "constructor", "is: "
- + is.getClass().getSimpleName() + " | os: " + os.getClass().getSimpleName());
- }
-
- private class ISWrapper extends InputStream {
- private final InputStream is;
-
- ISWrapper(InputStream is) {
- this.is = is;
- }
- @Override
- public int read() throws IOException {
- return is.read();
- }
- public void close() {
- Log.writeLog(this, "wrapper: close called");
- }
- }
-
- private class OSWrapper extends OutputStream {
- private final OutputStream os;
-
- OSWrapper(OutputStream is) {
- this.os = is;
- }
-
- @Override
- public void write(int b) throws IOException {
- this.os.write(b);
- }
-
- public void close() {
- Log.writeLog(this, "wrapper: close called");
- }
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAPSessionImpl.java b/src/main/java/net/sharksystem/asap/protocol/ASAPSessionImpl.java
deleted file mode 100644
index b149a29..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAPSessionImpl.java
+++ /dev/null
@@ -1,557 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import net.sharksystem.asap.ASAP;
-import net.sharksystem.asap.ASAPEncounterConnectionType;
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.engine.ASAPEngine;
-import net.sharksystem.asap.engine.ASAPInternalPeer;
-import net.sharksystem.asap.engine.ASAPUndecryptableMessageHandler;
-import net.sharksystem.asap.engine.EngineSetting;
-import net.sharksystem.utils.Log;
-import net.sharksystem.asap.crypto.ASAPKeyStore;
-
-import java.io.*;
-import java.util.ArrayList;
-import java.util.List;
-
-public class ASAPSessionImpl extends ASAPProtocolEngine
- implements ASAPConnection, Runnable, ThreadFinishedListener {
-
- private final List asapConnectionListener;
- private final ASAPInternalPeer asapInternalPeer;
- private final ThreadFinishedListener threadFinishedListener;
- private final boolean encrypt;
- private final boolean sign;
- private final ASAPEncounterConnectionType connectionType;
- private Thread managementThread = null;
- private final long maxExecutionTime;
- private String encounteredPeer;
-
- private List onlineMessageSources = new ArrayList<>();
- private Thread threadWaiting4StreamsLock;
- private boolean terminated = false;
-
- public ASAPSessionImpl(InputStream is, OutputStream os, ASAPInternalPeer asapInternalPeer,
- ASAP_1_0 protocol, ASAPUndecryptableMessageHandler unencryptableMessageHandler,
- ASAPKeyStore ASAPKeyStore,
- long maxExecutionTime, ASAPConnectionListener asapConnectionListener,
- ThreadFinishedListener threadFinishedListener,
- boolean encrypt, boolean sign, ASAPEncounterConnectionType connectionType) {
-
- super(is, os, protocol, unencryptableMessageHandler, ASAPKeyStore);
-
- this.asapInternalPeer = asapInternalPeer;
- this.maxExecutionTime = maxExecutionTime;
- this.asapConnectionListener = new ArrayList<>();
- this.asapConnectionListener.add(asapConnectionListener);
-
- this.threadFinishedListener = threadFinishedListener;
- this.encrypt = encrypt;
- this.sign = sign;
- this.connectionType = connectionType;
- }
-
- public void addASAPConnectionListener(ASAPConnectionListener asapConnectionListener) {
- this.asapConnectionListener.add(asapConnectionListener);
- }
-
- public void removeASAPConnectionListener(ASAPConnectionListener asapConnectionListener) {
- this.asapConnectionListener.remove(asapConnectionListener);
- }
-
- private String getLogParameter() {
- String s = "to: ";
- s += this.encounteredPeer != null ? this.encounteredPeer : "unknown yet";
- return s;
- }
-
- private void setEncounteredPeer(String remotePeerName) {
- if(this.encounteredPeer == null) {
-
- this.encounteredPeer = remotePeerName;
-
- StringBuilder sb = new StringBuilder();
- sb.append(this.getLogParameter());
- sb.append("set remotePeerName after reading first asap message: ");
- sb.append(remotePeerName);
- Log.startLog(this, sb.toString());
-
- if(this.asapConnectionListener != null) {
- for(ASAPConnectionListener l : this.asapConnectionListener) {
- l.asapConnectionStarted(remotePeerName, this);
- }
- }
- }
- }
-
- @Override
- public CharSequence getEncounteredPeer() {
- return this.encounteredPeer;
- }
-
- @Override
- public void removeOnlineMessageSource(ASAPOnlineMessageSource source) {
- this.onlineMessageSources.remove(source);
- }
-
- public boolean isSigned() {
- return false;
- }
-
- @Override
- public ASAPEncounterConnectionType getASAPEncounterConnectionType() {
- return this.connectionType;
- }
-
- @Override
- public void kill() {
- this.kill(new ASAPException("kill called from outside asap connection"));
- }
-
- public void kill(Exception e) {
- if(!this.terminated) {
- this.terminated = true;
- // kill reader - proved to be useful in a bluetooth environment
- if(this.pduReader != null && this.pduReader.isAlive()) {
- this.pduReader.interrupt();
- }
- if(this.managementThread != null && this.managementThread.isAlive()) {
- this.managementThread.interrupt();
- }
- // inform listener
- if (this.asapConnectionListener != null) {
- for(ASAPConnectionListener l : this.asapConnectionListener) {
- l.asapConnectionTerminated(e, this);
- }
- }
-
- if (this.threadFinishedListener != null) {
- this.threadFinishedListener.finished(Thread.currentThread());
- }
- }
- }
-
- @Override
- public void finished(Thread t) {
- if(this.managementThread != null) {
- this.managementThread.interrupt();
- }
- }
-
- private void terminate(String message, Throwable t) {
- // write log
- StringBuilder sb = new StringBuilder();
- sb.append(message);
- if(t != null) {
- sb.append(" | issued by: ");
- sb.append(t.getClass().getSimpleName());
- sb.append(": ");
- sb.append(t.getLocalizedMessage());
- // debugging
- //t.printStackTrace();
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- t.printStackTrace(new PrintStream(baos));
- sb.append("\n>>>>>>>>>>>>> stack trace:\n");
- sb.append(baos.toString());
- sb.append("<<<<<<<<<<<< stack trace");
- }
- Log.writeLog(this, this.getLogParameter(), sb.toString());
-
- this.kill();
- }
-
- private void sendOnlineMessages() throws IOException {
- List copy = this.onlineMessageSources;
- this.onlineMessageSources = new ArrayList<>();
- while(!copy.isEmpty()) {
- ASAPOnlineMessageSource asapOnline = copy.remove(0);
- StringBuilder sb = new StringBuilder();
- sb.append("going to send online message");
- Log.writeLog(this, this.getLogParameter(), sb.toString());
- asapOnline.sendStoredMessages(this, this.os);
- }
- }
-
- private class OnlineMessageSenderThread extends Thread {
- public void run() {
- try {
- // get exclusive access to streams
- Log.writeLog(this, getLogParameter(), "online sender is going to wait for stream access");
- wait4ExclusiveStreamsAccess();
- Log.writeLog(this, getLogParameter(), "online sender got stream access");
- sendOnlineMessages();
- // prepare a graceful death
- onlineMessageSenderThread = null;
- // are new message waiting in the meantime?
- checkRunningOnlineMessageSender();
- } catch (IOException e) {
- terminate("could not write data into stream", e);
- }
- finally {
- Log.writeLog(this, getLogParameter(), "online sender releases lock");
- releaseStreamsLock();
- }
- }
- }
-
- private OnlineMessageSenderThread onlineMessageSenderThread = null;
- private ASAPPDUReader pduReader = null;
- Thread executor = null;
-
- @Override
- public void addOnlineMessageSource(ASAPOnlineMessageSource source) {
- this.onlineMessageSources.add(source);
- this.checkRunningOnlineMessageSender();
- }
-
- private synchronized void checkRunningOnlineMessageSender() {
- if(this.onlineMessageSenderThread == null
- && this.onlineMessageSources != null && this.onlineMessageSources.size() > 0) {
- this.onlineMessageSenderThread = new OnlineMessageSenderThread();
- this.onlineMessageSenderThread.start();
- }
- }
-
- public void run() {
- ASAP_1_0 protocol = new ASAP_Modem_Impl(this.ASAPKeyStore, this.undecryptableMessageHandler);
-
- try {
- // let engine write their interest - at least management interest is sent which als introduces
- // this peer to the other one
- this.asapInternalPeer.pushInterests(this.os);
- } catch (IOException | ASAPException e) {
- this.terminate("error when pushing interest: ", e);
- //e.printStackTrace();
- return;
- }
-
- /////////////////////////////// read
- while (!this.terminated) {
- this.pduReader = new ASAPPDUReader(protocol, is, this);
- Throwable unexpectedThrowable = null;
- try {
- Log.writeLog(this, this.getLogParameter(), "start reading");
- this.runObservedThread(pduReader, this.maxExecutionTime);
- } catch (ASAPExecTimeExceededException e) {
- Log.writeLog(this, this.getLogParameter(), "reading on stream took longer than allowed");
- }
- catch(Throwable t) {
- unexpectedThrowable = t;
- Log.writeLog(this, this.getLogParameter(), "while reading PDU: "
- + t.getClass().getSimpleName() + ": " + t.getLocalizedMessage());
- }
-
- Log.writeLog(this, this.getLogParameter(), "back from reading");
- if(terminated) break; // thread could be killed in the meantime
-
- if (unexpectedThrowable != null || pduReader.getIoException() != null || pduReader.getAsapException() != null) {
- Log.writeLog(this, this.getLogParameter(), "connection broken");
-
- Throwable problem = pduReader.getIoException() != null ?
- pduReader.getIoException() : pduReader.getAsapException();
-
- if(problem == null) problem = unexpectedThrowable;
-
- try {
- Log.writeLog(this, this.getLogParameter(), "close input stream");
- this.is.close();
- } catch (IOException exception) {
- Log.writeLog(this, this.getLogParameter(),
- "tried to close stream after exception caught: " + exception.getLocalizedMessage());
- }
-
- this.terminate("problem when reading from stream (close asap session and stream): ", problem);
- break;
- }
-
- ASAP_PDU_1_0 asappdu = pduReader.getASAPPDU();
- /////////////////////////////// process
- if(asappdu != null) {
- Log.writeLog(this, this.getLogParameter(),
- "read valid pdu, remember meeting this peer and going to process pdu");
- this.setEncounteredPeer(asappdu.getSender());
-
- EngineSetting engineSettings = null;
- try {
- engineSettings = this.asapInternalPeer.getEngineSettings(asappdu.getFormat());
- } catch(ASAPException e) {
- // can happen with transient messages
- Log.writeLog(this, this.getLogParameter(), "no engine setting - set defaults");
- }
-
- try {
- if(engineSettings == null) {
- ASAPEngine asapEngine = this.asapInternalPeer.getASAPEngine(asappdu.getFormat());
- engineSettings = this.asapInternalPeer.getEngineSettings(asappdu.getFormat());
- engineSettings.engine = asapEngine;
- Log.writeLog(this, this.getLogParameter(), engineSettings.toString());
- }
-
- this.executor = new ASAPPDUExecutor(asappdu,
- this.encounteredPeer, this.is, this.os, engineSettings,
- protocol,this.connectionType, this);
-
- // get exclusive access to streams
- Log.writeLog(this, this.getLogParameter(), "asap pdu executor going to wait for stream access");
- this.wait4ExclusiveStreamsAccess();
- try {
- Log.writeLog(this, this.getLogParameter(), "asap pdu executor got stream access - process pdu");
- this.runObservedThread(executor, maxExecutionTime);
- } catch (ASAPExecTimeExceededException e) {
- Log.writeLog(this, this.getLogParameter(), "asap pdu processing took longer than allowed");
- this.terminate("asap pdu processing took longer than allowed", e);
- break;
- } finally {
- // wake waiting thread if any
- this.releaseStreamsLock();
- Log.writeLog(this, this.getLogParameter(), "asap pdu executor release locks");
- }
- } catch (ASAPException | IOException e) {
- // Log.writeLog(this, this.getLogParameter(), "problem when executing asap received pdu: " + e);
- this.terminate("problem when executing asap received pdu: ", e);
- }
- }
- }
-
- // asap session ended
- }
-
- private Thread threadUsingStreams = null;
- private synchronized Thread getThreadUsingStreams(Thread t) {
- if(this.threadUsingStreams == null) {
- this.threadUsingStreams = t;
- return null;
- }
-
- return this.threadUsingStreams;
- }
-
- // why not simply synchronized(this) { ... }?? OK, that code works but looks complicated (thsc42)
- private void wait4ExclusiveStreamsAccess() {
- // synchronize with other thread using streams
- Thread threadUsingStreams = this.getThreadUsingStreams(Thread.currentThread());
-
- // got lock - go ahead
- if(threadUsingStreams == null) {
- return;
- }
-
- // there is another thread - wait until it dies
- do {
- Log.writeLog(this, this.getLogParameter(), "enter waiting loop for exclusive stream access");
- // wait
- try {
- this.threadWaiting4StreamsLock = Thread.currentThread();
- threadUsingStreams.join();
- } catch (InterruptedException e) {
- Log.writeLog(this, this.getLogParameter(), "woke up from join");
- }
- finally {
- this.threadWaiting4StreamsLock = null;
- }
- // try again
- Log.writeLog(this, this.getLogParameter(), "try to get streams access again");
- threadUsingStreams = this.getThreadUsingStreams(Thread.currentThread());
- } while(threadUsingStreams != null);
- Log.writeLog(this, this.getLogParameter(), "leave waiting loop for exclusive stream access");
- }
-
- private void releaseStreamsLock() {
- this.threadUsingStreams = null; // take me out
- if(this.threadWaiting4StreamsLock != null) {
- Log.writeLog(this, this.getLogParameter(), "wake waiting thread");
- this.threadWaiting4StreamsLock.interrupt();
- }
- }
-
- private void runObservedThread(Thread t, long maxExecutionTime) throws ASAPExecTimeExceededException {
- this.managementThread = Thread.currentThread();
- t.start();
-
- // wait for reader
- try {
- Thread.sleep(maxExecutionTime);
- } catch (InterruptedException e) {
- // was woken up by thread - that's good
- return;
- }
-
- StringBuilder sb = new StringBuilder();
- sb.append("thread (");
- sb.append(t.getClass().getSimpleName());
- sb.append(") exceeded max execution time of ");
- sb.append(maxExecutionTime);
- sb.append(" ms");
-
- throw new ASAPExecTimeExceededException(sb.toString());
- }
-
- private class ASAPPDUExecutor extends Thread {
- private final ASAP_PDU_1_0 asapPDU;
- private final InputStream is;
- private final OutputStream os;
- private final EngineSetting engineSetting;
- private final ASAP_1_0 protocol;
- private final ThreadFinishedListener threadFinishedListener;
- private final String encounteredPeer;
- private final ASAPEncounterConnectionType connectionType;
-
- public ASAPPDUExecutor(ASAP_PDU_1_0 asapPDU, String encounteredPeer, InputStream is, OutputStream os,
- EngineSetting engineSetting, ASAP_1_0 protocol,
- ASAPEncounterConnectionType connectionType, ThreadFinishedListener threadFinishedListener) {
- this.asapPDU = asapPDU;
- this.encounteredPeer = encounteredPeer;
- this.is = is;
- this.os = os;
- this.engineSetting = engineSetting;
- this.protocol = protocol;
- this.connectionType = connectionType;
- this.threadFinishedListener = threadFinishedListener;
-
- StringBuilder sb = new StringBuilder();
- sb.append(getLogParameter());
- sb.append("ASAPPDUExecutor: ");
- sb.append("engine: " + engineSetting.engine.getClass().getSimpleName() + " | ");
- if(engineSetting.listener != null) {
- sb.append("listener: " + engineSetting.listener.getClass().getSimpleName() + " | ");
- }
- sb.append("folder: " + engineSetting.folder);
-
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(), sb.toString());
- }
-
- private void finish() {
- if(this.threadFinishedListener != null) {
- this.threadFinishedListener.finished(this);
- }
- }
-
- public void run() {
- if(engineSetting.engine == null) {
- Log.writeLogErr(this, ASAPSessionImpl.this.getLogParameter(),
- "ASAPPDUExecutor called without engine set - fatal");
- this.finish();
- return;
- }
-
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
- "ASAPPDUExecutor calls engine: " + engineSetting.engine.getClass().getSimpleName());
-
- try {
- switch (asapPDU.getCommand()) {
- // TODO add encrypt / sign as parameter..
- case ASAP_1_0.INTEREST_CMD:
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
- "ASAPPDUExecutor call handleASAPInterest");
- engineSetting.engine.handleASAPInterest(
- (ASAP_Interest_PDU_1_0) asapPDU, this.protocol,
- this.encounteredPeer,
- this.os,
- this.connectionType);
- break;
- case ASAP_1_0.ASSIMILATE_CMD:
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
- "ASAPPDUExecutor call handleASAPAssimilate");
- engineSetting.engine.handleASAPAssimilate(
- (ASAP_AssimilationPDU_1_0) this.asapPDU,
- this.protocol,
- this.encounteredPeer, this.is, this.os,
- this.connectionType,
- this.engineSetting.listener);
- break;
-
- default:
- Log.writeLogErr(this, ASAPSessionImpl.this.getLogParameter(),
- "unknown ASAP command: " + asapPDU.getCommand());
- }
- }
- catch(ASAPException asape) {
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
- "while processing PDU (go ahead): " + asape.getLocalizedMessage());
- }
- catch(IOException ioe) {
- Log.writeLogErr(this, ASAPSessionImpl.this.getLogParameter(),
- "IOException while processing ASAP PDU - close streams: " + ioe.getLocalizedMessage());
- try {
- os.close(); // more important to close than input stream - try first
- is.close();
- } catch (IOException ex) {
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(), ex.getLocalizedMessage());
- //ex.printStackTrace();
- }
- }
- finally {
- this.finish();
- }
- }
- }
-
- /**
- * Waits for one PDU and goes away if read.
- */
- private class ASAPPDUReader extends Thread {
- private final ASAP_1_0 protocol;
- private final InputStream is;
- private final ThreadFinishedListener pduReaderListener;
- private ASAP_PDU_1_0 asapPDU = null;
- private IOException ioException = null;
- private ASAPException asapException = null;
-
- ASAPPDUReader(ASAP_1_0 protocol, InputStream is, ThreadFinishedListener listener) {
- this.protocol = protocol;
- this.is = is;
- this.pduReaderListener = listener;
- }
-
- IOException getIoException() {
- return this.ioException;
- }
-
- ASAPException getAsapException() {
- return this.asapException;
- }
-
- ASAP_PDU_1_0 getASAPPDU() {
- return this.asapPDU;
- }
-
- public void run() {
- try {
- //boolean dropped = false;
- //do {
- //if(dropped) Log.writeLog(this, "dropped pdu: no sufficient encryption");
- this.asapPDU = protocol.readPDU(is);
- //dropped = true;
- //} // refuse lesser security settings and read next pdu
- //while((encrypt && !this.asapPDU.encrypted()) || (sign && !this.asapPDU.verified()));
- } catch (IOException e) {
- this.ioException = e;
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
- "IOException when reading from stream");
- } catch (ASAPException e) {
- Log.writeLog(this, ASAPSessionImpl.this.getLogParameter(),
- "ASAPException when reading from stream");
- this.asapException = e;
- }
- finally {
- if(this.pduReaderListener != null) {
- this.pduReaderListener.finished(this);
- }
- }
- }
- }
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(this.asapInternalPeer.getOwner());
- sb.append(" <--> ");
- if(this.encounteredPeer == null) sb.append("");
- else sb.append(this.encounteredPeer);
- sb.append(" | type: ");
- sb.append(this.connectionType);
- sb.append(" | encrypted: ");
- sb.append(this.encrypt);
- sb.append(" | sign: ");
- sb.append(this.sign);
- return sb.toString();
- }
-}
diff --git a/src/main/java/net/sharksystem/asap/protocol/ASAP_1_0.java b/src/main/java/net/sharksystem/asap/protocol/ASAP_1_0.java
deleted file mode 100644
index 5fc4e86..0000000
--- a/src/main/java/net/sharksystem/asap/protocol/ASAP_1_0.java
+++ /dev/null
@@ -1,229 +0,0 @@
-package net.sharksystem.asap.protocol;
-
-import net.sharksystem.asap.ASAPException;
-import net.sharksystem.asap.ASAPHop;
-import net.sharksystem.asap.ASAPSecurityException;
-import net.sharksystem.asap.crypto.ASAPPoint2PointCryptoSettings;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Descriptions of ASAP protocol data units and some constants
- */
-public interface ASAP_1_0 {
- byte DEFAULT_INITIAL_TTL = 6; // a small world is assumed
-
- int ENCRYPTED_MASK = 0x1; // 0001
- byte ENCRYPTED_CMD = 1;
-
- int CMD_MASK = 0x6; // 0110 - first bit tells if encrypted or not
- byte INTEREST_CMD = 0;
- byte ASSIMILATE_CMD = 2;
-
- String ANY_FORMAT = "ASAP_ANY_FORMAT";
- String ASAP_MANAGEMENT_FORMAT = "asap/control";
- int ERA_NOT_DEFINED = -1;
-
- /*
- OFFER: An peer (optional) in an range of era (optional) offers data for
- an channel (optional) in a format (mandatory)
- */
-
- /**
- * @param peer identifies a peer - can be null
- * @param era - current era of this peer (range 0..2^8) (-1 indicates: no information about era to be transmitted)
- * @param channel describes a channel (can be null)
- * @param format describes format - used to describe an application that can deal with transmitted data format.
- * @param os stream that PDU is to be sent
- * @param signed message is signed
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
-// void offer(CharSequence peer, CharSequence format, CharSequence channel, int era, OutputStream os, boolean signed)
-// throws IOException, ASAPException;
-
- /**
- * @param recipient identifies a peer - can be null
- * @param channel describes a channel (can be null)
- * @param format describes format - used to describe an application that can deal with transmitted data format.
- * @param os stream that PDU is to be sent
- * @param signed message is signed
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
-// void offer(CharSequence recipient, CharSequence format, CharSequence channel, OutputStream os, boolean signed)
-// throws IOException, ASAPException;
-
- /*
- INTEREST: Sender declares an interest for data from a peer (optional) within a range of era (optional) of a
- channel (optional) in a format (mandatory)
- */
-
- /**
- * @param sender identifies sender - can be null
- * @param recipient can be null - no restriction - any encountered peer will get it.
- * @param eraFrom lower limit of era range (-1 means undefined)
- * @param eraTo upper limit of era range (-1 means undefined)
- * @param channel whished / required channel (can be null)
- * @param format describes format - used to describe an application that can deal with transmitted data format.
- * @param os stream that PDU is to be sent
- * @param signed message is signed
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
- void interest(CharSequence sender, CharSequence recipient, CharSequence format,
- CharSequence channel, int eraFrom, int eraTo,
- OutputStream os, boolean signed) throws IOException, ASAPException;
-
- void interest(CharSequence sender, CharSequence recipient, CharSequence format,
- CharSequence channel, int eraFrom, int eraTo,
- OutputStream os, ASAPPoint2PointCryptoSettings cryptoSettings) throws IOException, ASAPException;
-
- void interest(CharSequence sender, CharSequence recipient, CharSequence format,
- CharSequence channel, int eraFrom, int eraTo,
- OutputStream os, ASAPPoint2PointCryptoSettings cryptoSettings,
- boolean asapRoutingAllowed) throws IOException, ASAPException;
-
- /**
- * @param sender identifies sender - can be null
- * @param recipient can be null - no restriction - any encountered peer will get it.
- * @param channel whished / required channel (can be null)
- * @param format describes format - used to describe an application that can deal with transmitted data format.
- * @param os stream that PDU is to be sent
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
- void interest(CharSequence sender, CharSequence recipient, CharSequence format,
- CharSequence channel, OutputStream os) throws IOException, ASAPException;
-
- /**
- * @param sender identifies sender - can be null
- * @param recipient can be null - no restriction - any encountered peer will get it.
- * @param eraFrom lower limit of era range (-1 means undefined)
- * @param eraTo upper limit of era range (-1 means undefined)
- * @param channel whished / required channel (can be null)
- * @param format describes format - used to describe an application that can deal with transmitted data format.
- * @param os stream that PDU is to be sent
- * @param sign sign message when sending
- * @param encrypted encrypt method - of possible
- * @throws IOException
- * @throws ASAPException
- */
- void interest(CharSequence sender, CharSequence recipient, CharSequence format,
- CharSequence channel, int eraFrom, int eraTo,
- OutputStream os, boolean sign, boolean encrypted)
- throws IOException, ASAPException, ASAPSecurityException;
-
- void interest(CharSequence sender, CharSequence recipient, CharSequence format,
- CharSequence channel, int eraFrom, int eraTo,
- OutputStream os, boolean sign, boolean encrypted,
- boolean asapRoutingAllowed, Map encounterMap)
- throws IOException, ASAPException, ASAPSecurityException;
-
- /**
- * @param sender identifies sender - can be null
- * @param channel whished / required channel (can be null)
- * @param format describes format - used to describe an application that can deal with transmitted data format.
- * @param os stream that PDU is to be sent
- * @param signed message is signed
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
- void interest(CharSequence sender, CharSequence format, CharSequence sourcePeer,
- CharSequence channel, OutputStream os, boolean signed, boolean encrypted)
- throws IOException, ASAPException;
-
- /*
- ASSIMILATE: Peer (optional) issues data (mandatory) to a channel (mandatory) in a format (mandatory) of a
- era (optional)
- */
-
- /**
- *
- * @param sender sender (optional, can be null)
- * @param recipient wished recipient (optional, can be null)
- * @param channelUri mandatory
- * @param format mandatory
- * @param offsets applications will probably store a number of messages in a data block. This (optional) list
- * of numbers represents the offset where a new app specific message begins.
- * @param dataIS stream from which are read to be transmitted to recipient mandatory
- * @param os stream that PDU is to be sent
- * @param signed message is signed
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
- void assimilate(CharSequence sender, CharSequence recipient, CharSequence format, CharSequence channelUri, int era,
- long length, List offsets, List asapHops, InputStream dataIS, OutputStream os, boolean signed)
- throws IOException, ASAPException;
-
-
- void assimilate(CharSequence sender, CharSequence recipient, CharSequence format,
- CharSequence channel, int era, long length, List offsets, List asapHopList,
- InputStream dataIS,
- OutputStream os, ASAPPoint2PointCryptoSettings secureSetting) throws IOException, ASAPException;
-
- /**
- *
- * @param sender sender (optional, can be null)
- * @param recipient wished recipient (optional, can be null)
- * @param channelUri mandatory
- * @param format mandatory
- * @param offsets applications will probably store a number of messages in a data block. This (optional) list
- * of numbers represents the offset where a new app specific message begins.
- * @param dataIS stream from which are read to be transmitted to recipient mandatory
- * @param os stream that PDU is to be sent
- * @param signed message is signed
- * @param encrypted encrypt or not
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
- void assimilate(CharSequence sender, CharSequence recipient, CharSequence format, CharSequence channelUri, int era,
- long length, List offsets, List asapHops,
- InputStream dataIS, OutputStream os, boolean signed, boolean encrypted)
- throws IOException, ASAPException;
-
- /**
- *
- * @param sender sender (optional, can be null)
- * @param recipient wished recipient (optional, can be null)
- * @param channel mandatory
- * @param format mandatory
- * @param offsets applications will probably store a number of messages in a data block. This (optional) list
- * of numbers represents the offset where a new app specific message begins.
- * @param data which are read to be transmitted to recipient mandatory
- * @param os stream that PDU is to be sent
- * @param signed message is signed
- * @throws IOException exception during writing on stream
- * @throws ASAPException protocol exception: mandatory parameter missing, invalid combination of parameters, ..
- */
- void assimilate(CharSequence sender, CharSequence recipient, CharSequence format, CharSequence channel, int era,
- List