Skip to content

Commit

Permalink
Merge pull request #6 from Sitrica/beta
Browse files Browse the repository at this point in the history
1.1.1
  • Loading branch information
TheLimeGlass authored Jul 21, 2020
2 parents d232bc4 + ff6a266 commit c16dc53
Show file tree
Hide file tree
Showing 8 changed files with 136 additions and 108 deletions.
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ plugins {

jar.archiveName = project.name + '.jar'
// Add SNAPSHOT to make this publish as a beta.
version '1.1.0'
version '1.1.1'

sourceCompatibility = 1.8

Expand Down
67 changes: 47 additions & 20 deletions src/main/java/com/sitrica/japson/client/JapsonClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ public class JapsonClient extends Japson {

protected long HEARTBEAT = 1000L, DELAY = 1000L; // in milliseconds.

private boolean check, valid = true;
private final Gson gson;

public JapsonClient(int port) throws UnknownHostException {
Expand Down Expand Up @@ -52,30 +53,19 @@ public JapsonClient(InetAddress address, int port, Gson gson) {
super(address, port);
this.gson = gson;
HeartbeatPacket packet = new HeartbeatPacket(password, port);
executor.scheduleAtFixedRate(() -> sendPacket(packet), DELAY, HEARTBEAT, TimeUnit.MILLISECONDS);
executor.scheduleAtFixedRate(() -> {
try {
Boolean success = sendPacket(packet);
if (check && success)
valid = true;
} catch (TimeoutException | InterruptedException | ExecutionException e) {
valid = false;
}
}, DELAY, HEARTBEAT, TimeUnit.MILLISECONDS);
if (debug)
logger.atInfo().log("Started Japson client bound to %s.", address.getHostAddress() + ":" + port);
}

/**
* The amount of milliseconds the heartbeat is set at, must match that of the JapsonClient.
*
* @param heartbeat time in milliseconds.
* @return The JapsonClient for chaining.
*/
public JapsonClient setHeartbeat(long heartbeat) {
this.HEARTBEAT = heartbeat;
return this;
}

public void shutdown() {
executor.shutdown();
}

public void kill() {
executor.shutdownNow();
}

@Override
public JapsonClient setAllowedAddresses(InetAddress... addesses) {
acceptable.clear();
Expand All @@ -95,13 +85,50 @@ public JapsonClient setPassword(String password) {
return this;
}

/**
* The amount of milliseconds the heartbeat is set at, must match that of the JapsonClient.
*
* @param heartbeat time in milliseconds.
* @return The JapsonClient for chaining.
*/
public JapsonClient setHeartbeat(long heartbeat) {
this.HEARTBEAT = heartbeat;
return this;
}

/**
* Will ensure that packets are only sent if heartbeats were successful.
*
* @return The JapsonClient for chaining.
*/
public JapsonClient makeSureConnectionValid() {
this.check = true;
return this;
}

@Override
public JapsonClient setTimeout(int timeout) {
this.TIMEOUT = timeout;
return this;
}

@Override
public JapsonClient enableDebug() {
this.debug = true;
return this;
}

public void shutdown() {
executor.shutdown();
}

public void kill() {
executor.shutdownNow();
}

public <T> T sendPacket(ReturnablePacket<T> japsonPacket) throws TimeoutException, InterruptedException, ExecutionException {
if (!valid)
throw new TimeoutException("No connection to the server. Cancelling sending packet.");
return sendPacket(address, port, japsonPacket, gson);
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.sitrica.japson.client.packets;

import com.google.gson.JsonObject;
import com.sitrica.japson.shared.Packet;
import com.sitrica.japson.shared.ReturnablePacket;

public class HeartbeatPacket extends Packet {
public class HeartbeatPacket extends ReturnablePacket<Boolean> {

private final String password;
private final int port;
Expand All @@ -23,4 +23,9 @@ public JsonObject toJson() {
return object;
}

@Override
public Boolean getObject(JsonObject object) {
return object.has("success");
}

}
37 changes: 21 additions & 16 deletions src/main/java/com/sitrica/japson/server/Connections.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
import com.google.common.cache.RemovalCause;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.sitrica.japson.shared.Executor;
import com.sitrica.japson.shared.Handler;

public class Connections extends Executor {
public class Connections extends Handler {

private final LoadingCache<InetSocketAddress, JapsonConnection> disconnected;
private final List<JapsonConnection> connections = new ArrayList<>();
Expand All @@ -30,7 +31,7 @@ public Connections(JapsonServer japson) {
super(0x00);
this.japson = japson;
disconnected = CacheBuilder.newBuilder()
.expireAfterWrite(japson.getExpiry(), TimeUnit.MINUTES)
.expireAfterWrite(japson.getConnectionExpiry(), TimeUnit.MINUTES)
.maximumSize(1000)
.removalListener(new RemovalListener<InetSocketAddress, JapsonConnection>() {
@Override
Expand Down Expand Up @@ -59,13 +60,13 @@ public JapsonConnection load(InetSocketAddress address) throws Exception {
continue;
listeners.forEach(listener -> listener.onUnresponsive(connection));
connection.unresponsive();
if (connection.getUnresponsiveCount() > japson.getMaxDisconnectAttempts()) {
if (connection.getUnresponsiveCount() > japson.getMaxReconnectAttempts()) {
listeners.forEach(listener -> listener.onDisconnect(connection));
disconnected.put(InetSocketAddress.createUnresolved(connection.getAddress().getHostName(), connection.getPort()), connection);
}
}
connections.removeIf(connection -> connection.getUnresponsiveCount() > japson.getMaxDisconnectAttempts());
}, japson.getHeartbeat(), TimeUnit.MILLISECONDS);
connections.removeIf(connection -> connection.getUnresponsiveCount() > japson.getMaxReconnectAttempts());
}, 1, TimeUnit.SECONDS);
}

public JapsonConnection addConnection(InetAddress address, int port) {
Expand Down Expand Up @@ -97,22 +98,26 @@ public Optional<JapsonConnection> getConnection(InetAddress address, int port) {
}

@Override
public void execute(InetAddress address, int packetPort, JsonObject json) {
public JsonObject handle(InetAddress address, int packetPort, JsonObject json) {
int port = json.get("port").getAsInt();
if (!japson.hasPassword()) {
JapsonConnection connection = addConnection(address, port);
connection.update();
} else {
Optional.ofNullable(json.get("password"))
.ifPresent(password -> {
if (!japson.passwordMatches(password.getAsString())) {
japson.getLogger().atWarning().log("A packet from %s did not match the correct password!", address.getHostName());
return;
}
JapsonConnection connection = addConnection(address, port);
connection.update();
});
Optional<JsonElement> optional = Optional.ofNullable(json.get("password"));
if (!optional.isPresent())
return null;
String password = optional.get().getAsString();
if (!japson.passwordMatches(password)) {
japson.getLogger().atWarning().log("A packet from %s did not match the correct password!", address.getHostName());
return null;
}
JapsonConnection connection = addConnection(address, port);
connection.update();
}
JsonObject returning = new JsonObject();
returning.addProperty("success", true);
return returning;
}

public class JapsonConnection {
Expand Down
78 changes: 35 additions & 43 deletions src/main/java/com/sitrica/japson/server/JapsonServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class JapsonServer extends Japson {
protected final Set<Listener> listeners = new HashSet<>();
private final Set<Integer> ignored = new HashSet<>();

private long TIMEOUT = 3000L, HEARTBEAT = 1000L, DISCONNECT = 5, EXPIRY = 10; // EXPIRY in minutes, DISCONNECT is amount, and rest in milliseconds.
private long RECONNECT = 5, EXPIRY = 10; // EXPIRY in minutes, DISCONNECT is amount.
private final Connections connections;
private final DatagramSocket socket;

Expand Down Expand Up @@ -64,28 +64,35 @@ public JapsonServer(InetAddress address, int port, Gson gson) throws SocketExcep
logger.atInfo().log("Started Japson server bound to %s.", address.getHostAddress() + ":" + port);
}

public JapsonServer setDisconnectAttempts(long disconnect) {
this.DISCONNECT = disconnect;
@Override
public JapsonServer setAllowedAddresses(InetAddress... addesses) {
acceptable.clear();
acceptable.addAll(Sets.newHashSet(addesses));
return this;
}

public Japson registerListeners(Listener... listeners) {
this.listeners.addAll(Sets.newHashSet(listeners));
public JapsonServer setMaxReconnectAttempts(long reconnect) {
this.RECONNECT = reconnect;
return this;
}

public Japson registerListener(Listener listener) {
return registerListeners(listener);
public Japson registerListeners(Listener... listeners) {
this.listeners.addAll(Sets.newHashSet(listeners));
return this;
}

public void addIgnoreDebugPackets(Integer... packets) {
ignored.addAll(Sets.newHashSet(packets));
}

@Override
public JapsonServer setAllowedAddresses(InetAddress... addesses) {
acceptable.clear();
acceptable.addAll(Sets.newHashSet(addesses));
/**
* The amount of minutes to wait before forgetting about a connection.
*
* @param minutes Time in minutes.
* @return The JapsonServer for chaining.
*/
public JapsonServer setConnectionExpiry(long minutes) {
this.EXPIRY = minutes;
return this;
}

Expand All @@ -95,35 +102,18 @@ public JapsonServer setPacketBufferSize(int buffer) {
return this;
}

public Japson registerListener(Listener listener) {
return registerListeners(listener);
}

@Override
public JapsonServer setPassword(String password) {
this.password = password;
return this;
}

@Override
public JapsonServer enableDebug() {
this.debug = true;
return this;
}

/**
* The amount of minutes to wait before forgetting about a connection.
*
* @param expiry time in minutes.
* @return The JapsonServer for chaining.
*/
public JapsonServer setExpiryMinutes(long expiry) {
this.EXPIRY = expiry;
return this;
}

public JapsonServer setHeartbeat(long heartbeat) {
this.HEARTBEAT = heartbeat;
return this;
}

public JapsonServer setTimeout(long timeout) {
public JapsonServer setTimeout(int timeout) {
this.TIMEOUT = timeout;
return this;
}
Expand All @@ -132,8 +122,8 @@ public Set<Integer> getIgnoredPackets() {
return Collections.unmodifiableSet(ignored);
}

public long getMaxDisconnectAttempts() {
return DISCONNECT;
public long getMaxReconnectAttempts() {
return RECONNECT;
}

public Connections getConnections() {
Expand All @@ -144,20 +134,22 @@ public Set<Listener> getListeners() {
return listeners;
}

public FluentLogger getLogger() {
return logger;
public long getConnectionExpiry() {
return EXPIRY;
}

public long getHeartbeat() {
return HEARTBEAT;
@Override
public JapsonServer enableDebug() {
this.debug = true;
return this;
}

public long getTimeout() {
return TIMEOUT;
public FluentLogger getLogger() {
return logger;
}

public long getExpiry() {
return EXPIRY;
public long getTimeout() {
return TIMEOUT;
}

public void shutdown() {
Expand Down
Loading

0 comments on commit c16dc53

Please sign in to comment.