Skip to main content
summaryrefslogtreecommitdiffstats
blob: 87265d1925e1c06b75839130e96ab1e02183c1ed (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
/*******************************************************************************
 * Copyright (c) 2004 Composent, Inc. and others. All rights reserved. This
 * program and the accompanying materials are made available under the terms of
 * the Eclipse Public License v1.0 which accompanies this distribution, and is
 * available at http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors: Composent, Inc. - initial API and implementation
 ******************************************************************************/
package org.eclipse.ecf.internal.provider.xmpp.smack;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.eclipse.core.runtime.IAdapterManager;
import org.eclipse.ecf.core.ContainerAuthenticationException;
import org.eclipse.ecf.core.ContainerConnectException;
import org.eclipse.ecf.core.identity.ID;
import org.eclipse.ecf.core.identity.IDFactory;
import org.eclipse.ecf.core.identity.Namespace;
import org.eclipse.ecf.core.util.ECFException;
import org.eclipse.ecf.internal.provider.xmpp.XmppPlugin;
import org.eclipse.ecf.provider.comm.DisconnectEvent;
import org.eclipse.ecf.provider.comm.IAsynchEventHandler;
import org.eclipse.ecf.provider.comm.IConnectionListener;
import org.eclipse.ecf.provider.comm.ISynchAsynchConnection;
import org.eclipse.ecf.provider.xmpp.identity.XMPPID;
import org.eclipse.ecf.provider.xmpp.identity.XMPPRoomID;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SSLXMPPConnection;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Message.Type;

public class ECFConnection implements ISynchAsynchConnection {

	/**
	 * 
	 */
	private static final String GOOGLE_TALK_HOST = "talk.google.com";
	public static final String CLIENT_TYPE = "ecf.";
	public static final boolean DEBUG = Boolean.getBoolean("smack.debug");

	protected static final String STRING_ENCODING = "UTF-8";
	public static final String OBJECT_PROPERTY_NAME = ECFConnection.class
			.getName()
			+ ".object";
	protected static final int XMPP_DEFAULT_PORT = 5222;
	protected static final int XMPPS_DEFAULT_PORT = 5223;

	private XMPPConnection connection = null;
	private IAsynchEventHandler handler = null;
	private boolean isStarted = false;
	private String serverName;
	private int serverPort = -1;
	private String serverResource;
	private final Map properties = null;
	private boolean isConnected = false;
	private Namespace namespace = null;

	private boolean google = false;

	private boolean secure = false;

	private boolean disconnecting = false;

	private final PacketListener packetListener = new PacketListener() {
		public void processPacket(Packet arg0) {
			handlePacket(arg0);
		}
	};

	private final ConnectionListener connectionListener = new ConnectionListener() {
		public void connectionClosed() {
			handleConnectionClosed(new IOException("Connection reset by peer"));
		}

		public void connectionClosedOnError(Exception e) {
			handleConnectionClosed(e);
		}
	};

	protected void logException(String msg, Throwable t) {
		XmppPlugin.log(msg, t);
	}

	public Map getProperties() {
		return properties;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.core.runtime.IAdaptable#getAdapter(java.lang.Class)
	 */
	public Object getAdapter(Class adapter) {
		if (adapter == null)
			return null;
		if (adapter.isInstance(this))
			return this;
		final IAdapterManager adapterManager = XmppPlugin.getDefault()
				.getAdapterManager();
		return (adapterManager == null) ? null : adapterManager.loadAdapter(
				this, adapter.getName());
	}

	public XMPPConnection getXMPPConnection() {
		return connection;
	}

	public ECFConnection(boolean google, Namespace ns, IAsynchEventHandler h,
			boolean secure) {
		this.handler = h;
		this.namespace = ns;
		this.google = google;
		this.secure = secure;
		if (DEBUG)
			XMPPConnection.DEBUG_ENABLED = true;
	}

	public ECFConnection(boolean google, Namespace ns, IAsynchEventHandler h) {
		this(google, ns, h, false);
	}

	protected String getPasswordForObject(Object data) {
		String password = null;
		try {
			password = (String) data;
		} catch (final ClassCastException e) {
			return null;
		}
		return password;
	}

	private XMPPID getXMPPID(ID remote) throws ECFException {
		XMPPID jabberID = null;
		try {
			jabberID = (XMPPID) remote;
		} catch (final ClassCastException e) {
			throw new ECFException(e);
		}
		return jabberID;
	}

	public synchronized Object connect(ID remote, Object data, int timeout)
			throws ECFException {
		if (connection != null)
			throw new ECFException("already connected");
		if (timeout > 0)
			SmackConfiguration.setPacketReplyTimeout(timeout);
		Roster.setDefaultSubscriptionMode(Roster.SUBSCRIPTION_MANUAL);

		final XMPPID jabberURI = getXMPPID(remote);
		final String username = jabberURI.getNodename();
		serverName = jabberURI.getHostname();
		serverPort = jabberURI.getPort();
		serverResource = jabberURI.getResourceName();
		if (serverResource == null
				|| serverResource.equals(XMPPID.PATH_DELIMITER)) {
			serverResource = getClientIdentifier();
			jabberURI.setResourceName(serverResource);
		}
		try {
			if (google)
				serverName = GOOGLE_TALK_HOST;
			if (secure) {
				serverPort = (serverPort < 0)?XMPPS_DEFAULT_PORT:serverPort;
				connection = new SSLXMPPConnection(serverName,
						serverPort, jabberURI.getHostname());
			} else {
				serverPort = (serverPort < 0)?XMPP_DEFAULT_PORT:serverPort;
				connection = new XMPPConnection(serverName, serverPort,
						jabberURI.getHostname());
			}
			connection.addPacketListener(packetListener, null);
			connection.addConnectionListener(connectionListener);
			// Login
			connection.login(username, (String) data, serverResource);
			isConnected = true;
		} catch (final XMPPException e) {
			if (e.getMessage().equals("(401)"))
				throw new ContainerAuthenticationException(
						"Password incorrect", e);
			throw new ContainerConnectException(e.getLocalizedMessage(), e);
		}
		return null;
	}

	private String getClientIdentifier() {
		return CLIENT_TYPE + handler.getEventHandlerID().getName();
	}

	public void sendPacket(Packet packet) throws XMPPException {
		if (connection != null)
			connection.sendPacket(packet);
	}

	public synchronized void disconnect() {
		disconnecting = true;
		if (isStarted()) {
			stop();
		}
		if (connection != null) {
			connection.removePacketListener(packetListener);
			connection.removeConnectionListener(connectionListener);
			connection.close();
			isConnected = false;
			connection = null;
		}
	}

	public synchronized boolean isConnected() {
		return (isConnected);
	}

	public synchronized ID getLocalID() {
		if (!isConnected())
			return null;
		try {
			return IDFactory.getDefault().createID(namespace.getName(),
					new Object[] { connection.getConnectionID() });
		} catch (final Exception e) {
			logException("Exception in getLocalID", e);
			return null;
		}
	}

	public synchronized void start() {
		if (isStarted())
			return;
		isStarted = true;
	}

	public boolean isStarted() {
		return isStarted;
	}

	public synchronized void stop() {
		isStarted = false;
	}

	protected void handleConnectionClosed(Exception e) {
		if (!disconnecting) {
			disconnecting = true;
			handler.handleDisconnectEvent(new DisconnectEvent(this, e, null));
		}
	}

	protected void handlePacket(Packet arg0) {
		try {
			final Object val = arg0.getProperty(OBJECT_PROPERTY_NAME);
			if (val != null) {
				handler.handleAsynchEvent(new ECFConnectionObjectPacketEvent(
						this, arg0, val));
			} else {
				handler.handleAsynchEvent(new ECFConnectionPacketEvent(this,
						arg0));
			}
		} catch (final IOException e) {
			logException("Exception in handleAsynchEvent", e);
			try {
				disconnect();
			} catch (final Exception e1) {
				logException("Exception in disconnect()", e1);
			}
		}
	}

	public synchronized void sendAsynch(ID receiver, byte[] data)
			throws IOException {
		if (data == null)
			throw new IOException("no data");
		final Message aMsg = new Message();
		aMsg.setProperty(OBJECT_PROPERTY_NAME, data);
		sendMessage(receiver, aMsg);
	}

	protected void sendMessage(ID receiver, Message aMsg) throws IOException {
		synchronized (this) {
			if (!isConnected())
				throw new IOException("not connected");
			try {
				if (receiver == null)
					throw new IOException(
							"receiver cannot be null for xmpp instant messaging");
				else if (receiver instanceof XMPPID) {
					final XMPPID rcvr = (XMPPID) receiver;
					aMsg.setType(Message.Type.CHAT);
					final String userAtHost = rcvr.getUsernameAtHost();
					final Chat localChat = connection.createChat(userAtHost);
					localChat.sendMessage(aMsg);
				} else if (receiver instanceof XMPPRoomID) {
					final XMPPRoomID roomID = (XMPPRoomID) receiver;
					aMsg.setType(Message.Type.GROUP_CHAT);
					final String to = roomID.getMucString();
					aMsg.setTo(to);
					connection.sendPacket(aMsg);
				} else
					throw new IOException(
							"receiver must be of type XMPPID or XMPPRoomID");
			} catch (final XMPPException e) {
				final IOException result = new IOException(
						"XMPPException in sendMessage: " + e.getMessage());
				result.setStackTrace(e.getStackTrace());
				throw result;
			}
		}
	}

	public synchronized Object sendSynch(ID receiver, byte[] data)
			throws IOException {
		if (data == null)
			throw new IOException("data cannot be null");
		// This is assumed to be disconnect...so we'll just disconnect
		// disconnect();
		return null;
	}

	public void addListener(IConnectionListener listener) {
		// XXX Not yet implemented
	}

	public void removeListener(IConnectionListener listener) {
		// XXX Not yet implemented
	}

	public void sendMessage(ID target, String message) throws IOException {
		if (target == null)
			throw new IOException("target cannot be null");
		if (message == null)
			throw new IOException("message cannot be null");
		final Message aMsg = new Message();
		aMsg.setBody(message);
		sendMessage(target, aMsg);
	}

	public static Map getPropertiesFromPacket(Packet packet) {
		final Map result = new HashMap();
		final Iterator i = packet.getPropertyNames();
		for (; i.hasNext();) {
			final String name = (String) i.next();
			result.put(name, packet.getProperty(name));
		}
		return result;
	}

	public static Packet setPropertiesInPacket(Packet input, Map properties) {
		if (properties != null) {
			for (final Iterator i = properties.keySet().iterator(); i.hasNext();) {
				final Object keyo = i.next();
				final Object val = properties.get(keyo);
				final String key = (keyo instanceof String) ? (String) keyo
						: keyo.toString();
				if (val instanceof Boolean)
					input.setProperty(key, ((Boolean) val).booleanValue());
				else if (val instanceof Double)
					input.setProperty(key, ((Double) val).doubleValue());
				else if (val instanceof Float)
					input.setProperty(key, ((Float) val).floatValue());
				else if (val instanceof Integer)
					input.setProperty(key, ((Integer) val).intValue());
				else if (val instanceof Long)
					input.setProperty(key, ((Long) val).floatValue());
				else if (val instanceof Object)
					input.setProperty(key, val);
			}
		}
		return input;
	}

	public void sendMessage(ID target, ID thread, Type type, String subject,
			String body, Map properties2) throws IOException {
		if (target == null)
			throw new IOException("XMPP target for message cannot be null");
		if (body == null)
			body = "";
		final Message aMsg = new Message();
		aMsg.setBody(body);
		if (thread != null)
			aMsg.setThread(thread.getName());
		if (type != null)
			aMsg.setType(type);
		if (subject != null)
			aMsg.setSubject(subject);
		setPropertiesInPacket(aMsg, properties2);
		sendMessage(target, aMsg);
	}

	public void sendPresenceUpdate(ID target, Presence presence)
			throws IOException {
		if (presence == null)
			throw new IOException("presence cannot be null");
		presence.setFrom(connection.getUser());
		if (target != null)
			presence.setTo(target.getName());
		synchronized (this) {
			if (!isConnected())
				throw new IOException("not connected");
			connection.sendPacket(presence);
		}
	}

	public void sendRosterAdd(String user, String name, String[] groups)
			throws IOException, XMPPException {
		final Roster r = getRoster();
		r.createEntry(user, name, groups);
	}

	public void sendRosterRemove(String user) throws XMPPException, IOException {
		final Roster r = getRoster();
		final RosterEntry re = r.getEntry(user);
		r.removeEntry(re);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.ecf.provider.xmpp.IIMMessageSender#getRoster()
	 */
	public Roster getRoster() throws IOException {
		if (connection == null || !connection.isConnected())
			return null;
		return connection.getRoster();
	}

}

Back to the top