Skip to content

Commit

Permalink
Reworked OSGi support of Smack (SMACK-343)
Browse files Browse the repository at this point in the history
Because of OSGi, no subproject of Smack (which is the same as a OSGi
bundle) must export a package that is already exported by another
subproject.

Therefore it was necessary to move the TCP and BOSH code into their own
packages: org.jivesoftware.smack.(tcp|bosh).

OSGi classloader restrictions also made it necessary to create a
Declarative Service for smack-extensions, smack-experimental and
smack-lagacy (i.e. smack subprojects which should be initialized), in
order to initialize them accordingly, as smack-core is, when used in a
OSGi environment, unable to load and initialize classes from other smack
bundles. OSGi's "Service Component Runtime" (SCR) will now take care of
running the initialization code of the particular Smack bundle by
activating its Declarative Service.

That is also the reason why most initialization related method now have an
additional classloader argument.

Note that due the refactoring, some ugly changes in XMPPTCPConnection
and its PacketReader and PacketWriter where necessary.
  • Loading branch information
Flowdalic committed May 15, 2014
1 parent 541b8b3 commit 4c76f26
Show file tree
Hide file tree
Showing 39 changed files with 414 additions and 447 deletions.
10 changes: 10 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,16 @@ subprojects {
}
}

['smack-extensions', 'smack-experimental', 'smack-legacy'].each { name ->
project(":$name") {
jar {
manifest {
instruction 'Service-Component', "org.jivesoftware.smackx/$name-components.xml"
}
}
}
}

