1
0
Fork 0
mirror of https://codeberg.org/Mercury-IM/Smack synced 2025-12-10 07:01:07 +01:00

Migrate from Ant to Gradle (SMACK-265)

This commit is contained in:
Florian Schmaus 2014-02-14 18:13:51 +01:00
parent 235eca3a3d
commit 201152ef42
767 changed files with 1088 additions and 4296 deletions

View file

@ -0,0 +1,183 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.packet.StreamInitiation;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.*;
import java.util.List;
import java.util.ArrayList;
/**
* The fault tolerant negotiator takes two stream negotiators, the primary and the secondary
* negotiator. If the primary negotiator fails during the stream negotiaton process, the second
* negotiator is used.
*/
public class FaultTolerantNegotiator extends StreamNegotiator {
private StreamNegotiator primaryNegotiator;
private StreamNegotiator secondaryNegotiator;
private Connection connection;
private PacketFilter primaryFilter;
private PacketFilter secondaryFilter;
public FaultTolerantNegotiator(Connection connection, StreamNegotiator primary,
StreamNegotiator secondary) {
this.primaryNegotiator = primary;
this.secondaryNegotiator = secondary;
this.connection = connection;
}
public PacketFilter getInitiationPacketFilter(String from, String streamID) {
if (primaryFilter == null || secondaryFilter == null) {
primaryFilter = primaryNegotiator.getInitiationPacketFilter(from, streamID);
secondaryFilter = secondaryNegotiator.getInitiationPacketFilter(from, streamID);
}
return new OrFilter(primaryFilter, secondaryFilter);
}
InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException {
throw new UnsupportedOperationException("Negotiation only handled by create incoming " +
"stream method.");
}
final Packet initiateIncomingStream(Connection connection, StreamInitiation initiation) {
throw new UnsupportedOperationException("Initiation handled by createIncomingStream " +
"method");
}
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException {
PacketCollector collector = connection.createPacketCollector(
getInitiationPacketFilter(initiation.getFrom(), initiation.getSessionID()));
connection.sendPacket(super.createInitiationAccept(initiation, getNamespaces()));
ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(2);
CompletionService<InputStream> service
= new ExecutorCompletionService<InputStream>(threadPoolExecutor);
List<Future<InputStream>> futures = new ArrayList<Future<InputStream>>();
InputStream stream = null;
XMPPException exception = null;
try {
futures.add(service.submit(new NegotiatorService(collector)));
futures.add(service.submit(new NegotiatorService(collector)));
int i = 0;
while (stream == null && i < futures.size()) {
Future<InputStream> future;
try {
i++;
future = service.poll(10, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
continue;
}
if (future == null) {
continue;
}
try {
stream = future.get();
}
catch (InterruptedException e) {
/* Do Nothing */
}
catch (ExecutionException e) {
exception = new XMPPException(e.getCause());
}
}
}
finally {
for (Future<InputStream> future : futures) {
future.cancel(true);
}
collector.cancel();
threadPoolExecutor.shutdownNow();
}
if (stream == null) {
if (exception != null) {
throw exception;
}
else {
throw new XMPPException("File transfer negotiation failed.");
}
}
return stream;
}
private StreamNegotiator determineNegotiator(Packet streamInitiation) {
return primaryFilter.accept(streamInitiation) ? primaryNegotiator : secondaryNegotiator;
}
public OutputStream createOutgoingStream(String streamID, String initiator, String target)
throws XMPPException {
OutputStream stream;
try {
stream = primaryNegotiator.createOutgoingStream(streamID, initiator, target);
}
catch (XMPPException ex) {
stream = secondaryNegotiator.createOutgoingStream(streamID, initiator, target);
}
return stream;
}
public String[] getNamespaces() {
String[] primary = primaryNegotiator.getNamespaces();
String[] secondary = secondaryNegotiator.getNamespaces();
String[] namespaces = new String[primary.length + secondary.length];
System.arraycopy(primary, 0, namespaces, 0, primary.length);
System.arraycopy(secondary, 0, namespaces, primary.length, secondary.length);
return namespaces;
}
public void cleanup() {
}
private class NegotiatorService implements Callable<InputStream> {
private PacketCollector collector;
NegotiatorService(PacketCollector collector) {
this.collector = collector;
}
public InputStream call() throws Exception {
Packet streamInitiation = collector.nextResult(
SmackConfiguration.getPacketReplyTimeout() * 2);
if (streamInitiation == null) {
throw new XMPPException("No response from remote client");
}
StreamNegotiator negotiator = determineNegotiator(streamInitiation);
return negotiator.negotiateIncomingStream(streamInitiation);
}
}
}

View file

@ -0,0 +1,377 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.XMPPException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Contains the generic file information and progress related to a particular
* file transfer.
*
* @author Alexander Wenckus
*
*/
public abstract class FileTransfer {
private String fileName;
private String filePath;
private long fileSize;
private String peer;
private Status status = Status.initial;
private final Object statusMonitor = new Object();
protected FileTransferNegotiator negotiator;
protected String streamID;
protected long amountWritten = -1;
private Error error;
private Exception exception;
/**
* Buffer size between input and output
*/
private static final int BUFFER_SIZE = 8192;
protected FileTransfer(String peer, String streamID,
FileTransferNegotiator negotiator) {
this.peer = peer;
this.streamID = streamID;
this.negotiator = negotiator;
}
protected void setFileInfo(String fileName, long fileSize) {
this.fileName = fileName;
this.fileSize = fileSize;
}
protected void setFileInfo(String path, String fileName, long fileSize) {
this.filePath = path;
this.fileName = fileName;
this.fileSize = fileSize;
}
/**
* Returns the size of the file being transfered.
*
* @return Returns the size of the file being transfered.
*/
public long getFileSize() {
return fileSize;
}
/**
* Returns the name of the file being transfered.
*
* @return Returns the name of the file being transfered.
*/
public String getFileName() {
return fileName;
}
/**
* Returns the local path of the file.
*
* @return Returns the local path of the file.
*/
public String getFilePath() {
return filePath;
}
/**
* Returns the JID of the peer for this file transfer.
*
* @return Returns the JID of the peer for this file transfer.
*/
public String getPeer() {
return peer;
}
/**
* Returns the progress of the file transfer as a number between 0 and 1.
*
* @return Returns the progress of the file transfer as a number between 0
* and 1.
*/
public double getProgress() {
if (amountWritten <= 0 || fileSize <= 0) {
return 0;
}
return (double) amountWritten / (double) fileSize;
}
/**
* Returns true if the transfer has been cancelled, if it has stopped because
* of a an error, or the transfer completed successfully.
*
* @return Returns true if the transfer has been cancelled, if it has stopped
* because of a an error, or the transfer completed successfully.
*/
public boolean isDone() {
return status == Status.cancelled || status == Status.error
|| status == Status.complete || status == Status.refused;
}
/**
* Returns the current status of the file transfer.
*
* @return Returns the current status of the file transfer.
*/
public Status getStatus() {
return status;
}
protected void setError(Error type) {
this.error = type;
}
/**
* When {@link #getStatus()} returns that there was an {@link Status#error}
* during the transfer, the type of error can be retrieved through this
* method.
*
* @return Returns the type of error that occurred if one has occurred.
*/
public Error getError() {
return error;
}
/**
* If an exception occurs asynchronously it will be stored for later
* retrieval. If there is an error there maybe an exception set.
*
* @return The exception that occurred or null if there was no exception.
* @see #getError()
*/
public Exception getException() {
return exception;
}
public String getStreamID() {
return streamID;
}
/**
* Cancels the file transfer.
*/
public abstract void cancel();
protected void setException(Exception exception) {
this.exception = exception;
}
protected void setStatus(Status status) {
synchronized (statusMonitor) {
this.status = status;
}
}
protected boolean updateStatus(Status oldStatus, Status newStatus) {
synchronized (statusMonitor) {
if (oldStatus != status) {
return false;
}
status = newStatus;
return true;
}
}
protected void writeToStream(final InputStream in, final OutputStream out)
throws XMPPException
{
final byte[] b = new byte[BUFFER_SIZE];
int count = 0;
amountWritten = 0;
do {
// write to the output stream
try {
out.write(b, 0, count);
} catch (IOException e) {
throw new XMPPException("error writing to output stream", e);
}
amountWritten += count;
// read more bytes from the input stream
try {
count = in.read(b);
} catch (IOException e) {
throw new XMPPException("error reading from input stream", e);
}
} while (count != -1 && !getStatus().equals(Status.cancelled));
// the connection was likely terminated abrubtly if these are not equal
if (!getStatus().equals(Status.cancelled) && getError() == Error.none
&& amountWritten != fileSize) {
setStatus(Status.error);
this.error = Error.connection;
}
}
/**
* A class to represent the current status of the file transfer.
*
* @author Alexander Wenckus
*
*/
public enum Status {
/**
* An error occurred during the transfer.
*
* @see FileTransfer#getError()
*/
error("Error"),
/**
* The initial status of the file transfer.
*/
initial("Initial"),
/**
* The file transfer is being negotiated with the peer. The party
* Receiving the file has the option to accept or refuse a file transfer
* request. If they accept, then the process of stream negotiation will
* begin. If they refuse the file will not be transfered.
*
* @see #negotiating_stream
*/
negotiating_transfer("Negotiating Transfer"),
/**
* The peer has refused the file transfer request halting the file
* transfer negotiation process.
*/
refused("Refused"),
/**
* The stream to transfer the file is being negotiated over the chosen
* stream type. After the stream negotiating process is complete the
* status becomes negotiated.
*
* @see #negotiated
*/
negotiating_stream("Negotiating Stream"),
/**
* After the stream negotiation has completed the intermediate state
* between the time when the negotiation is finished and the actual
* transfer begins.
*/
negotiated("Negotiated"),
/**
* The transfer is in progress.
*
* @see FileTransfer#getProgress()
*/
in_progress("In Progress"),
/**
* The transfer has completed successfully.
*/
complete("Complete"),
/**
* The file transfer was cancelled
*/
cancelled("Cancelled");
private String status;
private Status(String status) {
this.status = status;
}
public String toString() {
return status;
}
}
/**
* Return the length of bytes written out to the stream.
* @return the amount in bytes written out.
*/
public long getAmountWritten(){
return amountWritten;
}
public enum Error {
/**
* No error
*/
none("No error"),
/**
* The peer did not find any of the provided stream mechanisms
* acceptable.
*/
not_acceptable("The peer did not find any of the provided stream mechanisms acceptable."),
/**
* The provided file to transfer does not exist or could not be read.
*/
bad_file("The provided file to transfer does not exist or could not be read."),
/**
* The remote user did not respond or the connection timed out.
*/
no_response("The remote user did not respond or the connection timed out."),
/**
* An error occurred over the socket connected to send the file.
*/
connection("An error occured over the socket connected to send the file."),
/**
* An error occurred while sending or receiving the file
*/
stream("An error occured while sending or recieving the file.");
private final String msg;
private Error(String msg) {
this.msg = msg;
}
/**
* Returns a String representation of this error.
*
* @return Returns a String representation of this error.
*/
public String getMessage() {
return msg;
}
public String toString() {
return msg;
}
}
}

View file

@ -0,0 +1,33 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
/**
* File transfers can cause several events to be raised. These events can be
* monitored through this interface.
*
* @author Alexander Wenckus
*/
public interface FileTransferListener {
/**
* A request to send a file has been recieved from another user.
*
* @param request
* The request from the other user.
*/
public void fileTransferRequest(final FileTransferRequest request);
}

View file

@ -0,0 +1,179 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.IQTypeFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.packet.StreamInitiation;
import java.util.ArrayList;
import java.util.List;
/**
* The file transfer manager class handles the sending and recieving of files.
* To send a file invoke the {@link #createOutgoingFileTransfer(String)} method.
* <p>
* And to recieve a file add a file transfer listener to the manager. The
* listener will notify you when there is a new file transfer request. To create
* the {@link IncomingFileTransfer} object accept the transfer, or, if the
* transfer is not desirable reject it.
*
* @author Alexander Wenckus
*
*/
public class FileTransferManager {
private final FileTransferNegotiator fileTransferNegotiator;
private List<FileTransferListener> listeners;
private Connection connection;
/**
* Creates a file transfer manager to initiate and receive file transfers.
*
* @param connection
* The Connection that the file transfers will use.
*/
public FileTransferManager(Connection connection) {
this.connection = connection;
this.fileTransferNegotiator = FileTransferNegotiator
.getInstanceFor(connection);
}
/**
* Add a file transfer listener to listen to incoming file transfer
* requests.
*
* @param li
* The listener
* @see #removeFileTransferListener(FileTransferListener)
* @see FileTransferListener
*/
public void addFileTransferListener(final FileTransferListener li) {
if (listeners == null) {
initListeners();
}
synchronized (this.listeners) {
listeners.add(li);
}
}
private void initListeners() {
listeners = new ArrayList<FileTransferListener>();
connection.addPacketListener(new PacketListener() {
public void processPacket(Packet packet) {
fireNewRequest((StreamInitiation) packet);
}
}, new AndFilter(new PacketTypeFilter(StreamInitiation.class),
new IQTypeFilter(IQ.Type.SET)));
}
protected void fireNewRequest(StreamInitiation initiation) {
FileTransferListener[] listeners = null;
synchronized (this.listeners) {
listeners = new FileTransferListener[this.listeners.size()];
this.listeners.toArray(listeners);
}
FileTransferRequest request = new FileTransferRequest(this, initiation);
for (int i = 0; i < listeners.length; i++) {
listeners[i].fileTransferRequest(request);
}
}
/**
* Removes a file transfer listener.
*
* @param li
* The file transfer listener to be removed
* @see FileTransferListener
*/
public void removeFileTransferListener(final FileTransferListener li) {
if (listeners == null) {
return;
}
synchronized (this.listeners) {
listeners.remove(li);
}
}
/**
* Creates an OutgoingFileTransfer to send a file to another user.
*
* @param userID
* The fully qualified jabber ID (i.e. full JID) with resource of the user to
* send the file to.
* @return The send file object on which the negotiated transfer can be run.
* @exception IllegalArgumentException if userID is null or not a full JID
*/
public OutgoingFileTransfer createOutgoingFileTransfer(String userID) {
if (userID == null) {
throw new IllegalArgumentException("userID was null");
}
// We need to create outgoing file transfers with a full JID since this method will later
// use XEP-0095 to negotiate the stream. This is done with IQ stanzas that need to be addressed to a full JID
// in order to reach an client entity.
else if (!StringUtils.isFullJID(userID)) {
throw new IllegalArgumentException("The provided user id was not a full JID (i.e. with resource part)");
}
return new OutgoingFileTransfer(connection.getUser(), userID,
fileTransferNegotiator.getNextStreamID(),
fileTransferNegotiator);
}
/**
* When the file transfer request is acceptable, this method should be
* invoked. It will create an IncomingFileTransfer which allows the
* transmission of the file to procede.
*
* @param request
* The remote request that is being accepted.
* @return The IncomingFileTransfer which manages the download of the file
* from the transfer initiator.
*/
protected IncomingFileTransfer createIncomingFileTransfer(
FileTransferRequest request) {
if (request == null) {
throw new NullPointerException("RecieveRequest cannot be null");
}
IncomingFileTransfer transfer = new IncomingFileTransfer(request,
fileTransferNegotiator);
transfer.setFileInfo(request.getFileName(), request.getFileSize());
return transfer;
}
protected void rejectIncomingFileTransfer(FileTransferRequest request) {
StreamInitiation initiation = request.getStreamInitiation();
IQ rejection = FileTransferNegotiator.createIQ(
initiation.getPacketID(), initiation.getFrom(), initiation
.getTo(), IQ.Type.ERROR);
rejection.setError(new XMPPError(XMPPError.Condition.no_acceptable));
connection.sendPacket(rejection);
}
}

View file

@ -0,0 +1,482 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.packet.DataForm;
import org.jivesoftware.smackx.packet.StreamInitiation;
/**
* Manages the negotiation of file transfers according to JEP-0096. If a file is
* being sent the remote user chooses the type of stream under which the file
* will be sent.
*
* @author Alexander Wenckus
* @see <a href="http://xmpp.org/extensions/xep-0096.html">XEP-0096: SI File Transfer</a>
*/
public class FileTransferNegotiator {
// Static
private static final String[] NAMESPACE = {
"http://jabber.org/protocol/si/profile/file-transfer",
"http://jabber.org/protocol/si"};
private static final Map<Connection, FileTransferNegotiator> transferObject =
new ConcurrentHashMap<Connection, FileTransferNegotiator>();
private static final String STREAM_INIT_PREFIX = "jsi_";
protected static final String STREAM_DATA_FIELD_NAME = "stream-method";
private static final Random randomGenerator = new Random();
/**
* A static variable to use only offer IBB for file transfer. It is generally recommend to only
* set this variable to true for testing purposes as IBB is the backup file transfer method
* and shouldn't be used as the only transfer method in production systems.
*/
public static boolean IBB_ONLY = (System.getProperty("ibb") != null);//true;
/**
* Returns the file transfer negotiator related to a particular connection.
* When this class is requested on a particular connection the file transfer
* service is automatically enabled.
*
* @param connection The connection for which the transfer manager is desired
* @return The IMFileTransferManager
*/
public static FileTransferNegotiator getInstanceFor(
final Connection connection) {
if (connection == null) {
throw new IllegalArgumentException("Connection cannot be null");
}
if (!connection.isConnected()) {
return null;
}
if (transferObject.containsKey(connection)) {
return transferObject.get(connection);
}
else {
FileTransferNegotiator transfer = new FileTransferNegotiator(
connection);
setServiceEnabled(connection, true);
transferObject.put(connection, transfer);
return transfer;
}
}
/**
* Enable the Jabber services related to file transfer on the particular
* connection.
*
* @param connection The connection on which to enable or disable the services.
* @param isEnabled True to enable, false to disable.
*/
public static void setServiceEnabled(final Connection connection,
final boolean isEnabled) {
ServiceDiscoveryManager manager = ServiceDiscoveryManager
.getInstanceFor(connection);
List<String> namespaces = new ArrayList<String>();
namespaces.addAll(Arrays.asList(NAMESPACE));
namespaces.add(InBandBytestreamManager.NAMESPACE);
if (!IBB_ONLY) {
namespaces.add(Socks5BytestreamManager.NAMESPACE);
}
for (String namespace : namespaces) {
if (isEnabled) {
if (!manager.includesFeature(namespace)) {
manager.addFeature(namespace);
}
} else {
manager.removeFeature(namespace);
}
}
}
/**
* Checks to see if all file transfer related services are enabled on the
* connection.
*
* @param connection The connection to check
* @return True if all related services are enabled, false if they are not.
*/
public static boolean isServiceEnabled(final Connection connection) {
ServiceDiscoveryManager manager = ServiceDiscoveryManager
.getInstanceFor(connection);
List<String> namespaces = new ArrayList<String>();
namespaces.addAll(Arrays.asList(NAMESPACE));
namespaces.add(InBandBytestreamManager.NAMESPACE);
if (!IBB_ONLY) {
namespaces.add(Socks5BytestreamManager.NAMESPACE);
}
for (String namespace : namespaces) {
if (!manager.includesFeature(namespace)) {
return false;
}
}
return true;
}
/**
* A convenience method to create an IQ packet.
*
* @param ID The packet ID of the
* @param to To whom the packet is addressed.
* @param from From whom the packet is sent.
* @param type The IQ type of the packet.
* @return The created IQ packet.
*/
public static IQ createIQ(final String ID, final String to,
final String from, final IQ.Type type) {
IQ iqPacket = new IQ() {
public String getChildElementXML() {
return null;
}
};
iqPacket.setPacketID(ID);
iqPacket.setTo(to);
iqPacket.setFrom(from);
iqPacket.setType(type);
return iqPacket;
}
/**
* Returns a collection of the supported transfer protocols.
*
* @return Returns a collection of the supported transfer protocols.
*/
public static Collection<String> getSupportedProtocols() {
List<String> protocols = new ArrayList<String>();
protocols.add(InBandBytestreamManager.NAMESPACE);
if (!IBB_ONLY) {
protocols.add(Socks5BytestreamManager.NAMESPACE);
}
return Collections.unmodifiableList(protocols);
}
// non-static
private final Connection connection;
private final StreamNegotiator byteStreamTransferManager;
private final StreamNegotiator inbandTransferManager;
private FileTransferNegotiator(final Connection connection) {
configureConnection(connection);
this.connection = connection;
byteStreamTransferManager = new Socks5TransferNegotiator(connection);
inbandTransferManager = new IBBTransferNegotiator(connection);
}
private void configureConnection(final Connection connection) {
connection.addConnectionListener(new ConnectionListener() {
public void connectionClosed() {
cleanup(connection);
}
public void connectionClosedOnError(Exception e) {
cleanup(connection);
}
public void reconnectionFailed(Exception e) {
// ignore
}
public void reconnectionSuccessful() {
// ignore
}
public void reconnectingIn(int seconds) {
// ignore
}
});
}
private void cleanup(final Connection connection) {
if (transferObject.remove(connection) != null) {
inbandTransferManager.cleanup();
}
}
/**
* Selects an appropriate stream negotiator after examining the incoming file transfer request.
*
* @param request The related file transfer request.
* @return The file transfer object that handles the transfer
* @throws XMPPException If there are either no stream methods contained in the packet, or
* there is not an appropriate stream method.
*/
public StreamNegotiator selectStreamNegotiator(
FileTransferRequest request) throws XMPPException {
StreamInitiation si = request.getStreamInitiation();
FormField streamMethodField = getStreamMethodField(si
.getFeatureNegotiationForm());
if (streamMethodField == null) {
String errorMessage = "No stream methods contained in packet.";
XMPPError error = new XMPPError(XMPPError.Condition.bad_request, errorMessage);
IQ iqPacket = createIQ(si.getPacketID(), si.getFrom(), si.getTo(),
IQ.Type.ERROR);
iqPacket.setError(error);
connection.sendPacket(iqPacket);
throw new XMPPException(errorMessage, error);
}
// select the appropriate protocol
StreamNegotiator selectedStreamNegotiator;
try {
selectedStreamNegotiator = getNegotiator(streamMethodField);
}
catch (XMPPException e) {
IQ iqPacket = createIQ(si.getPacketID(), si.getFrom(), si.getTo(),
IQ.Type.ERROR);
iqPacket.setError(e.getXMPPError());
connection.sendPacket(iqPacket);
throw e;
}
// return the appropriate negotiator
return selectedStreamNegotiator;
}
private FormField getStreamMethodField(DataForm form) {
FormField field = null;
for (Iterator<FormField> it = form.getFields(); it.hasNext();) {
field = it.next();
if (field.getVariable().equals(STREAM_DATA_FIELD_NAME)) {
break;
}
field = null;
}
return field;
}
private StreamNegotiator getNegotiator(final FormField field)
throws XMPPException {
String variable;
boolean isByteStream = false;
boolean isIBB = false;
for (Iterator<FormField.Option> it = field.getOptions(); it.hasNext();) {
variable = it.next().getValue();
if (variable.equals(Socks5BytestreamManager.NAMESPACE) && !IBB_ONLY) {
isByteStream = true;
}
else if (variable.equals(InBandBytestreamManager.NAMESPACE)) {
isIBB = true;
}
}
if (!isByteStream && !isIBB) {
XMPPError error = new XMPPError(XMPPError.Condition.bad_request,
"No acceptable transfer mechanism");
throw new XMPPException(error.getMessage(), error);
}
//if (isByteStream && isIBB && field.getType().equals(FormField.TYPE_LIST_MULTI)) {
if (isByteStream && isIBB) {
return new FaultTolerantNegotiator(connection,
byteStreamTransferManager,
inbandTransferManager);
}
else if (isByteStream) {
return byteStreamTransferManager;
}
else {
return inbandTransferManager;
}
}
/**
* Reject a stream initiation request from a remote user.
*
* @param si The Stream Initiation request to reject.
*/
public void rejectStream(final StreamInitiation si) {
XMPPError error = new XMPPError(XMPPError.Condition.forbidden, "Offer Declined");
IQ iqPacket = createIQ(si.getPacketID(), si.getFrom(), si.getTo(),
IQ.Type.ERROR);
iqPacket.setError(error);
connection.sendPacket(iqPacket);
}
/**
* Returns a new, unique, stream ID to identify a file transfer.
*
* @return Returns a new, unique, stream ID to identify a file transfer.
*/
public String getNextStreamID() {
StringBuilder buffer = new StringBuilder();
buffer.append(STREAM_INIT_PREFIX);
buffer.append(Math.abs(randomGenerator.nextLong()));
return buffer.toString();
}
/**
* Send a request to another user to send them a file. The other user has
* the option of, accepting, rejecting, or not responding to a received file
* transfer request.
* <p/>
* If they accept, the packet will contain the other user's chosen stream
* type to send the file across. The two choices this implementation
* provides to the other user for file transfer are <a
* href="http://www.jabber.org/jeps/jep-0065.html">SOCKS5 Bytestreams</a>,
* which is the preferred method of transfer, and <a
* href="http://www.jabber.org/jeps/jep-0047.html">In-Band Bytestreams</a>,
* which is the fallback mechanism.
* <p/>
* The other user may choose to decline the file request if they do not
* desire the file, their client does not support JEP-0096, or if there are
* no acceptable means to transfer the file.
* <p/>
* Finally, if the other user does not respond this method will return null
* after the specified timeout.
*
* @param userID The userID of the user to whom the file will be sent.
* @param streamID The unique identifier for this file transfer.
* @param fileName The name of this file. Preferably it should include an
* extension as it is used to determine what type of file it is.
* @param size The size, in bytes, of the file.
* @param desc A description of the file.
* @param responseTimeout The amount of time, in milliseconds, to wait for the remote
* user to respond. If they do not respond in time, this
* @return Returns the stream negotiator selected by the peer.
* @throws XMPPException Thrown if there is an error negotiating the file transfer.
*/
public StreamNegotiator negotiateOutgoingTransfer(final String userID,
final String streamID, final String fileName, final long size,
final String desc, int responseTimeout) throws XMPPException {
StreamInitiation si = new StreamInitiation();
si.setSessionID(streamID);
si.setMimeType(URLConnection.guessContentTypeFromName(fileName));
StreamInitiation.File siFile = new StreamInitiation.File(fileName, size);
siFile.setDesc(desc);
si.setFile(siFile);
si.setFeatureNegotiationForm(createDefaultInitiationForm());
si.setFrom(connection.getUser());
si.setTo(userID);
si.setType(IQ.Type.SET);
PacketCollector collector = connection
.createPacketCollector(new PacketIDFilter(si.getPacketID()));
connection.sendPacket(si);
Packet siResponse = collector.nextResult(responseTimeout);
collector.cancel();
if (siResponse instanceof IQ) {
IQ iqResponse = (IQ) siResponse;
if (iqResponse.getType().equals(IQ.Type.RESULT)) {
StreamInitiation response = (StreamInitiation) siResponse;
return getOutgoingNegotiator(getStreamMethodField(response
.getFeatureNegotiationForm()));
}
else if (iqResponse.getType().equals(IQ.Type.ERROR)) {
throw new XMPPException(iqResponse.getError());
}
else {
throw new XMPPException("File transfer response unreadable");
}
}
else {
return null;
}
}
private StreamNegotiator getOutgoingNegotiator(final FormField field)
throws XMPPException {
String variable;
boolean isByteStream = false;
boolean isIBB = false;
for (Iterator<String> it = field.getValues(); it.hasNext();) {
variable = it.next();
if (variable.equals(Socks5BytestreamManager.NAMESPACE) && !IBB_ONLY) {
isByteStream = true;
}
else if (variable.equals(InBandBytestreamManager.NAMESPACE)) {
isIBB = true;
}
}
if (!isByteStream && !isIBB) {
XMPPError error = new XMPPError(XMPPError.Condition.bad_request,
"No acceptable transfer mechanism");
throw new XMPPException(error.getMessage(), error);
}
if (isByteStream && isIBB) {
return new FaultTolerantNegotiator(connection,
byteStreamTransferManager, inbandTransferManager);
}
else if (isByteStream) {
return byteStreamTransferManager;
}
else {
return inbandTransferManager;
}
}
private DataForm createDefaultInitiationForm() {
DataForm form = new DataForm(Form.TYPE_FORM);
FormField field = new FormField(STREAM_DATA_FIELD_NAME);
field.setType(FormField.TYPE_LIST_SINGLE);
if (!IBB_ONLY) {
field.addOption(new FormField.Option(Socks5BytestreamManager.NAMESPACE));
}
field.addOption(new FormField.Option(InBandBytestreamManager.NAMESPACE));
form.addField(field);
return form;
}
}

View file

@ -0,0 +1,135 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smackx.packet.StreamInitiation;
/**
* A request to send a file recieved from another user.
*
* @author Alexander Wenckus
*
*/
public class FileTransferRequest {
private final StreamInitiation streamInitiation;
private final FileTransferManager manager;
/**
* A recieve request is constructed from the Stream Initiation request
* received from the initator.
*
* @param manager
* The manager handling this file transfer
*
* @param si
* The Stream initiaton recieved from the initiator.
*/
public FileTransferRequest(FileTransferManager manager, StreamInitiation si) {
this.streamInitiation = si;
this.manager = manager;
}
/**
* Returns the name of the file.
*
* @return Returns the name of the file.
*/
public String getFileName() {
return streamInitiation.getFile().getName();
}
/**
* Returns the size in bytes of the file.
*
* @return Returns the size in bytes of the file.
*/
public long getFileSize() {
return streamInitiation.getFile().getSize();
}
/**
* Returns the description of the file provided by the requestor.
*
* @return Returns the description of the file provided by the requestor.
*/
public String getDescription() {
return streamInitiation.getFile().getDesc();
}
/**
* Returns the mime-type of the file.
*
* @return Returns the mime-type of the file.
*/
public String getMimeType() {
return streamInitiation.getMimeType();
}
/**
* Returns the fully-qualified jabber ID of the user that requested this
* file transfer.
*
* @return Returns the fully-qualified jabber ID of the user that requested
* this file transfer.
*/
public String getRequestor() {
return streamInitiation.getFrom();
}
/**
* Returns the stream ID that uniquely identifies this file transfer.
*
* @return Returns the stream ID that uniquely identifies this file
* transfer.
*/
public String getStreamID() {
return streamInitiation.getSessionID();
}
/**
* Returns the stream initiation packet that was sent by the requestor which
* contains the parameters of the file transfer being transfer and also the
* methods available to transfer the file.
*
* @return Returns the stream initiation packet that was sent by the
* requestor which contains the parameters of the file transfer
* being transfer and also the methods available to transfer the
* file.
*/
protected StreamInitiation getStreamInitiation() {
return streamInitiation;
}
/**
* Accepts this file transfer and creates the incoming file transfer.
*
* @return Returns the <b><i>IncomingFileTransfer</b></i> on which the
* file transfer can be carried out.
*/
public IncomingFileTransfer accept() {
return manager.createIncomingFileTransfer(this);
}
/**
* Rejects the file transfer request.
*/
public void reject() {
manager.rejectIncomingFileTransfer(this);
}
}

View file

@ -0,0 +1,149 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import java.io.InputStream;
import java.io.OutputStream;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromContainsFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamManager;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamRequest;
import org.jivesoftware.smackx.bytestreams.ibb.InBandBytestreamSession;
import org.jivesoftware.smackx.bytestreams.ibb.packet.Open;
import org.jivesoftware.smackx.packet.StreamInitiation;
/**
* The In-Band Bytestream file transfer method, or IBB for short, transfers the
* file over the same XML Stream used by XMPP. It is the fall-back mechanism in
* case the SOCKS5 bytestream method of transferring files is not available.
*
* @author Alexander Wenckus
* @author Henning Staib
* @see <a href="http://xmpp.org/extensions/xep-0047.html">XEP-0047: In-Band
* Bytestreams (IBB)</a>
*/
public class IBBTransferNegotiator extends StreamNegotiator {
private Connection connection;
private InBandBytestreamManager manager;
/**
* The default constructor for the In-Band Bytestream Negotiator.
*
* @param connection The connection which this negotiator works on.
*/
protected IBBTransferNegotiator(Connection connection) {
this.connection = connection;
this.manager = InBandBytestreamManager.getByteStreamManager(connection);
}
public OutputStream createOutgoingStream(String streamID, String initiator,
String target) throws XMPPException {
InBandBytestreamSession session = this.manager.establishSession(target, streamID);
session.setCloseBothStreamsEnabled(true);
return session.getOutputStream();
}
public InputStream createIncomingStream(StreamInitiation initiation)
throws XMPPException {
/*
* In-Band Bytestream initiation listener must ignore next in-band
* bytestream request with given session ID
*/
this.manager.ignoreBytestreamRequestOnce(initiation.getSessionID());
Packet streamInitiation = initiateIncomingStream(this.connection, initiation);
return negotiateIncomingStream(streamInitiation);
}
public PacketFilter getInitiationPacketFilter(String from, String streamID) {
/*
* this method is always called prior to #negotiateIncomingStream() so
* the In-Band Bytestream initiation listener must ignore the next
* In-Band Bytestream request with the given session ID
*/
this.manager.ignoreBytestreamRequestOnce(streamID);
return new AndFilter(new FromContainsFilter(from), new IBBOpenSidFilter(streamID));
}
public String[] getNamespaces() {
return new String[] { InBandBytestreamManager.NAMESPACE };
}
InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException {
// build In-Band Bytestream request
InBandBytestreamRequest request = new ByteStreamRequest(this.manager,
(Open) streamInitiation);
// always accept the request
InBandBytestreamSession session = request.accept();
session.setCloseBothStreamsEnabled(true);
return session.getInputStream();
}
public void cleanup() {
}
/**
* This PacketFilter accepts an incoming In-Band Bytestream open request
* with a specified session ID.
*/
private static class IBBOpenSidFilter extends PacketTypeFilter {
private String sessionID;
public IBBOpenSidFilter(String sessionID) {
super(Open.class);
if (sessionID == null) {
throw new IllegalArgumentException("StreamID cannot be null");
}
this.sessionID = sessionID;
}
public boolean accept(Packet packet) {
if (super.accept(packet)) {
Open bytestream = (Open) packet;
// packet must by of type SET and contains the given session ID
return this.sessionID.equals(bytestream.getSessionID())
&& IQ.Type.SET.equals(bytestream.getType());
}
return false;
}
}
/**
* Derive from InBandBytestreamRequest to access protected constructor.
*/
private static class ByteStreamRequest extends InBandBytestreamRequest {
private ByteStreamRequest(InBandBytestreamManager manager, Open byteStreamRequest) {
super(manager, byteStreamRequest);
}
}
}

View file

@ -0,0 +1,212 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.XMPPException;
import java.io.*;
import java.util.concurrent.*;
/**
* An incoming file transfer is created when the
* {@link FileTransferManager#createIncomingFileTransfer(FileTransferRequest)}
* method is invoked. It is a file being sent to the local user from another
* user on the jabber network. There are two stages of the file transfer to be
* concerned with and they can be handled in different ways depending upon the
* method that is invoked on this class.
* <p/>
* The first way that a file is recieved is by calling the
* {@link #recieveFile()} method. This method, negotiates the appropriate stream
* method and then returns the <b><i>InputStream</b></i> to read the file
* data from.
* <p/>
* The second way that a file can be recieved through this class is by invoking
* the {@link #recieveFile(File)} method. This method returns immediatly and
* takes as its parameter a file on the local file system where the file
* recieved from the transfer will be put.
*
* @author Alexander Wenckus
*/
public class IncomingFileTransfer extends FileTransfer {
private FileTransferRequest recieveRequest;
private InputStream inputStream;
protected IncomingFileTransfer(FileTransferRequest request,
FileTransferNegotiator transferNegotiator) {
super(request.getRequestor(), request.getStreamID(), transferNegotiator);
this.recieveRequest = request;
}
/**
* Negotiates the stream method to transfer the file over and then returns
* the negotiated stream.
*
* @return The negotiated InputStream from which to read the data.
* @throws XMPPException If there is an error in the negotiation process an exception
* is thrown.
*/
public InputStream recieveFile() throws XMPPException {
if (inputStream != null) {
throw new IllegalStateException("Transfer already negotiated!");
}
try {
inputStream = negotiateStream();
}
catch (XMPPException e) {
setException(e);
throw e;
}
return inputStream;
}
/**
* This method negotitates the stream and then transfer's the file over the
* negotiated stream. The transfered file will be saved at the provided
* location.
* <p/>
* This method will return immedialtly, file transfer progress can be
* monitored through several methods:
* <p/>
* <UL>
* <LI>{@link FileTransfer#getStatus()}
* <LI>{@link FileTransfer#getProgress()}
* <LI>{@link FileTransfer#isDone()}
* </UL>
*
* @param file The location to save the file.
* @throws XMPPException when the file transfer fails
* @throws IllegalArgumentException This exception is thrown when the the provided file is
* either null, or cannot be written to.
*/
public void recieveFile(final File file) throws XMPPException {
if (file != null) {
if (!file.exists()) {
try {
file.createNewFile();
}
catch (IOException e) {
throw new XMPPException(
"Could not create file to write too", e);
}
}
if (!file.canWrite()) {
throw new IllegalArgumentException("Cannot write to provided file");
}
}
else {
throw new IllegalArgumentException("File cannot be null");
}
Thread transferThread = new Thread(new Runnable() {
public void run() {
try {
inputStream = negotiateStream();
}
catch (XMPPException e) {
handleXMPPException(e);
return;
}
OutputStream outputStream = null;
try {
outputStream = new FileOutputStream(file);
setStatus(Status.in_progress);
writeToStream(inputStream, outputStream);
}
catch (XMPPException e) {
setStatus(Status.error);
setError(Error.stream);
setException(e);
}
catch (FileNotFoundException e) {
setStatus(Status.error);
setError(Error.bad_file);
setException(e);
}
if (getStatus().equals(Status.in_progress)) {
setStatus(Status.complete);
}
if (inputStream != null) {
try {
inputStream.close();
}
catch (Throwable io) {
/* Ignore */
}
}
if (outputStream != null) {
try {
outputStream.close();
}
catch (Throwable io) {
/* Ignore */
}
}
}
}, "File Transfer " + streamID);
transferThread.start();
}
private void handleXMPPException(XMPPException e) {
setStatus(FileTransfer.Status.error);
setException(e);
}
private InputStream negotiateStream() throws XMPPException {
setStatus(Status.negotiating_transfer);
final StreamNegotiator streamNegotiator = negotiator
.selectStreamNegotiator(recieveRequest);
setStatus(Status.negotiating_stream);
FutureTask<InputStream> streamNegotiatorTask = new FutureTask<InputStream>(
new Callable<InputStream>() {
public InputStream call() throws Exception {
return streamNegotiator
.createIncomingStream(recieveRequest.getStreamInitiation());
}
});
streamNegotiatorTask.run();
InputStream inputStream;
try {
inputStream = streamNegotiatorTask.get(15, TimeUnit.SECONDS);
}
catch (InterruptedException e) {
throw new XMPPException("Interruption while executing", e);
}
catch (ExecutionException e) {
throw new XMPPException("Error in execution", e);
}
catch (TimeoutException e) {
throw new XMPPException("Request timed out", e);
}
finally {
streamNegotiatorTask.cancel(true);
}
setStatus(Status.negotiated);
return inputStream;
}
public void cancel() {
setStatus(Status.cancelled);
}
}

View file

@ -0,0 +1,446 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.XMPPError;
import java.io.*;
/**
* Handles the sending of a file to another user. File transfer's in jabber have
* several steps and there are several methods in this class that handle these
* steps differently.
*
* @author Alexander Wenckus
*
*/
public class OutgoingFileTransfer extends FileTransfer {
private static int RESPONSE_TIMEOUT = 60 * 1000;
private NegotiationProgress callback;
/**
* Returns the time in milliseconds after which the file transfer
* negotiation process will timeout if the other user has not responded.
*
* @return Returns the time in milliseconds after which the file transfer
* negotiation process will timeout if the remote user has not
* responded.
*/
public static int getResponseTimeout() {
return RESPONSE_TIMEOUT;
}
/**
* Sets the time in milliseconds after which the file transfer negotiation
* process will timeout if the other user has not responded.
*
* @param responseTimeout
* The timeout time in milliseconds.
*/
public static void setResponseTimeout(int responseTimeout) {
RESPONSE_TIMEOUT = responseTimeout;
}
private OutputStream outputStream;
private String initiator;
private Thread transferThread;
protected OutgoingFileTransfer(String initiator, String target,
String streamID, FileTransferNegotiator transferNegotiator) {
super(target, streamID, transferNegotiator);
this.initiator = initiator;
}
protected void setOutputStream(OutputStream stream) {
if (outputStream == null) {
this.outputStream = stream;
}
}
/**
* Returns the output stream connected to the peer to transfer the file. It
* is only available after it has been successfully negotiated by the
* {@link StreamNegotiator}.
*
* @return Returns the output stream connected to the peer to transfer the
* file.
*/
protected OutputStream getOutputStream() {
if (getStatus().equals(FileTransfer.Status.negotiated)) {
return outputStream;
} else {
return null;
}
}
/**
* This method handles the negotiation of the file transfer and the stream,
* it only returns the created stream after the negotiation has been completed.
*
* @param fileName
* The name of the file that will be transmitted. It is
* preferable for this name to have an extension as it will be
* used to determine the type of file it is.
* @param fileSize
* The size in bytes of the file that will be transmitted.
* @param description
* A description of the file that will be transmitted.
* @return The OutputStream that is connected to the peer to transmit the
* file.
* @throws XMPPException
* Thrown if an error occurs during the file transfer
* negotiation process.
*/
public synchronized OutputStream sendFile(String fileName, long fileSize,
String description) throws XMPPException {
if (isDone() || outputStream != null) {
throw new IllegalStateException(
"The negotation process has already"
+ " been attempted on this file transfer");
}
try {
setFileInfo(fileName, fileSize);
this.outputStream = negotiateStream(fileName, fileSize, description);
} catch (XMPPException e) {
handleXMPPException(e);
throw e;
}
return outputStream;
}
/**
* This methods handles the transfer and stream negotiation process. It
* returns immediately and its progress will be updated through the
* {@link NegotiationProgress} callback.
*
* @param fileName
* The name of the file that will be transmitted. It is
* preferable for this name to have an extension as it will be
* used to determine the type of file it is.
* @param fileSize
* The size in bytes of the file that will be transmitted.
* @param description
* A description of the file that will be transmitted.
* @param progress
* A callback to monitor the progress of the file transfer
* negotiation process and to retrieve the OutputStream when it
* is complete.
*/
public synchronized void sendFile(final String fileName,
final long fileSize, final String description,
final NegotiationProgress progress)
{
if(progress == null) {
throw new IllegalArgumentException("Callback progress cannot be null.");
}
checkTransferThread();
if (isDone() || outputStream != null) {
throw new IllegalStateException(
"The negotation process has already"
+ " been attempted for this file transfer");
}
setFileInfo(fileName, fileSize);
this.callback = progress;
transferThread = new Thread(new Runnable() {
public void run() {
try {
OutgoingFileTransfer.this.outputStream = negotiateStream(
fileName, fileSize, description);
progress.outputStreamEstablished(OutgoingFileTransfer.this.outputStream);
}
catch (XMPPException e) {
handleXMPPException(e);
}
}
}, "File Transfer Negotiation " + streamID);
transferThread.start();
}
private void checkTransferThread() {
if (transferThread != null && transferThread.isAlive() || isDone()) {
throw new IllegalStateException(
"File transfer in progress or has already completed.");
}
}
/**
* This method handles the stream negotiation process and transmits the file
* to the remote user. It returns immediately and the progress of the file
* transfer can be monitored through several methods:
*
* <UL>
* <LI>{@link FileTransfer#getStatus()}
* <LI>{@link FileTransfer#getProgress()}
* <LI>{@link FileTransfer#isDone()}
* </UL>
*
* @param file the file to transfer to the remote entity.
* @param description a description for the file to transfer.
* @throws XMPPException
* If there is an error during the negotiation process or the
* sending of the file.
*/
public synchronized void sendFile(final File file, final String description)
throws XMPPException {
checkTransferThread();
if (file == null || !file.exists() || !file.canRead()) {
throw new IllegalArgumentException("Could not read file");
} else {
setFileInfo(file.getAbsolutePath(), file.getName(), file.length());
}
transferThread = new Thread(new Runnable() {
public void run() {
try {
outputStream = negotiateStream(file.getName(), file
.length(), description);
} catch (XMPPException e) {
handleXMPPException(e);
return;
}
if (outputStream == null) {
return;
}
if (!updateStatus(Status.negotiated, Status.in_progress)) {
return;
}
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
writeToStream(inputStream, outputStream);
} catch (FileNotFoundException e) {
setStatus(FileTransfer.Status.error);
setError(Error.bad_file);
setException(e);
} catch (XMPPException e) {
setStatus(FileTransfer.Status.error);
setException(e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
outputStream.flush();
outputStream.close();
} catch (IOException e) {
/* Do Nothing */
}
}
updateStatus(Status.in_progress, FileTransfer.Status.complete);
}
}, "File Transfer " + streamID);
transferThread.start();
}
/**
* This method handles the stream negotiation process and transmits the file
* to the remote user. It returns immediately and the progress of the file
* transfer can be monitored through several methods:
*
* <UL>
* <LI>{@link FileTransfer#getStatus()}
* <LI>{@link FileTransfer#getProgress()}
* <LI>{@link FileTransfer#isDone()}
* </UL>
*
* @param in the stream to transfer to the remote entity.
* @param fileName the name of the file that is transferred
* @param fileSize the size of the file that is transferred
* @param description a description for the file to transfer.
*/
public synchronized void sendStream(final InputStream in, final String fileName, final long fileSize, final String description){
checkTransferThread();
setFileInfo(fileName, fileSize);
transferThread = new Thread(new Runnable() {
public void run() {
//Create packet filter
try {
outputStream = negotiateStream(fileName, fileSize, description);
} catch (XMPPException e) {
handleXMPPException(e);
return;
}
if (outputStream == null) {
return;
}
if (!updateStatus(Status.negotiated, Status.in_progress)) {
return;
}
try {
writeToStream(in, outputStream);
} catch (XMPPException e) {
setStatus(FileTransfer.Status.error);
setException(e);
} finally {
try {
if (in != null) {
in.close();
}
outputStream.flush();
outputStream.close();
} catch (IOException e) {
/* Do Nothing */
}
}
updateStatus(Status.in_progress, FileTransfer.Status.complete);
}
}, "File Transfer " + streamID);
transferThread.start();
}
private void handleXMPPException(XMPPException e) {
XMPPError error = e.getXMPPError();
if (error != null) {
int code = error.getCode();
if (code == 403) {
setStatus(Status.refused);
return;
}
else if (code == 400) {
setStatus(Status.error);
setError(Error.not_acceptable);
}
else {
setStatus(FileTransfer.Status.error);
}
}
setException(e);
}
/**
* Returns the amount of bytes that have been sent for the file transfer. Or
* -1 if the file transfer has not started.
* <p>
* Note: This method is only useful when the {@link #sendFile(File, String)}
* method is called, as it is the only method that actually transmits the
* file.
*
* @return Returns the amount of bytes that have been sent for the file
* transfer. Or -1 if the file transfer has not started.
*/
public long getBytesSent() {
return amountWritten;
}
private OutputStream negotiateStream(String fileName, long fileSize,
String description) throws XMPPException {
// Negotiate the file transfer profile
if (!updateStatus(Status.initial, Status.negotiating_transfer)) {
throw new XMPPException("Illegal state change");
}
StreamNegotiator streamNegotiator = negotiator.negotiateOutgoingTransfer(
getPeer(), streamID, fileName, fileSize, description,
RESPONSE_TIMEOUT);
if (streamNegotiator == null) {
setStatus(Status.error);
setError(Error.no_response);
return null;
}
// Negotiate the stream
if (!updateStatus(Status.negotiating_transfer, Status.negotiating_stream)) {
throw new XMPPException("Illegal state change");
}
outputStream = streamNegotiator.createOutgoingStream(streamID,
initiator, getPeer());
if (!updateStatus(Status.negotiating_stream, Status.negotiated)) {
throw new XMPPException("Illegal state change");
}
return outputStream;
}
public void cancel() {
setStatus(Status.cancelled);
}
@Override
protected boolean updateStatus(Status oldStatus, Status newStatus) {
boolean isUpdated = super.updateStatus(oldStatus, newStatus);
if(callback != null && isUpdated) {
callback.statusUpdated(oldStatus, newStatus);
}
return isUpdated;
}
@Override
protected void setStatus(Status status) {
Status oldStatus = getStatus();
super.setStatus(status);
if(callback != null) {
callback.statusUpdated(oldStatus, status);
}
}
@Override
protected void setException(Exception exception) {
super.setException(exception);
if(callback != null) {
callback.errorEstablishingStream(exception);
}
}
/**
* A callback class to retrieve the status of an outgoing transfer
* negotiation process.
*
* @author Alexander Wenckus
*
*/
public interface NegotiationProgress {
/**
* Called when the status changes
*
* @param oldStatus the previous status of the file transfer.
* @param newStatus the new status of the file transfer.
*/
void statusUpdated(Status oldStatus, Status newStatus);
/**
* Once the negotiation process is completed the output stream can be
* retrieved.
*
* @param stream the established stream which can be used to transfer the file to the remote
* entity
*/
void outputStreamEstablished(OutputStream stream);
/**
* Called when an exception occurs during the negotiation progress.
*
* @param e the exception that occurred.
*/
void errorEstablishingStream(Exception e);
}
}

View file

@ -0,0 +1,164 @@
/**
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.FromMatchesFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamManager;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamRequest;
import org.jivesoftware.smackx.bytestreams.socks5.Socks5BytestreamSession;
import org.jivesoftware.smackx.bytestreams.socks5.packet.Bytestream;
import org.jivesoftware.smackx.packet.StreamInitiation;
/**
* Negotiates a SOCKS5 Bytestream to be used for file transfers. The implementation is based on the
* {@link Socks5BytestreamManager} and the {@link Socks5BytestreamRequest}.
*
* @author Henning Staib
* @see <a href="http://xmpp.org/extensions/xep-0065.html">XEP-0065: SOCKS5 Bytestreams</a>
*/
public class Socks5TransferNegotiator extends StreamNegotiator {
private Connection connection;
private Socks5BytestreamManager manager;
Socks5TransferNegotiator(Connection connection) {
this.connection = connection;
this.manager = Socks5BytestreamManager.getBytestreamManager(this.connection);
}
@Override
public OutputStream createOutgoingStream(String streamID, String initiator, String target)
throws XMPPException {
try {
return this.manager.establishSession(target, streamID).getOutputStream();
}
catch (IOException e) {
throw new XMPPException("error establishing SOCKS5 Bytestream", e);
}
catch (InterruptedException e) {
throw new XMPPException("error establishing SOCKS5 Bytestream", e);
}
}
@Override
public InputStream createIncomingStream(StreamInitiation initiation) throws XMPPException,
InterruptedException {
/*
* SOCKS5 initiation listener must ignore next SOCKS5 Bytestream request with given session
* ID
*/
this.manager.ignoreBytestreamRequestOnce(initiation.getSessionID());
Packet streamInitiation = initiateIncomingStream(this.connection, initiation);
return negotiateIncomingStream(streamInitiation);
}
@Override
public PacketFilter getInitiationPacketFilter(final String from, String streamID) {
/*
* this method is always called prior to #negotiateIncomingStream() so the SOCKS5
* InitiationListener must ignore the next SOCKS5 Bytestream request with the given session
* ID
*/
this.manager.ignoreBytestreamRequestOnce(streamID);
return new AndFilter(new FromMatchesFilter(from), new BytestreamSIDFilter(streamID));
}
@Override
public String[] getNamespaces() {
return new String[] { Socks5BytestreamManager.NAMESPACE };
}
@Override
InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException,
InterruptedException {
// build SOCKS5 Bytestream request
Socks5BytestreamRequest request = new ByteStreamRequest(this.manager,
(Bytestream) streamInitiation);
// always accept the request
Socks5BytestreamSession session = request.accept();
// test input stream
try {
PushbackInputStream stream = new PushbackInputStream(session.getInputStream());
int firstByte = stream.read();
stream.unread(firstByte);
return stream;
}
catch (IOException e) {
throw new XMPPException("Error establishing input stream", e);
}
}
@Override
public void cleanup() {
/* do nothing */
}
/**
* This PacketFilter accepts an incoming SOCKS5 Bytestream request with a specified session ID.
*/
private static class BytestreamSIDFilter extends PacketTypeFilter {
private String sessionID;
public BytestreamSIDFilter(String sessionID) {
super(Bytestream.class);
if (sessionID == null) {
throw new IllegalArgumentException("StreamID cannot be null");
}
this.sessionID = sessionID;
}
@Override
public boolean accept(Packet packet) {
if (super.accept(packet)) {
Bytestream bytestream = (Bytestream) packet;
// packet must by of type SET and contains the given session ID
return this.sessionID.equals(bytestream.getSessionID())
&& IQ.Type.SET.equals(bytestream.getType());
}
return false;
}
}
/**
* Derive from Socks5BytestreamRequest to access protected constructor.
*/
private static class ByteStreamRequest extends Socks5BytestreamRequest {
private ByteStreamRequest(Socks5BytestreamManager manager, Bytestream byteStreamRequest) {
super(manager, byteStreamRequest);
}
}
}

