private void openWebSocket(String url) { try { ws = new WebSocketFactory().createSocket(url).addListener(new WebSocketAdapter() { @Override public void onTextMessage(WebSocket websocket, String message) { JsonObject json = Jsoner.deserialize(message, new JsonObject()); if (json.containsKey("type")) { if (json.getString(Jsoner.mintJsonKey("type", null)).equals("message")) { //TODO: Figure out if there is a way to get the user id of a bot instead of just using janet's SlackUser info = json.containsKey("bot_id") ? getUserInfo("U2Y19AVNJ") : getUserInfo(json.getString(Jsoner.mintJsonKey("user", null))); String text = json.getString(Jsoner.mintJsonKey("text", null)); while (text.contains("<") && text.contains(">")) text = text.split("<@")[0] + '@' + getUserInfo(text.split("<@")[1].split(">:")[0]).getName() + ':' + text.split("<@")[1].split(">:")[1]; String channel = json.getString(Jsoner.mintJsonKey("channel", null)); if (channel.startsWith("D")) //Direct Message sendSlackChat(info, text, true); else if (channel.startsWith("C") || channel.startsWith("G")) //Channel or Group sendSlackChat(info, text, false); } } } }).connect(); } catch (Exception ignored) { } }
public PullRequest createPullRequest(CreatePullRequestTask task, GitHubApi gitHubApi) throws IOException { if (task.isDryRun()) { LOG.lifecycle(" Skipping pull request creation due to dryRun = true"); return null; } String headBranch = BranchUtils.getHeadBranch(task.getForkRepositoryName(), task.getVersionBranch()); IncubatingWarning.warn("creating pull requests"); LOG.lifecycle(" Creating a pull request of title '{}' in repository '{}' between base = '{}' and head = '{}'.", task.getPullRequestTitle(), task.getUpstreamRepositoryName(), task.getBaseBranch(), headBranch); String body = "{" + " \"title\": \"" + task.getPullRequestTitle() + "\"," + " \"body\": \"" + task.getPullRequestDescription() + "\"," + " \"head\": \"" + headBranch + "\"," + " \"base\": \"" + task.getBaseBranch() + "\"," + " \"maintainer_can_modify\": true" + "}"; String response = gitHubApi.post("/repos/" + task.getUpstreamRepositoryName() + "/pulls", body); JsonObject pullRequest = Jsoner.deserialize(response, new JsonObject()); return toPullRequest(pullRequest); }
public PullRequest findOpenPullRequest(String upstreamRepositoryName, String versionBranchRegex, GitHubApi gitHubApi) throws IOException { String response = gitHubApi.get("/repos/" + upstreamRepositoryName + "/pulls?state=open"); JsonArray pullRequests = Jsoner.deserialize(response, new JsonArray()); for (Object pullRequest : pullRequests) { PullRequest openPullRequest = PullRequestUtils.toPullRequest((JsonObject) pullRequest); if (openPullRequest != null && openPullRequest.getRef().matches(versionBranchRegex)) { LOG.lifecycle(" Found an open pull request with version upgrade on branch {}", openPullRequest.getRef()); return openPullRequest; } } LOG.lifecycle(" New pull request will be opened because we didn't find an existing PR to reuse."); return null; }
@Override public String toJson() { final StringBuilder improvementsBuilder = new StringBuilder(); final Iterator<Improvement> iterator = improvements.iterator(); while (iterator.hasNext()) { improvementsBuilder.append(iterator.next().toJson()); if (iterator.hasNext()) { improvementsBuilder.append(","); } } return String.format(JSON_FORMAT, Jsoner.escape(version), Jsoner.escape(String.valueOf(date.getTime())), contributions.toJson(), improvementsBuilder.toString(), Jsoner.escape(previousVersionTag == null ? "" : previousVersionTag), Jsoner.escape(thisVersionTag) ); }
@Override public String toJson() { final StringBuilder labelsBuilder = new StringBuilder(); final Iterator<String> iterator = labels.iterator(); while (iterator.hasNext()) { labelsBuilder.append("\"").append(Jsoner.escape(iterator.next())).append("\""); if (iterator.hasNext()) { labelsBuilder.append(","); } } return String.format(JSON_FORMAT, id.toString(), Jsoner.escape(title), Jsoner.escape(url), labelsBuilder.toString(), String.valueOf(isPullRequest)); }
public ProjectContributorsSet deserialize(String json) { ProjectContributorsSet set = new DefaultProjectContributorsSet(); try { LOG.debug("Deserialize project contributors from: {}", json); JsonArray array = (JsonArray) Jsoner.deserialize(json); for (Object object : array) { JsonObject jsonObject = (JsonObject) object; String name = jsonObject.getString("name"); String login = jsonObject.getString("login"); String profileUrl = jsonObject.getString("profileUrl"); Integer numberOfContributions = jsonObject.getInteger("numberOfContributions"); set.addContributor(new DefaultProjectContributor(name, login, profileUrl, numberOfContributions)); } } catch (Exception e) { throw new RuntimeException("Can't deserialize JSON: " + json, e); } return set; }
public ContributorsSet deserialize() { String json = ""; ContributorsSet set = new DefaultContributorsSet(); try { json = IOUtil.readFully(file); LOG.info("Deserialize contributors from: {}", json); JsonArray array = (JsonArray) Jsoner.deserialize(json); for (Object object : array) { JsonObject jsonObject = (JsonObject) object; String name = jsonObject.getString("name"); String login = jsonObject.getString("login"); String profileUrl = jsonObject.getString("profileUrl"); set.addContributor(new DefaultContributor(name, login, profileUrl)); } } catch (Exception e) { throw new RuntimeException("Can't deserialize JSON: " + json, e); } return set; }
private static JsonObject extractResponse(Response response) throws StashClientException { PeekableInputStream bodyStream = new PeekableInputStream(response.getResponseBodyAsStream()); try { if (!bodyStream.peek().isPresent()) { return null; } String contentType = response.getHeader("Content-Type"); if (!JSON.match(contentType.trim())) { throw new StashClientException("Received response with type " + contentType + " instead of JSON"); } Reader body = new InputStreamReader(bodyStream); Object obj = Jsoner.deserialize(body); return (JsonObject)obj; } catch (DeserializationException | ClassCastException | IOException e) { throw new StashClientException("Could not parse JSON response: " + e, e); } }
private Property getSkin() { try { BufferedReader in = new BufferedReader(new InputStreamReader(new URL("https://sessionserver.mojang.com/session/minecraft/profile/136f2ba62be3444ca2968ec597edb57e?unsigned=false").openConnection().getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); JsonObject json = Jsoner.deserialize(response.toString(), new JsonObject()); JsonObject jo = (JsonObject) ((JsonArray) json.get("properties")).get(0); String signature = jo.getString(Jsoner.mintJsonKey("signature", null)), value = jo.getString(Jsoner.mintJsonKey("value", null)); return new Property("textures", value, signature); } catch (Exception ignored) { } return null; }
private void getDevInfo() { try { BufferedReader in = new BufferedReader(new InputStreamReader(new URL("http://galaxygaming.gg/staff.json").openConnection().getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); JsonObject json = Jsoner.deserialize(response.toString(), new JsonObject()); JsonArray ar = (JsonArray) json.get("devs"); JsonObject ls = (JsonObject) json.get("Lavasurvival"); JsonArray lsDevs = (JsonArray) ls.get("devs"); for (int i = 0; i < lsDevs.size(); i++) { int devID = lsDevs.getInteger(i); JsonObject dev = (JsonObject) ar.stream().filter(a -> devID == ((JsonObject) a).getInteger(Jsoner.mintJsonKey("devID", null))).findFirst().orElse(null); if (dev != null) this.devs.add(new DevInfo(dev)); } } catch (Exception ignored) { } }
public void setSkin(UUID uuid) {//TODO make this refresh their skin. Currently changes their gameprofile to have correct skin... but doesn't refresh the player if (bukkitPlayer == null) return; GameProfile profile = ((CraftPlayer) bukkitPlayer).getHandle().getProfile(); try { Field prop = profile.getProperties().getClass().getDeclaredField("properties"); prop.setAccessible(true); Multimap<String, Property> properties = (Multimap<String, Property>) prop.get(profile.getProperties()); BufferedReader in = new BufferedReader(new InputStreamReader(new URL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid.toString().replaceAll("-", "") + "?unsigned=false").openConnection().getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); JsonObject json = Jsoner.deserialize(response.toString(), new JsonObject()); JsonObject jo = (JsonObject) ((JsonArray) json.get("properties")).get(0); String signature = jo.getString(Jsoner.mintJsonKey("signature", null)), value = jo.getString(Jsoner.mintJsonKey("value", null)); properties.removeAll("textures"); properties.put("textures", new Property("textures", value, signature)); } catch (Exception e) { e.printStackTrace(); } }
/** * Sends a message to slack. * @param message The message to send. */ //sendPost("https://slack.com/api/chat.postMessage?token=" + token + "&channel=%23" + channel + "&text=" + ChatColor.stripColor(message.replaceAll(" ", "%20")) + "&as_user=true&pretty=1"); public void sendMessage(String message) { message = ChatColor.stripColor(message); if (message.endsWith("\n")) message = message.substring(0, message.length() - 1); JsonObject json = new JsonObject(); json.put("text", message); try { HttpsURLConnection con = (HttpsURLConnection) hookURL.openConnection(); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json;"); con.setRequestProperty("Accept", "application/json,text/plain"); con.setRequestMethod("POST"); OutputStream os = con.getOutputStream(); os.write(Jsoner.serialize(json).getBytes("UTF-8")); os.close(); InputStream is = con.getInputStream(); is.close(); con.disconnect(); } catch (Exception ignored) { } }
private void connect() { if (isConnected) return; try { URL url = new URL("https://slack.com/api/rtm.connect?token=" + token); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); JsonObject json = Jsoner.deserialize(response.toString(), new JsonObject()); String webSocketUrl = json.getString(Jsoner.mintJsonKey("url", null)); if (webSocketUrl != null) openWebSocket(webSocketUrl); } catch (Exception ignored) { } setUsers(); setUserChannels(); sendPost("https://slack.com/api/users.setPresence?token=" + this.token + "&presence=auto"); isConnected = true; sendMessage("Connected."); }
private void setUsers() { try { URL url = new URL("https://slack.com/api/users.list?token=" + token + "&presence=true"); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); JsonObject json = Jsoner.deserialize(response.toString(), new JsonObject()); //Map users JsonArray users = (JsonArray) json.get("members"); for (Object u : users) { JsonObject user = (JsonObject) u; if (user.getBoolean(Jsoner.mintJsonKey("deleted", null))) continue; String id = user.getString(Jsoner.mintJsonKey("id", null)); if (!userMap.containsKey(id)) userMap.put(id, new SlackUser(user)); } } catch (Exception ignored) { } }
private void setUserChannels() { try { URL url = new URL("https://slack.com/api/im.list?token=" + token); HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); JsonObject json = Jsoner.deserialize(response.toString(), new JsonObject()); //Map user channels for (Object i : (JsonArray) json.get("ims")) { JsonObject im = (JsonObject) i; String userID = im.getString(Jsoner.mintJsonKey("user", null)); if (userMap.containsKey(userID)) userMap.get(userID).setChannel(im.getString(Jsoner.mintJsonKey("id", null))); } } catch (Exception ignored) { } }
SlackUser(JsonObject json) { this.id = json.getString(Jsoner.mintJsonKey("id", null)); this.name = json.getString(Jsoner.mintJsonKey("name", null)); if (json.getBoolean(Jsoner.mintJsonKey("is_bot", null))) { this.isBot = true; this.rank = 2; } else if (json.getBoolean(Jsoner.mintJsonKey("is_primary_owner", null))) this.rank = 3; else if (json.getBoolean(Jsoner.mintJsonKey("is_owner", null))) this.rank = 2; else if (json.getBoolean(Jsoner.mintJsonKey("is_admin", null))) this.rank = 1; else if (json.getBoolean(Jsoner.mintJsonKey("is_ultra_restricted", null))) this.rank = -2; else if (json.getBoolean(Jsoner.mintJsonKey("is_restricted", null))) this.rank = -1; //else leave it at 0 for member }
void sendPrivateMessage(String message) { if (message.endsWith("\n")) message = message.substring(0, message.length() - 1); JsonObject json = new JsonObject(); json.put("text", message); json.put("channel", this.channel); try { HttpsURLConnection con = (HttpsURLConnection) hookURL.openConnection(); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json;"); con.setRequestProperty("Accept", "application/json,text/plain"); con.setRequestMethod("POST"); OutputStream os = con.getOutputStream(); os.write(Jsoner.serialize(json).getBytes("UTF-8")); os.close(); InputStream is = con.getInputStream(); is.close(); con.disconnect(); } catch (Exception ignored) { } }
/** * Gets the uuid of an offline player based on their name. * @param name The name to search for. * @return The uuid of an offline player based on their name. */ public static UUID getOfflineID(String name) { if (name == null) return null; try { BufferedReader in = new BufferedReader(new InputStreamReader(new URL("https://api.mojang.com/users/profiles/minecraft/" + name).openConnection().getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) response.append(inputLine); in.close(); return UUID.fromString(((String) Jsoner.deserialize(response.toString(), new JsonObject()).get("id")).replaceAll("(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})", "$1-$2-$3-$4-$5")); } catch (Exception ignored) { } return null; }
@Test public void testExtractMeasure() throws Exception { JsonObject o = readJsonResource("componentMeasure.json"); assertEquals( DefaultSonarClient.extractMeasure(o, CoreMetrics.COMPLEXITY), Optional.of("12") ); assertEquals( DefaultSonarClient.extractMeasure( (JsonObject) Jsoner.deserialize("{}"), CoreMetrics.COMPLEXITY), Optional.empty() ); }
/** * Creates a Gist with the given fileContent and uploads it. * Returns the url that you can use to access the uploaded Gist. * * @param fileContent the content which will be uploaded */ public String uploadFile(String fileName, String fileContent) throws Exception { String body = getBody(fileName, fileContent); String response = gitHubApi.post("/gists", body); JsonObject responseJson = (JsonObject) Jsoner.deserialize(response); return responseJson.getString("html_url"); }
public Collection<ReleaseNotesData> deserialize(String jsonData) { try { final JsonArray jsonArray = (JsonArray) Jsoner.deserialize(jsonData); return deserialize(jsonArray); } catch (DeserializationException e) { throw new RuntimeException("Can't deserialize JSON: " + jsonData, e); } }
public GitCommit deserialize(String jsonData) { try { final JsonObject jsonObject = (JsonObject) Jsoner.deserialize(jsonData); return deserialize(jsonObject); } catch (DeserializationException e) { throw new RuntimeException("Can't deserialize JSON: " + jsonData, e); } }
public DefaultContributionSet deserialize(String jsonData) { try { final JsonObject jsonObject = (JsonObject) Jsoner.deserialize(jsonData); return deserialize(jsonObject); } catch (DeserializationException e) { throw new RuntimeException("Can't deserialize JSON: " + jsonData, e); } }
@Override public String toJson() { return String.format(JSON_FORMAT, Jsoner.escape(commitId), Jsoner.escape(email), Jsoner.escape(author), Jsoner.escape(message)); }
public DefaultImprovement deserialize(String jsonData) { try { final JsonObject jsonObject = (JsonObject) Jsoner.deserialize(jsonData); return deserialize(jsonObject); } catch (DeserializationException e) { throw new RuntimeException("Can't deserialize JSON: " + jsonData, e); } }
private JsonObject parseJsonFrom(URLConnection urlConnection) throws IOException, DeserializationException { InputStream response = urlConnection.getInputStream(); String content = IOUtil.readFully(response); LOG.info("GitHub API responded successfully."); return (JsonObject) Jsoner.deserialize(content); }
private List<JsonObject> parseJsonFrom(URLConnection urlConnection) throws IOException, DeserializationException { InputStream response = urlConnection.getInputStream(); LOG.info("Reading remote stream from GitHub API"); String content = IOUtil.readFully(response); LOG.info("GitHub API responded successfully."); @SuppressWarnings("unchecked") List<JsonObject> issues = (List<JsonObject>) Jsoner.deserialize(content); LOG.info("GitHub API returned {} Json objects.", issues.size()); return issues; }
private JsonObject readJsonResource(String name) throws DeserializationException, IOException { return (JsonObject) Jsoner.deserialize(new InputStreamReader(getClass().getClassLoader().getResourceAsStream(name))); }
private JsonObject getStatusCheck(MergePullRequestTask task, GitHubApi gitHubApi) throws IOException { String statusesResponse = gitHubApi.get("/repos/" + task.getUpstreamRepositoryName() + "/commits/" + task.getPullRequestSha() + "/status"); return Jsoner.deserialize(statusesResponse, new JsonObject()); }
@Override public String toJson() { final String serializedCommits = Jsoner.serialize(commits); return String.format(JSON_FORMAT, serializedCommits); }
public String serialize(ProjectContributorsSet contributorsSet) { Collection<ProjectContributor> allContributors = contributorsSet.getAllContributors(); String json = Jsoner.serialize(allContributors); LOG.debug("Serialize contributors to: {}", json); return json; }
public void serialize(ContributorsSet contributorsSet) { Collection<Contributor> allContributors = contributorsSet.getAllContributors(); String json = Jsoner.serialize(allContributors); LOG.info("Serialize contributors to: {}", json); IOUtil.writeFile(file, json); }
private String escape(String login) { return Jsoner.escape(login); }
@Override public String toJson() { return String.format(JSON_FORMAT, Jsoner.escape(name), Jsoner.escape(login), Jsoner.escape(profileUrl)); }
private static JsonObject parse(String s) throws Exception { return (JsonObject) Jsoner.deserialize(s); }
private DevInfo(JsonObject dev) { this.mcUUID = UUID.fromString(dev.getString(Jsoner.mintJsonKey("mcUUID", null))); this.slackID = dev.getString(Jsoner.mintJsonKey("slackID", null)); this.name = dev.getString(Jsoner.mintJsonKey("name", null)); }