diff --git a/Jenkinsfile b/Jenkinsfile index 6e3d75eb..3288335d 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -30,6 +30,7 @@ node('docker') { } stage('Test') { + sh "mvn -Pdocker clean verify" } junit testResults: 'target/surefire-reports/TEST-*.xml' diff --git a/pom.xml b/pom.xml index 155cd24b..66f55a89 100644 --- a/pom.xml +++ b/pom.xml @@ -15,6 +15,8 @@ UTF-8 1.653 7 + + false 2.13 1.11 @@ -154,9 +156,19 @@ org.apache.maven.plugins maven-failsafe-plugin + + integration-test + verify + + + ${failsafeArgLine} + ${skipITs} + + **/*IT.class + - ldap://127.0.0.1:${rocket.port} + http://127.0.0.1:${rocket.port} @@ -342,7 +354,9 @@ JIRA - https://issues.jenkins-ci.org/browse/JENKINS-40595?jql=project%20%3D%20JENKINS%20AND%20component%20%3D%20rocket-chat-notifier-plugin + + https://issues.jenkins-ci.org/browse/JENKINS-40595?jql=project%20%3D%20JENKINS%20AND%20component%20%3D%20rocket-chat-notifier-plugin + diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/RocketChatNotifier.java b/src/main/java/jenkins/plugins/rocketchatnotifier/RocketChatNotifier.java index c8074256..12f7a6a9 100644 --- a/src/main/java/jenkins/plugins/rocketchatnotifier/RocketChatNotifier.java +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/RocketChatNotifier.java @@ -15,6 +15,7 @@ import hudson.util.FormValidation; import jenkins.model.JenkinsLocationConfiguration; import jenkins.plugins.rocketchatnotifier.rocket.RocketChatClient; +import jenkins.plugins.rocketchatnotifier.rocket.RocketChatClientImpl; import net.sf.json.JSONObject; import org.apache.commons.lang.StringUtils; import org.kohsuke.stapler.DataBoundConstructor; @@ -298,7 +299,7 @@ public boolean configure(StaplerRequest sr, JSONObject formData) throws FormExce } RocketChatClient getRocketChatClient(final String rocketServerURL, final String username, final String password) { - return new RocketChatClient(rocketServerURL, username, password); + return new RocketChatClientImpl(rocketServerURL, username, password); } @Override diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/RocketClientImpl.java b/src/main/java/jenkins/plugins/rocketchatnotifier/RocketClientImpl.java index 41440d8a..6c2cf6e5 100644 --- a/src/main/java/jenkins/plugins/rocketchatnotifier/RocketClientImpl.java +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/RocketClientImpl.java @@ -2,6 +2,7 @@ import jenkins.plugins.rocketchatnotifier.rocket.RocketChatClient; +import jenkins.plugins.rocketchatnotifier.rocket.RocketChatClientImpl; import sun.security.validator.ValidatorException; import java.io.IOException; @@ -22,7 +23,7 @@ public class RocketClientImpl implements RocketClient { public RocketClientImpl(String serverUrl, String user, String password, String channel) { - this.client = new RocketChatClient(serverUrl + API_PATH, user, password); + this.client = new RocketChatClientImpl(serverUrl + API_PATH, user, password); this.channel = channel; } diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/model/Response.java b/src/main/java/jenkins/plugins/rocketchatnotifier/model/Response.java new file mode 100644 index 00000000..902ef78f --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/model/Response.java @@ -0,0 +1,72 @@ +package jenkins.plugins.rocketchatnotifier.model; + + +public class Response { + private boolean success; + private Message[] messages; + private Message message; + private User[] users; + private User user; + private Room[] channels; + private Room channel; + + public void setSuccess(boolean result) { + this.success = result; + } + + public boolean isSuccessful() { + return this.success; + } + + public void setMessages(final Message[] messages) { + this.messages = messages.clone(); + } + + public Message[] getMessages() { + return this.messages.clone(); + } + + public boolean isMessages() { + return this.messages != null; + } + + public void setMessage(final Message message) { + this.message = message; + } + + public Message getMessage() { + return this.message; + } + + public boolean isMessage() { + return this.message != null; + } + + public void setUsers(final User[] users) { + this.users = users.clone(); + } + + public User[] getUsers() { + return this.users.clone(); + } + + public Room[] getChannels() { + return this.channels.clone(); + } + + public boolean isUsers() { + return this.users != null; + } + + public void setUser(final User user) { + this.user = user; + } + + public User getUser() { + return this.user; + } + + public boolean isUser() { + return this.user != null; + } +} diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/model/User.java b/src/main/java/jenkins/plugins/rocketchatnotifier/model/User.java new file mode 100644 index 00000000..35c84286 --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/model/User.java @@ -0,0 +1,139 @@ +package jenkins.plugins.rocketchatnotifier.model; + +import java.util.Date; + +/** + * Represents a Rocket.Chat user. + * + * @author Bradley Hilton (graywolf336) + * @version 0.0.1 + * @since 0.1.0 + */ +public class User extends Identified { + private String username, name; + private Date createdAt, lastLogin; + private boolean active; + private int utcOffset; + + /** + * Sets the username of this user. + * + * @param username of this user + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Gets the username of this user. + * + * @return user of this user + */ + public String getUsername() { + return this.username; + } + + /** + * Sets the display name of this user. + * + * @param name of this user + */ + public void setName(String name) { + this.name = name; + } + + /** + * Gets the display name of this user. + * + * @return the name of this user + */ + public String getName() { + return this.name; + } + + /** + * Sets the created date of this user. + * + * @param date this user was created + */ + public void setCreatedAt(Date date) { + this.createdAt = new Date(date.getTime()); + } + + /** + * Gets the date this user was created + * + * @return creation date of this user + */ + public Date getCreatedAt() { + return new Date(this.createdAt.getTime()); + } + + /** + * Sets the last login date of this user. + * + * @param date this user last logged in + */ + public void setLastLogin(Date date) { + this.lastLogin = new Date(date.getTime()); + } + + /** + * Gets the date this user last logged in + * + * @return last logged in date + */ + public Date getLastLogin() { + return new Date(this.lastLogin.getTime()); + } + + /** + * Sets whether this user is active or not + * + * @param active whether this user is active or not + */ + public void setActive(boolean active) { + this.active = active; + } + + /** + * Gets whether this user is active or not, non-active users can not log in. + * + * @return whether this user is logged in or not + */ + public boolean getActive() { + return this.active; + } + + /** + * Checks whether this user is active or not, non-active users can not log in. + * + * @return whether this user is logged in or not + */ + public boolean isActive() { + return this.active; + } + + /** + * Sets the UTC Offset of this user. + * + * @param offset of this user + */ + public void setUtcOffset(int offset) { + this.utcOffset = offset; + } + + /** + * Gets the UTC Offset of this user + * + * @return utc offset for this user + */ + public int getUtcOffset() { + return this.utcOffset; + } +} + +/* + * "type": "user",//TODO: Convert to ENUM "status": "offline",//TODO: Convert to ENUM "roles": [ + * "user" ], "statusConnection": "offline",//TODO: Convert to ENUM + */ diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/HttpMethods.java b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/HttpMethods.java new file mode 100644 index 00000000..2783e091 --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/HttpMethods.java @@ -0,0 +1,13 @@ +package jenkins.plugins.rocketchatnotifier.rocket; + + +/** + * Represents the http methods. + * + * @author Bradley Hilton (graywolf336) + * @version 1.0.0 + * @since 0.1.0 + */ +public enum HttpMethods { + GET, POST, PUT, DELETE, PATCH +} diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/LegacyRocketChatClient.java b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/LegacyRocketChatClient.java new file mode 100644 index 00000000..8ac8fe78 --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/LegacyRocketChatClient.java @@ -0,0 +1,151 @@ +package jenkins.plugins.rocketchatnotifier.rocket; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.Unirest; +import com.mashape.unirest.http.exceptions.UnirestException; +import jenkins.plugins.rocketchatnotifier.model.Message; +import jenkins.plugins.rocketchatnotifier.model.Room; +import jenkins.plugins.rocketchatnotifier.model.Rooms; +import org.json.JSONObject; +import sun.security.validator.ValidatorException; + +import java.io.IOException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Created by mreinhardt on 26.12.16. + */ +public class LegacyRocketChatClient { + private final String serverUrl; + private final String user; + private final String password; + private String xAuthToken; + private String xUserId; + private ObjectMapper jacksonObjectMapper; + Map roomCache = new HashMap(); + JSONObject lazyVersions; + + public LegacyRocketChatClient(String serverUrl, String user, String password) { + this.serverUrl = serverUrl; + this.user = user; + this.password = password; + this.jacksonObjectMapper = new ObjectMapper(); + this.jacksonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + public Set getPublicRooms() throws IOException { + Rooms rooms = (Rooms) this.authenticatedGet("publicRooms", Rooms.class); + HashSet ret = new HashSet(); + this.roomCache.clear(); + Room[] roomsArray = rooms.getRooms(); + int numberOfRooms = roomsArray.length; + + for (int i = 0; i < numberOfRooms; ++i) { + Room room = roomsArray[i]; + ret.add(room); + this.roomCache.put(room.getName(), room); + } + + return ret; + } + + private T authenticatedGet(String method, Class reponseClass) throws IOException { + try { + HttpResponse e = Unirest.get(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).asString(); + if (e.getStatus() == 401) { + this.login(); + return this.authenticatedGet(method, reponseClass); + } else { + return this.jacksonObjectMapper.readValue((String) e.getBody(), reponseClass); + } + } catch (UnirestException var4) { + throw new IOException(var4); + } + } + + private void authenticatedPost(String method, Object request) throws ValidatorException, IOException { + this.authenticatedPost(method, request, (Class) null); + } + + private T authenticatedPost(String method, Object request, Class reponseClass) throws ValidatorException, IOException { + try { + HttpResponse e = Unirest.post(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).header("Content-Type", "application/json").body(this.jacksonObjectMapper.writeValueAsString(request)).asString(); + if (e.getStatus() == 401) { + this.login(); + return this.authenticatedPost(method, request, reponseClass); + } else { + return reponseClass == null ? null : this.jacksonObjectMapper.readValue((String) e.getBody(), reponseClass); + } + } catch (UnirestException var5) { + throw new IOException(var5); + } + } + + void login() throws UnirestException { + HttpResponse asJson = Unirest.post(this.serverUrl + "login").field("user", this.user).field("password", this.password).asJson(); + if (asJson.getStatus() == 401) { + throw new UnirestException("401 - Unauthorized"); + } else { + JSONObject data = ((JsonNode) asJson.getBody()).getObject().getJSONObject("data"); + this.xAuthToken = data.getString("authToken"); + this.xUserId = data.getString("userId"); + } + } + + public void logout() throws IOException { + try { + Unirest.post(this.serverUrl + "logout").header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).asJson(); + } catch (UnirestException var2) { + throw new IOException(var2); + } + } + + public String getApiVersion() throws IOException { + return this.getVersions().getString("api"); + } + + public String getRocketChatVersion() throws IOException { + return this.getVersions().getString("rocketchat"); + } + + private JSONObject getVersions() throws IOException { + if (this.lazyVersions == null) { + try { + this.lazyVersions = ((JsonNode) Unirest.get(this.serverUrl + "version").asJson().getBody()).getObject().getJSONObject("versions"); + } catch (UnirestException var2) { + throw new IOException(var2); + } + } + + return this.lazyVersions; + } + + public void send(String roomName, String message) throws ValidatorException, IOException { + Room room = this.getRoom(roomName); + if (room == null) { + throw new IOException(String.format("unknown room : %s", new Object[]{roomName})); + } else { + this.send(room, message); + } + } + + public void send(Room room, String message) throws ValidatorException, IOException { + this.authenticatedPost("rooms/" + room.get_id() + "/send", new Message(message)); + } + + public Room getRoom(String room) throws IOException { + Room ret = (Room) this.roomCache.get(room); + if (ret == null) { + this.getPublicRooms(); + ret = (Room) this.roomCache.get(room); + } + + return ret; + } +} diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClient.java b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClient.java index 4077829d..9ab3df26 100644 --- a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClient.java +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClient.java @@ -1,151 +1,43 @@ package jenkins.plugins.rocketchatnotifier.rocket; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.mashape.unirest.http.HttpResponse; -import com.mashape.unirest.http.JsonNode; -import com.mashape.unirest.http.Unirest; -import com.mashape.unirest.http.exceptions.UnirestException; -import jenkins.plugins.rocketchatnotifier.model.Message; import jenkins.plugins.rocketchatnotifier.model.Room; -import jenkins.plugins.rocketchatnotifier.model.Rooms; -import org.json.JSONObject; +import jenkins.plugins.rocketchatnotifier.model.User; import sun.security.validator.ValidatorException; import java.io.IOException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; /** - * Created by mreinhardt on 26.12.16. + * */ -public class RocketChatClient { - private final String serverUrl; - private final String user; - private final String password; - private String xAuthToken; - private String xUserId; - private ObjectMapper jacksonObjectMapper; - Map roomCache = new HashMap(); - JSONObject lazyVersions; +public interface RocketChatClient { + /** + * Gets all of the users from a Rocket.Chat server, if you have a ton this will + * take some time. + * + * @return an array of {@link User}s + * @throws IOException is thrown if there was a problem connecting, including if the result + * wasn't successful + */ + User[] getUsers() throws IOException; + + /** + * Retrieves a {@link User} from the Rocket.Chat server. + * + * @param userId of the user to retrieve + * @return an instance of the {@link User} + * @throws IOException is thrown if there was a problem connecting, including if the result + * wasn't successful or there is no user + */ + User getUser(String userId) throws IOException; + + /** + * @return + * @throws IOException + */ + Room[] getChannels() throws IOException; + + void send(Room room, String message) throws ValidatorException, IOException; + + void send(String room, String message) throws ValidatorException, IOException; - public RocketChatClient(String serverUrl, String user, String password) { - this.serverUrl = serverUrl; - this.user = user; - this.password = password; - this.jacksonObjectMapper = new ObjectMapper(); - this.jacksonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - } - - public Set getPublicRooms() throws IOException { - Rooms rooms = (Rooms) this.authenticatedGet("publicRooms", Rooms.class); - HashSet ret = new HashSet(); - this.roomCache.clear(); - Room[] roomsArray = rooms.getRooms(); - int numberOfRooms = roomsArray.length; - - for (int i = 0; i < numberOfRooms; ++i) { - Room room = roomsArray[i]; - ret.add(room); - this.roomCache.put(room.getName(), room); - } - - return ret; - } - - private T authenticatedGet(String method, Class reponseClass) throws IOException { - try { - HttpResponse e = Unirest.get(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).asString(); - if (e.getStatus() == 401) { - this.login(); - return this.authenticatedGet(method, reponseClass); - } else { - return this.jacksonObjectMapper.readValue((String) e.getBody(), reponseClass); - } - } catch (UnirestException var4) { - throw new IOException(var4); - } - } - - private void authenticatedPost(String method, Object request) throws ValidatorException, IOException { - this.authenticatedPost(method, request, (Class) null); - } - - private T authenticatedPost(String method, Object request, Class reponseClass) throws ValidatorException, IOException { - try { - HttpResponse e = Unirest.post(this.serverUrl + method).header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).header("Content-Type", "application/json").body(this.jacksonObjectMapper.writeValueAsString(request)).asString(); - if (e.getStatus() == 401) { - this.login(); - return this.authenticatedPost(method, request, reponseClass); - } else { - return reponseClass == null ? null : this.jacksonObjectMapper.readValue((String) e.getBody(), reponseClass); - } - } catch (UnirestException var5) { - throw new IOException(var5); - } - } - - void login() throws UnirestException { - HttpResponse asJson = Unirest.post(this.serverUrl + "login").field("user", this.user).field("password", this.password).asJson(); - if (asJson.getStatus() == 401) { - throw new UnirestException("401 - Unauthorized"); - } else { - JSONObject data = ((JsonNode) asJson.getBody()).getObject().getJSONObject("data"); - this.xAuthToken = data.getString("authToken"); - this.xUserId = data.getString("userId"); - } - } - - public void logout() throws IOException { - try { - Unirest.post(this.serverUrl + "logout").header("X-Auth-Token", this.xAuthToken).header("X-User-Id", this.xUserId).asJson(); - } catch (UnirestException var2) { - throw new IOException(var2); - } - } - - public String getApiVersion() throws IOException { - return this.getVersions().getString("api"); - } - - public String getRocketChatVersion() throws IOException { - return this.getVersions().getString("rocketchat"); - } - - private JSONObject getVersions() throws IOException { - if (this.lazyVersions == null) { - try { - this.lazyVersions = ((JsonNode) Unirest.get(this.serverUrl + "version").asJson().getBody()).getObject().getJSONObject("versions"); - } catch (UnirestException var2) { - throw new IOException(var2); - } - } - - return this.lazyVersions; - } - - public void send(String roomName, String message) throws ValidatorException, IOException { - Room room = this.getRoom(roomName); - if (room == null) { - throw new IOException(String.format("unknown room : %s", new Object[]{roomName})); - } else { - this.send(room, message); - } - } - - public void send(Room room, String message) throws ValidatorException, IOException { - this.authenticatedPost("rooms/" + room.get_id() + "/send", new Message(message)); - } - - public Room getRoom(String room) throws IOException { - Room ret = (Room) this.roomCache.get(room); - if (ret == null) { - this.getPublicRooms(); - ret = (Room) this.roomCache.get(room); - } - - return ret; - } } diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientCallBuilder.java b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientCallBuilder.java new file mode 100644 index 00000000..dfde8039 --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientCallBuilder.java @@ -0,0 +1,139 @@ +package jenkins.plugins.rocketchatnotifier.rocket; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.mashape.unirest.http.HttpResponse; +import com.mashape.unirest.http.JsonNode; +import com.mashape.unirest.http.Unirest; +import com.mashape.unirest.http.exceptions.UnirestException; +import com.mashape.unirest.request.GetRequest; +import com.mashape.unirest.request.HttpRequestWithBody; +import jenkins.plugins.rocketchatnotifier.model.Response; +import org.json.JSONObject; + +import java.io.IOException; +import java.util.Map.Entry; + +/** + * The call builder for the {@link RocketChatClient} and is only supposed to be used internally. + * + * @author Bradley Hilton (graywolf336) + * @version 0.0.1 + * @since 0.1.0 + */ +public class RocketChatClientCallBuilder { + private final ObjectMapper objectMapper; + private final String serverUrl; + private final String user; + private final String password; + private String authToken; + private String userId; + + protected RocketChatClientCallBuilder(String serverUrl, String user, String password) { + if (!serverUrl.endsWith("api/")) { + this.serverUrl = serverUrl + (serverUrl.endsWith("/") ? "" : "/") + "api/"; + } else { + this.serverUrl = serverUrl; + } + + this.user = user; + this.password = password; + this.authToken = ""; + this.userId = ""; + this.objectMapper = new ObjectMapper(); + this.objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + } + + protected Response buildCall(RocketChatRestApiV1 call) throws IOException { + return this.buildCall(call, null, null); + } + + protected Response buildCall(RocketChatRestApiV1 call, RocketChatQueryParams queryParams) throws IOException { + return this.buildCall(call, queryParams, null); + } + + protected Response buildCall(RocketChatRestApiV1 call, RocketChatQueryParams queryParams, Object body) throws IOException { + if (call.requiresAuth() && (authToken.isEmpty() || userId.isEmpty())) { + login(); + } + + switch (call.getHttpMethod()) { + case GET: + return this.buildGetCall(call, queryParams); + case POST: + return this.buildPostCall(call, queryParams, body); + default: + throw new IOException("Http Method " + call.getHttpMethod().toString() + " is not supported."); + } + } + + private void login() throws IOException { + HttpResponse loginResult; + + try { + loginResult = Unirest.post(serverUrl + "v1/login").field("user", user).field("password", password).asJson(); + } catch (UnirestException e) { + throw new IOException(e); + } + + if (loginResult.getStatus() == 401) + throw new IOException("The username and password provided are incorrect."); + + if (loginResult.getStatus() != 200) + throw new IOException("The login failed with a result of: " + loginResult.getStatus()); + + JSONObject data = loginResult.getBody().getObject().getJSONObject("data"); + this.authToken = data.getString("authToken"); + this.userId = data.getString("userId"); + } + + private Response buildGetCall(RocketChatRestApiV1 call, RocketChatQueryParams queryParams) throws IOException { + GetRequest req = Unirest.get(serverUrl + call.getMethodName()); + + if (call.requiresAuth()) { + req.header("X-Auth-Token", authToken); + req.header("X-User-Id", userId); + } + + if (queryParams != null && !queryParams.isEmpty()) { + for (Entry e : queryParams.get().entrySet()) { + req.queryString(e.getKey(), e.getValue()); + } + } + + try { + HttpResponse res = req.asString(); + + return objectMapper.readValue(res.getBody(), Response.class); + } catch (UnirestException e) { + throw new IOException(e); + } + } + + private Response buildPostCall(RocketChatRestApiV1 call, RocketChatQueryParams queryParams, Object body) throws IOException { + HttpRequestWithBody req = Unirest.post(serverUrl + call.getMethodName()).header("Content-Type", "application/json"); + + if (call.requiresAuth()) { + req.header("X-Auth-Token", authToken); + req.header("X-User-Id", userId); + } + + if (queryParams != null && !queryParams.isEmpty()) { + for (Entry e : queryParams.get().entrySet()) { + req.queryString(e.getKey(), e.getValue()); + } + } + + if (body != null) { + req.body(objectMapper.writeValueAsString(body)); + } + + try { + HttpResponse res = req.asString(); + + return objectMapper.readValue(res.getBody(), Response.class); + } catch (UnirestException e) { + throw new IOException(e); + } + } +} diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientImpl.java b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientImpl.java new file mode 100644 index 00000000..24773254 --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientImpl.java @@ -0,0 +1,79 @@ +package jenkins.plugins.rocketchatnotifier.rocket; + +import jenkins.plugins.rocketchatnotifier.model.Response; +import jenkins.plugins.rocketchatnotifier.model.Room; +import jenkins.plugins.rocketchatnotifier.model.User; +import sun.security.validator.ValidatorException; + +import java.io.IOException; + +/** + * Client for Rocket.Chat which relies on the REST API v1. + *

+ * Please note, this client does not cache any of the results. + * + * @version 0.1.0 + * @since 0.0.1 + */ +public class RocketChatClientImpl implements RocketChatClient { + private RocketChatClientCallBuilder callBuilder; + + /** + * Initialize a new instance of the client providing the server's url along with username and + * password to use. + * + * @param serverUrl of the Rocket.Chat server, with or without it ending in "/api/" + * @param user which to authenticate with + * @param password of the user to authenticate with + */ + public RocketChatClientImpl(String serverUrl, String user, String password) { + this.callBuilder = new RocketChatClientCallBuilder(serverUrl, user, password); + } + + + @Override + public User[] getUsers() throws IOException { + Response res = this.callBuilder.buildCall(RocketChatRestApiV1.UsersList); + + if (!res.isSuccessful()) { + throw new IOException("The call to get the User's Information was unsuccessful."); + } + if (!res.isUsers()) { + throw new IOException("Get User Information failed to retrieve a user."); + } + return res.getUsers(); + } + + @Override + public User getUser(String userId) throws IOException { + Response res = this.callBuilder.buildCall(RocketChatRestApiV1.UsersInfo, new RocketChatQueryParams("userId", userId)); + + if (!res.isSuccessful()) + throw new IOException("The call to get the User's Information was unsuccessful."); + + if (!res.isUser()) + throw new IOException("Get User Information failed to retrieve a user."); + + return res.getUser(); + } + + @Override + public Room[] getChannels() throws IOException { + Response res = this.callBuilder.buildCall(RocketChatRestApiV1.ChannelsList); + + if (!res.isSuccessful()) { + throw new IOException("The call to get the all Channel Information was unsuccessful."); + } + return res.getChannels(); + } + + @Override + public void send(Room room, String message) throws ValidatorException, IOException { + + } + + @Override + public void send(String room, String message) throws ValidatorException, IOException { + + } +} diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatQueryParams.java b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatQueryParams.java new file mode 100644 index 00000000..69fe15f9 --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatQueryParams.java @@ -0,0 +1,73 @@ +package jenkins.plugins.rocketchatnotifier.rocket; + + +import java.util.HashMap; +import java.util.Map; + +/** + * Contains the keys and values for the query string. + * + * @author Bradley Hilton (graywolf336) + * @since 0.1.0 + * @version 0.0.1 + */ +public class RocketChatQueryParams { + private HashMap queryParams; + + /** Initializes an empty query parameters object. */ + public RocketChatQueryParams() { + this.queryParams = new HashMap(); + } + + /** + * Initializes query parameter object with one parameter already added. + * + * @param param the query name + * @param value the value of the parameter + */ + public RocketChatQueryParams(String param, String value) { + this.queryParams = new HashMap(); + this.queryParams.put(param, value); + } + + /** + * Check to see if there are any query parameters. + * + * @return whether the query parameters is empty + */ + public boolean isEmpty() { + return this.queryParams.isEmpty(); + } + + /** + * Gets all of the query parameters. + * + * @return the query parameters + */ + public Map get() { + return this.queryParams; + } + + /** + * Adds a query parameter to the list. + * + * @param param the query name + * @param value the value of the parameter + * @return the instance of the {@link RocketChatQueryParams} + */ + public RocketChatQueryParams add(String param, String value) { + this.queryParams.put(param, value); + return this; + } + + /** + * Adds all of the provided query parameters to the list. + * + * @param params the query parameters + * @return the instance of the {@link RocketChatQueryParams} + */ + public RocketChatQueryParams addAll(Map params) { + this.queryParams.putAll(params); + return this; + } +} diff --git a/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatRestApiV1.java b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatRestApiV1.java new file mode 100644 index 00000000..0047426d --- /dev/null +++ b/src/main/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatRestApiV1.java @@ -0,0 +1,65 @@ +package jenkins.plugins.rocketchatnotifier.rocket; + + +/** + * Enumeration of the available REST API methods. + * + * @author Bradley Hilton (graywolf336) + * @version 0.0.1 + * @since 0.1.0 + */ +public enum RocketChatRestApiV1 { + /** + * Retrieves a list of all the users in the server. + */ + UsersList("users.list", HttpMethods.GET, true), + /** + * Retrieves the user information from the server. + */ + UsersInfo("users.info", HttpMethods.GET, true), + /** + * Retrieves a list of all the channels in the server. + */ + ChannelsList("channels.list", HttpMethods.GET, true), + /** + * Retrieves a list of all the channels in the server. + */ + ChannelsInfo("channels.info", HttpMethods.GET, true); + + private String methodName; + private HttpMethods httpMethod; + private boolean requiresAuth; + + private RocketChatRestApiV1(String methodName, HttpMethods httpMethod, boolean requiresAuth) { + this.methodName = methodName; + this.httpMethod = httpMethod; + this.requiresAuth = requiresAuth; + } + + /** + * Gets the method name to be called to the server. + * + * @return the method name plus "v1/" at the start + */ + public String getMethodName() { + return "v1/" + this.methodName; + } + + /** + * Gets the {@link HttpMethods http method} which should be used. + * + * @return {@link HttpMethods http method} to be used + */ + public HttpMethods getHttpMethod() { + return this.httpMethod; + } + + /** + * Check whether the method requires authentication or not. + * + * @return whether this requires authentication or not + */ + public boolean requiresAuth() { + return this.requiresAuth; + } +} diff --git a/src/test/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientIT.java b/src/test/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientIT.java index 1b6080d5..7cdec0a0 100644 --- a/src/test/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientIT.java +++ b/src/test/java/jenkins/plugins/rocketchatnotifier/rocket/RocketChatClientIT.java @@ -1,36 +1,27 @@ package jenkins.plugins.rocketchatnotifier.rocket; import jenkins.plugins.rocketchatnotifier.model.Room; -import org.junit.After; import org.junit.Before; import org.junit.Test; -import java.util.Set; - import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; /** * Created by mreinhardt on 26.12.16. */ - public class RocketChatClientIT { +public class RocketChatClientIT { private RocketChatClient client; @Before public void setup() throws Exception { - this.client = new RocketChatClient("http://localhost:4443/api/v1/", "admin", "supersecret"); // TODO read from env - this.client.login(); - } - - @After - public void cleanUp() throws Exception { - this.client.logout(); + this.client = new RocketChatClientImpl("http://localhost:4443/api/", "admin", "supersecret"); // TODO read from env } @Test public void shouldReadRooms() throws Exception { - Set rooms = this.client.getPublicRooms(); - assertThat(rooms, hasSize(0)); + Room[] rooms = this.client.getChannels(); + assertThat(rooms.length, is(1)); } }