View file

@ -0,0 +1,164 @@
/**
*
* Copyright 2003-2006 Jive Software.
*
* All rights reserved. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx.filetransfer;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.Connection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.XMPPError;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.FormField;
import org.jivesoftware.smackx.packet.DataForm;
import org.jivesoftware.smackx.packet.StreamInitiation;
import java.io.InputStream;
import java.io.OutputStream;
/**
* After the file transfer negotiation process is completed according to
* JEP-0096, the negotiation process is passed off to a particular stream
* negotiator. The stream negotiator will then negotiate the chosen stream and
* return the stream to transfer the file.
*
* @author Alexander Wenckus
*/
public abstract class StreamNegotiator {
/**
* Creates the initiation acceptance packet to forward to the stream
* initiator.
*
* @param streamInitiationOffer The offer from the stream initiator to connect for a stream.
* @param namespaces The namespace that relates to the accepted means of transfer.
* @return The response to be forwarded to the initiator.
*/
public StreamInitiation createInitiationAccept(
StreamInitiation streamInitiationOffer, String[] namespaces)
{
StreamInitiation response = new StreamInitiation();
response.setTo(streamInitiationOffer.getFrom());
response.setFrom(streamInitiationOffer.getTo());
response.setType(IQ.Type.RESULT);
response.setPacketID(streamInitiationOffer.getPacketID());
DataForm form = new DataForm(Form.TYPE_SUBMIT);
FormField field = new FormField(
FileTransferNegotiator.STREAM_DATA_FIELD_NAME);
for (String namespace : namespaces) {
field.addValue(namespace);
}
form.addField(field);
response.setFeatureNegotiationForm(form);
return response;
}
public IQ createError(String from, String to, String packetID, XMPPError xmppError) {
IQ iq = FileTransferNegotiator.createIQ(packetID, to, from, IQ.Type.ERROR);
iq.setError(xmppError);
return iq;
}
Packet initiateIncomingStream(Connection connection, StreamInitiation initiation) throws XMPPException {
StreamInitiation response = createInitiationAccept(initiation,
getNamespaces());
// establish collector to await response
PacketCollector collector = connection
.createPacketCollector(getInitiationPacketFilter(initiation.getFrom(), initiation.getSessionID()));
connection.sendPacket(response);
Packet streamMethodInitiation = collector
.nextResult(SmackConfiguration.getPacketReplyTimeout());
collector.cancel();
if (streamMethodInitiation == null) {
throw new XMPPException("No response from file transfer initiator");
}
return streamMethodInitiation;
}
/**
* Returns the packet filter that will return the initiation packet for the appropriate stream
* initiation.
*
* @param from The initiator of the file transfer.
* @param streamID The stream ID related to the transfer.
* @return The <b><i>PacketFilter</b></i> that will return the packet relatable to the stream
* initiation.
*/
public abstract PacketFilter getInitiationPacketFilter(String from, String streamID);
abstract InputStream negotiateIncomingStream(Packet streamInitiation) throws XMPPException,
InterruptedException;
/**
* This method handles the file stream download negotiation process. The
* appropriate stream negotiator's initiate incoming stream is called after
* an appropriate file transfer method is selected. The manager will respond
* to the initiator with the selected means of transfer, then it will handle
* any negotiation specific to the particular transfer method. This method
* returns the InputStream, ready to transfer the file.
*
* @param initiation The initiation that triggered this download.
* @return After the negotiation process is complete, the InputStream to
* write a file to is returned.
* @throws XMPPException If an error occurs during this process an XMPPException is
* thrown.
* @throws InterruptedException If thread is interrupted.
*/
public abstract InputStream createIncomingStream(StreamInitiation initiation)
throws XMPPException, InterruptedException;
/**
* This method handles the file upload stream negotiation process. The
* particular stream negotiator is determined during the file transfer
* negotiation process. This method returns the OutputStream to transmit the
* file to the remote user.
*
* @param streamID The streamID that uniquely identifies the file transfer.
* @param initiator The fully-qualified JID of the initiator of the file transfer.
* @param target The fully-qualified JID of the target or receiver of the file
* transfer.
* @return The negotiated stream ready for data.
* @throws XMPPException If an error occurs during the negotiation process an
* exception will be thrown.
*/
public abstract OutputStream createOutgoingStream(String streamID,
String initiator, String target) throws XMPPException;
/**
* Returns the XMPP namespace reserved for this particular type of file
* transfer.
*
* @return Returns the XMPP namespace reserved for this particular type of
* file transfer.
*/
public abstract String[] getNamespaces();
/**
* Cleanup any and all resources associated with this negotiator.
*/
public abstract void cleanup();
}