def getGitCommit() {
def dotGit = new File("$projectDir/.git")
if (!dotGit.isDirectory()) return 'non-git build'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

package org.jivesoftware.smack;
package org.jivesoftware.smack.bosh;

import java.net.URI;
import java.net.URISyntaxException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

package org.jivesoftware.smack;
package org.jivesoftware.smack.bosh;

import java.io.StringReader;

Expand Down Expand Up @@ -153,7 +153,7 @@ private void parseFeatures(XmlPullParser parser) throws Exception {
// The server supports sessions
connection.serverSupportsSession();
} else if (parser.getName().equals("register")) {
AccountManager.getInstance(connection).setSupportsAccountCreation(true);
connection.serverSupportsAccountCreation();
}
} else if (eventType == XmlPullParser.END_TAG) {
if (parser.getName().equals("features")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

package org.jivesoftware.smack;
package org.jivesoftware.smack.bosh;

import java.io.IOException;
import java.io.PipedReader;
Expand All @@ -27,9 +27,11 @@

import javax.security.sasl.SaslException;

import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.SmackException.NotConnectedException;
import org.jivesoftware.smack.SmackException.AlreadyLoggedInException;
import org.jivesoftware.smack.SmackException.ConnectionException;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.ConnectionCreationListener;
import org.jivesoftware.smack.ConnectionListener;
Expand Down Expand Up @@ -137,7 +139,7 @@ public XMPPBOSHConnection(BOSHConfiguration config) {
}

@Override
void connectInternal() throws SmackException {
protected void connectInternal() throws SmackException {
if (connected) {
throw new IllegalStateException("Already connected to a server.");
}
Expand Down Expand Up @@ -267,7 +269,7 @@ public void login(String username, String password, String resource)
if (response != null) {
this.user = response;
// Update the serviceName with the one returned by the server
config.setServiceName(StringUtils.parseServer(response));
setServiceName(StringUtils.parseServer(response));
} else {
this.user = username + "@" + getServiceName();
if (resource != null) {
Expand All @@ -285,7 +287,7 @@ public void login(String username, String password, String resource)
anonymous = false;

// Stores the autentication for future reconnection
config.setLoginInfo(username, password, resource);
setLoginInfo(username, password, resource);

// If debugging is enabled, change the the debug window title to include
// the
Expand Down Expand Up @@ -316,7 +318,7 @@ public void loginAnonymously() throws XMPPException, SmackException, IOException
// Set the user value.
this.user = response;
// Update the serviceName with the one returned by the server
config.setServiceName(StringUtils.parseServer(response));
setServiceName(StringUtils.parseServer(response));

// Set presence to online.
if (config.isSendPresence()) {
Expand All @@ -337,7 +339,8 @@ public void loginAnonymously() throws XMPPException, SmackException, IOException
callConnectionAuthenticatedListener();
}

void sendPacketInternal(Packet packet) throws NotConnectedException {
@Override
protected void sendPacketInternal(Packet packet) throws NotConnectedException {
if (done) {
throw new NotConnectedException();
}
Expand Down Expand Up @@ -508,6 +511,30 @@ protected void notifyConnectionError(Exception e) {
callConnectionClosedOnErrorListener(e);
}

@Override
protected void processPacket(Packet packet) {
super.processPacket(packet);
}

@Override
protected SASLAuthentication getSASLAuthentication() {
return super.getSASLAuthentication();
}

@Override
protected void serverRequiresBinding() {
super.serverRequiresBinding();
}

@Override
protected void serverSupportsSession() {
super.serverSupportsSession();
}

@Override
protected void serverSupportsAccountCreation() {
super.serverSupportsAccountCreation();
}

/**
* A listener class which listen for a successfully established connection
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,14 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smack.compression;
package org.jivesoftware.smack.compression.jzlib;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.compression.XMPPInputOutputStream;

import com.jcraft.jzlib.JZlib;
import com.jcraft.jzlib.ZInputStream;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ public void authenticateAnonymously() throws SASLErrorException, SaslException,
* @param mechanisms collection of strings with the available SASL mechanism reported
* by the server.
*/
void setAvailableSASLMethods(Collection<String> mechanisms) {
public void setAvailableSASLMethods(Collection<String> mechanisms) {
this.serverMechanisms = mechanisms;
}

Expand All @@ -429,15 +429,15 @@ public boolean isAuthenticated() {
* @throws IOException If a network error occures while authenticating.
* @throws NotConnectedException
*/
void challengeReceived(String challenge) throws IOException, NotConnectedException {
public void challengeReceived(String challenge) throws IOException, NotConnectedException {
currentMechanism.challengeReceived(challenge);
}

/**
* Notification message saying that SASL authentication was successful. The next step
* would be to bind the resource.
*/
void authenticated() {
public void authenticated() {
saslNegotiated = true;
// Wake up the thread that is waiting in the #authenticate method
synchronized (this) {
Expand All @@ -452,7 +452,7 @@ void authenticated() {
* @param saslFailure the SASL failure as reported by the server
* @see <a href="https://tools.ietf.org/html/rfc6120#section-6.5">RFC6120 6.5</a>
*/
void authenticationFailed(SASLFailure saslFailure) {
public void authenticationFailed(SASLFailure saslFailure) {
this.saslFailure = saslFailure;
// Wake up the thread that is waiting in the #authenticate method
synchronized (this) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,18 +311,24 @@ public static List<XMPPInputOutputStream> getCompresionHandlers() {
return res;
}

public static void processConfigFile(InputStream cfgFileStream, Collection<Exception> exceptions) throws Exception {
public static void processConfigFile(InputStream cfgFileStream,
Collection<Exception> exceptions) throws Exception {
processConfigFile(cfgFileStream, exceptions, SmackConfiguration.class.getClassLoader());
}

public static void processConfigFile(InputStream cfgFileStream,
Collection<Exception> exceptions, ClassLoader classLoader) throws Exception {
XmlPullParser parser = XmlPullParserFactory.newInstance().newPullParser();
parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
parser.setInput(cfgFileStream, "UTF-8");
int eventType = parser.getEventType();
do {
if (eventType == XmlPullParser.START_TAG) {
if (parser.getName().equals("startupClasses")) {
parseClassesToLoad(parser, false, exceptions);
parseClassesToLoad(parser, false, exceptions, classLoader);
}
else if (parser.getName().equals("optionalStartupClasses")) {
parseClassesToLoad(parser, true, exceptions);
parseClassesToLoad(parser, true, exceptions, classLoader);
}
}
eventType = parser.next();
Expand All @@ -336,7 +342,9 @@ else if (parser.getName().equals("optionalStartupClasses")) {
}
}

private static void parseClassesToLoad(XmlPullParser parser, boolean optional, Collection<Exception> exceptions) throws XmlPullParserException, IOException, Exception {
private static void parseClassesToLoad(XmlPullParser parser, boolean optional,
Collection<Exception> exceptions, ClassLoader classLoader)
throws XmlPullParserException, IOException, Exception {
final String startName = parser.getName();
int eventType;
String name;
Expand All @@ -350,26 +358,30 @@ private static void parseClassesToLoad(XmlPullParser parser, boolean optional, C
}
else {
try {
loadSmackClass(classToLoad, optional);
} catch (Exception e) {
loadSmackClass(classToLoad, optional, classLoader);
}
catch (Exception e) {
// Don't throw the exception if an exceptions collection is given, instead
// record it there. This is used for unit testing purposes.
if (exceptions != null) {
exceptions.add(e);
} else {
}
else {
throw e;
}
}
}
}
} while (! (eventType == XmlPullParser.END_TAG && startName.equals(name)));
}
while (!(eventType == XmlPullParser.END_TAG && startName.equals(name)));
}

private static void loadSmackClass(String className, boolean optional) throws Exception {
private static void loadSmackClass(String className, boolean optional, ClassLoader classLoader) throws Exception {
Class<?> initClass;
try {
// Attempt to load the class so that the class can get initialized
initClass = Class.forName(className);
// Attempt to load and initialize the class so that all static initializer blocks of
// class are executed
initClass = Class.forName(className, true, classLoader);
}
catch (ClassNotFoundException cnfe) {
Level logLevel;
Expand All @@ -388,8 +400,7 @@ private static void loadSmackClass(String className, boolean optional) throws Ex
}
if (SmackInitializer.class.isAssignableFrom(initClass)) {
SmackInitializer initializer = (SmackInitializer) initClass.newInstance();
initializer.initialize();
List<Exception> exceptions = initializer.getExceptions();
List<Exception> exceptions = initializer.initialize();
if (exceptions.size() == 0) {
LOGGER.log(Level.FINE, "Loaded SmackInitializer " + className);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ public int getPort() {
*/
public abstract boolean isSecureConnection();

abstract void sendPacketInternal(Packet packet) throws NotConnectedException;
protected abstract void sendPacketInternal(Packet packet) throws NotConnectedException;

/**
* Returns true if network traffic is being compressed. When using stream compression network
Expand Down Expand Up @@ -398,7 +398,7 @@ public void connect() throws SmackException, IOException, XMPPException {
* @throws IOException
* @throws XMPPException
*/
abstract void connectInternal() throws SmackException, IOException, XMPPException;
protected abstract void connectInternal() throws SmackException, IOException, XMPPException;

/**
* Logs in to the server using the strongest authentication mode supported by
Expand Down Expand Up @@ -476,7 +476,7 @@ public void login(String username, String password) throws XMPPException, SmackE
* Notification message saying that the server requires the client to bind a
* resource to the stream.
*/
void serverRequiresBinding() {
protected void serverRequiresBinding() {
synchronized (bindingRequired) {
bindingRequired.set(true);
bindingRequired.notify();
Expand All @@ -488,11 +488,11 @@ void serverRequiresBinding() {
* sessions the client needs to send a Session packet after successfully binding a resource
* for the session.
*/
void serverSupportsSession() {
protected void serverSupportsSession() {
sessionSupported = true;
}

String bindResourceAndEstablishSession(String resource) throws XMPPErrorException,
protected String bindResourceAndEstablishSession(String resource) throws XMPPErrorException,
ResourceBindingNotOfferedException, NoResponseException, NotConnectedException {

synchronized (bindingRequired) {
Expand Down Expand Up @@ -537,6 +537,30 @@ protected void throwConnectionExceptionOrNoResponse() throws IOException, NoResp
}
}

protected Reader getReader() {
return reader;
}

protected Writer getWriter() {
return writer;
}

protected void setServiceName(String serviceName) {
config.setServiceName(serviceName);
}

protected void setLoginInfo(String username, String password, String resource) {
config.setLoginInfo(username, password, resource);
}

protected void serverSupportsAccountCreation() {
AccountManager.getInstance(this).setSupportsAccountCreation(true);
}

protected void maybeResolveDns() throws Exception {
config.maybeResolveDns();
}

/**
* Sends the specified packet to the server.
*
Expand Down Expand Up @@ -627,14 +651,15 @@ public Roster getRoster() {
}
return roster;
}

/**
* Returns the SASLAuthentication manager that is responsible for authenticating with
* the server.
*
* @return the SASLAuthentication manager that is responsible for authenticating with
* the server.
*/
public SASLAuthentication getSASLAuthentication() {
protected SASLAuthentication getSASLAuthentication() {
return saslAuthentication;
}

Expand Down Expand Up @@ -1127,13 +1152,13 @@ protected void setWasAuthenticated(boolean authenticated) {
}
}

void callConnectionConnectedListener() {
protected void callConnectionConnectedListener() {
for (ConnectionListener listener : getConnectionListeners()) {
listener.connected(this);
}
}

void callConnectionAuthenticatedListener() {
protected void callConnectionAuthenticatedListener() {
for (ConnectionListener listener : getConnectionListeners()) {
listener.authenticated(this);
}
Expand All @@ -1152,7 +1177,7 @@ void callConnectionClosedListener() {
}
}

void callConnectionClosedOnErrorListener(Exception e) {
protected void callConnectionClosedOnErrorListener(Exception e) {
LOGGER.log(Level.WARNING, "Connection closed with error", e);
for (ConnectionListener listener : getConnectionListeners()) {
try {
Expand Down
Loading

0 comments on commit 4c76f26

Please sign in to comment.