| 1 | package edu.ucsb.cs156.frontiers.services; | |
| 2 | ||
| 3 | import com.fasterxml.jackson.databind.JsonNode; | |
| 4 | import com.fasterxml.jackson.databind.ObjectMapper; | |
| 5 | import edu.ucsb.cs156.frontiers.errors.SlackApiException; | |
| 6 | import edu.ucsb.cs156.frontiers.models.SlackAuthTestResponse; | |
| 7 | import edu.ucsb.cs156.frontiers.models.SlackChannel; | |
| 8 | import edu.ucsb.cs156.frontiers.models.SlackUser; | |
| 9 | import edu.ucsb.cs156.frontiers.models.SlackUsersListResponse; | |
| 10 | import java.time.Duration; | |
| 11 | import java.util.ArrayList; | |
| 12 | import java.util.List; | |
| 13 | import java.util.Optional; | |
| 14 | import lombok.extern.slf4j.Slf4j; | |
| 15 | import org.springframework.boot.web.client.RestTemplateBuilder; | |
| 16 | import org.springframework.http.HttpEntity; | |
| 17 | import org.springframework.http.HttpHeaders; | |
| 18 | import org.springframework.http.HttpMethod; | |
| 19 | import org.springframework.http.ResponseEntity; | |
| 20 | import org.springframework.stereotype.Service; | |
| 21 | import org.springframework.util.LinkedMultiValueMap; | |
| 22 | import org.springframework.util.MultiValueMap; | |
| 23 | import org.springframework.web.client.HttpClientErrorException; | |
| 24 | import org.springframework.web.client.RestClientException; | |
| 25 | import org.springframework.web.client.RestTemplate; | |
| 26 | ||
| 27 | /** | |
| 28 | * Service for interacting with the Slack Web API. | |
| 29 | * | |
| 30 | * <p>A Slack bot token (<code>xoxb-...</code>) is already associated with a specific workspace, so | |
| 31 | * the token alone is sufficient to identify where API calls go. | |
| 32 | * | |
| 33 | * <p>Note that the Slack Web API typically returns HTTP 200 even for failures; the <code>ok</code> | |
| 34 | * field of the response indicates success, and <code>error</code> contains an error code (e.g. | |
| 35 | * <code>invalid_auth</code>, <code>missing_scope</code>). | |
| 36 | * | |
| 37 | * <p>Tokens are secrets; they must never be logged. | |
| 38 | */ | |
| 39 | @Slf4j | |
| 40 | @Service | |
| 41 | public class SlackService { | |
| 42 | ||
| 43 | public static final String AUTH_TEST_ENDPOINT = "https://slack.com/api/auth.test"; | |
| 44 | ||
| 45 | public static final String USERS_LIST_ENDPOINT = "https://slack.com/api/users.list?limit=200"; | |
| 46 | ||
| 47 | /** | |
| 48 | * Upper bound on the number of pages of users fetched (200 users per page), so that a misbehaving | |
| 49 | * cursor can never cause an endless loop. | |
| 50 | */ | |
| 51 | public static final int MAX_USER_PAGES = 50; | |
| 52 | ||
| 53 | /** Error code used when Slack could not be reached or returned an unusable response. */ | |
| 54 | public static final String SLACK_UNREACHABLE = "slack_unreachable"; | |
| 55 | ||
| 56 | private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(10); | |
| 57 | private static final Duration READ_TIMEOUT = Duration.ofSeconds(30); | |
| 58 | ||
| 59 | public static final String SLACK_API = "https://slack.com/api/"; | |
| 60 | ||
| 61 | public static final String CONVERSATIONS_LIST_ENDPOINT = | |
| 62 | SLACK_API + "conversations.list?types=public_channel&exclude_archived=false&limit=200"; | |
| 63 | ||
| 64 | public static final String PRIVATE_CONVERSATIONS_LIST_ENDPOINT = | |
| 65 | SLACK_API + "conversations.list?types=private_channel&exclude_archived=false&limit=200"; | |
| 66 | ||
| 67 | /** Upper bound on the number of pages fetched for any paginated method; see MAX_USER_PAGES. */ | |
| 68 | public static final int MAX_PAGES = 50; | |
| 69 | ||
| 70 | /** Error code used when Slack kept rate limiting a call, even after waiting as it asked. */ | |
| 71 | public static final String RATE_LIMITED = "ratelimited"; | |
| 72 | ||
| 73 | /** | |
| 74 | * Slack's error code when a workspace preference forbids the action: for <code> | |
| 75 | * conversations.kick</code>, when the workspace does not let this bot remove members from public | |
| 76 | * channels (by default only Workspace Owners and Admins may). | |
| 77 | */ | |
| 78 | public static final String RESTRICTED_ACTION = "restricted_action"; | |
| 79 | ||
| 80 | /** What to tell the instructor when removing a member fails with {@link #RESTRICTED_ACTION}. */ | |
| 81 | public static final String REMOVAL_RESTRICTED_ADVICE = | |
| 82 | "Slack does not allow this bot to remove members from public channels, so no more members will be removed in this run. By default only Workspace Owners and Admins may remove members. A Workspace Owner can change this in Slack under Workspace settings, Roles & permissions (on older workspaces: Permissions, Channel Management): set \"People who can remove members from public channels\" to \"Everyone, except guests\". Then run this job again."; | |
| 83 | ||
| 84 | /** How many times a rate limited (HTTP 429) call is tried again, after waiting. */ | |
| 85 | public static final int MAX_RATE_LIMIT_RETRIES = 3; | |
| 86 | ||
| 87 | /** Longest wait, in seconds, before trying a rate limited call again. */ | |
| 88 | public static final long MAX_RETRY_AFTER_SECONDS = 60; | |
| 89 | ||
| 90 | /** Waits for the given number of milliseconds; replaceable so that tests do not really wait. */ | |
| 91 | @FunctionalInterface | |
| 92 | public interface Sleeper { | |
| 93 | void sleep(long milliseconds) throws InterruptedException; | |
| 94 | } | |
| 95 | ||
| 96 | private final RestTemplate restTemplate; | |
| 97 | private final ObjectMapper objectMapper = new ObjectMapper(); | |
| 98 | private Sleeper sleeper = Thread::sleep; | |
| 99 | ||
| 100 | public SlackService(RestTemplateBuilder builder) { | |
| 101 | this.restTemplate = builder.connectTimeout(CONNECT_TIMEOUT).readTimeout(READ_TIMEOUT).build(); | |
| 102 | } | |
| 103 | ||
| 104 | public void setSleeper(Sleeper sleeper) { | |
| 105 | this.sleeper = sleeper; | |
| 106 | } | |
| 107 | ||
| 108 | /** | |
| 109 | * Calls the Slack <code>auth.test</code> method to check whether a bot token is valid. | |
| 110 | * | |
| 111 | * @param token the (plaintext) Slack bot token | |
| 112 | * @return the response from Slack; if <code>ok</code> is true, <code>team</code> and <code>teamId | |
| 113 | * </code> identify the workspace the token belongs to. If Slack cannot be reached, a response | |
| 114 | * with <code>ok</code> false and error {@link #SLACK_UNREACHABLE} is returned. | |
| 115 | */ | |
| 116 | public SlackAuthTestResponse authTest(String token) { | |
| 117 | HttpHeaders headers = new HttpHeaders(); | |
| 118 |
1
1. authTest : removed call to org/springframework/http/HttpHeaders::setBearerAuth → KILLED |
headers.setBearerAuth(token); |
| 119 | HttpEntity<String> entity = new HttpEntity<>(headers); | |
| 120 | try { | |
| 121 | ResponseEntity<SlackAuthTestResponse> response = | |
| 122 | restTemplate.exchange( | |
| 123 | AUTH_TEST_ENDPOINT, HttpMethod.POST, entity, SlackAuthTestResponse.class); | |
| 124 | SlackAuthTestResponse body = response.getBody(); | |
| 125 |
1
1. authTest : negated conditional → KILLED |
if (body == null) { |
| 126 |
1
1. authTest : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::authTest → KILLED |
return SlackAuthTestResponse.builder().ok(false).error(SLACK_UNREACHABLE).build(); |
| 127 | } | |
| 128 |
1
1. authTest : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::authTest → KILLED |
return body; |
| 129 | } catch (RestClientException e) { | |
| 130 | // Deliberately log only the exception class: the message could echo request details. | |
| 131 | log.warn("Error calling Slack auth.test: {}", e.getClass().getSimpleName()); | |
| 132 |
1
1. authTest : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::authTest → KILLED |
return SlackAuthTestResponse.builder().ok(false).error(SLACK_UNREACHABLE).build(); |
| 133 | } | |
| 134 | } | |
| 135 | ||
| 136 | /** | |
| 137 | * Calls the Slack <code>users.list</code> method (following pagination) to get all members of the | |
| 138 | * workspace the token belongs to. This includes bots, deactivated accounts, and users who have | |
| 139 | * been invited but have not yet signed in; see {@link SlackUser#isActivePerson()}. | |
| 140 | * | |
| 141 | * <p>Requires the <code>users:read</code> scope; emails are only included if the token also has | |
| 142 | * the <code>users:read.email</code> scope. | |
| 143 | * | |
| 144 | * @param token the (plaintext) Slack bot token | |
| 145 | * @return all members of the workspace | |
| 146 | * @throws SlackApiException with the Slack error code (e.g. <code>missing_scope</code>) if Slack | |
| 147 | * reports an error, or {@link #SLACK_UNREACHABLE} if Slack cannot be reached | |
| 148 | */ | |
| 149 | public List<SlackUser> listUsers(String token) { | |
| 150 | HttpHeaders headers = new HttpHeaders(); | |
| 151 |
1
1. listUsers : removed call to org/springframework/http/HttpHeaders::setBearerAuth → KILLED |
headers.setBearerAuth(token); |
| 152 | HttpEntity<String> entity = new HttpEntity<>(headers); | |
| 153 | ||
| 154 | List<SlackUser> users = new ArrayList<>(); | |
| 155 | String cursor = ""; | |
| 156 |
2
1. listUsers : negated conditional → KILLED 2. listUsers : changed conditional boundary → KILLED |
for (int page = 0; page < MAX_USER_PAGES; page++) { |
| 157 | SlackUsersListResponse body = getUsersPage(entity, cursor); | |
| 158 |
1
1. listUsers : negated conditional → KILLED |
if (body == null) { |
| 159 | throw new SlackApiException(SLACK_UNREACHABLE); | |
| 160 | } | |
| 161 |
1
1. listUsers : negated conditional → KILLED |
if (!body.getOk()) { |
| 162 | throw new SlackApiException(String.valueOf(body.getError())); | |
| 163 | } | |
| 164 |
1
1. listUsers : negated conditional → KILLED |
if (body.getMembers() != null) { |
| 165 | users.addAll(body.getMembers()); | |
| 166 | } | |
| 167 | cursor = body.nextCursor(); | |
| 168 |
1
1. listUsers : negated conditional → KILLED |
if (cursor.isEmpty()) { |
| 169 |
1
1. listUsers : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::listUsers → KILLED |
return users; |
| 170 | } | |
| 171 | } | |
| 172 | log.warn("Slack users.list: stopped after {} pages", MAX_USER_PAGES); | |
| 173 |
1
1. listUsers : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::listUsers → KILLED |
return users; |
| 174 | } | |
| 175 | ||
| 176 | private SlackUsersListResponse getUsersPage(HttpEntity<String> entity, String cursor) { | |
| 177 | try { | |
| 178 |
1
1. getUsersPage : negated conditional → KILLED |
if (cursor.isEmpty()) { |
| 179 |
1
1. getUsersPage : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::getUsersPage → KILLED |
return restTemplate |
| 180 | .exchange(USERS_LIST_ENDPOINT, HttpMethod.GET, entity, SlackUsersListResponse.class) | |
| 181 | .getBody(); | |
| 182 | } | |
| 183 | // cursor is passed as a URI template variable so that it gets URL encoded | |
| 184 |
1
1. getUsersPage : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::getUsersPage → KILLED |
return restTemplate |
| 185 | .exchange( | |
| 186 | USERS_LIST_ENDPOINT + "&cursor={cursor}", | |
| 187 | HttpMethod.GET, | |
| 188 | entity, | |
| 189 | SlackUsersListResponse.class, | |
| 190 | cursor) | |
| 191 | .getBody(); | |
| 192 | } catch (RestClientException e) { | |
| 193 | // Deliberately log only the exception class: the message could echo request details. | |
| 194 | log.warn("Error calling Slack users.list: {}", e.getClass().getSimpleName()); | |
| 195 | throw new SlackApiException(SLACK_UNREACHABLE); | |
| 196 | } | |
| 197 | } | |
| 198 | ||
| 199 | /** | |
| 200 | * Calls the Slack <code>conversations.list</code> method (following pagination) to get all public | |
| 201 | * channels of the workspace, including archived ones (the name of an archived channel is still | |
| 202 | * taken). Requires the <code>channels:read</code> scope. | |
| 203 | * | |
| 204 | * @param token the (plaintext) Slack bot token | |
| 205 | * @return the public channels of the workspace | |
| 206 | * @throws SlackApiException with the Slack error code if the call fails | |
| 207 | */ | |
| 208 | public List<SlackChannel> listPublicChannels(String token) { | |
| 209 |
1
1. listPublicChannels : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::listPublicChannels → KILLED |
return listChannels(token, CONVERSATIONS_LIST_ENDPOINT); |
| 210 | } | |
| 211 | ||
| 212 | /** | |
| 213 | * Calls the Slack <code>conversations.list</code> method (following pagination) to get the | |
| 214 | * private channels that the bot is a member of, including archived ones; Slack does not tell a | |
| 215 | * bot about any other private channels. Requires the <code>groups:read</code> scope. | |
| 216 | * | |
| 217 | * @param token the (plaintext) Slack bot token | |
| 218 | * @return the private channels of the workspace that the bot is a member of | |
| 219 | * @throws SlackApiException with the Slack error code if the call fails | |
| 220 | */ | |
| 221 | public List<SlackChannel> listPrivateChannels(String token) { | |
| 222 |
1
1. listPrivateChannels : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::listPrivateChannels → KILLED |
return listChannels(token, PRIVATE_CONVERSATIONS_LIST_ENDPOINT); |
| 223 | } | |
| 224 | ||
| 225 | private List<SlackChannel> listChannels(String token, String url) { | |
| 226 | List<SlackChannel> channels = new ArrayList<>(); | |
| 227 | for (JsonNode page : getAllPages(token, url)) { | |
| 228 | for (JsonNode channel : page.path("channels")) { | |
| 229 | channels.add(objectMapper.convertValue(channel, SlackChannel.class)); | |
| 230 | } | |
| 231 | } | |
| 232 |
1
1. listChannels : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::listChannels → KILLED |
return channels; |
| 233 | } | |
| 234 | ||
| 235 | /** | |
| 236 | * Calls the Slack <code>conversations.create</code> method to create a public channel; the bot | |
| 237 | * becomes a member of the channel it creates. Requires the <code>channels:manage</code> scope. | |
| 238 | * | |
| 239 | * @param token the (plaintext) Slack bot token | |
| 240 | * @param name name of the channel (lowercase letters, digits, hyphens and underscores) | |
| 241 | * @return the new channel | |
| 242 | * @throws SlackApiException with the Slack error code (e.g. <code>name_taken</code>, <code> | |
| 243 | * invalid_name_specials</code>) if the call fails | |
| 244 | */ | |
| 245 | public SlackChannel createPublicChannel(String token, String name) { | |
| 246 | MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); | |
| 247 |
1
1. createPublicChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("name", name); |
| 248 | JsonNode body = post(token, "conversations.create", form); | |
| 249 |
1
1. createPublicChannel : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::createPublicChannel → KILLED |
return objectMapper.convertValue(body.path("channel"), SlackChannel.class); |
| 250 | } | |
| 251 | ||
| 252 | /** | |
| 253 | * Calls the Slack <code>conversations.create</code> method to create a private channel; the bot | |
| 254 | * becomes a member of the channel it creates. Requires the <code>groups:write</code> scope. | |
| 255 | * | |
| 256 | * @param token the (plaintext) Slack bot token | |
| 257 | * @param name name of the channel (lowercase letters, digits, hyphens and underscores) | |
| 258 | * @return the new channel | |
| 259 | * @throws SlackApiException with the Slack error code (e.g. <code>name_taken</code>) if the call | |
| 260 | * fails | |
| 261 | */ | |
| 262 | public SlackChannel createPrivateChannel(String token, String name) { | |
| 263 | MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); | |
| 264 |
1
1. createPrivateChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("name", name); |
| 265 |
1
1. createPrivateChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("is_private", "true"); |
| 266 | JsonNode body = post(token, "conversations.create", form); | |
| 267 |
1
1. createPrivateChannel : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::createPrivateChannel → KILLED |
return objectMapper.convertValue(body.path("channel"), SlackChannel.class); |
| 268 | } | |
| 269 | ||
| 270 | /** | |
| 271 | * Calls the Slack <code>conversations.rename</code> method to rename a channel that the bot | |
| 272 | * created. Requires the <code>channels:manage</code> scope for a public channel, and the <code> | |
| 273 | * groups:write</code> scope for a private one. | |
| 274 | * | |
| 275 | * @param token the (plaintext) Slack bot token | |
| 276 | * @param channelId id of the channel | |
| 277 | * @param name the new name of the channel | |
| 278 | * @throws SlackApiException with the Slack error code (e.g. <code>name_taken</code>, <code> | |
| 279 | * not_authorized</code>) if the call fails | |
| 280 | */ | |
| 281 | public void renameChannel(String token, String channelId, String name) { | |
| 282 | MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); | |
| 283 |
1
1. renameChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("channel", channelId); |
| 284 |
1
1. renameChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("name", name); |
| 285 | post(token, "conversations.rename", form); | |
| 286 | } | |
| 287 | ||
| 288 | /** | |
| 289 | * Calls the Slack <code>conversations.join</code> method so that the bot is a member of a public | |
| 290 | * channel, which it has to be to invite or remove members. Joining a channel the bot is already | |
| 291 | * in is not an error. Requires the <code>channels:join</code> scope. | |
| 292 | * | |
| 293 | * @param token the (plaintext) Slack bot token | |
| 294 | * @param channelId id of the channel | |
| 295 | * @throws SlackApiException with the Slack error code if the call fails | |
| 296 | */ | |
| 297 | public void joinChannel(String token, String channelId) { | |
| 298 | MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); | |
| 299 |
1
1. joinChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("channel", channelId); |
| 300 | post(token, "conversations.join", form); | |
| 301 | } | |
| 302 | ||
| 303 | /** | |
| 304 | * Calls the Slack <code>conversations.members</code> method (following pagination). Requires the | |
| 305 | * <code>channels:read</code> scope for a public channel, and the <code>groups:read</code> scope | |
| 306 | * for a private one. | |
| 307 | * | |
| 308 | * @param token the (plaintext) Slack bot token | |
| 309 | * @param channelId id of the channel | |
| 310 | * @return the Slack user ids of the members of the channel | |
| 311 | * @throws SlackApiException with the Slack error code if the call fails | |
| 312 | */ | |
| 313 | public List<String> listChannelMembers(String token, String channelId) { | |
| 314 | List<String> members = new ArrayList<>(); | |
| 315 | String url = SLACK_API + "conversations.members?limit=200&channel=" + channelId; | |
| 316 | for (JsonNode page : getAllPages(token, url)) { | |
| 317 | for (JsonNode member : page.path("members")) { | |
| 318 | members.add(member.asText()); | |
| 319 | } | |
| 320 | } | |
| 321 |
1
1. listChannelMembers : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::listChannelMembers → KILLED |
return members; |
| 322 | } | |
| 323 | ||
| 324 | /** | |
| 325 | * Calls the Slack <code>conversations.invite</code> method to add users to a channel that the bot | |
| 326 | * is a member of. Slack adds either all of the users or none of them. Requires the <code> | |
| 327 | * channels:manage</code> scope for a public channel, and the <code>groups:write</code> scope for | |
| 328 | * a private one. | |
| 329 | * | |
| 330 | * @param token the (plaintext) Slack bot token | |
| 331 | * @param channelId id of the channel | |
| 332 | * @param userIds Slack user ids; at most 1000 | |
| 333 | * @throws SlackApiException with the Slack error code (e.g. <code>already_in_channel</code>) if | |
| 334 | * the call fails | |
| 335 | */ | |
| 336 | public void inviteToChannel(String token, String channelId, List<String> userIds) { | |
| 337 | MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); | |
| 338 |
1
1. inviteToChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("channel", channelId); |
| 339 |
1
1. inviteToChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("users", String.join(",", userIds)); |
| 340 | post(token, "conversations.invite", form); | |
| 341 | } | |
| 342 | ||
| 343 | /** | |
| 344 | * Calls the Slack <code>conversations.kick</code> method to remove a user from a channel that the | |
| 345 | * bot is a member of. Requires the <code>channels:manage</code> scope for a public channel, and | |
| 346 | * the <code>groups:write</code> scope for a private one. Whether the bot is allowed to remove | |
| 347 | * members is also a workspace setting; if it is not, Slack answers {@link #RESTRICTED_ACTION}, | |
| 348 | * and for public channels {@link #REMOVAL_RESTRICTED_ADVICE} says how to fix that. | |
| 349 | * | |
| 350 | * @param token the (plaintext) Slack bot token | |
| 351 | * @param channelId id of the channel | |
| 352 | * @param userId Slack user id | |
| 353 | * @throws SlackApiException with the Slack error code (e.g. <code>restricted_action</code>) if | |
| 354 | * the call fails | |
| 355 | */ | |
| 356 | public void removeFromChannel(String token, String channelId, String userId) { | |
| 357 | MultiValueMap<String, String> form = new LinkedMultiValueMap<>(); | |
| 358 |
1
1. removeFromChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("channel", channelId); |
| 359 |
1
1. removeFromChannel : removed call to org/springframework/util/MultiValueMap::add → KILLED |
form.add("user", userId); |
| 360 | post(token, "conversations.kick", form); | |
| 361 | } | |
| 362 | ||
| 363 | private JsonNode post(String token, String method, MultiValueMap<String, String> form) { | |
| 364 | HttpHeaders headers = new HttpHeaders(); | |
| 365 |
1
1. post : removed call to org/springframework/http/HttpHeaders::setBearerAuth → KILLED |
headers.setBearerAuth(token); |
| 366 | // RestTemplate sends a MultiValueMap as application/x-www-form-urlencoded | |
| 367 |
1
1. post : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::post → KILLED |
return call(SLACK_API + method, HttpMethod.POST, new HttpEntity<>(form, headers), null); |
| 368 | } | |
| 369 | ||
| 370 | /** Gets every page of a cursor paginated method; url must already have a query string. */ | |
| 371 | private List<JsonNode> getAllPages(String token, String url) { | |
| 372 | HttpHeaders headers = new HttpHeaders(); | |
| 373 |
1
1. getAllPages : removed call to org/springframework/http/HttpHeaders::setBearerAuth → KILLED |
headers.setBearerAuth(token); |
| 374 | HttpEntity<Void> entity = new HttpEntity<>(headers); | |
| 375 | ||
| 376 | List<JsonNode> pages = new ArrayList<>(); | |
| 377 | String cursor = ""; | |
| 378 |
2
1. getAllPages : negated conditional → KILLED 2. getAllPages : changed conditional boundary → KILLED |
for (int page = 0; page < MAX_PAGES; page++) { |
| 379 | JsonNode body = | |
| 380 |
1
1. getAllPages : negated conditional → KILLED |
cursor.isEmpty() |
| 381 | ? call(url, HttpMethod.GET, entity, null) | |
| 382 | : call(url + "&cursor={cursor}", HttpMethod.GET, entity, cursor); | |
| 383 | pages.add(body); | |
| 384 | cursor = body.path("response_metadata").path("next_cursor").asText(""); | |
| 385 |
1
1. getAllPages : negated conditional → KILLED |
if (cursor.isEmpty()) { |
| 386 |
1
1. getAllPages : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::getAllPages → KILLED |
return pages; |
| 387 | } | |
| 388 | } | |
| 389 | log.warn("Slack: stopped after {} pages", MAX_PAGES); | |
| 390 |
1
1. getAllPages : replaced return value with Collections.emptyList for edu/ucsb/cs156/frontiers/services/SlackService::getAllPages → KILLED |
return pages; |
| 391 | } | |
| 392 | ||
| 393 | /** | |
| 394 | * Makes one call to the Slack Web API. If Slack answers 429 (rate limited), waits for as long as | |
| 395 | * the Retry-After header asks and tries again, a limited number of times. | |
| 396 | * | |
| 397 | * @return the response, which has ok=true | |
| 398 | * @throws SlackApiException with the Slack error code if ok=false, {@link #RATE_LIMITED} if still | |
| 399 | * rate limited after retrying, or {@link #SLACK_UNREACHABLE} for other failures | |
| 400 | */ | |
| 401 | private JsonNode call(String url, HttpMethod httpMethod, HttpEntity<?> entity, String cursor) { | |
| 402 |
1
1. call : Changed increment from 1 to -1 → KILLED |
for (int attempt = 0; ; attempt++) { |
| 403 | try { | |
| 404 | ResponseEntity<JsonNode> response = | |
| 405 |
1
1. call : negated conditional → KILLED |
cursor == null |
| 406 | ? restTemplate.exchange(url, httpMethod, entity, JsonNode.class) | |
| 407 | : restTemplate.exchange(url, httpMethod, entity, JsonNode.class, cursor); | |
| 408 | JsonNode body = response.getBody(); | |
| 409 |
1
1. call : negated conditional → KILLED |
if (body == null) { |
| 410 | throw new SlackApiException(SLACK_UNREACHABLE); | |
| 411 | } | |
| 412 |
1
1. call : negated conditional → KILLED |
if (!body.path("ok").asBoolean()) { |
| 413 | throw new SlackApiException(body.path("error").asText("null")); | |
| 414 | } | |
| 415 |
1
1. call : replaced return value with null for edu/ucsb/cs156/frontiers/services/SlackService::call → KILLED |
return body; |
| 416 | } catch (HttpClientErrorException.TooManyRequests e) { | |
| 417 |
2
1. call : changed conditional boundary → KILLED 2. call : negated conditional → KILLED |
if (attempt >= MAX_RATE_LIMIT_RETRIES) { |
| 418 | throw new SlackApiException(RATE_LIMITED); | |
| 419 | } | |
| 420 |
1
1. call : removed call to edu/ucsb/cs156/frontiers/services/SlackService::waitBeforeRetry → KILLED |
waitBeforeRetry(e.getResponseHeaders()); |
| 421 | } catch (RestClientException e) { | |
| 422 | // Deliberately log only the exception class: the message could echo request details. | |
| 423 | log.warn("Error calling Slack: {}", e.getClass().getSimpleName()); | |
| 424 | throw new SlackApiException(SLACK_UNREACHABLE); | |
| 425 | } | |
| 426 | } | |
| 427 | } | |
| 428 | ||
| 429 | private void waitBeforeRetry(HttpHeaders responseHeaders) { | |
| 430 | long seconds = 1; | |
| 431 | // (the headers of an exception are declared nullable, though a 429 response always has some) | |
| 432 | String retryAfter = | |
| 433 | Optional.ofNullable(responseHeaders) | |
| 434 |
1
1. lambda$waitBeforeRetry$0 : replaced return value with "" for edu/ucsb/cs156/frontiers/services/SlackService::lambda$waitBeforeRetry$0 → KILLED |
.map(headers -> headers.getFirst("Retry-After")) |
| 435 | .orElse(null); | |
| 436 |
1
1. waitBeforeRetry : negated conditional → KILLED |
if (retryAfter != null) { |
| 437 | try { | |
| 438 | seconds = Long.parseLong(retryAfter.strip()); | |
| 439 | } catch (NumberFormatException e) { | |
| 440 | seconds = 1; | |
| 441 | } | |
| 442 | } | |
| 443 | seconds = Math.max(1, Math.min(seconds, MAX_RETRY_AFTER_SECONDS)); | |
| 444 | try { | |
| 445 |
2
1. waitBeforeRetry : removed call to edu/ucsb/cs156/frontiers/services/SlackService$Sleeper::sleep → KILLED 2. waitBeforeRetry : Replaced long multiplication with division → KILLED |
sleeper.sleep(seconds * 1000); |
| 446 | } catch (InterruptedException e) { | |
| 447 |
1
1. waitBeforeRetry : removed call to java/lang/Thread::interrupt → KILLED |
Thread.currentThread().interrupt(); |
| 448 | throw new SlackApiException(SLACK_UNREACHABLE); | |
| 449 | } | |
| 450 | } | |
| 451 | } | |
Mutations | ||
| 118 |
1.1 |
|
| 125 |
1.1 |
|
| 126 |
1.1 |
|
| 128 |
1.1 |
|
| 132 |
1.1 |
|
| 151 |
1.1 |
|
| 156 |
1.1 2.2 |
|
| 158 |
1.1 |
|
| 161 |
1.1 |
|
| 164 |
1.1 |
|
| 168 |
1.1 |
|
| 169 |
1.1 |
|
| 173 |
1.1 |
|
| 178 |
1.1 |
|
| 179 |
1.1 |
|
| 184 |
1.1 |
|
| 209 |
1.1 |
|
| 222 |
1.1 |
|
| 232 |
1.1 |
|
| 247 |
1.1 |
|
| 249 |
1.1 |
|
| 264 |
1.1 |
|
| 265 |
1.1 |
|
| 267 |
1.1 |
|
| 283 |
1.1 |
|
| 284 |
1.1 |
|
| 299 |
1.1 |
|
| 321 |
1.1 |
|
| 338 |
1.1 |
|
| 339 |
1.1 |
|
| 358 |
1.1 |
|
| 359 |
1.1 |
|
| 365 |
1.1 |
|
| 367 |
1.1 |
|
| 373 |
1.1 |
|
| 378 |
1.1 2.2 |
|
| 380 |
1.1 |
|
| 385 |
1.1 |
|
| 386 |
1.1 |
|
| 390 |
1.1 |
|
| 402 |
1.1 |
|
| 405 |
1.1 |
|
| 409 |
1.1 |
|
| 412 |
1.1 |
|
| 415 |
1.1 |
|
| 417 |
1.1 2.2 |
|
| 420 |
1.1 |
|
| 434 |
1.1 |
|
| 436 |
1.1 |
|
| 445 |
1.1 2.2 |
|
| 447 |
1.1 |