Commit 6c78e9a9 authored by Daniel Henninger's avatar Daniel Henninger Committed by dhenninger

Adding in updated code from Ravin and Patrick.

git-svn-id: http://svn.igniterealtime.org/svn/repos/wildfire/trunk@7306 b35dd754-fafc-0310-a699-88a17e54d16e
parent 2378b9e4
...@@ -11,12 +11,18 @@ ...@@ -11,12 +11,18 @@
package org.jivesoftware.wildfire.gateway.protocols.simple; package org.jivesoftware.wildfire.gateway.protocols.simple;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParserFactory;
import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.QName;
import org.jivesoftware.util.Log; import org.jivesoftware.util.Log;
import org.xml.sax.Attributes; import org.xml.sax.Attributes;
import org.xml.sax.SAXException; import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.helpers.DefaultHandler;
import org.xmpp.packet.Presence;
/** /**
* This class performs conversions between presence packets of XMPP and SIMPLE formats. * This class performs conversions between presence packets of XMPP and SIMPLE formats.
...@@ -166,6 +172,15 @@ public class SimplePresence { ...@@ -166,6 +172,15 @@ public class SimplePresence {
return this.tupleStatus; return this.tupleStatus;
} }
private String getEightLength(int hash) {
StringBuffer buffer = new StringBuffer(Integer.toHexString(hash));
while (buffer.length() < 8) {
buffer.insert(0, "0");
}
return new String(buffer);
}
public String toXML() { public String toXML() {
String result = String result =
...@@ -175,8 +190,13 @@ public class SimplePresence { ...@@ -175,8 +190,13 @@ public class SimplePresence {
" xmlns:rpid='urn:ietf:params:xml:ns:pidf:rpid'" + " xmlns:rpid='urn:ietf:params:xml:ns:pidf:rpid'" +
" xmlns:c='urn:ietf:params:xml:ns:pidf:cipid'" + " xmlns:c='urn:ietf:params:xml:ns:pidf:cipid'" +
" entity='" + entity + "'>" + " entity='" + entity + "'>" +
"<tuple id='t" + hashCode() + "'><status><basic>" + tupleStatus.toString() + "</basic></status></tuple>" + "<tuple id='t" + getEightLength(tupleStatus.hashCode()) + "'><status><basic>" + tupleStatus.toString() + "</basic></status></tuple>" +
"<dm:person id='p" + hashCode() + "'><rpid:activities><rpid:" + rpid.toString() + "/></rpid:activities></dm:person></presence>"; "<dm:person id='p" + getEightLength(this.hashCode()) + "'><rpid:activities><rpid:" + rpid.toString() + "/></rpid:activities>" +
// "<tuple><status><basic>" + tupleStatus.toString() + "</basic></status></tuple>" +
// "<dm:person><rpid:activities><rpid:" + rpid.toString() + "/></rpid:activities>" +
((dmNote != null && !dmNote.equals("")) ? "<dm:note>" + dmNote + "</dm:note>" : "") +
"</dm:person>" +
"</presence>";
// DocumentFactory docFactory = DocumentFactory.getInstance(); // DocumentFactory docFactory = DocumentFactory.getInstance();
// //
...@@ -205,6 +225,7 @@ public class SimplePresence { ...@@ -205,6 +225,7 @@ public class SimplePresence {
return result; return result;
} }
// public Presence convertSIPPresenceToXMPP(String sipPresence) { // public Presence convertSIPPresenceToXMPP(String sipPresence) {
// Presence xmppPresence = new Presence(); // Presence xmppPresence = new Presence();
// //
...@@ -344,16 +365,7 @@ public class SimplePresence { ...@@ -344,16 +365,7 @@ public class SimplePresence {
tupleStatus = TupleStatus.getTupleStatus(data); tupleStatus = TupleStatus.getTupleStatus(data);
} }
catch (IllegalArgumentException ex) { catch (IllegalArgumentException ex) {
// Ignore
} }
// if(data.equals("open")) {
// statusType = "online";
// statusName = "Online";
// }
// else {
// statusType = "offline";
// statusName = "Offline";
// }
} }
else if (isStatusType) { else if (isStatusType) {
// statusType = data; // statusType = data;
......
/**
* $Revision$
* $Date$
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.wildfire.gateway.protocols.simple;
import java.util.Hashtable;
import org.jivesoftware.util.Log;
/**
* This class represents the roster of SIP transport.
* <br><br>
* By now the SIP has no rosters stored so clients got to implement rosters themselves.
* @author Patrick Siu
* @version 0.0.2
*/
public class SimpleRoster {
private SimpleSession mySimpleSession;
private Hashtable<String, SimpleRosterItem> rosterItemList;
private boolean activated = false;
public SimpleRoster(SimpleSession mySimpleSession) {
if (mySimpleSession == null)
throw new NullPointerException("The SIP session provided cannot be null!");
this.mySimpleSession = mySimpleSession;
}
public synchronized void activate() {
this.activated = true;
}
public synchronized void deactivate() {
this.activated = false;
}
public void addEntry(String userid, SimpleRosterItem item) {
rosterItemList.put(userid, item);
}
public void removeEntry(String userid) {
rosterItemList.remove(userid);
}
public SimpleRosterItem getEntry(String userid) {
return rosterItemList.get(userid);
}
/**
* Loads the SIP roster from persistent store.
*/
public void loadRoster() {
// Roster should be loaded in persistent stores.
}
/**
* Stores the SIP roster into persistent store.
*/
public void storeRoster() {
// Roster should be stored in persistent stores.
}
public void finalize() {
Log.debug("SimpleRoster shutting down!");
rosterItemList.clear();
}
}
/**
* $Revision$
* $Date$
*
* Copyright (C) 2006 Jive Software. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package org.jivesoftware.wildfire.gateway.protocols.simple;
import javax.sip.Dialog;
/**
* This class represents a roster item of SIP transport.
*/
public class SimpleRosterItem {
private String userid;
private String nickname;
private SimplePresence presence;
private Dialog outgoingDialog;
private long seqNum;
public SimpleRosterItem(String userid, String nickname, long seqNum) {
this.userid = userid;
this.nickname = nickname;
this.seqNum = seqNum;
presence = new SimplePresence();
presence.setTupleStatus(SimplePresence.TupleStatus.CLOSED);
outgoingDialog = null;
}
public void incrementSeqNum() {
seqNum++;
}
public long getSeqNum() {
return seqNum;
}
public void updatePresence(String newPresence) throws Exception {
presence.parse(newPresence);
}
public void setOutgoingDialog(Dialog outgoingDialog) {
this.outgoingDialog = outgoingDialog;
}
public Dialog getOutgoingDialog() {
return outgoingDialog;
}
}
\ No newline at end of file
...@@ -11,7 +11,9 @@ ...@@ -11,7 +11,9 @@
package org.jivesoftware.wildfire.gateway.protocols.simple; package org.jivesoftware.wildfire.gateway.protocols.simple;
import java.net.InetAddress; import java.net.InetAddress;
import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
...@@ -19,11 +21,18 @@ import java.util.Properties; ...@@ -19,11 +21,18 @@ import java.util.Properties;
import java.util.TooManyListenersException; import java.util.TooManyListenersException;
import javax.sip.ClientTransaction; import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.InvalidArgumentException;
import javax.sip.ListeningPoint; import javax.sip.ListeningPoint;
import javax.sip.RequestEvent;
import javax.sip.ServerTransaction;
import javax.sip.SipException; import javax.sip.SipException;
import javax.sip.SipFactory; import javax.sip.SipFactory;
import javax.sip.SipProvider; import javax.sip.SipProvider;
import javax.sip.SipStack; import javax.sip.SipStack;
import javax.sip.TransactionAlreadyExistsException;
import javax.sip.TransactionDoesNotExistException;
import javax.sip.TransactionUnavailableException;
import javax.sip.address.Address; import javax.sip.address.Address;
import javax.sip.address.AddressFactory; import javax.sip.address.AddressFactory;
import javax.sip.address.SipURI; import javax.sip.address.SipURI;
...@@ -53,7 +62,7 @@ public class SimpleSession extends TransportSession { ...@@ -53,7 +62,7 @@ public class SimpleSession extends TransportSession {
private String sipHost; private String sipHost;
private int sipPort; private int sipPort;
private String username; private String username;
private String sessionId = ""; private String sessionId = null;
private long seqNum; private long seqNum;
private ListeningPoint tcp = null; private ListeningPoint tcp = null;
...@@ -66,6 +75,7 @@ public class SimpleSession extends TransportSession { ...@@ -66,6 +75,7 @@ public class SimpleSession extends TransportSession {
private HeaderFactory headerFactory; private HeaderFactory headerFactory;
private SipStack sipStack; private SipStack sipStack;
private SimpleSessionListener myListener; private SimpleSessionListener myListener;
private SimpleRoster myRoster;
/** /**
...@@ -88,15 +98,18 @@ public class SimpleSession extends TransportSession { ...@@ -88,15 +98,18 @@ public class SimpleSession extends TransportSession {
init(); init();
} }
/** /** This process initializes the session by building (or retrieving) a SIP Stack and adding listeners to it. */
* The initialization process.
*/
private void init() { private void init() {
// Initialize local variable first!
myRoster = new SimpleRoster(this);
seqNum = 1L;
sipHost = JiveGlobals.getProperty("plugin.gateway.sip.connecthost", ""); sipHost = JiveGlobals.getProperty("plugin.gateway.sip.connecthost", "");
sipPort = ((SimpleTransport) transport).generateListenerPort(); sipPort = ((SimpleTransport) transport).generateListenerPort();
// Initialize the SipFactory // Initialize the SipFactory
sipFactory = SipFactory.getInstance(); sipFactory = SipFactory.getInstance();
if (sipFactory.getPathName() == null || !sipFactory.getPathName().equals("gov.nist"))
sipFactory.setPathName("gov.nist"); sipFactory.setPathName("gov.nist");
// Initialize the SipStack for this session // Initialize the SipStack for this session
...@@ -135,9 +148,11 @@ public class SimpleSession extends TransportSession { ...@@ -135,9 +148,11 @@ public class SimpleSession extends TransportSession {
if (tcp == null) { if (tcp == null) {
tcp = sipStack.createListeningPoint(localIP, sipPort, ListeningPoint.TCP); tcp = sipStack.createListeningPoint(localIP, sipPort, ListeningPoint.TCP);
sipPort = tcp.getPort();
} }
if (udp == null) { if (udp == null) {
udp = sipStack.createListeningPoint(localIP, sipPort, ListeningPoint.UDP); udp = sipStack.createListeningPoint(localIP, sipPort, ListeningPoint.UDP);
sipPort = udp.getPort();
} }
Iterator sipProviderIterator = sipStack.getSipProviders(); Iterator sipProviderIterator = sipStack.getSipProviders();
...@@ -157,7 +172,6 @@ public class SimpleSession extends TransportSession { ...@@ -157,7 +172,6 @@ public class SimpleSession extends TransportSession {
udpSipProvider = sipStack.createSipProvider(udp); udpSipProvider = sipStack.createSipProvider(udp);
} catch (Exception ex) { } catch (Exception ex) {
Log.debug(ex); Log.debug(ex);
return;
} }
try { try {
...@@ -166,28 +180,27 @@ public class SimpleSession extends TransportSession { ...@@ -166,28 +180,27 @@ public class SimpleSession extends TransportSession {
udpSipProvider.addSipListener(myListener); udpSipProvider.addSipListener(myListener);
} catch (TooManyListenersException ex) { } catch (TooManyListenersException ex) {
Log.debug(ex); Log.debug(ex);
return;
} }
try { try {
sipStack.start(); sipStack.start();
} catch (SipException ex) { } catch (SipException ex) {
Log.debug(ex); Log.debug(ex);
return;
} }
seqNum = 1L;
} }
/** /**
* Perform rollback action once the login fails or logout goes on the way. * Perform rollback action once the login fails or logout goes on the way.
*/ */
private void rollback() { private void rollback() {
// if (myListener != null)
} }
public void updateStatus(PresenceType presenceType, String verboseStatus) { public void updateStatus(PresenceType presenceType, String verboseStatus) {
Log.debug("SimpleSession(" + getJID().getNode() + ").updateStatus: Method commenced!"); Log.debug("SimpleSession(" + getJID().getNode() + ").updateStatus: Method commenced!");
SimplePresence simplePresence = ((SimpleTransport) getTransport()).convertJabStatusToSIP(presenceType);
} }
public void addContact(RosterItem item) { public void addContact(RosterItem item) {
...@@ -195,88 +208,153 @@ public class SimpleSession extends TransportSession { ...@@ -195,88 +208,153 @@ public class SimpleSession extends TransportSession {
if (item.getNickname() != null && !item.getNickname().equals("")) { if (item.getNickname() != null && !item.getNickname().equals("")) {
nickname = item.getNickname(); nickname = item.getNickname();
} }
lockRoster(item.getJid().toString());
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Roster of " + item.getJid().toString() + " locked!");
JID destJid = item.getJid();
String destId = ((SimpleTransport) transport).convertJIDToID(destJid);
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Starting addContact function for " + destId);
Request subscribeRequest = null;
try {
subscribeRequest = prepareSubscribeRequest(destId);
subscribeRequest.addHeader(headerFactory.createExpiresHeader(365 * 24 * 60 * 60));
}
catch (Exception e) {
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Unable to prepare SUBSCRIBE request.", e);
unlockRoster(item.getJid().toString());
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Roster of " + item.getJid().toString() + " unlocked!");
return;
}
try {
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.ACK));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.BYE));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.CANCEL));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.INFO));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.INVITE));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.MESSAGE));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.NOTIFY));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.OPTIONS));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.REFER));
subscribeRequest.addHeader(headerFactory.createAllowHeader(Request.SUBSCRIBE));
subscribeRequest.addHeader(headerFactory.createEventHeader("presence"));
subscribeRequest.addHeader(headerFactory.createAcceptHeader("application", "pidf+xml"));
}
catch (Exception e) {
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Unable to add a header", e);
}
try {
sendRequest(subscribeRequest, ListeningPoint.UDP);
}
catch (Exception e) {
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Unable to send request.", e);
unlockRoster(item.getJid().toString());
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Roster of " + item.getJid().toString() + " unlocked!");
return;
}
destJid = getTransport().convertIDToJID(destId);
try {
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Adding contact '" + destJid.toString() + "' to roster...");
getTransport().addOrUpdateRosterItem(getJID(), destJid, nickname, item.getGroups());
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Contact '" + destJid.toString() + "' added!");
}
catch (Exception ex) {
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Unable to add contact.", ex);
}
unlockRoster(item.getJid().toString());
Log.debug("SimpleSession(" + jid.getNode() + ").addContact: Roster of " + item.getJid().toString() + " unlocked!");
}
public void removeContact(RosterItem item) {
String nickname = getTransport().convertJIDToID(item.getJid());
if (item.getNickname() != null && !item.getNickname().equals("")) {
nickname = item.getNickname();
}
lockRoster(item.getJid().toString()); lockRoster(item.getJid().toString());
Log.debug("SimpleSession(" + jid.getNode() + ").removeContact: Roster of " + item.getJid().toString() + " locked!");
JID destJid = item.getJid(); JID destJid = item.getJid();
String destId = ((SimpleTransport) transport).convertJIDToID(destJid); String destId = ((SimpleTransport) transport).convertJIDToID(destJid);
Log.debug("SimpleSession(" + this.jid.getNode() + ").addContact: Starting addContact function for " + destId); Log.debug("SimpleSession(" +jid.getNode() + ").removeContact: Starting addContact function for " + destId);
List<Header> customHeaders = new ArrayList<Header>(13); List<Header> customHeaders = new ArrayList<Header>(13);
try { customHeaders.add(headerFactory.createExpiresHeader(365 * 24 * 60 * 60)); } try { customHeaders.add(headerFactory.createExpiresHeader(0)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.ACK)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.BYE)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.CANCEL)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.INFO)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.INVITE)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.MESSAGE)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.NOTIFY)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.OPTIONS)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.REFER)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.SUBSCRIBE)); }
catch (Exception e) {} // Ignore catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createEventHeader("presence")); } try { customHeaders.add(headerFactory.createEventHeader("presence")); }
catch (Exception e) {} // Ignore catch (Exception e) {} // Ignore
prepareRequest(RequestType.SUBSCRIBE, destId, null, null, 1L, 70, customHeaders, null); // prepareRequest(RequestType.SUBSCRIBE, destId, null, null, 1L, 70, customHeaders, null);
destJid = getTransport().convertIDToJID(destId); destJid = getTransport().convertIDToJID(destId);
try { try {
Log.debug("SimpleSession(" + getJID().getNode() + ").addContact: Adding contact '" + destJid.toString() + "' to roster..."); Log.debug("SimpleSession(" + jid.getNode() + ").removeContact: Removing contact '" + destJid.toString() + "' from roster...");
getTransport().addOrUpdateRosterItem(getJID(), destJid, nickname, item.getGroups()); getTransport().removeFromRoster(getJID(), destJid);
Log.debug("SimpleSession(" + getJID().getNode() + ").addContact: Contact '" + destJid.toString() + "' added!"); Log.debug("SimpleSession(" + jid.getNode() + ").removeContact: Contact '" + destJid.toString() + "' removed!");
} }
catch (Exception ex) { catch (Exception ex) {
Log.debug("SimpleSession(" + getJID().getNode() + ").addContact: Unable to add contact.", ex); Log.debug("SimpleSession(" + jid.getNode() + ").removeContact: Unable to add contact.", ex);
}
} }
public void removeContact(RosterItem item) { unlockRoster(item.getJid().toString());
Log.debug("SimpleSession(" + jid.getNode() + ").removeContact: Roster of " + item.getJid().toString() + " unlocked!");
} }
public void updateContact(RosterItem item) { public void updateContact(RosterItem item) {
Log.debug("SimpleSession(" + jid.getNode() + ").updateContact: I was called!");
} }
public void sendMessage(JID jid, String message) { public void sendMessage(JID jid, String message) {
Log.debug("SimpleSession(" + this.jid.getNode() + "): Starting message sending process."); Log.debug("SimpleSession(" + jid.getNode() + "): Starting message sending process.");
ContentTypeHeader contentTypeHeader = null; ContentTypeHeader contentTypeHeader = null;
try { try {
contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain"); contentTypeHeader = headerFactory.createContentTypeHeader("text", "plain");
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + this.jid.getNode() + ").sendMessage: Unable to initiate ContentType header.", e); Log.debug("SimpleSession(" + jid.getNode() + ").sendMessage: Unable to initiate ContentType header.", e);
return; return;
} }
Log.debug("SimpleSession(" + this.jid.getNode() + "): Finished adding ContentType header."); Log.debug("SimpleSession(" + jid.getNode() + "): Finished adding ContentType header.");
MessageContent content = new MessageContent(contentTypeHeader, message); MessageContent content = new MessageContent(contentTypeHeader, message);
if (!prepareRequest(RequestType.MESSAGE, ((SimpleTransport) transport).convertJIDToID(jid), null, null, 1L, 70, null, content)) {
Log.debug("SimpleSession(" + this.jid.getNode() + ").sendMessage: Unable to send message!"); try {
Request request = prepareMessageRequest(content, ((SimpleTransport) transport).convertJIDToID(jid));
sendRequest(request, ListeningPoint.UDP);
} }
catch (Exception e) {
Log.debug("SimpleSession(" + jid.getNode() + ").sendMessage: Unable to send message.", e);
}
// if (!prepareRequest(RequestType.MESSAGE, ((SimpleTransport) transport).convertJIDToID(jid), null, null, 1L, 70, null, content)) {
// Log.debug("SimpleSession(" + this.jid.getNode() + ").sendMessage: Unable to send message!");
// }
} }
public void sendServerMessage(String message) { public void sendServerMessage(String message) {
Log.debug("SimpleSession(" + jid.getNode() + ").sendServerMessage: I was called!");
} }
public void sendChatState(JID jid, ChatStateType chatState) { public void sendChatState(JID jid, ChatStateType chatState) {
Log.debug("SimpleSession(" + jid.getNode() + ").sendChatState: I was called!");
} }
public void retrieveContactStatus(JID jid) { public void retrieveContactStatus(JID jid) {
Log.debug("SimpleSession(" + this.jid.getNode() + ").retrieveContactStatus: I was called!");
} }
public void resendContactStatuses(JID jid) { public void resendContactStatuses(JID jid) {
Log.debug("SimpleSession(" + this.jid.getNode() + ").resendContactStatuses: I was called!");
} }
...@@ -285,58 +363,48 @@ public class SimpleSession extends TransportSession { ...@@ -285,58 +363,48 @@ public class SimpleSession extends TransportSession {
if (!this.isLoggedIn()) { if (!this.isLoggedIn()) {
this.setLoginStatus(TransportLoginStatus.LOGGING_IN); this.setLoginStatus(TransportLoginStatus.LOGGING_IN);
Log.debug("SimpleSession(" + getJID().getNode() + ").login: Start login as " + registration.getUsername() + "."); Log.debug("SimpleSession(" + jid.getNode() + ").login: Start login as " + registration.getUsername() + ".");
List<Header> customHeaders = new ArrayList<Header>(13); Request registerRequest = prepareRegisterRequest();
try { customHeaders.add(headerFactory.createExpiresHeader(365 * 24 * 60 * 60)); }
catch (Exception e) { if (registerRequest.getHeader(CallIdHeader.NAME) == null) {
Log.debug("SimpleSession(" + getJID().getNode() + ").login: " + Log.debug("SimpleSession(" + getJID().getNode() + ").login: Unable to create a SIP session ID!!");
"Unable to set the expiry interval, which is essential for a login.", e); this.setLoginStatus(TransportLoginStatus.LOGGED_OUT);
return; return;
} }
else {
sessionId = ((CallIdHeader) registerRequest.getHeader(CallIdHeader.NAME)).getCallId();
}
try { customHeaders.add(headerFactory.createAllowHeader(Request.ACK)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.BYE)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.CANCEL)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.INFO)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.INVITE)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.MESSAGE)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.NOTIFY)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.OPTIONS)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.REFER)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createAllowHeader(Request.SUBSCRIBE)); }
catch (Exception e) {} // Ignore
try { customHeaders.add(headerFactory.createEventHeader("presence")); }
catch (Exception e) {} // Ignore
String myUsername = registration.getUsername();
if (myUsername.indexOf("sip:") < 0) myUsername = "sip:" + myUsername;
if (myUsername.indexOf("@") < 0) myUsername = myUsername + "@" + sipHost;
String callId = null;
try { try {
callId = udpSipProvider.getNewCallId().getCallId(); registerRequest.addHeader(headerFactory.createExpiresHeader(365 * 24 * 60 * 60));
this.sessionId = callId;
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").login: Unable to create a SIP session ID!!", e); Log.debug("SimpleSession(" + jid.getNode() + ").login: " +
"Unable to set the expiry interval, which is essential for a login.", e);
this.setLoginStatus(TransportLoginStatus.LOGGED_OUT); this.setLoginStatus(TransportLoginStatus.LOGGED_OUT);
return; return;
} }
Log.debug("SimpleSession(" + getJID().getNode() + ").login: Created Session ID = '" + this.sessionId + "'!!"); try {
registerRequest.addHeader(headerFactory.createAllowHeader(Request.ACK));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.BYE));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.CANCEL));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.INFO));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.INVITE));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.MESSAGE));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.NOTIFY));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.OPTIONS));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.REFER));
registerRequest.addHeader(headerFactory.createAllowHeader(Request.SUBSCRIBE));
}
catch (Exception e) {} // Ignore
if (!prepareRequest(RequestType.REGISTER, myUsername, null, this.sessionId, seqNum++, 70, customHeaders, null)) { try {
sendRequest(registerRequest, ListeningPoint.UDP);
}
catch (Exception e) {
Log.debug("SimpleSession(" + jid.getNode() + ").login: Unable to send login packet.", e);
this.setLoginStatus(TransportLoginStatus.LOGGED_OUT); this.setLoginStatus(TransportLoginStatus.LOGGED_OUT);
} }
} }
...@@ -345,23 +413,52 @@ public class SimpleSession extends TransportSession { ...@@ -345,23 +413,52 @@ public class SimpleSession extends TransportSession {
public void logout() { public void logout() {
this.setLoginStatus(TransportLoginStatus.LOGGING_OUT); this.setLoginStatus(TransportLoginStatus.LOGGING_OUT);
myRoster.deactivate();
// Lots of logout work here... // Lots of logout work here...
Log.debug("SimpleSession(" + getJID().getNode() + ").logout: Preparing logout packet..."); Log.debug("SimpleSession(" + getJID().getNode() + ").logout: Preparing logout packet...");
List<Header> customHeaders = new ArrayList<Header>(1); Request registerRequest = prepareRegisterRequest();
try { customHeaders.add(headerFactory.createExpiresHeader(0)); }
try {
registerRequest.addHeader(headerFactory.createExpiresHeader(0));
sendRequest(registerRequest, ListeningPoint.UDP);
}
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").logout: " + Log.debug("SimpleSession(" + jid.getNode() + ").login: Unable to logout.", e);
"Unable to set the expiry interval, which is essential for a logout.", e); this.setLoginStatus(TransportLoginStatus.LOGGED_IN);
return; return;
} // Ignore }
// List<Header> customHeaders = new ArrayList<Header>(1);
// try { customHeaders.add(headerFactory.createExpiresHeader(0)); }
// catch (Exception e) {
// Log.debug("SimpleSession(" + getJID().getNode() + ").logout: " +
// "Unable to set the expiry interval, which is essential for a logout.", e);
// return;
// }
// String myUsername = registration.getUsername();
// if (myUsername.indexOf("sip:") < 0) myUsername = "sip:" + myUsername;
// if (myUsername.indexOf("@") < 0) myUsername = myUsername + "@" + sipHost;
//
// prepareRequest(RequestType.REGISTER, myUsername, null, this.sessionId, seqNum++, 70, customHeaders, null);
this.setLoginStatus(TransportLoginStatus.LOGGED_OUT);
}
public void sipUserLoggedIn() {
myRoster.activate();
getRegistration().setLastLogin(new Date());
setLoginStatus(TransportLoginStatus.LOGGED_IN);
}
public void sipUserLoggedOut() {
// If anybody subscribed me, send NOTIFY or subscription termination
String myUsername = registration.getUsername(); myRoster.deactivate();
if (myUsername.indexOf("sip:") < 0) myUsername = "sip:" + myUsername;
if (myUsername.indexOf("@") < 0) myUsername = myUsername + "@" + sipHost;
prepareRequest(RequestType.REGISTER, myUsername, null, this.sessionId, seqNum++, 70, customHeaders, null); setLoginStatus(TransportLoginStatus.LOGGED_OUT);
// this.setLoginStatus(TransportLoginStatus.LOGGED_OUT);
} }
...@@ -378,12 +475,14 @@ public class SimpleSession extends TransportSession { ...@@ -378,12 +475,14 @@ public class SimpleSession extends TransportSession {
try { try {
sipStack.deleteSipProvider(tcpSipProvider); sipStack.deleteSipProvider(tcpSipProvider);
sipStack.deleteSipProvider(udpSipProvider); sipStack.deleteSipProvider(udpSipProvider);
Log.debug("SimpleSession(" + jid.getNode() + ").shutdown: SIP Providers deleted.");
sipStack.deleteListeningPoint(tcp); sipStack.deleteListeningPoint(tcp);
sipStack.deleteListeningPoint(udp); sipStack.deleteListeningPoint(udp);
Log.debug("SimpleSession(" + jid.getNode() + ").shutdown: Listening points deleted.");
} }
catch (Exception ex) { catch (Exception ex) {
Log.debug(ex); Log.debug("SimpleSession for " + jid.getNode() + " is unable to gracefully shut down.", ex);
Log.debug("SimpleSession for " + jid.getNode() + " is unable to gracefully shut down.");
} }
sipStack.stop(); sipStack.stop();
...@@ -453,103 +552,111 @@ public class SimpleSession extends TransportSession { ...@@ -453,103 +552,111 @@ public class SimpleSession extends TransportSession {
} }
/** /**
* Prepares a Request packet. * Sends a request with the specified request and transport.
* <br><br> * @param request The request packet.
* The "From", "To", "Via", "Contact", "CSeq", "MaxForwards" and "CallId" headers, * @param transport The transport protocol used.
* as well as the content (if provided) are prepared in the method.
* <br>
* Additional headers should be provided as customer headers. See the "headers" parameter for further details.
* @param requestType An inner request type enum
* @param destination The recipient of this request
* @param toTag Additional tag code of the destination. Can usually leave it <code>null</code>.
* @param callId A String representing an ongoing SIP CallID. Leave it <code>null</code> if a new CallID should be generated.
* @param seqNum A sequence number for an ongoing session.
* @param maxForward Maximum times of forwarding allowed for this packet.
* @param headers Additional headers that have to be added. Leave <code>null</code> if no custom header is to be added.
* @param content An object containing the content of the message, as well as the header defining the content type.
* Can leave <code>null</code> if no content is to be specified.
* @see org.jivesoftware.wildfire.gateway.protocols.simple.SimpleSession.RequestType
*/ */
private boolean prepareRequest( private void sendRequest(Request request, String transport)
RequestType requestType, throws TransactionUnavailableException, TransactionDoesNotExistException, SipException {
String destination, sendRequest(request, transport, null);
String toTag, }
String callId,
long seqNum, /**
int maxForward, * Sends a request with the specified request and transport.
List<Header> headers, * @param request The request packet.
MessageContent content) { * @param transport The transport protocol used.
String myJiveId = this.jid.getNode(); * @param dialog The dialog for a persistent transaction.
String mySipUsername = registration.getUsername(); * Leave it <code>null</code> if no dialog is associated with this request.
*/
private void sendRequest(Request request, String transport, Dialog dialog)
throws TransactionUnavailableException, TransactionDoesNotExistException, SipException {
for (Iterator sipProviders = sipStack.getSipProviders(); sipProviders.hasNext(); ) {
SipProvider provider = (SipProvider) sipProviders.next();
if (provider.getListeningPoint(transport) != null) {
Log.debug("Sending packet: \n" + request.toString() + "\n========\n");
ClientTransaction transaction = provider.getNewClientTransaction(request);
if (dialog != null)
dialog.sendRequest(transaction);
else
transaction.sendRequest();
return;
}
}
Log.debug("SimpleSession(" + this.jid.getNode() + "): No SipProvider found for that transport!");
}
/**
* @param destUri The SipURI for the destination. Leave <code>null</code> if a loopback request (e.g. REGISTER) is being made.
* @param toTag The tag for to header. Can leave null.
* @param requestUri The Request URI to set in the message. Leave null if the default destination SipURI should be used.
*/
private Request prepareRequest(RequestType requestType, SipURI destUri, String toTag, SipURI requestUri, String callId, long seqNum) {
Request request = null;
String myJiveId = this.jid.getNode();
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing request packet of type '" + requestType + "'"); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing request packet of type '" + requestType + "'");
try {
// Prepare request packet first
request = messageFactory.createRequest(null);
request.setMethod(requestType.toString());
}
catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing request.", e);
}
// Prepare "From" header // Prepare "From" header
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"From\" header..."); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"From\" header...");
FromHeader fromHeader = null; String mySipUsername = registration.getUsername();
try { try {
SipURI fromUri = addressFactory.createSipURI(mySipUsername, sipHost); SipURI fromUri = addressFactory.createSipURI(mySipUsername, sipHost);
Address fromNameAddress = addressFactory.createAddress(fromUri); Address fromNameAddress = addressFactory.createAddress(fromUri);
fromNameAddress.setDisplayName(mySipUsername); fromNameAddress.setDisplayName(mySipUsername);
fromHeader = headerFactory.createFromHeader(fromNameAddress, "SipGateway"); FromHeader fromHeader = headerFactory.createFromHeader(fromNameAddress, getTag());
// Use "set" because this header is mandatory.
request.setHeader(fromHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing FromHeader.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing FromHeader.", e);
return false; return null;
} }
// Prepare "To" header // Prepare "To" header
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"To\" header..."); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"To\" header...");
ToHeader toHeader = null;
String destUsername = "";
String destAddress = "";
if (destination.indexOf(":") > 0 && destination.indexOf("@") > destination.indexOf(":")) {
destUsername = destination.substring(destination.indexOf(":") + 1, destination.indexOf("@"));
destAddress = destination.substring(destination.indexOf("@") + 1);
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: destUsername = '" + destUsername + "'; destAddress = '" + destAddress + "'");
}
else {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ToHeader.",
new IllegalArgumentException("The destination specified is not a valid SIP address"));
return false;
}
try {
SipURI toAddress = addressFactory.createSipURI(destUsername, destAddress);
Address toNameAddress = addressFactory.createAddress(toAddress);
String displayName = destUsername;
try { try {
RosterItem ri = getRoster().getRosterItem(this.getTransport().convertIDToJID(destination)); if (destUri == null)
if (ri != null) displayName = ri.getNickname(); destUri = addressFactory.createSipURI(mySipUsername, sipHost);
}
catch (Exception e) {} // Ignore the exception. We don't need to handle it.
toNameAddress.setDisplayName(displayName); Address toNameAddress = addressFactory.createAddress(destUri);
ToHeader toHeader = headerFactory.createToHeader(toNameAddress, toTag);
toHeader = headerFactory.createToHeader(toNameAddress, toTag); // Use "set" because this header is mandatory.
request.setHeader(toHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ToHeader.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ToHeader.", e);
return false; return null;
} }
// Prepare "Via" header // Prepare "Via" header
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"Via\" header..."); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"Via\" header...");
ArrayList viaHeaders = new ArrayList();
try { try {
ViaHeader viaHeader = headerFactory.createViaHeader(InetAddress.getLocalHost().getHostAddress(), sipPort, ListeningPoint.UDP, null); ViaHeader viaHeader = headerFactory.createViaHeader(InetAddress.getLocalHost().getHostAddress(), sipPort, ListeningPoint.UDP, null);
viaHeaders.add(viaHeader);
// Use "set" because this header is mandatory.
request.setHeader(viaHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ViaHeader.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ViaHeader.", e);
return false; return null;
} }
// Prepare "CallId" header // Prepare "CallId" header
...@@ -560,139 +667,420 @@ public class SimpleSession extends TransportSession { ...@@ -560,139 +667,420 @@ public class SimpleSession extends TransportSession {
callIdHeader = headerFactory.createCallIdHeader(callId); callIdHeader = headerFactory.createCallIdHeader(callId);
else else
callIdHeader = udpSipProvider.getNewCallId(); callIdHeader = udpSipProvider.getNewCallId();
// Use "set" because this header is mandatory.
request.setHeader(callIdHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing CallIdHeader.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing CallIdHeader.", e);
return false; return null;
} }
// Prepare "CSeq" header // Prepare "CSeq" header
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"CSeq\" header..."); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"CSeq\" header...");
CSeqHeader cSeqHeader = null;
try { try {
cSeqHeader = headerFactory.createCSeqHeader(seqNum, requestType.toString()); CSeqHeader cSeqHeader = headerFactory.createCSeqHeader(seqNum, requestType.toString());
// Use "set" because this header is mandatory.
request.setHeader(cSeqHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing CSeqHeader.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing CSeqHeader.", e);
return false; return null;
} }
// Prepare "MaxForwards" header // Prepare "MaxForwards" header
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"MaxForwards\" header..."); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"MaxForwards\" header...");
MaxForwardsHeader maxForwardsHeader = null;
try { try {
maxForwardsHeader = headerFactory.createMaxForwardsHeader(maxForward); MaxForwardsHeader maxForwardsHeader = headerFactory.createMaxForwardsHeader(70);
// Use "set" because this header is mandatory.
request.setHeader(maxForwardsHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing MaxForwardsHeader.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing MaxForwardsHeader.", e);
return false; return null;
} }
// Prepare request URI // Setting Request URI
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing request URI..."); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: setting request URI...");
SipURI requestURI = null;
try { try {
requestURI = addressFactory.createSipURI(destUsername, destAddress); if (requestUri == null) {
requestURI.setTransportParam(ListeningPoint.UDP); requestUri = (SipURI) destUri.clone();
} requestUri.setTransportParam(ListeningPoint.UDP);
catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing Request URI.", e);
return false;
} }
request.setRequestURI(requestUri);
// Instantiate Request packet
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Instantiating Request packet...");
Request request = null;
try {
request = messageFactory.createRequest(
requestURI, requestType.toString(),
callIdHeader, cSeqHeader,
fromHeader, toHeader,
viaHeaders, maxForwardsHeader
);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when instantiating Request packet.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when setting request URI.", e);
return false; return null;
}
// Add custom headers
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Start adding custom headers...");
int headerCount = 0;
if (headers != null) {
headerCount = headers.size();
for (ListIterator<Header> headersIterator = headers.listIterator(); headersIterator.hasNext(); ) {
Header aHeader = headersIterator.next();
try {
request.addHeader(aHeader);
}
catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when adding a " +
aHeader.getClass().toString() + " to the request packet.", e);
headerCount--;
}
}
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Finished adding custom headers. " +
headerCount + " of " + headers.size() + " headers successfully added.");
}
else {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: The custom headers input is null. No custom headers to add.");
} }
// Add "Contact" header // Add "Contact" header
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"Contact\" header..."); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"Contact\" header...");
try { try {
SipURI contactURI; SipURI contactURI = addressFactory.createSipURI(mySipUsername, InetAddress.getLocalHost().getHostAddress());
if (requestType.equals(RequestType.NOTIFY))
contactURI = addressFactory.createSipURI(null, InetAddress.getLocalHost().getHostAddress());
else
contactURI = addressFactory.createSipURI(mySipUsername, InetAddress.getLocalHost().getHostAddress());
contactURI.setPort(sipPort); contactURI.setPort(sipPort);
// Address contactAddress = addressFactory.createAddress("<" + InetAddress.getLocalHost().getHostAddress() + ":" + sipPort + ">");
Address contactAddress = addressFactory.createAddress(contactURI); Address contactAddress = addressFactory.createAddress(contactURI);
if (!requestType.equals(RequestType.NOTIFY))
contactAddress.setDisplayName(mySipUsername); contactAddress.setDisplayName(mySipUsername);
ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress); ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
request.addHeader(contactHeader); request.setHeader(contactHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when adding ContactHeader.", e); Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when adding ContactHeader.", e);
return false; return null;
} }
return request;
}
// /**
// * Prepares a Request packet.
// * <br><br>
// * The "From", "To", "Via", "Contact", "CSeq", "MaxForwards" and "CallId" headers,
// * as well as the content (if provided) are prepared in the method.
// * <br>
// * Additional headers should be provided as customer headers. See the "headers" parameter for further details.
// * @param requestType An inner request type enum
// * @param destination The recipient of this request
// * @param toTag Additional tag code of the destination. Can usually leave it <code>null</code>.
// * @param callId A String representing an ongoing SIP CallID. Leave it <code>null</code> if a new CallID should be generated.
// * @param seqNum A sequence number for an ongoing session.
// * @param maxForward Maximum times of forwarding allowed for this packet.
// * @param headers Additional headers that have to be added. Leave <code>null</code> if no custom header is to be added.
// * @param content An object containing the content of the message, as well as the header defining the content type.
// * Can leave <code>null</code> if no content is to be specified.
// * @see org.jivesoftware.wildfire.gateway.protocols.simple.SimpleSession.RequestType
// */
// private boolean prepareRequest(
// RequestType requestType,
// String destination,
// String toTag,
// String callId,
// long seqNum,
// int maxForward,
// List<Header> headers,
// MessageContent content) {
// String myJiveId = this.jid.getNode();
// String mySipUsername = registration.getUsername();
//
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing request packet of type '" + requestType + "'");
//
// // Prepare "From" header
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"From\" header...");
// FromHeader fromHeader = null;
// try {
// SipURI fromUri = addressFactory.createSipURI(mySipUsername, sipHost);
// Address fromNameAddress = addressFactory.createAddress(fromUri);
// fromNameAddress.setDisplayName(mySipUsername);
//
// fromHeader = headerFactory.createFromHeader(fromNameAddress, getTag());
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing FromHeader.", e);
//
// return false;
// }
//
// // Prepare "To" header
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"To\" header...");
// ToHeader toHeader = null;
//
// String destUsername = "";
// String destAddress = "";
//
// // Code modification to allow address be input without specifying "sip:"
// if (destination.startsWith("sip:")) {
// destination = destination.substring("sip:".length());
// }
//
// if (destination.indexOf("@") > 0) {
// destUsername = destination.substring(destination.indexOf(":") + 1, destination.indexOf("@"));
// destAddress = destination.substring(destination.indexOf("@") + 1);
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: destUsername = '" + destUsername + "'; destAddress = '" + destAddress + "'");
// }
// else {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ToHeader.",
// new IllegalArgumentException("The destination specified is not a valid SIP address"));
//
// return false;
// }
//
// try {
// SipURI toAddress = addressFactory.createSipURI(destUsername, destAddress);
// Address toNameAddress = addressFactory.createAddress(toAddress);
//
// String displayName = destUsername;
// try {
// RosterItem ri = getRoster().getRosterItem(this.getTransport().convertIDToJID(destination));
// if (ri != null) displayName = ri.getNickname();
// }
// catch (Exception e) {} // Ignore the exception. We don't need to handle it.
//
// toNameAddress.setDisplayName(displayName);
//
// toHeader = headerFactory.createToHeader(toNameAddress, toTag);
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ToHeader.", e);
//
// return false;
// }
//
// // Prepare "Via" header
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"Via\" header...");
// ArrayList viaHeaders = new ArrayList();
// try {
// ViaHeader viaHeader = headerFactory.createViaHeader(InetAddress.getLocalHost().getHostAddress(), sipPort, ListeningPoint.UDP, null);
// viaHeaders.add(viaHeader);
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing ViaHeader.", e);
//
// return false;
// }
//
// // Prepare "CallId" header
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"CallId\" header...");
// CallIdHeader callIdHeader = null;
// try {
// if (callId != null)
// callIdHeader = headerFactory.createCallIdHeader(callId);
// else
// callIdHeader = udpSipProvider.getNewCallId();
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing CallIdHeader.", e);
//
// return false;
// }
//
// // Prepare "CSeq" header
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"CSeq\" header...");
// CSeqHeader cSeqHeader = null;
// try {
// cSeqHeader = headerFactory.createCSeqHeader(seqNum, requestType.toString());
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing CSeqHeader.", e);
//
// return false;
// }
//
// // Prepare "MaxForwards" header
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"MaxForwards\" header...");
// MaxForwardsHeader maxForwardsHeader = null;
// try {
// maxForwardsHeader = headerFactory.createMaxForwardsHeader(maxForward);
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing MaxForwardsHeader.", e);
//
// return false;
// }
//
// // Prepare request URI
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing request URI...");
// SipURI requestURI = null;
// try {
// requestURI = addressFactory.createSipURI(destUsername, destAddress);
// requestURI.setTransportParam(ListeningPoint.UDP);
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when preparing Request URI.", e);
//
// return false;
// }
//
// // Instantiate Request packet
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Instantiating Request packet...");
// Request request = null;
// try {
// request = messageFactory.createRequest(
// requestURI, requestType.toString(),
// callIdHeader, cSeqHeader,
// fromHeader, toHeader,
// viaHeaders, maxForwardsHeader
// );
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when instantiating Request packet.", e);
//
// return false;
// }
//
// // Add custom headers
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Start adding custom headers...");
// int headerCount = 0;
// if (headers != null) {
// headerCount = headers.size();
// for (ListIterator<Header> headersIterator = headers.listIterator(); headersIterator.hasNext(); ) {
// Header aHeader = headersIterator.next();
// try {
// request.addHeader(aHeader);
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when adding a " +
// aHeader.getClass().toString() + " to the request packet.", e);
// headerCount--;
// }
// }
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Finished adding custom headers. " +
// headerCount + " of " + headers.size() + " headers successfully added.");
// }
// else {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: The custom headers input is null. No custom headers to add.");
// }
//
// // Add "Contact" header
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Preparing \"Contact\" header...");
// try {
// SipURI contactURI;
// if (requestType.equals(RequestType.NOTIFY))
// contactURI = addressFactory.createSipURI(null, InetAddress.getLocalHost().getHostAddress());
// else
// contactURI = addressFactory.createSipURI(mySipUsername, InetAddress.getLocalHost().getHostAddress());
// contactURI.setPort(sipPort);
//
// Address contactAddress = addressFactory.createAddress(contactURI);
//
// if (!requestType.equals(RequestType.NOTIFY))
// contactAddress.setDisplayName(mySipUsername);
//
// ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
// request.addHeader(contactHeader);
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when adding ContactHeader.", e);
//
// return false;
// }
//
// if (content != null) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Content is specified. Adding content...");
// try {
// request.setContent(content.getContent(), content.getContentTypeHeader());
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when adding content to the request packet.", e);
// // Just tell, then continue the request!
// }
// }
//
// // Send the request
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Sending Request packet: \n" + request.toString());
// try {
// ClientTransaction clientTransaction = udpSipProvider.getNewClientTransaction(request);
// clientTransaction.sendRequest();
// }
// catch (Exception e) {
// Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when sending Request packet.", e);
// return false;
// }
//
// return true;
// }
private Request prepareRegisterRequest() {
return prepareRequest(RequestType.REGISTER, null, null, null, sessionId, seqNum++);
}
private Request prepareMessageRequest(MessageContent content, String destination) throws InvalidArgumentException, ParseException {
String destUsername = destination;
String destHost = sipHost;
if (destination.indexOf("@") == 0 || destination.indexOf("@") == destination.length() - 1) {
throw new InvalidArgumentException("The address provided is invalid!");
}
else if (destination.indexOf("@") > 0) {
destUsername = destination.substring(0, destination.indexOf("@"));
destHost = destination.substring(destination.indexOf("@") + 1);
}
SipURI destUri = addressFactory.createSipURI(destUsername, destHost);
Request messageRequest = prepareRequest(RequestType.MESSAGE, destUri, null, destUri, sessionId, seqNum++);
messageRequest.setContent(content.content, content.contentTypeHeader);
return messageRequest;
}
private Request prepareSubscribeRequest(String destination) throws InvalidArgumentException, ParseException {
String destUsername = destination;
String destHost = sipHost;
if (destination.indexOf("@") == 0 || destination.indexOf("@") == destination.length() - 1) {
throw new InvalidArgumentException("The address provided is invalid!");
}
else if (destination.indexOf("@") > 0) {
destUsername = destination.substring(0, destination.indexOf("@"));
destHost = destination.substring(destination.indexOf("@") + 1);
}
SipURI destUri = addressFactory.createSipURI(destUsername, destHost);
Request messageRequest = prepareRequest(RequestType.SUBSCRIBE, destUri, null, destUri, null, 1L);
return messageRequest;
}
private Request prepareNotifyRequest(Dialog dialog) throws ParseException {
printDialog(dialog);
String fromTag = dialog.getRemoteTag();
Address fromAddress = dialog.getRemoteParty();
SipURI destUri = (SipURI) fromAddress.getURI();
if (content != null) { dialog.incrementLocalSequenceNumber();
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Content is specified. Adding content..."); long seqNum = dialog.getLocalSeqNumber();
try { String callId = dialog.getCallId().getCallId();
request.setContent(content.getContent(), content.getContentTypeHeader());
} SipURI fromReqUri = null;
catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when adding content to the request packet.", e); if (dialog != null) {
// Just tell, then continue the request! Log.debug("Getting request URI from dialog");
} Address fromReqAddr = dialog.getRemoteTarget();
if (fromReqAddr != null && fromReqAddr.getURI() != null && fromReqAddr.getURI() instanceof SipURI)
fromReqUri = (SipURI) fromReqAddr.getURI();
} }
// Send the request if (fromReqUri == null) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Sending Request packet: \n" + request.toString()); Log.debug("Getting request URI from destination URI");
try { fromReqUri = destUri;
// udpSipProvider.sendRequest(request);
ClientTransaction clientTransaction = udpSipProvider.getNewClientTransaction(request);
clientTransaction.sendRequest();
} }
catch (Exception e) {
Log.debug("SimpleSession(" + myJiveId + ").prepareRequest: Exception occured when sending Request packet.", e); // Instantiate request packet
return false; Request notifyRequest = prepareRequest(RequestType.NOTIFY, destUri, fromTag, fromReqUri, callId, seqNum);
// Request notifyRequest = dialog.createRequest(Request.NOTIFY);
((FromHeader) notifyRequest.getHeader(FromHeader.NAME)).setTag(dialog.getLocalTag());
// Set "subscription state" header
SubscriptionStateHeader subscriptionStateHeader = headerFactory.createSubscriptionStateHeader(SubscriptionStateHeader.ACTIVE.toLowerCase());
// if (expires > 0) subscriptionStateHeader.setExpires(expires);
notifyRequest.setHeader(subscriptionStateHeader);
// Set "event" header
notifyRequest.setHeader(headerFactory.createEventHeader("presence"));
return notifyRequest;
} }
return true; private Request prepareNotifyRequest(Dialog dialog, SimplePresence simplePresence) throws ParseException {
Request request = prepareNotifyRequest(dialog);
request.setContent(simplePresence.toXML(), headerFactory.createContentTypeHeader("application", "pidf+xml"));
return request;
} }
public void contactSubscribed(String targetSipAddress) { public void contactSubscribed(String targetSipAddress) {
...@@ -701,160 +1089,132 @@ public class SimpleSession extends TransportSession { ...@@ -701,160 +1089,132 @@ public class SimpleSession extends TransportSession {
JID contactJID = getTransport().convertIDToJID(targetSipAddress); JID contactJID = getTransport().convertIDToJID(targetSipAddress);
RosterItem item = roster.getRosterItem(contactJID); RosterItem item = roster.getRosterItem(contactJID);
Log.debug("SimpleSession(" + getJID().getNode() + ").contactSubscribed: Preparing presence packet..."); Log.debug("SimpleSession(" + jid.getNode() + ").contactSubscribed: Preparing presence packet...");
Presence presence = new Presence(); Presence presence = new Presence();
presence.setFrom(contactJID); presence.setFrom(contactJID);
presence.setTo(getJID()); presence.setTo(getJID());
presence.setType(Presence.Type.subscribed); presence.setType(Presence.Type.subscribed);
getTransport().sendPacket(presence); getTransport().sendPacket(presence);
Log.debug("SimpleSession(" + getJID().getNode() + ").contactSubscribed: Presence packet sent ==> \n" + presence.toXML()); Log.debug("SimpleSession(" + jid.getNode() + ").contactSubscribed: Presence packet sent ==> \n" + presence.toXML());
// Log.debug("SimpleSession(" + jid.getNode() + ").contactSubscribed: Synchronizing SIP user roster...");
// String rosteruserid = ((SimpleTransport) transport).convertJIDToID(item.getJid());
// if (myRoster.getEntry(rosteruserid) == null) {
// SimpleRosterItem simpleRosterItem = new SimpleRosterItem(rosteruserid, item.getNickname(), 1L);
// myRoster.addEntry(rosteruserid, simpleRosterItem);
// }
// Log.debug("SimpleSession(" + jid.getNode() + ").contactSubscribed: Finished synchronizing SIP user roster.");
// syncContactGroups(contact, item.getGroups()); // syncContactGroups(contact, item.getGroups());
unlockRoster(contactJID.toString()); // unlockRoster(contactJID.toString());
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").contactSubscribed: Exception occured when adding pending contact " + targetSipAddress, e); Log.debug("SimpleSession(" + jid.getNode() + ").contactSubscribed: Exception occured when adding pending contact " + targetSipAddress, e);
JID contactJID = getTransport().convertIDToJID(targetSipAddress); JID contactJID = getTransport().convertIDToJID(targetSipAddress);
unlockRoster(contactJID.toString()); // unlockRoster(contactJID.toString());
} }
} }
public void sendResponse(int status, Request request) { public void contactUnsubscribed(String targetSipAddress) {
try { try {
Log.debug("SimpleSession for " + this.jid.getNode() + ": Starting response sending process."); Roster roster = getTransport().getRosterManager().getRoster(getJID().getNode());
JID contactJID = getTransport().convertIDToJID(targetSipAddress);
Response response = messageFactory.createResponse(status, request); RosterItem item = roster.getRosterItem(contactJID);
udpSipProvider.sendResponse(response);
Log.debug("SimpleSession for " + this.jid.getNode() + ": Response sent!");
}
catch (Exception ex) {
Log.debug("SimpleSession for " + this.jid.getNode() + ": ", ex);
}
}
/**
* Sends a NOTIFY packet based on the SUBSCRIBE packet received.
* @throw
*/
public void sendNotify(Request inputRequest) throws Exception {
if (!inputRequest.getMethod().equals(Request.SUBSCRIBE)) {
// Should throw an Exception telling the packet is wrong;
throw new Exception("The REQUEST packet is not of method SUBSCRIBE!");
}
String dest = ""; Log.debug("SimpleSession(" + getJID().getNode() + ").contactUnsubscribed: Preparing presence packet...");
String toTag = ""; Presence presence = new Presence();
if (inputRequest.getHeader(FromHeader.NAME) != null) { presence.setFrom(contactJID);
FromHeader fromHeader = (FromHeader) inputRequest.getHeader(FromHeader.NAME); presence.setTo(getJID());
presence.setType(Presence.Type.unsubscribed);
getTransport().sendPacket(presence);
Log.debug("SimpleSession(" + getJID().getNode() + ").contactUnsubscribed: Presence packet sent ==> \n" + presence.toXML());
toTag = fromHeader.getTag(); // Log.debug("SimpleSession(" + jid.getNode() + ").contactUnsubscribed: Synchronizing SIP user roster...");
dest = fromHeader.getAddress().getURI().toString(); // String rosteruserid = ((SimpleTransport) transport).convertJIDToID(item.getJid());
} // myRoster.removeEntry(rosteruserid);
// Log.debug("SimpleSession(" + jid.getNode() + ").contactUnsubscribed: Finished synchronizing SIP user roster.");
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Parsing SUBSCRIBE packet..."); // syncContactGroups(contact, item.getGroups());
long seqNum = 1L; // unlockRoster(contactJID.toString());
if (inputRequest.getHeader(CSeqHeader.NAME) != null) {
seqNum = ((CSeqHeader) inputRequest.getHeader(CSeqHeader.NAME)).getSeqNumber() + 1;
} }
catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").contactUnsubscribed: Exception occured when adding pending contact " + targetSipAddress, e);
int expires = 0; JID contactJID = getTransport().convertIDToJID(targetSipAddress);
if (inputRequest.getHeader(ExpiresHeader.NAME) != null) { // unlockRoster(contactJID.toString());
expires = ((ExpiresHeader) inputRequest.getHeader(ExpiresHeader.NAME)).getExpires();
} }
String callId = null;
if (inputRequest.getHeader(CallIdHeader.NAME) != null) {
callId = ((CallIdHeader) inputRequest.getHeader(CallIdHeader.NAME)).getCallId();
} }
User me = XMPPServer.getInstance().getUserManager().getUser(getJID().getNode()); public ServerTransaction sendResponse(int status, Request request, ServerTransaction serverTransaction) {
Presence myPresence = XMPPServer.getInstance().getPresenceManager().getPresence(me); try {
Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse: Starting response sending process.");
List<Header> routeHeaders = new ArrayList<Header>();
String routingProxies = "";
for (Iterator recRouteHeaders = inputRequest.getHeaders(RecordRouteHeader.NAME); recRouteHeaders.hasNext(); ) if (serverTransaction == null)
routingProxies += "," + ((RecordRouteHeader) recRouteHeaders.next()).toString().substring("Record-Route: ".length()); serverTransaction = udpSipProvider.getNewServerTransaction(request);
if (routingProxies.startsWith(",")) routingProxies = routingProxies.substring(1);
int commaIndex = routingProxies.lastIndexOf(","); Response response = messageFactory.createResponse(status, request);
while (true) {
String uri = "";
if (commaIndex > 0)
uri = routingProxies.substring(commaIndex + 1);
else
uri = routingProxies;
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: uri = " + uri); // Set "Exprires" header
if (request.getHeader(ExpiresHeader.NAME) != null)
response.setHeader(request.getHeader(ExpiresHeader.NAME));
// Works and works here... // Add "Contact" header
if (uri != null && uri.trim().length() > 0) { Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse: Preparing \"Contact\" header...");
RouteHeader routeHeader = headerFactory.createRouteHeader(addressFactory.createAddress(uri)); try {
routeHeaders.add(routeHeader); SipURI contactURI = addressFactory.createSipURI(null, InetAddress.getLocalHost().getHostAddress());
} contactURI.setPort(sipPort);
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: routeHeaders.size = " + Address contactAddress = addressFactory.createAddress(contactURI);
routeHeaders.size());
if (commaIndex < 0) break; // contactAddress.setDisplayName(mySipUsername);
routingProxies = routingProxies.substring(0, commaIndex); ContactHeader contactHeader = headerFactory.createContactHeader(contactAddress);
commaIndex = routingProxies.lastIndexOf(","); response.addHeader(contactHeader);
} }
catch (Exception e) {
sendNotify(dest, toTag, callId, seqNum, expires, 70, myPresence, routeHeaders); Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse: Exception occured when adding ContactHeader.", e);
// return false; // We can continue with this though.
} }
public void sendNotify(String dest, String toTag, String callId, long seqNum, int expires, int maxForward, Presence presence, List<Header> routeHeaders) { Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse: Sending response: " + response.toString());
List<Header> customHeaders = new ArrayList<Header>(3);
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Setting subscription state header..."); serverTransaction.sendResponse(response);
try { // udpSipProvider.sendResponse(response);
SubscriptionStateHeader subscriptionStateHeader = headerFactory.createSubscriptionStateHeader(SubscriptionStateHeader.ACTIVE.toLowerCase());
subscriptionStateHeader.setExpires(expires); Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse: Response sent!");
customHeaders.add(subscriptionStateHeader);
return serverTransaction;
} }
catch (Exception e) { catch (Exception ex) {
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Unable to set subscription state header.", e); Log.debug("SimpleSession(" + jid.getNode() + ").sendResponse: ", ex);
return;
} }
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Setting event header..."); return null;
try {
customHeaders.add(headerFactory.createEventHeader("presence"));
}
catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Unable to set event header.", e);
return;
} }
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Adding route headers..."); public void sendNotify(Dialog dialog) throws ParseException, SipException, InvalidArgumentException {
Request notifyRequest = prepareNotifyRequest(dialog);
try { try {
customHeaders.addAll(routeHeaders); User me = XMPPServer.getInstance().getUserManager().getUser(getJID().getNode());
} Presence myPresence = XMPPServer.getInstance().getPresenceManager().getPresence(me);
catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Unable to add route headers.", e);
return;
}
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Writing simple presence.");
String presenceContent = ""; String presenceContent = "";
try {
SimplePresence simplePresence = new SimplePresence(); SimplePresence simplePresence = new SimplePresence();
simplePresence.setEntity("pres:" + registration.getUsername() + "@" + sipHost); simplePresence.setEntity("pres:" + registration.getUsername() + "@" + sipHost);
simplePresence.setDmNote(presence.getStatus()); simplePresence.setDmNote(myPresence.getStatus());
if (presence.getStatus() != null && presence.getStatus().equalsIgnoreCase("Offline")) if (myPresence.getStatus() != null && myPresence.getStatus().equalsIgnoreCase("Offline"))
simplePresence.setTupleStatus(SimplePresence.TupleStatus.CLOSED); simplePresence.setTupleStatus(SimplePresence.TupleStatus.CLOSED);
else { else {
simplePresence.setTupleStatus(SimplePresence.TupleStatus.OPEN); simplePresence.setTupleStatus(SimplePresence.TupleStatus.OPEN);
if (presence.getShow() != null) { if (myPresence.getShow() != null) {
switch (presence.getShow()) { switch (myPresence.getShow()) {
case away: case away:
simplePresence.setRpid(SimplePresence.Rpid.AWAY); simplePresence.setRpid(SimplePresence.Rpid.AWAY);
break; break;
...@@ -870,29 +1230,61 @@ public class SimpleSession extends TransportSession { ...@@ -870,29 +1230,61 @@ public class SimpleSession extends TransportSession {
} }
} }
presenceContent =simplePresence.toXML(); presenceContent = simplePresence.toXML();
}
catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Unable to write simple presence.", e);
return;
}
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Creating content type header.");
ContentTypeHeader contentTypeHeader;
try { ContentTypeHeader contentTypeHeader = headerFactory.createContentTypeHeader("application", "pidf+xml");
contentTypeHeader = headerFactory.createContentTypeHeader("application", "pidf+xml"); notifyRequest.setContent(presenceContent, contentTypeHeader);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Unable to create content type header.", e); Log.debug("Unable to include presence details in the packet.", e);
return; }
}
sendRequest(notifyRequest, ListeningPoint.UDP, dialog);
Log.debug(presenceContent); }
MessageContent msgContent = new MessageContent(contentTypeHeader, presenceContent); private String getTag() {
if (!prepareRequest(RequestType.NOTIFY, dest, toTag, callId, seqNum, maxForward, customHeaders, msgContent)) { StringBuffer tag = new StringBuffer(Integer.toHexString(this.hashCode()));
Log.debug("SimpleSession(" + getJID().getNode() + ").sendNotify: Unable to send NOTIFY packet."); while (tag.length() < 8) {
tag.insert(0, "0");
}
return new String(tag);
}
void printDialog(Dialog dialog) {
if (dialog != null) {
StringBuffer log = new StringBuffer(1024);
log.append("Printing dialog: \n");
log.append("Call id = ");
log.append(dialog.getCallId().getCallId());
log.append("\n");
log.append("Dialog id = ");
log.append(dialog.getDialogId());
log.append("\n");
log.append("Local party = ");
log.append(dialog.getLocalParty());
log.append("\n");
log.append("Remote party = ");
log.append(dialog.getRemoteParty());
log.append("\n");
log.append("Remote targ = ");
log.append(dialog.getRemoteTarget());
log.append("\n");
log.append("Local seq = ");
log.append(dialog.getLocalSeqNumber());
log.append("\n");
log.append("Remote seq = ");
log.append(dialog.getRemoteSeqNumber());
log.append("\n");
log.append("Local tag = ");
log.append(dialog.getLocalTag());
log.append("\n");
log.append("Remote tag = ");
log.append(dialog.getRemoteTag());
log.append("\n");
log.append("Dialog state = ");
log.append(dialog.getState());
Log.debug(new String(log));
} }
} }
} }
\ No newline at end of file
...@@ -10,27 +10,35 @@ ...@@ -10,27 +10,35 @@
package org.jivesoftware.wildfire.gateway.protocols.simple; package org.jivesoftware.wildfire.gateway.protocols.simple;
import java.util.Date; import gov.nist.javax.sip.address.SipUri;
import java.util.ListIterator; import java.util.ListIterator;
import javax.sip.ClientTransaction;
import javax.sip.Dialog;
import javax.sip.DialogTerminatedEvent; import javax.sip.DialogTerminatedEvent;
import javax.sip.IOExceptionEvent; import javax.sip.IOExceptionEvent;
import javax.sip.RequestEvent; import javax.sip.RequestEvent;
import javax.sip.ResponseEvent; import javax.sip.ResponseEvent;
import javax.sip.ServerTransaction;
import javax.sip.SipListener; import javax.sip.SipListener;
import javax.sip.TimeoutEvent; import javax.sip.TimeoutEvent;
import javax.sip.TransactionTerminatedEvent; import javax.sip.TransactionTerminatedEvent;
import javax.sip.address.Address; import javax.sip.address.Address;
import javax.sip.address.SipURI;
import javax.sip.address.URI; import javax.sip.address.URI;
import javax.sip.header.CSeqHeader; import javax.sip.header.CSeqHeader;
import javax.sip.header.CallIdHeader;
import javax.sip.header.ContactHeader; import javax.sip.header.ContactHeader;
import javax.sip.header.ExpiresHeader; import javax.sip.header.ExpiresHeader;
import javax.sip.header.FromHeader; import javax.sip.header.FromHeader;
import javax.sip.header.MaxForwardsHeader;
import javax.sip.header.RecordRouteHeader;
import javax.sip.header.SubscriptionStateHeader; import javax.sip.header.SubscriptionStateHeader;
import javax.sip.header.ToHeader; import javax.sip.header.ToHeader;
import javax.sip.message.Request; import javax.sip.message.Request;
import javax.sip.message.Response; import javax.sip.message.Response;
import org.jivesoftware.util.Log; import org.jivesoftware.util.Log;
import org.jivesoftware.wildfire.gateway.TransportLoginStatus; import org.jivesoftware.wildfire.gateway.TransportLoginStatus;
import org.jivesoftware.wildfire.user.UserNotFoundException;
import org.xmpp.packet.JID; import org.xmpp.packet.JID;
import org.xmpp.packet.Presence; import org.xmpp.packet.Presence;
...@@ -67,28 +75,39 @@ public class SimpleSessionListener implements SipListener { ...@@ -67,28 +75,39 @@ public class SimpleSessionListener implements SipListener {
} }
public void processRequest(RequestEvent requestEvent) { public void processRequest(RequestEvent requestEvent) {
ServerTransaction serverTransaction = requestEvent.getServerTransaction();
Dialog dialog = null;
if (serverTransaction != null) {
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Getting dialog");
dialog = serverTransaction.getDialog();
}
int responseCode = 200; int responseCode = 200;
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Received a request event: \n" + requestEvent.getRequest().toString()); Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Received a request event: \n" + requestEvent.getRequest().toString());
String fromAddr = ""; String fromAddr = "";
Request request = requestEvent.getRequest(); Request request = requestEvent.getRequest();
ListIterator headerNames = request.getHeaderNames();
while (headerNames.hasNext()) { if (request.getHeader(FromHeader.NAME) != null) {
String headerName = (String) headerNames.next();
if (headerName.equals(FromHeader.NAME)) {
FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME); FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
Address fromAddress = fromHeader.getAddress(); Address fromAddress = fromHeader.getAddress();
String displayName = fromAddress.getDisplayName();
URI fromUri = fromAddress.getURI(); URI fromUri = fromAddress.getURI();
if (fromUri != null) { if (fromUri != null) {
if (fromUri.isSipURI()) {
SipURI fromSipUri = (SipURI) fromUri;
fromAddr = fromSipUri.getUser() + "@" + fromSipUri.getHost();
}
else {
fromAddr = fromUri.toString(); fromAddr = fromUri.toString();
break;
} }
} }
} }
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: FromAddr = " + fromAddr);
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Request method = '" + request.getMethod() + "'"); Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Request method = '" + request.getMethod() + "'");
if (request.getMethod().equals(Request.MESSAGE)) { if (request.getMethod().equals(Request.MESSAGE)) {
...@@ -102,9 +121,13 @@ public class SimpleSessionListener implements SipListener { ...@@ -102,9 +121,13 @@ public class SimpleSessionListener implements SipListener {
mySimpleSession.getTransport().sendMessage(mySimpleSession.getJID(), senderJid, msgContent); mySimpleSession.getTransport().sendMessage(mySimpleSession.getJID(), senderJid, msgContent);
mySimpleSession.sendResponse(responseCode, request); mySimpleSession.sendResponse(responseCode, request, serverTransaction);
} }
else if (request.getMethod().equals(Request.NOTIFY)) { else if (request.getMethod().equals(Request.NOTIFY)) {
Presence presence = new Presence();
presence.setFrom(mySimpleSession.getTransport().convertIDToJID(fromAddr));
presence.setTo(mySimpleSession.getJID());
SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) request.getHeader(SubscriptionStateHeader.NAME); SubscriptionStateHeader subscriptionStateHeader = (SubscriptionStateHeader) request.getHeader(SubscriptionStateHeader.NAME);
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: NOTIFY request handling process started."); Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: NOTIFY request handling process started.");
...@@ -116,10 +139,6 @@ public class SimpleSessionListener implements SipListener { ...@@ -116,10 +139,6 @@ public class SimpleSessionListener implements SipListener {
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: NOTIFY Expiry = " + expires); Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: NOTIFY Expiry = " + expires);
try { try {
Presence presence = new Presence();
presence.setFrom(mySimpleSession.getTransport().convertIDToJID(fromAddr));
presence.setTo(mySimpleSession.getJID());
if (expires > 0) { if (expires > 0) {
String content = ""; String content = "";
if (request.getContent() != null) if (request.getContent() != null)
...@@ -127,117 +146,81 @@ public class SimpleSessionListener implements SipListener { ...@@ -127,117 +146,81 @@ public class SimpleSessionListener implements SipListener {
if (content.length() > 0) { if (content.length() > 0) {
SimplePresence simplePresence = SimplePresence.parseSimplePresence(content); SimplePresence simplePresence = SimplePresence.parseSimplePresence(content);
if (simplePresence.getTupleStatus().isOpen()) { ((SimpleTransport) mySimpleSession.getTransport()).convertSIPStatusToJap(presence, simplePresence);
presence.setStatus("Online");
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: " +
"SIP user '" + fromAddr + "' is '" + simplePresence.getRpid().toString() + "'!");
switch (simplePresence.getRpid()) {
case AWAY:
presence.setShow(Presence.Show.away);
presence.setStatus("Away");
break;
case BUSY:
presence.setShow(Presence.Show.dnd);
presence.setStatus("Do Not Disturb");
break;
case HOLIDAY:
presence.setShow(Presence.Show.xa);
presence.setStatus("(SIP) On Holiday");
break;
case IN_TRANSIT:
presence.setShow(Presence.Show.xa);
presence.setStatus("(SIP) In Transit");
break;
case ON_THE_PHONE:
presence.setShow(Presence.Show.away);
presence.setStatus("On Phone");
break;
case PERMANENT_ABSENCE:
presence.setStatus("Offline");
break;
case SLEEPING:
presence.setShow(Presence.Show.away);
presence.setStatus("(SIP) Idle");
break;
default:
break;
} }
} }
} else { else {
presence.setStatus("Offline");
}
} else {
presence.setType(Presence.Type.unsubscribed); presence.setType(Presence.Type.unsubscribed);
} }
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Sending XMPP presence packet."); Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Sending XMPP presence packet.");
mySimpleSession.getTransport().sendPacket(presence); }
} catch (Exception ex) { catch (Exception ex) {
Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Exception occured when processing NOTIFY packet...", ex); Log.debug("SimpleSessionListener(" + myUsername + ").processRequest: Exception occured when processing NOTIFY packet...", ex);
} }
} }
else if (subscriptionStateHeader.getState().equalsIgnoreCase(SubscriptionStateHeader.TERMINATED)) {
presence.setType(Presence.Type.unsubscribed);
}
mySimpleSession.sendResponse(responseCode, request); mySimpleSession.getTransport().sendPacket(presence);
mySimpleSession.sendResponse(responseCode, request, serverTransaction);
} }
else if (request.getMethod().equals(Request.SUBSCRIBE)) { else if (request.getMethod().equals(Request.SUBSCRIBE)) {
Log.debug("SimpleSessionListener for " + myUsername + ": SUBSCRIBE request handling process."); Log.debug("SimpleSessionListener for " + myUsername + ": SUBSCRIBE request handling process.");
mySimpleSession.sendResponse(202, request); ServerTransaction transaction = mySimpleSession.sendResponse(202, request, serverTransaction);
Log.debug("SimpleSessionListener for " + myUsername + ": SUBSCRIBE should be followed by a NOTIFY"); Log.debug("SimpleSessionListener for " + myUsername + ": SUBSCRIBE should be followed by a NOTIFY");
// Send NOTIFY packet. // Send NOTIFY packet.
try { try {
mySimpleSession.sendNotify(request); if (transaction != null)
mySimpleSession.sendNotify(transaction.getDialog());
else
mySimpleSession.sendNotify(dialog);
} }
catch (Exception e) { catch (Exception e) {
Log.debug("SimpleSessionListener for " + myUsername + ": Unable to prepare NOTIFY packet.", e); Log.debug("SimpleSessionListener for " + myUsername + ": Unable to prepare NOTIFY packet.", e);
} }
// long seqNum = 1L;
// if (request.getHeader(CSeqHeader.NAME) != null) {
// seqNum = ((CSeqHeader) request.getHeader(CSeqHeader.NAME)).getSeqNumber() + 1;
// }
//
// int expires = 0;
// if (request.getHeader(ExpiresHeader.NAME) != null) {
// expires = ((ExpiresHeader) request.getHeader(ExpiresHeader.NAME)).getExpires();
// }
//
// String callId = null;
// if (request.getHeader(CallIdHeader.NAME) != null) {
// callId = ((CallIdHeader) request.getHeader(CallIdHeader.NAME)).getCallId();
// }
// int maxForward = 0;
// if (request.getHeader(MaxForwardsHeader.NAME) != null) {
// maxForward = ((MaxForwardsHeader) request.getHeader(MaxForwardsHeader.NAME)).getMaxForwards();
// }
// if (maxForward > 0) maxForward--;
// if (request.getHeader(RecordRouteHeader.NAME) != null) {
// String recordRouteHeader = ((RecordRouteHeader) request.getHeader(RecordRouteHeader.NAME)).toString();
// }
// Send notify packet to show my own presence.
// mySimpleSession.sendNotify(fromAddr, callId, seqNum, expires, maxForward, new Presence());
} }
} }
public void processResponse(ResponseEvent responseEvent) { public void processResponse(ResponseEvent responseEvent) {
if (responseEvent.getClientTransaction() != null) {
Log.debug("SimpleSessionListener for " + myUsername + ": Getting client transaction...");
ClientTransaction clientTransaction = responseEvent.getClientTransaction();
Dialog clientDialog = clientTransaction.getDialog();
mySimpleSession.printDialog(clientDialog);
}
Log.debug("SimpleSessionListener for " + myUsername + ": Received a response event: " + responseEvent.getResponse().toString()); Log.debug("SimpleSessionListener for " + myUsername + ": Received a response event: " + responseEvent.getResponse().toString());
String fromAddr = "";
String toAddr = ""; String toAddr = "";
Response response = responseEvent.getResponse(); Response response = responseEvent.getResponse();
if (response.getHeader(FromHeader.NAME) != null) {
FromHeader fromHeader = (FromHeader) response.getHeader(FromHeader.NAME);
URI fromUri = fromHeader.getAddress().getURI();
if (fromUri instanceof SipUri)
fromAddr = ((SipUri) fromUri).getUser() + "@" + ((SipUri) fromUri).getHost();
else
fromAddr = fromUri.toString();
}
if (response.getHeader(ToHeader.NAME) != null) { if (response.getHeader(ToHeader.NAME) != null) {
ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME); ToHeader toHeader = (ToHeader) response.getHeader(ToHeader.NAME);
toAddr = toHeader.getAddress().getURI().toString(); URI toUri = toHeader.getAddress().getURI();
if (toUri instanceof SipUri)
toAddr = ((SipUri) toUri).getUser() + "@" + ((SipUri) toUri).getHost();
else
toAddr = toUri.toString();
} }
if (response.getHeader(CSeqHeader.NAME) != null) { if (response.getHeader(CSeqHeader.NAME) != null) {
String method = ((CSeqHeader) response.getHeader(CSeqHeader.NAME)).getMethod(); String method = ((CSeqHeader) response.getHeader(CSeqHeader.NAME)).getMethod();
if (method.equals(Request.REGISTER)) { if (method.equals(Request.REGISTER)) {
if (response.getStatusCode() - response.getStatusCode() % 100 == 200) { if (response.getStatusCode() / 100 == 2) {
int expires = 0; int expires = 0;
if (response.getHeader(ContactHeader.NAME) != null) { if (response.getHeader(ContactHeader.NAME) != null) {
expires = ((ContactHeader) response.getHeader(ContactHeader.NAME)).getExpires(); expires = ((ContactHeader) response.getHeader(ContactHeader.NAME)).getExpires();
...@@ -249,22 +232,23 @@ public class SimpleSessionListener implements SipListener { ...@@ -249,22 +232,23 @@ public class SimpleSessionListener implements SipListener {
Log.debug("SimpleSessionListener(" + myUsername + ").processResponse: " + Log.debug("SimpleSessionListener(" + myUsername + ").processResponse: " +
mySimpleSession.getRegistration().getUsername() + " log in successful!"); mySimpleSession.getRegistration().getUsername() + " log in successful!");
mySimpleSession.getRegistration().setLastLogin(new Date()); mySimpleSession.sipUserLoggedIn();
mySimpleSession.setLoginStatus(TransportLoginStatus.LOGGED_IN); // mySimpleSession.getRegistration().setLastLogin(new Date());
// mySimpleSession.setLoginStatus(TransportLoginStatus.LOGGED_IN);
} }
else { else {
if (mySimpleSession.getLoginStatus().equals(TransportLoginStatus.LOGGING_OUT)) { if (mySimpleSession.getLoginStatus().equals(TransportLoginStatus.LOGGING_OUT)) {
Log.debug("SimpleSessionListener(" + myUsername + ").processResponse: " + Log.debug("SimpleSessionListener(" + myUsername + ").processResponse: " +
mySimpleSession.getRegistration().getUsername() + " log out successful!"); mySimpleSession.getRegistration().getUsername() + " log out successful!");
mySimpleSession.setLoginStatus(TransportLoginStatus.LOGGED_OUT); mySimpleSession.sipUserLoggedOut();
mySimpleSession.removeStack(); mySimpleSession.removeStack();
} }
} }
} }
} }
if (method.equals(Request.SUBSCRIBE)) { if (method.equals(Request.SUBSCRIBE)) {
if (response.getStatusCode() - response.getStatusCode() % 100 == 200) { if (response.getStatusCode() / 100 == 2) {
Log.debug("SimpleSessionListener for " + myUsername + ": Handling SUBSCRIBE acknowledgement!!"); Log.debug("SimpleSessionListener for " + myUsername + ": Handling SUBSCRIBE acknowledgement!!");
int expires = 0; int expires = 0;
...@@ -280,33 +264,34 @@ public class SimpleSessionListener implements SipListener { ...@@ -280,33 +264,34 @@ public class SimpleSessionListener implements SipListener {
// presence.setTo(mySimpleSession.getJID()); // presence.setTo(mySimpleSession.getJID());
if (expires > 0) { if (expires > 0) {
// Confirm addition of roster item // Confirm subscription of roster item
// presence.setType(Presence.Type.subscribed);
mySimpleSession.contactSubscribed(toAddr); mySimpleSession.contactSubscribed(toAddr);
} else { } else {
// Confirm deletion of roster item // Confirm unsubscription of roster item
// presence.setType(Presence.Type.unsubscribed); mySimpleSession.contactUnsubscribed(toAddr);
} }
Log.debug("SimpleSessionListener for " + myUsername + ": Handled SUBSCRIBE acknowledgement!!"); Log.debug("SimpleSessionListener for " + myUsername + ": Handled SUBSCRIBE acknowledgement!!");
// mySimpleSession.getTransport().sendPacket(presence);
} }
} }
} }
} }
public void processTimeout(TimeoutEvent timeoutEvent) { public void processTimeout(TimeoutEvent timeoutEvent) {
Log.debug("SimpleSessionListener for " + myUsername + " received a timeout event: " + Log.debug("SimpleSessionListener for " + myUsername + " received a timeout event: " + timeoutEvent.getTimeout().toString());
timeoutEvent.getTimeout().toString());
// timeoutEvent.getTimeout().
// Should we try to resend the packet?
} }
public void processIOException(IOExceptionEvent iOExceptionEvent) { public void processIOException(IOExceptionEvent iOExceptionEvent) {
Log.debug("SimpleSessionListener for " + myUsername + " received an IOException event: " + Log.debug("SimpleSessionListener for " + myUsername + " received an IOException event: " + iOExceptionEvent.toString());
iOExceptionEvent.toString());
} }
public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) { public void processTransactionTerminated(TransactionTerminatedEvent transactionTerminatedEvent) {
Log.debug("SimpleSessionListener(" + myUsername + "): Received a TransactionTerminatedEvent [" + transactionTerminatedEvent.hashCode() + "]"); Log.debug("SimpleSessionListener(" + myUsername + "): Received a TransactionTerminatedEvent [" + transactionTerminatedEvent.hashCode() + "]");
// Should we obtain the transaction and log down the tranaction terminated?
} }
public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) { public void processDialogTerminated(DialogTerminatedEvent dialogTerminatedEvent) {
......
...@@ -10,14 +10,31 @@ ...@@ -10,14 +10,31 @@
package org.jivesoftware.wildfire.gateway.protocols.simple; package org.jivesoftware.wildfire.gateway.protocols.simple;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.TooManyListenersException;
import javax.sip.InvalidArgumentException;
import javax.sip.ListeningPoint; import javax.sip.ListeningPoint;
import javax.sip.ObjectInUseException;
import javax.sip.PeerUnavailableException;
import javax.sip.SipFactory; import javax.sip.SipFactory;
import javax.sip.SipProvider;
import javax.sip.SipStack;
import javax.sip.TransportNotSupportedException;
import javax.sip.address.AddressFactory;
import javax.sip.header.HeaderFactory;
import javax.sip.message.MessageFactory;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.LocaleUtils; import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import org.jivesoftware.wildfire.gateway.BaseTransport; import org.jivesoftware.wildfire.gateway.BaseTransport;
import org.jivesoftware.wildfire.gateway.PresenceType; import org.jivesoftware.wildfire.gateway.PresenceType;
import org.jivesoftware.wildfire.gateway.Registration; import org.jivesoftware.wildfire.gateway.Registration;
import org.jivesoftware.wildfire.gateway.TransportLoginStatus;
import org.jivesoftware.wildfire.gateway.TransportSession; import org.jivesoftware.wildfire.gateway.TransportSession;
import org.xmpp.packet.JID; import org.xmpp.packet.JID;
import org.xmpp.packet.Presence;
/** /**
* A transport implementation for SIMPLE protocol. * A transport implementation for SIMPLE protocol.
...@@ -47,12 +64,15 @@ public class SimpleTransport extends BaseTransport { ...@@ -47,12 +64,15 @@ public class SimpleTransport extends BaseTransport {
public void registrationLoggedOut(TransportSession session) { public void registrationLoggedOut(TransportSession session) {
((SimpleSession) session).logout(); ((SimpleSession) session).logout();
((SimpleSession) session).removeStack();
session.sessionDone(); session.sessionDone();
// Just in case. // Just in case.
// session.setLoginStatus(TransportLoginStatus.LOGGED_OUT); session.setLoginStatus(TransportLoginStatus.LOGGED_OUT);
} }
/**
*/
public String getTerminologyUsername() { public String getTerminologyUsername() {
return LocaleUtils.getLocalizedString("gateway.sip.username", "gateway"); return LocaleUtils.getLocalizedString("gateway.sip.username", "gateway");
} }
...@@ -61,40 +81,179 @@ public class SimpleTransport extends BaseTransport { ...@@ -61,40 +81,179 @@ public class SimpleTransport extends BaseTransport {
return LocaleUtils.getLocalizedString("gateway.sip.password", "gateway"); return LocaleUtils.getLocalizedString("gateway.sip.password", "gateway");
} }
/**
* @see org.jivesoftware.wildfire.gateway.BaseTransport#getTerminologyNickname()
*/
public String getTerminologyNickname() { public String getTerminologyNickname() {
// If this string is needed, then take it. Just put a draft code to ensure integrity. // If this string is needed, then take it. Just put a draft code to ensure integrity.
return null; String result = null;
return result;
} }
/**
* @see org.jivesoftware.wildfire.gateway.BaseTransport#getTerminologyRegistration()
*/
public String getTerminologyRegistration() { public String getTerminologyRegistration() {
return LocaleUtils.getLocalizedString("gateway.sip.registration", "gateway"); return LocaleUtils.getLocalizedString("gateway.sip.registration", "gateway");
} }
/**
* @see org.jivesoftware.wildfire.gateway.BaseTransport#isPasswordRequired()
*/
public Boolean isPasswordRequired() { public Boolean isPasswordRequired() {
// Just put a draft code to ensure integrity. // Just put a draft code to ensure integrity.
return true; Boolean result = true;
return result;
} }
/**
* @see org.jivesoftware.wildfire.gateway.BaseTransport#isNicknameRequired()
*/
public Boolean isNicknameRequired() { public Boolean isNicknameRequired() {
// Just put a draft code to ensure integrity. // Just put a draft code to ensure integrity.
return false; Boolean result = false;
return result;
} }
/**
* @see org.jivesoftware.wildfire.gateway.BaseTransport#isUsernameValid(String)
*/
public Boolean isUsernameValid(String username) { public Boolean isUsernameValid(String username) {
// Just put a draft code to ensure integrity. // Just put a draft code to ensure integrity.
Log.debug("SimpleTransport.isUsernameValid: Checking '" + username + "'");
return username.matches("\\w+"); // Boolean result = username.matches("\\w+");
Boolean result = username.matches("[^ \\p{Cntrl}()@,;:\\\\\"\\[\\]]+@[^ \\p{Cntrl}()@,;:\\\\\"\\[\\]]+");
return result;
} }
// The following code are generic custom classes for SIP-XMPP conversion. // The following code are generic custom classes for SIP-XMPP conversion.
public void convertJabStatusToSIP(PresenceType jabStatus) { public SimplePresence convertJabStatusToSIP(PresenceType jabStatus) {
SimplePresence simplePresence = new SimplePresence();
switch (jabStatus) {
case available:
// simplePresence.setRpid(SimplePresence.Rpid.UNKNOWN);
simplePresence.setDmNote("Online");
break;
case away:
simplePresence.setRpid(SimplePresence.Rpid.AWAY);
break;
case chat:
simplePresence.setRpid(SimplePresence.Rpid.OTHER);
simplePresence.setDmNote("Free to chat");
break;
case dnd:
simplePresence.setRpid(SimplePresence.Rpid.BUSY);
break;
case unavailable:
simplePresence.setTupleStatus(SimplePresence.TupleStatus.CLOSED);
break;
case unknown:
simplePresence.setRpid(SimplePresence.Rpid.UNKNOWN);
break;
case xa:
simplePresence.setRpid(SimplePresence.Rpid.AWAY);
break;
default:
break;
} }
public void convertSIPStatusToJap() { return simplePresence;
}
public void convertSIPStatusToJap(Presence presence, SimplePresence simplePresence) {
if (simplePresence.getTupleStatus().isOpen()) {
switch (simplePresence.getRpid()) {
case APPOINTMENT:
presence.setShow(Presence.Show.dnd);
break;
case AWAY:
presence.setShow(Presence.Show.away);
break;
case BREAKFAST:
presence.setShow(Presence.Show.xa);
break;
case BUSY:
presence.setShow(Presence.Show.dnd);
break;
case DINNER:
presence.setShow(Presence.Show.xa);
break;
case HOLIDAY:
presence.setShow(Presence.Show.xa);
break;
case IN_TRANSIT:
presence.setShow(Presence.Show.xa);
break;
case LOOKING_FOR_WORK:
presence.setShow(Presence.Show.dnd);
break;
case LUNCH:
case MEAL:
presence.setShow(Presence.Show.xa);
break;
case MEETING:
presence.setShow(Presence.Show.dnd);
break;
case ON_THE_PHONE:
presence.setShow(Presence.Show.away);
presence.setStatus("On Phone");
break;
case OTHER:
break;
case PERFORMANCE:
presence.setShow(Presence.Show.dnd);
break;
case PERMANENT_ABSENCE:
presence.setType(Presence.Type.unavailable);
break;
case PLAYING:
presence.setShow(Presence.Show.away);
break;
case PRESENTATION:
presence.setShow(Presence.Show.dnd);
break;
case SHOPPING:
presence.setShow(Presence.Show.xa);
break;
case SLEEPING:
presence.setShow(Presence.Show.xa);
break;
case SPECTATOR:
presence.setShow(Presence.Show.xa);
break;
case STEERING:
presence.setShow(Presence.Show.xa);
break;
case TRAVEL:
presence.setShow(Presence.Show.xa);
break;
case TV:
presence.setShow(Presence.Show.away);
break;
case UNKNOWN:
// presence.setType(Presence.Type.unavailable);
break;
case VACATION:
presence.setShow(Presence.Show.xa);
break;
case WORKING:
presence.setShow(Presence.Show.dnd);
break;
case WORSHIP:
presence.setShow(Presence.Show.dnd);
break;
default:
break;
}
}
else {
presence.setType(Presence.Type.unavailable);
}
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment