Skip to content

Commit

Permalink
addressing issue #5
Browse files Browse the repository at this point in the history
Change-Id: I47403b58d2283107bb364d52cde50d192d80b2cc
  • Loading branch information
Benoit Corne committed Mar 27, 2015
1 parent 166e2c4 commit 9f02bd1
Show file tree
Hide file tree
Showing 4 changed files with 85 additions and 48 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.ullink.slack.simpleslackapi;

import java.io.IOException;
import java.util.Collection;
import com.ullink.slack.simpleslackapi.impl.SlackChatConfiguration;

Expand All @@ -24,7 +25,7 @@ public interface SlackSession

SlackBot findBotById(String botId);

void connect();
void connect() throws IOException;

SlackMessageHandle deleteMessage(String timeStamp, SlackChannel channel);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import org.json.simple.parser.ParseException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.ConnectException;
import java.util.HashMap;
import java.util.Map;

Expand All @@ -24,6 +25,8 @@ class SlackJSONSessionStatusParser

private String toParse;

private String error;

SlackJSONSessionStatusParser(String toParse)
{
this.toParse = toParse;
Expand All @@ -49,12 +52,21 @@ public String getWebSocketURL()
return webSocketURL;
}

public String getError()
{
return error;
}

void parse() throws ParseException
{
LOGGER.debug("parsing session status : " + toParse);
JSONParser parser = new JSONParser();
JSONObject jsonResponse = (JSONObject) parser.parse(toParse);

Boolean ok = (Boolean)jsonResponse.get("ok");
if (Boolean.FALSE.equals(ok)) {
error = (String)jsonResponse.get("error");
return;
}
JSONArray usersJson = (JSONArray) jsonResponse.get("users");

for (Object jsonObject : usersJson)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.Proxy;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import javax.websocket.DeploymentException;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
Expand Down Expand Up @@ -82,7 +85,7 @@ class SlackWebSocketSessionImpl extends AbstractSlackSessionImpl implements Slac
}

@Override
public void connect()
public void connect() throws IOException
{
long currentTime = System.nanoTime();
while (lastConnectionTime >= 0 && currentTime - lastConnectionTime < TimeUnit.SECONDS.toNanos(30))
Expand All @@ -100,32 +103,45 @@ public void connect()
}
LOGGER.info("connecting to slack");
lastConnectionTime = currentTime;
HttpClient httpClient = getHttpClient();
HttpGet request = new HttpGet(SLACK_HTTPS_AUTH_URL + authToken);
HttpResponse response;
response = httpClient.execute(request);
LOGGER.debug(response.getStatusLine().toString());
String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
SlackJSONSessionStatusParser sessionParser = new SlackJSONSessionStatusParser(jsonResponse);
try
{
HttpClient httpClient = getHttpClient();
HttpGet request = new HttpGet(SLACK_HTTPS_AUTH_URL + authToken);
HttpResponse response = httpClient.execute(request);
String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
SlackJSONSessionStatusParser sessionParser = new SlackJSONSessionStatusParser(jsonResponse);
sessionParser.parse();
users = sessionParser.getUsers();
bots = sessionParser.getBots();
channels = sessionParser.getChannels();
LOGGER.info(users.size() + " users found on this session");
LOGGER.info(bots.size() + " bots found on this session");
LOGGER.info(channels.size() + " channels found on this session");

String wssurl = sessionParser.getWebSocketURL();
}
catch (ParseException e1)
{
LOGGER.error(e1.toString());
}
if (sessionParser.getError() != null)
{
LOGGER.error("Error during authentication : " + sessionParser.getError());
throw new ConnectException(sessionParser.getError());
}
users = sessionParser.getUsers();
bots = sessionParser.getBots();
channels = sessionParser.getChannels();
LOGGER.info(users.size() + " users found on this session");
LOGGER.info(bots.size() + " bots found on this session");
LOGGER.info(channels.size() + " channels found on this session");
String wssurl = sessionParser.getWebSocketURL();

