You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.2 KiB
69 lines
2.2 KiB
4 years ago
|
package dev.garrettmills.csx.matterlinkreboot;
|
||
|
|
||
|
import org.apache.http.HttpEntity;
|
||
|
import org.apache.http.client.methods.CloseableHttpResponse;
|
||
|
import org.apache.http.client.methods.HttpGet;
|
||
|
import org.apache.http.client.methods.HttpPost;
|
||
|
import org.apache.http.entity.StringEntity;
|
||
|
import org.apache.http.impl.client.CloseableHttpClient;
|
||
|
import org.apache.http.impl.client.HttpClients;
|
||
|
import org.apache.http.util.EntityUtils;
|
||
|
import org.apache.logging.log4j.LogManager;
|
||
|
import org.apache.logging.log4j.Logger;
|
||
|
|
||
|
import java.io.IOException;
|
||
|
|
||
|
public class MatterbridgeAPIClient {
|
||
|
|
||
|
// Directly reference a log4j logger.
|
||
|
private static final Logger LOGGER = LogManager.getLogger(MatterlinkReboot.MOD_ID);
|
||
|
|
||
|
private static final CloseableHttpClient http = HttpClients.createDefault();
|
||
|
|
||
|
public static final IncomingMessage[] NO_MESSAGES = {};
|
||
|
|
||
|
public static void close() throws IOException {
|
||
|
http.close();
|
||
|
}
|
||
|
|
||
|
public static IncomingMessage[] getMessages() {
|
||
|
String url = MatterbridgeAPIClient.buildURL("messages");
|
||
|
|
||
|
HttpGet req = new HttpGet(url);
|
||
|
|
||
|
try {
|
||
|
CloseableHttpResponse res = http.execute(req);
|
||
|
HttpEntity body = res.getEntity();
|
||
|
|
||
|
if ( body != null ) {
|
||
|
String result = EntityUtils.toString(body);
|
||
|
return IncomingMessage.fromStringArray(result);
|
||
|
}
|
||
|
} catch (Exception e) {
|
||
|
LOGGER.error(e);
|
||
|
}
|
||
|
|
||
|
return NO_MESSAGES;
|
||
|
}
|
||
|
|
||
|
public static void sendMessage(OutgoingMessage message) {
|
||
|
try {
|
||
|
HttpPost post = new HttpPost(buildURL("message"));
|
||
|
StringEntity body = new StringEntity(message.toJSON());
|
||
|
|
||
|
post.setHeader("Content-Type", "application/json");
|
||
|
post.setEntity(body);
|
||
|
|
||
|
http.execute(post);
|
||
|
} catch (Exception e) {
|
||
|
LOGGER.error(e);
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public static String buildURL(String endpoint) {
|
||
|
return MatterlinkRebootConfig.GENERAL.BridgeProtocol.get() + "://"
|
||
|
+ MatterlinkRebootConfig.GENERAL.BridgeHost.get() + ":" + MatterlinkRebootConfig.GENERAL.BridgePort.get()
|
||
|
+ "/api/" + endpoint;
|
||
|
}
|
||
|
}
|