Added Telegram Bot class and refactored REST class
This commit is contained in:
parent
bd1bb168da
commit
55c0d739be
6 changed files with 166 additions and 34 deletions
|
|
@ -99,7 +99,7 @@ public class HttpClient implements AutoCloseable {
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* If set to true the the request will contain the full URL instead of only the path to the page.
|
* If set to true the request will contain the full URL instead of only the path to the page.
|
||||||
*/
|
*/
|
||||||
public void setAbsoluteURL(boolean absoluteURL) {
|
public void setAbsoluteURL(boolean absoluteURL) {
|
||||||
this.absoluteURL = absoluteURL;
|
this.absoluteURL = absoluteURL;
|
||||||
|
|
|
||||||
77
src/zutil/net/ws/app/TelegramBot.java
Normal file
77
src/zutil/net/ws/app/TelegramBot.java
Normal file
|
|
@ -0,0 +1,77 @@
|
||||||
|
package zutil.net.ws.app;
|
||||||
|
|
||||||
|
import zutil.io.IOUtil;
|
||||||
|
import zutil.log.LogUtil;
|
||||||
|
import zutil.net.http.HttpClient;
|
||||||
|
import zutil.net.http.HttpHeader;
|
||||||
|
import zutil.net.http.HttpURL;
|
||||||
|
import zutil.net.ws.rest.RESTClient;
|
||||||
|
import zutil.parser.DataNode;
|
||||||
|
import zutil.parser.json.JSONParser;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.net.MalformedURLException;
|
||||||
|
import java.util.logging.Level;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Class connects to the Telegram API endpoints to send messages.
|
||||||
|
*
|
||||||
|
* @see <a href="https://core.telegram.org/bots/api">Telegram API Documentation</a>
|
||||||
|
*/
|
||||||
|
public class TelegramBot {
|
||||||
|
private static final Logger logger = LogUtil.getLogger();
|
||||||
|
private static String TELEGRAM_API_URL = "https://api.telegram.org";
|
||||||
|
|
||||||
|
/** Token used to authenticate to the API **/
|
||||||
|
private String token;
|
||||||
|
|
||||||
|
/**
|
||||||
|
*
|
||||||
|
* @param token token used to authenticate to the API
|
||||||
|
*/
|
||||||
|
public TelegramBot(String token) {
|
||||||
|
this.token = token;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String getBaseUrl() {
|
||||||
|
return TELEGRAM_API_URL + "/bot" + token;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Send a message to a user or group.
|
||||||
|
*
|
||||||
|
* @param chatId a chat ID number, this could be the ID of a user or a group.
|
||||||
|
* @param msg the message to send in the chat.
|
||||||
|
*/
|
||||||
|
public void sendMessage(long chatId, String msg) {
|
||||||
|
try {
|
||||||
|
HttpURL url = new HttpURL(getBaseUrl() + "/sendMessage");
|
||||||
|
url.setParameter("chat_id", String.valueOf(chatId));
|
||||||
|
url.setParameter("text", msg);
|
||||||
|
|
||||||
|
DataNode reponse = RESTClient.get(url);
|
||||||
|
|
||||||
|
} catch (MalformedURLException e) {
|
||||||
|
logger.log(Level.SEVERE, "Failed to generate API URL.", e);
|
||||||
|
} catch (IOException e) {
|
||||||
|
logger.log(Level.SEVERE, "Failed to send API request.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Use this method to receive incoming updates using long polling (wiki). Returns an Array of Update objects.
|
||||||
|
*/
|
||||||
|
public void getUpdates() {
|
||||||
|
try {
|
||||||
|
HttpURL url = new HttpURL(getBaseUrl() + "/getUpdates");
|
||||||
|
|
||||||
|
DataNode reponse = RESTClient.get(url);
|
||||||
|
|
||||||
|
} catch (MalformedURLException e) {
|
||||||
|
logger.log(Level.SEVERE, "Failed to generate API URL.", e);
|
||||||
|
} catch (IOException e) {
|
||||||
|
logger.log(Level.SEVERE, "Failed to send API request.", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
75
src/zutil/net/ws/rest/RESTClient.java
Normal file
75
src/zutil/net/ws/rest/RESTClient.java
Normal file
|
|
@ -0,0 +1,75 @@
|
||||||
|
package zutil.net.ws.rest;
|
||||||
|
|
||||||
|
import zutil.io.IOUtil;
|
||||||
|
import zutil.log.LogUtil;
|
||||||
|
import zutil.net.http.HttpClient;
|
||||||
|
import zutil.net.http.HttpHeader;
|
||||||
|
import zutil.net.http.HttpURL;
|
||||||
|
import zutil.net.ws.WSInterface.RequestType;
|
||||||
|
import zutil.parser.DataNode;
|
||||||
|
import zutil.parser.json.JSONParser;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A class for making basic REST request to a remote service.
|
||||||
|
*/
|
||||||
|
public class RESTClient {
|
||||||
|
private static Logger logger = LogUtil.getLogger();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* See {@link #request(RequestType, HttpURL)} for details.
|
||||||
|
*/
|
||||||
|
public static DataNode get(HttpURL url) throws IOException {
|
||||||
|
return request(RequestType.GET, url);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* See {@link #request(RequestType, HttpURL)} for details.
|
||||||
|
*/
|
||||||
|
public static DataNode post(HttpURL url) throws IOException {
|
||||||
|
return request(RequestType.POST, url);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* See {@link #request(RequestType, HttpURL)} for details.
|
||||||
|
*/
|
||||||
|
public static DataNode put(HttpURL url) throws IOException {
|
||||||
|
return request(RequestType.POST, url);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* See {@link #request(RequestType, HttpURL)} for details.
|
||||||
|
*/
|
||||||
|
public static DataNode patch(HttpURL url) throws IOException {
|
||||||
|
return request(RequestType.PATCH, url);
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* See {@link #request(RequestType, HttpURL)} for details.
|
||||||
|
*/
|
||||||
|
public static DataNode delete(HttpURL url) throws IOException {
|
||||||
|
return request(RequestType.DELETE, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This method will do a REST request to the specified remote endpoint.
|
||||||
|
*
|
||||||
|
* @param type is the HTTP type of the request.
|
||||||
|
* @param url is the URL to the endpoint including URL parameters.
|
||||||
|
* @return a DataNode object parsed from the JSON response from the REST endpoint.
|
||||||
|
*/
|
||||||
|
public static DataNode request(RequestType type, HttpURL url) throws IOException {
|
||||||
|
HttpClient request = new HttpClient(String.valueOf(type));
|
||||||
|
request.setURL(url);
|
||||||
|
|
||||||
|
logger.fine("Sending request for: " + url);
|
||||||
|
HttpHeader responseHeader = request.send();
|
||||||
|
logger.fine("Received response code: " + responseHeader.getResponseStatusCode());
|
||||||
|
|
||||||
|
String responseStr = IOUtil.readContentAsString(request.getResponseInputStream());
|
||||||
|
request.close();
|
||||||
|
logger.finest("Received response body:");
|
||||||
|
logger.finest(responseStr);
|
||||||
|
|
||||||
|
DataNode json = JSONParser.read(responseStr);
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -34,7 +34,7 @@ import java.net.URL;
|
||||||
import java.util.logging.Logger;
|
import java.util.logging.Logger;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* This is an factory that generates clients for web services
|
* This is a factory that generates clients for web services
|
||||||
*
|
*
|
||||||
* @author Ziver
|
* @author Ziver
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -24,16 +24,13 @@
|
||||||
|
|
||||||
package zutil.net.ws.rest;
|
package zutil.net.ws.rest;
|
||||||
|
|
||||||
import zutil.io.IOUtil;
|
|
||||||
import zutil.log.LogUtil;
|
import zutil.log.LogUtil;
|
||||||
import zutil.net.http.HttpClient;
|
|
||||||
import zutil.net.http.HttpHeader;
|
|
||||||
import zutil.net.http.HttpURL;
|
import zutil.net.http.HttpURL;
|
||||||
|
import zutil.net.ws.WSInterface.RequestType;
|
||||||
import zutil.net.ws.WSMethodDef;
|
import zutil.net.ws.WSMethodDef;
|
||||||
import zutil.net.ws.WSParameterDef;
|
import zutil.net.ws.WSParameterDef;
|
||||||
import zutil.net.ws.WebServiceDef;
|
import zutil.net.ws.WebServiceDef;
|
||||||
import zutil.parser.DataNode;
|
import zutil.parser.DataNode;
|
||||||
import zutil.parser.json.JSONParser;
|
|
||||||
|
|
||||||
import java.lang.reflect.InvocationHandler;
|
import java.lang.reflect.InvocationHandler;
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
|
|
@ -72,31 +69,15 @@ public class RESTClientInvocationHandler implements InvocationHandler {
|
||||||
WSMethodDef methodDef = wsDef.getMethod(method.getName());
|
WSMethodDef methodDef = wsDef.getMethod(method.getName());
|
||||||
HttpURL url = generateRESTRequest(methodDef, args);
|
HttpURL url = generateRESTRequest(methodDef, args);
|
||||||
|
|
||||||
String requestType = "GET";
|
RequestType requestType = RequestType.GET;
|
||||||
if (methodDef.getRequestType() != null)
|
if (methodDef.getRequestType() != null) {
|
||||||
requestType = methodDef.getRequestType().toString();
|
requestType = RequestType.valueOf(methodDef.getRequestType().toString());
|
||||||
|
}
|
||||||
|
|
||||||
// Send request
|
// Send request
|
||||||
|
|
||||||
HttpClient request = new HttpClient(HttpClient.HttpRequestType.POST);
|
DataNode jsonResponse = RESTClient.request(requestType, url);
|
||||||
request.setURL(url);
|
Object rspObj = parseRESTResponse(methodDef, jsonResponse);
|
||||||
request.setType(requestType);
|
|
||||||
|
|
||||||
logger.fine("Sending request for: " + url);
|
|
||||||
HttpHeader response = request.send();
|
|
||||||
logger.fine("Received response(" + response.getResponseStatusCode() + ")");
|
|
||||||
|
|
||||||
// Parse response
|
|
||||||
|
|
||||||
String rspStr = IOUtil.readContentAsString(request.getResponseInputStream());
|
|
||||||
request.close();
|
|
||||||
|
|
||||||
//if (logger.isLoggable(Level.FINEST)) {
|
|
||||||
System.out.println("********** Response: " + url);
|
|
||||||
System.out.println(rspStr);
|
|
||||||
//}
|
|
||||||
|
|
||||||
Object rspObj = parseRESTResponse(methodDef, rspStr);
|
|
||||||
return rspObj;
|
return rspObj;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -119,13 +100,12 @@ public class RESTClientInvocationHandler implements InvocationHandler {
|
||||||
return url;
|
return url;
|
||||||
}
|
}
|
||||||
|
|
||||||
private Object parseRESTResponse(WSMethodDef methodDef, String str) {
|
private Object parseRESTResponse(WSMethodDef methodDef, DataNode jsonResponse) {
|
||||||
DataNode json = JSONParser.read(str);
|
|
||||||
List<WSParameterDef> outputs = methodDef.getOutputs();
|
List<WSParameterDef> outputs = methodDef.getOutputs();
|
||||||
|
|
||||||
if (outputs.size() == 1) {
|
if (outputs.size() == 1) {
|
||||||
if (outputs.get(0).getParamClass().isAssignableFrom(DataNode.class))
|
if (outputs.get(0).getParamClass().isAssignableFrom(DataNode.class))
|
||||||
return json;
|
return jsonResponse;
|
||||||
}
|
}
|
||||||
|
|
||||||
throw new RuntimeException("WS JSON return type currently not supported: " + methodDef);
|
throw new RuntimeException("WS JSON return type currently not supported: " + methodDef);
|
||||||
|
|
|
||||||
|
|
@ -37,7 +37,7 @@ import static org.junit.Assert.assertNotNull;
|
||||||
*/
|
*/
|
||||||
public class RESTClientTest {
|
public class RESTClientTest {
|
||||||
|
|
||||||
public interface OpenWeartherMap extends WSInterface {
|
public interface OpenWeatherMap extends WSInterface {
|
||||||
|
|
||||||
@WSPath("")
|
@WSPath("")
|
||||||
int weather(@WSParamName("q") String city);
|
int weather(@WSParamName("q") String city);
|
||||||
|
|
@ -46,9 +46,9 @@ public class RESTClientTest {
|
||||||
|
|
||||||
//@Test
|
//@Test
|
||||||
public void testREST() throws MalformedURLException {
|
public void testREST() throws MalformedURLException {
|
||||||
OpenWeartherMap restObj = RESTClientFactory.createClient(
|
OpenWeatherMap restObj = RESTClientFactory.createClient(
|
||||||
new URL("http://samples.openweathermap.org/data/2.5/"),
|
new URL("http://samples.openweathermap.org/data/2.5/"),
|
||||||
OpenWeartherMap.class);
|
OpenWeatherMap.class);
|
||||||
|
|
||||||
assertNotNull(restObj.weather("London,uk"));
|
assertNotNull(restObj.weather("London,uk"));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue