Java Code Examples for org.jivesoftware.smack.SmackException#SmackMessageException

The following examples show how to use org.jivesoftware.smack.SmackException#SmackMessageException . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IoTDiscoveryIntegrationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
public static ThingState registerThing(IoTDiscoveryManager iotDiscoveryManager, Thing thing)
                throws XMPPErrorException, InterruptedException, SmackException.SmackMessageException,
                NotConnectedException, NoResponseException {
    int attempts = 0;
    while (true) {
        try {
            return iotDiscoveryManager.registerThing(thing);
        }
        catch (IoTClaimedException e) {
            iotDiscoveryManager.unregister();
        }
        if (attempts++ > 3) {
            throw new SmackException.SmackMessageException("Could no register thing");
        }
    }
}
 
Example 2
Source File: Socks5ClientForInitiator.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public Socket getSocket(int timeout) throws IOException, InterruptedException,
                TimeoutException, XMPPException, SmackMessageException, NotConnectedException, NoResponseException {
    Socket socket;

    // check if stream host is the local SOCKS5 proxy
    if (this.streamHost.getJID().equals(this.connection.get().getUser())) {
        socket = Socks5Proxy.getSocketForDigest(this.digest);
        if (socket == null) {
            throw new SmackException.SmackMessageException("target is not connected to SOCKS5 proxy");
        }
    }
    else {
        socket = super.getSocket(timeout);

        try {
            activate();
        }
        catch (XMPPException e1) {
            socket.close();
            throw e1;
        }
        catch (NoResponseException e2) {
            socket.close();
            throw e2;
        }

    }

    return socket;
}
 
Example 3
Source File: BridgedResolver.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize() throws SmackException.SmackMessageException, XMPPErrorException, InterruptedException,
                NoResponseException, NotConnectedException {

    clearCandidates();

    if (!RTPBridge.serviceAvailable(connection)) {
        setInitialized();
        throw new SmackException.SmackMessageException("No RTP Bridge service available");
    }
    setInitialized();

}
 
Example 4
Source File: HttpFileUploadManager.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Request a new upload slot with optional content type from custom upload service.
 *
 * When you get slot you should upload file to PUT URL and share GET URL.
 * Note that this is a synchronous call -- Smack must wait for the server response.
 *
 * @param filename name of file to be uploaded
 * @param fileSize file size in bytes.
 * @param contentType file content-type or null
 * @param uploadServiceAddress the address of the upload service to use or null for default one
 * @return file upload Slot in case of success
 * @throws IllegalArgumentException if fileSize is less than or equal to zero or greater than the maximum size
 *         supported by the service.
 * @throws SmackException if Smack detected an exceptional situation.
 * @throws InterruptedException if the calling thread was interrupted.
 * @throws XMPPException.XMPPErrorException if there was an XMPP error returned.
 */
public Slot requestSlot(String filename, long fileSize, String contentType, DomainBareJid uploadServiceAddress)
        throws SmackException, InterruptedException, XMPPException.XMPPErrorException {
    final XMPPConnection connection = connection();
    final UploadService defaultUploadService = this.defaultUploadService;

    // The upload service we are going to use.
    UploadService uploadService;

    if (uploadServiceAddress == null) {
        uploadService = defaultUploadService;
    } else {
        if (defaultUploadService != null && defaultUploadService.getAddress().equals(uploadServiceAddress)) {
            // Avoid performing a service discovery if we already know about the given service.
            uploadService = defaultUploadService;
        } else {
            DiscoverInfo discoverInfo = ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(uploadServiceAddress);
            if (!containsHttpFileUploadNamespace(discoverInfo)) {
                throw new IllegalArgumentException("There is no HTTP upload service running at the given address '"
                                + uploadServiceAddress + '\'');
            }
            uploadService = uploadServiceFrom(discoverInfo);
        }
    }

    if (uploadService == null) {
        throw new SmackException.SmackMessageException("No upload service specified and also none discovered.");
    }

    if (!uploadService.acceptsFileOfSize(fileSize)) {
        throw new IllegalArgumentException(
                        "Requested file size " + fileSize + " is greater than max allowed size " + uploadService.getMaxFileSize());
    }

    SlotRequest slotRequest;
    switch (uploadService.getVersion()) {
    case v0_3:
        slotRequest = new SlotRequest(uploadService.getAddress(), filename, fileSize, contentType);
        break;
    case v0_2:
        slotRequest = new SlotRequest_V0_2(uploadService.getAddress(), filename, fileSize, contentType);
        break;
    default:
        throw new AssertionError();
    }

    return connection.createStanzaCollectorAndSend(slotRequest).nextResultOrThrow();
}
 
Example 5
Source File: XMPPBOSHConnection.java    From Smack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
protected void connectInternal() throws SmackException, InterruptedException {
    done = false;
    notified = false;
    try {
        // Ensure a clean starting state
        if (client != null) {
            client.close();
            client = null;
        }
        sessionID = null;

        // Initialize BOSH client
        BOSHClientConfig.Builder cfgBuilder = BOSHClientConfig.Builder
                .create(config.getURI(), config.getXMPPServiceDomain().toString());
        if (config.isProxyEnabled()) {
            cfgBuilder.setProxy(config.getProxyAddress(), config.getProxyPort());
        }

        cfgBuilder.setCompressionEnabled(config.isCompressionEnabled());

        for (Map.Entry<String, String> h : config.getHttpHeaders().entrySet()) {
            cfgBuilder.addHttpHeader(h.getKey(), h.getValue());
        }

        client = BOSHClient.create(cfgBuilder.build());

        client.addBOSHClientConnListener(new BOSHConnectionListener());
        client.addBOSHClientResponseListener(new BOSHPacketReader());

        // Initialize the debugger
        if (debugger != null) {
            initDebugger();
        }

        // Send the session creation request
        client.send(ComposableBody.builder()
                .setNamespaceDefinition("xmpp", XMPP_BOSH_NS)
                .setAttribute(BodyQName.createWithPrefix(XMPP_BOSH_NS, "version", "xmpp"), "1.0")
                .build());
    } catch (Exception e) {
        throw new GenericConnectionException(e);
    }

    // Wait for the response from the server
    synchronized (this) {
        if (!connected) {
            final long deadline = System.currentTimeMillis() + getReplyTimeout();
            while (!notified) {
                final long now = System.currentTimeMillis();
                if (now >= deadline) break;
                wait(deadline - now);
            }
        }
    }

    // If there is no feedback, throw an remote server timeout error
    if (!connected && !done) {
        done = true;
        String errorMessage = "Timeout reached for the connection to "
                + getHost() + ":" + getPort() + ".";
        throw new SmackException.SmackMessageException(errorMessage);
    }
}
 
Example 6
Source File: Socks5Client.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Initializes the connection to the SOCKS5 proxy by negotiating authentication method and
 * requesting a stream for the given digest. Currently only the no-authentication method is
 * supported by the Socks5Client.
 *
 * @param socket connected to a SOCKS5 proxy
 * @throws IOException if an I/O error occurred.
 * @throws SmackMessageException if there was an error.
 */
protected void establish(Socket socket) throws IOException, SmackMessageException {

    byte[] connectionRequest;
    byte[] connectionResponse;
    /*
     * use DataInputStream/DataOutpuStream to assure read and write is completed in a single
     * statement
     */
    DataInputStream in = new DataInputStream(socket.getInputStream());
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());

    // authentication negotiation
    byte[] cmd = new byte[3];

    cmd[0] = (byte) 0x05; // protocol version 5
    cmd[1] = (byte) 0x01; // number of authentication methods supported
    cmd[2] = (byte) 0x00; // authentication method: no-authentication required

    out.write(cmd);
    out.flush();

    byte[] response = new byte[2];
    in.readFully(response);

    // check if server responded with correct version and no-authentication method
    if (response[0] != (byte) 0x05 || response[1] != (byte) 0x00) {
        throw new SmackException.SmackMessageException("Remote SOCKS5 server responded with unexpected version: " + response[0] + ' ' + response[1] + ". Should be 0x05 0x00.");
    }

    // request SOCKS5 connection with given address/digest
    connectionRequest = createSocks5ConnectRequest();
    out.write(connectionRequest);
    out.flush();

    // receive response
    connectionResponse = Socks5Utils.receiveSocks5Message(in);

    // verify response
    connectionRequest[1] = (byte) 0x00; // set expected return status to 0
    if (!Arrays.equals(connectionRequest, connectionResponse)) {
        throw new SmackException.SmackMessageException(
                        "Connection request does not equal connection response. Response: "
                                        + Arrays.toString(connectionResponse) + ". Request: "
                                        + Arrays.toString(connectionRequest));
    }
}
 
Example 7
Source File: Socks5Proxy.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Negotiates a SOCKS5 connection and stores it on success.
 *
 * @param socket connection to the client
 * @throws SmackException if client requests a connection in an unsupported way
 * @throws IOException if a network error occurred
 */
private void establishConnection(Socket socket) throws SmackException, IOException {
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    DataInputStream in = new DataInputStream(socket.getInputStream());

    // first byte is version should be 5
    int b = in.read();
    if (b != 5) {
        throw new SmackException.SmackMessageException("Only SOCKS5 supported: Peer send " + b + " but we expect 5");
    }

    // second byte number of authentication methods supported
    b = in.read();

    // read list of supported authentication methods
    byte[] auth = new byte[b];
    in.readFully(auth);

    byte[] authMethodSelectionResponse = new byte[2];
    authMethodSelectionResponse[0] = (byte) 0x05; // protocol version

    // only authentication method 0, no authentication, supported
    boolean noAuthMethodFound = false;
    for (int i = 0; i < auth.length; i++) {
        if (auth[i] == (byte) 0x00) {
            noAuthMethodFound = true;
            break;
        }
    }

    if (!noAuthMethodFound) {
        authMethodSelectionResponse[1] = (byte) 0xFF; // no acceptable methods
        out.write(authMethodSelectionResponse);
        out.flush();
        throw new SmackException.SmackMessageException("Authentication method not supported");
    }

    authMethodSelectionResponse[1] = (byte) 0x00; // no-authentication method
    out.write(authMethodSelectionResponse);
    out.flush();

    // receive connection request
    byte[] connectionRequest = Socks5Utils.receiveSocks5Message(in);

    // extract digest
    String responseDigest = new String(connectionRequest, 5, connectionRequest[4], StandardCharsets.UTF_8);

    // return error if digest is not allowed
    if (!allowAllConnections && !Socks5Proxy.this.allowedConnections.contains(responseDigest)) {
        connectionRequest[1] = (byte) 0x05; // set return status to 5 (connection refused)
        out.write(connectionRequest);
        out.flush();

        throw new SmackException.SmackMessageException(
                        "Connection with digest '" + responseDigest + "' is not allowed");
    }

    // Store the connection before we send the return status.
    Socks5Proxy.this.connectionMap.put(responseDigest, socket);

    connectionRequest[1] = (byte) 0x00; // set return status to 0 (success)
    out.write(connectionRequest);
    out.flush();
}