LOGGER.debug("retrieved websocket URL : " + wssurl);
ClientManager client = ClientManager.createClient();
client.getProperties().put(ClientProperties.LOG_HTTP_UPGRADE, true);
if (proxyAddress != null)
{
client.getProperties().put(ClientProperties.PROXY_URI, "http://" + proxyAddress + ":" + proxyPort);
}
final MessageHandler handler = this;
LOGGER.debug("initiating connection to websocket");
LOGGER.debug("retrieved websocket URL : " + wssurl);
ClientManager client = ClientManager.createClient();
client.getProperties().put(ClientProperties.LOG_HTTP_UPGRADE, true);
if (proxyAddress != null)
{
client.getProperties().put(ClientProperties.PROXY_URI, "http://" + proxyAddress + ":" + proxyPort);
}
final MessageHandler handler = this;
LOGGER.debug("initiating connection to websocket");
try
{
websocketSession = client.connectToServer(new Endpoint()
{
@Override
Expand All @@ -135,27 +151,25 @@ public void onOpen(Session session, EndpointConfig config)
}

}, URI.create(wssurl));
for (SlackMessageListener slackMessageListener : messageListeners)
{
slackMessageListener.onSessionLoad(this);
}
if (websocketSession != null)
{
LOGGER.debug("websocket connection established");
LOGGER.info("slack session ready");
}
if (connectionMonitoringThread == null)
{
LOGGER.debug("starting connection monitoring");
startConnectionMonitoring();
}
}
catch (Exception e)
catch (DeploymentException e)
{
// TODO : improve exception handling
e.printStackTrace();
LOGGER.error(e.toString());
}
for (SlackMessageListener slackMessageListener : messageListeners)
{
slackMessageListener.onSessionLoad(this);
}
if (websocketSession != null)
{
LOGGER.debug("websocket connection established");
LOGGER.info("slack session ready");
}
if (connectionMonitoringThread == null)
{
LOGGER.debug("starting connection monitoring");
startConnectionMonitoring();
}

}

private void startConnectionMonitoring()
Expand Down Expand Up @@ -215,7 +229,8 @@ public SlackMessageHandle sendMessage(SlackChannel channel, String message, Slac
List<NameValuePair> nameValuePairList = new ArrayList<>();
nameValuePairList.add(new BasicNameValuePair("token", authToken));
nameValuePairList.add(new BasicNameValuePair("channel", channel.getId()));
if (chatConfiguration.asUser) {
if (chatConfiguration.asUser)
{
nameValuePairList.add(new BasicNameValuePair("as_user", "true"));
}
nameValuePairList.add(new BasicNameValuePair("text", message));
Expand All @@ -227,7 +242,8 @@ public SlackMessageHandle sendMessage(SlackChannel channel, String message, Slac
{
nameValuePairList.add(new BasicNameValuePair("icon_emoji", chatConfiguration.avatarDescription));
}
if (chatConfiguration.userName != null) {
if (chatConfiguration.userName != null)
{
nameValuePairList.add(new BasicNameValuePair("username", chatConfiguration.userName));
}
if (attachment != null)
Expand Down Expand Up @@ -263,7 +279,7 @@ public SlackMessageHandle deleteMessage(String timeStamp, SlackChannel channel)
nameValuePairList.add(new BasicNameValuePair("ts", timeStamp));
try
{
request.setEntity(new UrlEncodedFormEntity(nameValuePairList,"UTF-8"));
request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
HttpResponse response = client.execute(request);
String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
LOGGER.debug("PostMessage return: " + jsonResponse);
Expand Down Expand Up @@ -291,7 +307,7 @@ public SlackMessageHandle updateMessage(String timeStamp, SlackChannel channel,
nameValuePairList.add(new BasicNameValuePair("text", message));
try
{
request.setEntity(new UrlEncodedFormEntity(nameValuePairList,"UTF-8"));
request.setEntity(new UrlEncodedFormEntity(nameValuePairList, "UTF-8"));
HttpResponse response = client.execute(request);
String jsonResponse = CharStreams.toString(new InputStreamReader(response.getEntity().getContent()));
LOGGER.debug("PostMessage return: " + jsonResponse);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.ullink.slack.simpleslackapi.impl;

import java.io.IOException;
import com.ullink.slack.simpleslackapi.SlackAttachment;
import com.ullink.slack.simpleslackapi.SlackChannel;
import com.ullink.slack.simpleslackapi.SlackMessage;
Expand Down Expand Up @@ -69,7 +70,14 @@ public SlackMessageHandle updateMessage(String timeStamp, SlackChannel channel,
}

};
session.connect();
try
{
session.connect();
}
catch (IOException e)
{
e.printStackTrace();
}
}

@Test
Expand Down

0 comments on commit 9f02bd1

Please sign in to comment.