Skip to content

Commit a8645c7

Browse files
committed
Import api from advancedcore
1 parent 2b0e6f5 commit a8645c7

File tree

13 files changed

+848
-0
lines changed

13 files changed

+848
-0
lines changed

SimpleAPI/.settings/org.eclipse.core.resources.prefs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
eclipse.preferences.version=1
22
encoding//src/main/java=Cp1252
3+
encoding//src/main/java/com/bencodez/simpleapi/servercomm/mqtt/MqttServerComm.java=UTF-8
34
encoding//src/main/resources=Cp1252
45
encoding//src/test/java=Cp1252
56
encoding//src/test/resources=Cp1252

SimpleAPI/pom.xml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,16 @@
204204
<version>3.4.1</version>
205205
<scope>compile</scope>
206206
</dependency>
207+
<dependency>
208+
<groupId>org.eclipse.paho</groupId>
209+
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
210+
<version>1.2.5</version>
211+
</dependency>
212+
<dependency>
213+
<groupId>redis.clients</groupId>
214+
<artifactId>jedis</artifactId>
215+
<version>5.0.2</version>
216+
</dependency>
207217
</dependencies>
208218
<profiles>
209219
<profile>
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
package com.bencodez.simpleapi.encryption;
2+
3+
import java.io.File;
4+
import java.io.FileWriter;
5+
import java.io.IOException;
6+
import java.nio.file.Files;
7+
import java.nio.file.Paths;
8+
import java.security.InvalidKeyException;
9+
import java.security.NoSuchAlgorithmException;
10+
import java.util.Base64;
11+
12+
import javax.crypto.Cipher;
13+
import javax.crypto.KeyGenerator;
14+
import javax.crypto.NoSuchPaddingException;
15+
import javax.crypto.SecretKey;
16+
import javax.crypto.spec.SecretKeySpec;
17+
18+
public class EncryptionHandler {
19+
private static Cipher dcipher;
20+
private static Cipher ecipher;
21+
22+
private static SecretKey key;
23+
24+
public EncryptionHandler(String pluginName, File file) {
25+
try {
26+
if (file.exists()) {
27+
loadKey(file);
28+
} else {
29+
generateKey();
30+
save(file);
31+
}
32+
33+
ecipher = Cipher.getInstance("AES");
34+
dcipher = Cipher.getInstance("AES");
35+
36+
// initialize the ciphers with the given key
37+
ecipher.init(Cipher.ENCRYPT_MODE, key);
38+
dcipher.init(Cipher.DECRYPT_MODE, key);
39+
40+
String msg = "This is a classified message!";
41+
String encrypted = encrypt(msg);
42+
String decrypted = decrypt(encrypted);
43+
if (!msg.equals(decrypted)) {
44+
System.out.println(pluginName + ": Encryption/Decryption failed: " + decrypted);
45+
}
46+
} catch (NoSuchAlgorithmException e) {
47+
System.out.println("No Such Algorithm:" + e.getMessage());
48+
e.printStackTrace();
49+
} catch (NoSuchPaddingException e) {
50+
System.out.println("No Such Padding:" + e.getMessage());
51+
e.printStackTrace();
52+
} catch (InvalidKeyException e) {
53+
System.out.println("Invalid Key:" + e.getMessage());
54+
e.printStackTrace();
55+
} catch (Exception e) {
56+
e.printStackTrace();
57+
}
58+
}
59+
60+
public String decrypt(String str) {
61+
try {
62+
// decode with base64 to get bytes
63+
byte[] dec = Base64.getDecoder().decode(str.getBytes());
64+
byte[] utf8 = dcipher.doFinal(dec);
65+
// create new string based on the specified charset
66+
return new String(utf8, "UTF8");
67+
} catch (Exception e) {
68+
e.printStackTrace();
69+
}
70+
return null;
71+
}
72+
73+
public String encrypt(String str) {
74+
try {
75+
// encode the string into a sequence of bytes using the named charset
76+
// storing the result into a new byte array.
77+
byte[] utf8 = str.getBytes("UTF8");
78+
byte[] enc = ecipher.doFinal(utf8);
79+
return Base64.getEncoder().encodeToString(enc);
80+
} catch (Exception e) {
81+
e.printStackTrace();
82+
}
83+
return null;
84+
}
85+
86+
private void generateKey() throws NoSuchAlgorithmException {
87+
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
88+
keyGenerator.init(256); // Use 256-bit AES
89+
key = keyGenerator.generateKey();
90+
}
91+
92+
private void loadKey(File file) throws IOException {
93+
String str = new String(Files.readAllBytes(Paths.get(file.getAbsolutePath())));
94+
key = new SecretKeySpec(Base64.getDecoder().decode(str), "AES");
95+
}
96+
97+
public void save(File file) throws IOException {
98+
FileWriter fileWriter = new FileWriter(file);
99+
fileWriter.write(Base64.getEncoder().withoutPadding().encodeToString(key.getEncoded()));
100+
fileWriter.close();
101+
}
102+
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
package com.bencodez.simpleapi.servercomm.mqtt;
2+
3+
import java.util.UUID;
4+
import java.util.concurrent.ConcurrentHashMap;
5+
import java.util.concurrent.Executors;
6+
import java.util.concurrent.ScheduledExecutorService;
7+
import java.util.concurrent.TimeUnit;
8+
9+
/**
10+
* General-purpose MQTT communication handler with support for RPC and pub/sub.
11+
*/
12+
public class MqttHandler {
13+
14+
public interface MessageHandler {
15+
void onMessage(String topic, String payload);
16+
}
17+
18+
public interface RpcCallback {
19+
void onComplete(RpcResponse response, Exception error);
20+
}
21+
22+
public static class RpcResponse {
23+
private final String requestId;
24+
private final String payload;
25+
26+
public RpcResponse(String requestId, String payload) {
27+
this.requestId = requestId;
28+
this.payload = payload;
29+
}
30+
31+
public String getRequestId() {
32+
return requestId;
33+
}
34+
35+
public String getPayload() {
36+
return payload;
37+
}
38+
}
39+
40+
private final MqttServerComm mqtt;
41+
private final ConcurrentHashMap<String, RpcCallback> pendingRpcs = new ConcurrentHashMap<>();
42+
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
43+
private int defaultQos;
44+
45+
public MqttHandler(MqttServerComm mqtt, int defaultQos) {
46+
this.mqtt = mqtt;
47+
setDefaultQos(defaultQos);
48+
}
49+
50+
public MqttHandler(MqttServerComm mqtt) {
51+
this(mqtt, 2);
52+
}
53+
54+
public void setDefaultQos(int qos) {
55+
if (qos < 0 || qos > 2) {
56+
throw new IllegalArgumentException("QoS must be 0, 1, or 2");
57+
}
58+
this.defaultQos = qos;
59+
}
60+
61+
public void connect() throws Exception {
62+
mqtt.connect();
63+
}
64+
65+
public void disconnect() throws Exception {
66+
mqtt.disconnect();
67+
scheduler.shutdownNow();
68+
}
69+
70+
public boolean isConnected() {
71+
return mqtt.isConnected();
72+
}
73+
74+
public void publish(String topic, String message) throws Exception {
75+
mqtt.publish(topic, message, defaultQos, false);
76+
}
77+
78+
public void subscribe(String topicFilter, MessageHandler handler) throws Exception {
79+
mqtt.subscribe(topicFilter, defaultQos, (topic, msg) -> {
80+
handler.onMessage(topic, new String(msg.getPayload()));
81+
});
82+
}
83+
84+
public void unsubscribe(String topicFilter) throws Exception {
85+
mqtt.unsubscribe(topicFilter);
86+
}
87+
88+
public void request(String topic, String message, long timeoutMillis, RpcCallback callback) throws Exception {
89+
String requestId = UUID.randomUUID().toString();
90+
pendingRpcs.put(requestId, callback);
91+
scheduler.schedule(() -> {
92+
RpcCallback cb = pendingRpcs.remove(requestId);
93+
if (cb != null) {
94+
cb.onComplete(null, new Exception("RPC timeout"));
95+
}
96+
}, timeoutMillis, TimeUnit.MILLISECONDS);
97+
98+
mqtt.publish(topic + "/" + requestId, message, defaultQos, false);
99+
}
100+
101+
public void handleRpcResponse(String topic, String payload) {
102+
String[] parts = topic.split("/");
103+
if (parts.length == 0) return;
104+
String requestId = parts[parts.length - 1];
105+
RpcCallback cb = pendingRpcs.remove(requestId);
106+
if (cb != null) {
107+
cb.onComplete(new RpcResponse(requestId, payload), null);
108+
}
109+
}
110+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package com.bencodez.simpleapi.servercomm.mqtt;
2+
3+
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
4+
import org.eclipse.paho.client.mqttv3.IMqttAsyncClient;
5+
import org.eclipse.paho.client.mqttv3.IMqttToken;
6+
import org.eclipse.paho.client.mqttv3.MqttAsyncClient;
7+
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
8+
import org.eclipse.paho.client.mqttv3.MqttException;
9+
import org.eclipse.paho.client.mqttv3.MqttMessage;
10+
11+
/**
12+
* Very basic MQTT client wrapper using Eclipse Paho.
13+
* Provides connect/disconnect, publish, subscribe, and serverId access.
14+
*/
15+
public class MqttServerComm {
16+
17+
private final String serverId;
18+
private final IMqttAsyncClient client;
19+
20+
public MqttServerComm(String serverId, String brokerUrl, MqttConnectOptions opts) throws MqttException {
21+
this.serverId = serverId;
22+
this.client = new MqttAsyncClient(brokerUrl, serverId);
23+
this.client.connect(opts).waitForCompletion();
24+
}
25+
26+
public String getServerId() {
27+
return serverId;
28+
}
29+
30+
public void connect() throws MqttException {
31+
if (!client.isConnected()) {
32+
client.reconnect();
33+
}
34+
}
35+
36+
public void disconnect() throws MqttException {
37+
if (client.isConnected()) {
38+
client.disconnect();
39+
}
40+
}
41+
42+
public boolean isConnected() {
43+
return client.isConnected();
44+
}
45+
46+
public void publish(String topic, String payload, int qos, boolean retained) throws MqttException {
47+
MqttMessage msg = new MqttMessage(payload.getBytes());
48+
msg.setQos(qos);
49+
msg.setRetained(retained);
50+
client.publish(topic, msg);
51+
}
52+
53+
public void subscribe(String topicFilter, int qos, MessageListener listener) throws MqttException {
54+
client.subscribe(topicFilter, qos, null, new IMqttActionListener() {
55+
@Override
56+
public void onSuccess(IMqttToken asyncActionToken) { /* no‑op */ }
57+
@Override
58+
public void onFailure(IMqttToken asyncActionToken, Throwable exception) { exception.printStackTrace(); }
59+
}, (topic, msg) -> listener.messageArrived(topic, msg));
60+
}
61+
62+
public void unsubscribe(String topicFilter) throws MqttException {
63+
client.unsubscribe(topicFilter);
64+
}
65+
66+
/** Simple bridge from Paho’s callback to our handler. */
67+
public interface MessageListener {
68+
void messageArrived(String topic, MqttMessage message) throws Exception;
69+
}
70+
}

0 commit comments

Comments
 (0)