Migrate markdown documentation to javadoc

While markdown is easier to write, Smack's markdown documentation was
never tightly coupled with the source. For example, the markdown
documentation never provided links to the actual Java classes and
methods. This poses the risk that the documentation and the code
diverge over time. Furthermore, javadoc is constantly improving (for
example @snippet annotations) and I expect that one will be able to
write javadoc in markdown.

Fixes SMACK-928.
This commit is contained in:
Florian Schmaus 2023-02-03 09:36:54 +01:00
parent f65cf45b5c
commit c9a9982cef
101 changed files with 4441 additions and 5754 deletions

163
DEVELOPING.md Normal file
View File

@ -0,0 +1,163 @@
# Building Smack
## Linux
Building Smack is as simple as
```
git clone git@github.com:igniterealtime/Smack.git
cd Smack
gradle assemble
```
## Mac
Smack requires a case-sensitive file system in order to build. Unfortunately, the macOS operating system is case-insensitive by default.
To get around this, you can create a case-sensitive disk image to work from.
1. Launch Disk Utility (Applications > Utilities)
2. Click the +, or go to Edit > Add APFS Volume
3. Give it a name, e.g. "Smack"
4. Change the format to "APFS (Case-sensitive)"
5. Click Add
It'll auto-mount into /Volumes, e.g. /Volumes/Smack
```bash
cd /Volumes/Smack
git clone git@github.com:igniterealtime/Smack.git
cd Smack
gradle assemble
```
## Windows
Smack requires a case-sensitive file system in order to build. Unfortunately, Windows NTFS is case-insensitive by default.
To get around this, you can set specific folders as case-sensitive (requires Windows 10 v1803 or higher).
In an Administrator console:
```batch
fsutil.exe file SetCaseSensitiveInfo C:\git\Smack enable
cd \git\Smack
git clone git@github.com:igniterealtime/Smack.git
cd Smack
gradle assemble
```
# IDE Config
### Eclipse
Import IDE settings from `./resources/eclipse/` to configure proper ordering of imports and correct formatting that should pass the CheckStyle rules.
### IntelliJ IDEA
Import Java Code Style settings from `./resources/intellij/smack_formatter.xml` to configure import optimisation and code formatting to pass the CheckStyle rules when building or submitting PRs.
_We've noticed, at time of writing, that IntelliJ often requires a restart when applying new rules - no amount of OK/Apply will do the trick._
# Smack Providers
Providers are responsible for parsing the XMPP XML stream into new Java objects.
## Provider Design
Assume you want to parse the following stanza extension element
```xml
<myExtension attrFoo='fourthyTwo'>
<myElement>Foo is greater then Bar</myElement>
<myInfo alpha='true' delta='-1337'/>
</myExtension>
```
then the related provider would look like this
```java
public MyExtension parse(XmlPullParser parser, int initialDepth) {
MyElement myElement = null;
MyInfo myInfo = null;
String attrFoo = parser.getAttributeValue("", "attrFoo");
// Main parsing loop, use a loop label instead of "boolean done"
outerloop: while(true) {
// Make sure to have already parse all attributes of the outermost element,
// i.e. 'attrFoo' of 'myExtension' in this example. Then advance the parser
XmlPullParser.Event event = parser.next();
// Use switch/case of int instead of a if/else-if cascade
switch (event) {
case START_ELEMENT:
// Determine the name of the element which start tag we are seeing
String name = parser.getName();
// We can use switch/case of Strings since Java7, make use of its advantages
// and collect the values of the sub elements. If the sub elements are more
// complex then those of this example, consider creating extra *private static*
// parsing methods for them.
switch(name) {
case "myElement":
// You should only use XmlPullParser.nextText() when the element is
// required to have a text.
myElement = new MyElement(parser.nextText());
break;
case "myInfo";
// Use ParserUtils to parse Java primitives
boolenan alpha = ParserUtils.getBooleanAttribute(parser, "alpha");
int delta = ParserUtils.getIntegerAttribute(parser, "delta");
myInfo = new MyInfo(alpha, delta);
break;
}
break;
case END_ELEMENT:
// The abort condition with the break labeled loop statement
if (parser.getDepth() == initialDepth) {
break outerloop;
}
break;
default:
// Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
break;
}
}
// Create the actual class at the very end, design the classes as immutable as possible
return new MyExtension(attrFoo, myElement, myInfo);
}
```
## Common Pitfalls
Use a `long` instead of `int` when the XML schema says `xs:unsignedInt`, because Java's `int` range is to small for this XML numeric data type.
# Stanzas
## General Rules
All classes which subclass `TopLevelStreamElement` and `ExtensionElement` must either
1. be immutable (and ideally provide a Builder)
2. implement `TypedCloneable`
and must be `Serializable`.
The reason that it must be either 1. or 2. is that it makes no sense to clone an inmutable instance.
The preferred option is 1.
Note that there is legacy code in Smack which does not follow these rules. Patches are welcome.
## ExtensionElement
Extension elements are XML elements that are used in various parts and levels of stanzas.
## The static `from(Stanza)` Method
Every ExtensionElement class must have a static `from()` method that retrieves that extension for a given Stanza (if any).
Sample Code
```java
public static RSMSet from(Stanza) {
return packet.getExtension(ELEMENT, NAMESPACE);
}
```
Sometimes certain ExtensionElement's are only found in one stanza type, in that case, specify the parameter type. For example `public static CarbonExtension getFrom(Message)`.

View File

@ -1 +0,0 @@
index.md

View File

@ -1,35 +0,0 @@
Smack's Modular Connection Architecture
======================================
[Back](index.md)
**Note: Everything related to the modular connection architecture is currently considered experimental and should not be used in production. Use the mature `XMPPTCPConnection` if you do not feel adventurous.
Smack's modular connection architecture allows to extend a XMPP c2s (client-to-server) connection with additional functionality by adding modules.
Those modules extend the Finite State Machine (FSM) within the `ModularXmppClientToServerConnection` with new states.
Connection modules can either be
- Transports
- Extensions
Transports bind the XMPP XML stream to an underlying transport like TCP, WebSockets, BOSH, and allow for the different particularities of transports like DirectTLS ([XEP-0368](https://xmpp.org/extensions/xep-0368.html)).
This eventually means that a single transport module can implement multiple transport mechanisms.
For example the TCP transport module implements the RFC6120 TCP and the XEP-0368 direct TLS TCP transport bindings.
Extensions allow for a richer functionality of the connection. Those include
- Compression
- zlib ([XEP-0138](https://xmpp.org/extensions/xep-0138.html))
- [Efficient XML Interchange (EXI)](https://www.w3.org/TR/exi/)
- Instant Stream Resumption ([XEP-0397](https://xmpp.org/extensions/xep-0397.html)
- Bind2
- Stream Management
Note that not all extensions work with every transport.
For example compression only works with TCP-based transport bindings.
Connection modules are plugged into the the modular connection via their constructor. and they usually declare backwards edges to some common, generic connection state of the FSM.
Modules and states always have an accompanying *descriptor* type.
`ModuleDescriptor` and `StateDescriptor` exist without an connection instance.
They describe the module and state metadata, while their modules and states are instanciated once a modular connection is instanciated.

View File

@ -1,58 +0,0 @@
Smack: XMPPConnection Management
================================
[Back](index.md)
Creating a Connection
---------------------
The `org.jivesoftware.smack.XMPPConnection` interface manages your connection to
an XMPP server. The default implementation is the
`org.jivesoftware.smack.tcp.XMPPTCPConnection` class. The class contains three constructors. The simplest, `XMPPTCPConnection(CharSequence, String, String)` takes the username, password, and server name you'd like
to connect to as arguments. All default connection settings will be used:
* A DNS SRV lookup will be performed to find the exact address and port (typically 5222) that the server resides at.
* The maximum security possible will be negotiated with the server, including TLS encryption, but the connection will fall back to lower security settings if necessary.
* The XMPP resource name "Smack" will be used for the connection.
Alternatively, you can use the `XMPPTCPConnection(ConnectionConfiguration)`
constructor to specify advanced connection settings. Some of these settings
include:
* Manually specify the server address and port of the server rather than using a DNS SRV lookup.
* Enable connection compression.
* Customize security settings, such as flagging the connection to require TLS encryption in order to connect.
* Specify a custom connection resource name such as "Work" or "Home". Every connection by a user to a server must have a unique resource name. For the user "jsmith@example.com", the full address with resource might be "jsmith@example.com/Smack". With unique resource names, a user can be logged into the server from multiple locations at once, or using multiple devices. The presence priority value used with each resource will determine which particular connection receives messages to the bare address ("jsmith@example.com" in our example).
Connect and Disconnect
----------------------
```
// Create the configuration for this new connection
XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
configBuilder.setUsernameAndPassword("username", "password");
configBuilder.setResource("SomeResource");
configBuilder.setXmppDomain("jabber.org");
AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
// Connect to the server
connection.connect();
// Log into the server
connection.login();
...
// Disconnect from the server
connection.disconnect();
```
By default Smack will try to reconnect the connection in case it was abruptly
disconnected. The reconnection manager will try to immediately
reconnect to the server and increase the delay between attempts as successive
reconnections keep failing._
In case you want to force a reconnection while the reconnection manager is
waiting for the next reconnection, you can just use _AbstractXMPPConnection#connect()_
and a new attempt will be made. If the manual attempt also failed then the
reconnection manager will still continue the reconnection job.
Copyright (C) Jive Software 2002-2008

View File

@ -1,62 +0,0 @@
Debugging with Smack
====================
[Back](index.md)
Smack includes two built-in debugging consoles that will let you track
all XML traffic between the client and server. A lite debugger and an
enhanced debugger contained in `smack-debug.jar`, and a console debugger in `smack-core.jar`.
Debugging mode can be enabled in two different ways:
1. Add the following line of code **before** creating new connections:
`SmackConfiguration.DEBUG = true;`
2. Set the Java system property `smack.debugEnabled` to true. The system property can be set on the command line such as:
`java -Dsmack.debugEnabled=true SomeApp `
If you wish to explicitly disable debug mode in your application, including
using the command-line parameter, add the following line to your application
before opening new connections:
`SmackConfiguration.DEBUG = false;`
Smack uses the following logic to decide the debugger console to use:
1. It will first try use the debugger class specified in the Java system property `smack.debuggerClass`. If you need to develop your own debugger, implement the `SmackDebugger` interface and then set the system property on the command line such as:
`java -Dsmack.debuggerClass=my.company.com.MyDebugger SomeApp `
2. If step 1 fails then Smack will try to use the enhanced debugger. The file `smack-debug.jar` contains the enhanced debugger. Therefore you will need to place the jar file in the classpath. For situations where space is an issue you may want to only deploy `smack-core.jar` in which case the enhanced and lite debugger won't be available, but only the console debugger.
3. The last option if the previous two steps fail is to use the console debugger. The console debugger is a very good option for situations where you need to have low memory footprint.
Enhanced Debugger
-----------------
![Full Debug Window](images/enhanceddebugger.png) When debugging mode is
enabled, a debug window will appear containing tabs for each new created
connection. The window will contain the following information:
* XMPPConnection tabs -- each tab shows debugging information related to the connection.
* Smack info tab -- shows information about Smack (e.g. Smack version, installed components, etc.). The connection tab will contain the following information:
* All Stanzas -- shows sent and received packets information parsed by Smack.
* Raw Sent Stanzas -- raw XML traffic generated by Smack and sent to the server.
* Raw Received Stanzas -- raw XML traffic sent by the server to the client.
* Ad-hoc message -- allows to send ad-hoc packets of any type.
* Information -- shows connection state and statistics.
Lite Debugger
-------------
![Lite Debug Window](images/debugwindow.gif) When debugging mode is enabled, a
debug window will appear when each new connection is created. The window will
contain the following information:
* Client Traffic (red text) -- raw XML traffic generated by Smack and sent to the server.
* Server Traffic (blue text) -- raw XML traffic sent by the server to the client.
* Interpreted Stanzas (green text) -- shows XML packets from the server as parsed by Smack. Right click on any of the panes to bring up a menu with the choices to copy of the contents to the system clipboard or to clear the contents of the pane.
Copyright (C) Jive Software 2002-2008

View File

@ -1,63 +0,0 @@
Building Smack
==============
Linux
-----
Building Smack is as simple as
```
git clone git@github.com:igniterealtime/Smack.git
cd Smack
gradle assemble
```
Mac
---
Smack requires a case-sensitive file system in order to build. Unfortunately, the macOS operating system is case-insensitive by default.
To get around this, you can create a case-sensitive disk image to work from.
1. Launch Disk Utility (Applications > Utilities)
2. Click the +, or go to Edit > Add APFS Volume
3. Give it a name, e.g. "Smack"
4. Change the format to "APFS (Case-sensitive)"
5. Click Add
It'll auto-mount into /Volumes, e.g. /Volumes/Smack
```bash
cd /Volumes/Smack
git clone git@github.com:igniterealtime/Smack.git
cd Smack
gradle assemble
```
Windows
-------
Smack requires a case-sensitive file system in order to build. Unfortunately, Windows NTFS is case-insensitive by default.
To get around this, you can set specific folders as case-sensitive (requires Windows 10 v1803 or higher).
In an Administrator console:
```batch
fsutil.exe file SetCaseSensitiveInfo C:\git\Smack enable
cd \git\Smack
git clone git@github.com:igniterealtime/Smack.git
cd Smack
gradle assemble
```
IDE Config
----------
### Eclipse
Import IDE settings from `./resources/eclipse/` to configure proper ordering of imports and correct formatting that should pass the CheckStyle rules.
### IntelliJ IDEA
Import Java Code Style settings from `./resources/intellij/smack_formatter.xml` to configure import optimisation and code formatting to pass the CheckStyle rules when building or submitting PRs.
_We've noticed, at time of writing, that IntelliJ often requires a restart when applying new rules - no amount of OK/Apply will do the trick._

View File

@ -1,209 +0,0 @@
Smack's Integration Test Framework
==================================
Introduction
------------
Smack's Integration Test Framework is used to run a set of tests against a real XMPP service.
The framework discovers on start-up the available tests by reflection.
Quickstart
----------
You can run the framework against an XMPP service with
```bash
$ gradle integrationTest -Dsinttest.service=my.xmppservice.org
```
Note that the service needs to have In-Band Registration (IBR) enabled.
A better alternative to IBR is using XEP-0133: Service Administration
to create the throw away accounts used by the integration test
framework. Simply use
```bash
$ gradle integrationTest -Dsinttest.service=my.xmppservice.org \
-Dsinttest.adminAccountUsername=admin \
-Dsinttest.adminAccountPassword=aeR0Wuub
```
to run Smack's integration test framework against `my.xmppservice.org`
with an admin account named `admin` and `aeR0Wuub` as password.
Configuration
-------------
The framework is configured with a standard Java properties file.
This file simply contains key/value pairs, which are separated by an equals sign ("=").
The most important configuration value is the `service` value, it's also the only required setting.
The file properties can be overridden with Java system properties.
The name of a system property that is used by the framework needs to be prefixed with `sinttest.` (*S*mack *Int*egration *Test* Framework).
For example the `service` property becomes `sinttest.service`.
### Minimal example **properties** file
```bash
service=example.org
```
### Another example **properties** file
```bash
service=example.org
serviceTlsPin=CERTSHA256:2F:92:C9:4D:30:58:E1:05:21:9A:57:59:5F:6E:25:9A:0F:BF:FF:64:1A:C3:4B:EC:06:7D:4A:6F:0A:D5:21:85
debugger=console
```
### Framework properties
| Name | Description |
|----------------------|-----------------------------------------------------------------------------|
| service | XMPP service to run the tests on |
| serviceTlsPin | TLS Pin (used by [java-pinning](https://github.com/Flowdalic/java-pinning)) |
| securityMode | Either 'required' or 'disabled' |
| replyTimeout | In milliseconds |
| adminAccountUsername | Username of the XEP-0133 Admin account |
| adminAccountPassword | Password of the XEP-0133 Admin account |
| accountOneUsername | Username of the first XMPP account |
| accountOnePassword | Password of the first XMPP account |
| accountTwoUsername | Username of the second XMPP account |
| accountTwoPassword | Password of the second XMPP account |
| accountThreeUsername | Username of the third XMPP account |
| accountThreePassword | Password of the third XMPP account |
| debugger | 'console' for console debugger, 'enhanced' for the enhanced debugger |
| enabledTests | List of enabled tests |
| disabledTests | List of disabled tests |
| defaultConnection | Nickname of the default connection |
| enabledConnections | List of enabled connection's nicknames |
| disabledConnections | List of disabled connection's nicknames |
| testPackages | List of packages with tests |
| verbose | If `true` set output to verbose |
| dnsResolver | One of 'minidns', 'javax' or 'dnsjava'. Defaults to 'minidns'. |
### Where to place the properties file
The framework will first load the properties file from `~/.config/smack-integration-test/properties`
### Running selected tests only
Using `enabledTests` is is possible to run only selected tests. The
tests can be selected on a per class base or by specifying concrete
test methods. In the latter case, the methods must be qualified by a
(simple) class name.
For example:
```bash
$ gradle integrationTest -Dsinttest.enabledTests=SoftwareInfoIntegrationTest.test
```
will only run the `test()` method of `SoftwareInfoIntegrationTest`, whereas
```bash
$ gradle integrationTest -Dsinttest.enabledTests=SoftwareInfoIntegrationTest
```
would run all tests defined in the `SoftwareInfoIntegrationTest` class.
Overview of the components
--------------------------
Package `org.igniterealtime.smack.inttest`
### `SmackIntegrationTestFramework`
Contains `public static void main` method, i.e. the entry point for the framework.
Here the available integration tests are discovered by means of reflection, the configuration is read and a `IntegrationTestEnvironment` instance created, which includes the XMPPConnections.
### `AbstractSmackIntegrationTest`
The base class that integration tests need to subclass.
### `AbstractSmackLowLevelIntegrationTest`
Allows low level integration test, i.e. every test method will have its own exclusive XMPPTCPConnection instances.
### `AbstractSmackSpecificLowLevelIntegrationTest`
Operates, like `AbstractSmackLowLevelIntegrationTest` on its own `XMPPConnection` instances, but is limited to a particular type of `XMPPConnection`.
### `IntegrationTestEnvironment`
The environment, e.g. the `XMPPConnections` provided to the integration tests by the framework. Note that for convenience `AbstractSmackIntegrationTest` contains some of those as protected members.
### `SmackIntegrationTest`
An annotation that needs to be added to all methods that represent a single integration test.
Annotated integration test methods must not take any arguments (i.e. their parameter count is 0), and should return void as it's not evaluated in any way.
The methods are supposed to throw an exception if their integration test fails.
### `TestNotPossibleException`
Can be thrown by test methods or constructors to signal that their test is not possible, e.g. because the service does not support the required feature.
Running the integration tests
-----------------------------
Smack's Gradle build system is configured with a special task called `integrationTest`, which means you can run the tests simply with
```bash
$ gradle integrationTest -Dsinttest.service=my.xmppservice.org
```
If one of `accountOneUsername`, `accountOnePassword`, `accountTwoUsername` or `accountTwoPassword` is not configured, then the framework will automatically create the accounts on the service. Of course this requires account registration (IBR) to be enabled.
If the accounts got created automatically by the framework, then they will also be deleted at the end of the test.
Implementing Integration Tests
------------------------------
Create a new class which extends `AbstractSmackIntegrationTest`.
Every non-static method, including the constructor, of this class will have two XMPPConnections available to perform the integration tests with: `conOne` and `conTwo`.
You can use the constructor to check if the XMPP service does provide the required XMPP feature.
If it does not, simply throw a `TestNotPossibleException`.
Test methods must be `public`, take zero arguments i.e. declare no parameters and be annoated with `@SmackIntegrationTest`.
If the test method is not able to perform a test then it should throw a `TestNotPossibleException`.
### Rules for integration tests
Tests should not leave any traces on the service if they are finished, i.e. the service state at the end of the test must be equal to the state of the beginning.
It must be possible to run the tests in parallel.
### Why are there two mechanisms to signal that the test is not possible?
Because the XMPP service may provide a component that is required to perform a certain integration test, but that component may not support all features.
For example, the XMPP service may provides a PubSub (XEP-0060) component, but this component may not support all features of XEP-0060.
### Low-Level Integration Tests
Classes that implement low-level integration tests need to sublcass `AbstractSmackLowLevelIntegrationTest`.
The test methods can declare as many parameters as they need to, but every parameter must be of type `XMPPTCPConnection`.
The framework will automatically create, register and login the connections.
After the test is finished, the connections will be unregistered with the XMPP service and terminated.
Debugging Integration Tests
------------------------------
A test, like any other code, may not be perfect on the first attempt, and you may require more information in order to ascertain quite what's wrong.
### Smack Debugger options
As listed in the main Smack [Debugging](../debugging.md) doc, there are two built-in debuggers that could surface you more information. Using the 'enhanced' debugger config option listed above, you'll get the Smack Debug Window launching when your tests launch, and you'll get a stanza-by-stanza account of what happened on each connection, hopefully enough to diagnose what went wrong.
### Debugging in the IDE
If the output isn't enough, you may need to debug and inspect running code within the IDE. Depending on the IDE, in order to get execution to pause at your breakpoints, you may need to switch your configuration. Instead of running `gradle integrationTest`, instead run the `SmackIntegrationTestFramework` class directly with the same command-line options.
Running your own integration tests
----------------------------------
The framework can be used to run your own tests residing outside of the framework's default package scope.
Simply set the `testPackages` property to a comma separated list of package names where the framework should look for integration tests.
Example:
```bash
$ gradle integrationTest -Dsinttest.service=my.xmppserivce.org -Dsinttest.testPackages=org.mypackage,org.otherpackage
```

View File

@ -1,75 +0,0 @@
Smack Providers
===============
Providers are responsible for parsing the XMPP XML stream into new Java objects.
Provider Design
---------------
Assume you want to parse the following stanza extension element
```xml
<myExtension attrFoo='fourthyTwo'>
<myElement>Foo is greater then Bar</myElement>
<myInfo alpha='true' delta='-1337'/>
</myExtension>
```
then the related provider would look like this
```java
public MyExtension parse(XmlPullParser parser, int initialDepth) {
MyElement myElement = null;
MyInfo myInfo = null;
String attrFoo = parser.getAttributeValue("", "attrFoo");
// Main parsing loop, use a loop label instead of "boolean done"
outerloop: while(true) {
// Make sure to have already parse all attributes of the outermost element,
// i.e. 'attrFoo' of 'myExtension' in this example. Then advance the parser
XmlPullParser.Event event = parser.next();
// Use switch/case of int instead of a if/else-if cascade
switch (event) {
case START_ELEMENT:
// Determine the name of the element which start tag we are seeing
String name = parser.getName();
// We can use switch/case of Strings since Java7, make use of its advantages
// and collect the values of the sub elements. If the sub elements are more
// complex then those of this example, consider creating extra *private static*
// parsing methods for them.
switch(name) {
case "myElement":
// You should only use XmlPullParser.nextText() when the element is
// required to have a text.
myElement = new MyElement(parser.nextText());
break;
case "myInfo";
// Use ParserUtils to parse Java primitives
boolenan alpha = ParserUtils.getBooleanAttribute(parser, "alpha");
int delta = ParserUtils.getIntegerAttribute(parser, "delta");
myInfo = new MyInfo(alpha, delta);
break;
}
break;
case END_ELEMENT:
// The abort condition with the break labeled loop statement
if (parser.getDepth() == initialDepth) {
break outerloop;
}
break;
default:
// Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
break;
}
}
// Create the actual class at the very end, design the classes as immutable as possible
return new MyExtension(attrFoo, myElement, myInfo);
}
```
Common Pitfalls
---------------
Use a `long` instead of `int` when the XML schema says `xs:unsignedInt`, because Java's `int` range is to small for this XML numeric data type.

View File

@ -1,33 +0,0 @@
General Rules
=============
All classes which subclass `TopLevelStreamElement` and `ExtensionElement` must either
1. be immutable (and ideally provide a Builder)
2. implement `TypedCloneable`
and must be `Serializable`.
The reason that it must be either 1. or 2. is that it makes no sense to clone an inmutable instance.
The preferred option is 1.
Note that there is legacy code in Smack which does not follow these rules. Patches are welcome.
ExtensionElement
================
Extension elements are XML elements that are used in various parts and levels of stanzas.
The static `from(Stanza)` Method
--------------------------------
Every ExtensionElement class must have a static `from()` method that retrieves that extension for a given Stanza (if any).
Sample Code
```java
public static RSMSet from(Stanza) {
return packet.getExtension(ELEMENT, NAMESPACE);
}
```
Sometimes certain ExtensionElement's are only found in one stanza type, in that case, specify the parameter type. For example `public static CarbonExtension getFrom(Message)`.

View File

@ -1,75 +0,0 @@
DNSSEC and DANE
===============
[Back](index.md)
**DNSSEC and DANE support in Smack and MiniDNS is still in its
infancy. It should be considered experimental and not ready for
production use at this time.** We would like to see more thorough
testing and review by the security community. If you can help, then
please do not hesitate to contact us.
About
-----
DNSSEC ([RFC 4033](https://tools.ietf.org/html/rfc4033) and others)
authenticates DNS answers, positive and negative ones. This means that
if a DNS response secured by DNSSEC turns out to be authentic, then
you can be sure that the domain either exists, and that the returned
resource records (RRs) are the ones the domain owner authorized, or
that the domain does not exists and that nobody tried to fake its non
existence.
The tricky part is that an application using DNSSEC can not determine
whether a domain uses DNSSEC, does not use DNSSEC or if someone
downgraded your DNS query using DNSSEC to a response without DNSSEC.
[DANE](https://tools.ietf.org/html/rfc6698) allows the verification of
a TLS certificate with information stored in the DNS system and
secured by DNSSEC. Thus DANE requires DNSSEC.
Prerequisites
-------------
From the three DNS resolver providers (MiniDNS, javax, dnsjava)
supported by Smack only [MiniDNS](https://github.com/rtreffer/minidns)
currently supports DNSSEC. MiniDNS is the default resolver when
smack-android is used. For other configurations, make sure to add
smack-resolver-minidns to your dependencies and call
`MiniDnsResolver.setup()` prior using Smack (e.g. in a `static {}`
code block).
DNSSEC API
----------
Smack's DNSSEC API is very simple: Just use
`ConnectionConfiguration.Builder..setDnssecMode(DnssecMode)` to enable
DNSSEC. `DnssecMode` can be one of
- `disabled`
- `needsDnssec`
- `needsDnssecAndDane`
The default is `disabled`.
If `needsDnssec` is used, then Smack will only connect if the DNS
results required to determine a host for the XMPP domain could be
verified using DNSSEC.
If `needsDnssecAndDane` then DANE will be used to verify the XMPP
service's TLS certificate if STARTTLS is used. Note that you may want
to configure
`ConnectionConfiguration.Builder.setSecurityMode(SecurityMode.required)`
if you use this DNSSEC mode setting.
Best practices
--------------
We recommend that applications using Smack's DNSSEC API do not ask the
user if DNSSEC is avaialble. Instead they should check for DNSSEC
suport on every connection attempt. Once DNSSEC support has been
discovered, the application should use the `needsDnssec` mode for all
future connection attempts. The same scheme can be applied when using
DANE. This approach is similar to the scheme established by
to
["HTTP Strict Transport Security" (HSTS, RFC 6797)](https://tools.ietf.org/html/rfc6797).

View File

@ -1,76 +0,0 @@
Blocking Command
================
[Back](index.md)
Allows one to manage communications blocking.
* Check push notifications support
* Get blocking list
* Block contact
* Unblock contact
* Unblock all
* Check if a message has a blocked error
**XEP related:** [XEP-0191](http://xmpp.org/extensions/xep-0191.html)
Get an instance of Blocking Command Manager
-------------------------------------------
```
BlockingCommandManager blockingCommandManager = BlockingCommandManager.getInstanceFor(connection);
```
Check blocking command support
------------------------------
```
boolean isSupported = blockingCommandManager.isSupportedByServer();
```
Get block list
--------------
```
List<Jid> blockList = blockingCommandManager.getBlockList();
```
Block contact
-------------
```
blockingCommandManager.blockContacts(jids);
```
*jids* is a `java.util.List<Jid>`
Unblock contact
---------------
```
blockingCommandManager.unblockContacts(jids);
```
*jids* is a `java.util.List<Jid>`
Unblock all
-----------
```
blockingCommandManager.unblockAll();
```
Check if a message has a blocked error
--------------------------------------
```
BlockedErrorExtension.isInside(message));
```
*message* is a `Message`

View File

@ -1,49 +0,0 @@
Entity Capabilities
===================
[Back](index.md)
This section details the usage of Smacks implementation of Entity
Capabilities.
**XEP related:** [XEP-0115: Entity Capabilities](http://xmpp.org/extensions/xep-0115.html)
**Description**
Entity Capabilities is an XMPP Protocol extension, which, in order to minimize
network impact, caches the capabilities of XMPP entities. Those capabilities
are determined with the help of the Service Discovery Protocol
([XEP-0030](http://xmpp.org/extensions/xep-0030.html)).
**Usage**
Entity Capabilities work silently in the background when enabled. If the remote
XMPP entity does not support XEP-0115 but XEP-0030 then XEP-0030 mechanisms
are transparently used. You can enable or disable Entity Capabilities by using
_**EntityCapsManager**_.
The cache used by Smack for Entity Capabilities is non-persistent as default.
That is, the cache only uses memory. But it is also possible to set a
persistent Entity Capabilities cache, which is recommended.
**Examples**
Enable Entity Capabilities
```
// Get an instance of entity caps manager for the specified connection
EntityCapsManager mgr = EntityCapsManager.getInstanceFor(connection);
// Enable entity capabilities
mgr.enableEntityCaps();
```
Configure a persistent cache for Entity Capabilities
```
// Get an instance of entity caps manager for the specified connection
EntityCapsManager mgr = EntityCapsManager.getInstanceFor(connection);
// Create an cache, see smackx.entitycaps.cache for pre-defined cache implementations
EntityCapsPersistentCache cache = new SimpleDirectoryPersistentCache(new File("/foo/cachedir"));
// Set the cache
mgr.setPersistentCache(cache);
```

View File

@ -1,37 +0,0 @@
Consistent Colors
=================
[Back](index.md)
Since XMPP can be used on multiple platforms at the same time,
it might be a good idea to render given Strings like nicknames in the same
color on all platforms to provide a consistent user experience.
The utility class `ConsistentColor` allows the generation of colors to a given
string following the specification of [XEP-0392](https://xmpp.org/extensions/xep-0392.html).
## Usage
To generate a consistent color for a given string, call
```
float[] rgb = ConsistentColor.RGBFrom(input);
```
The resulting float array contains values for RGB in the range of 0 to 1.
## Color Deficiency Corrections
Some users might suffer from color vision deficiencies. To compensate those deficiencies,
the API allows for color correction. The color correction mode is a static value, which can be changed at any time.
To correct colors for users with red-green color deficiency use the following code:
```
ConsistentColor.activateRedGreenBlindnessCorrection();
```
For color correction for users with blue-blindness, call
```
ConsistentColor.activateBlueBlindnessCorrection();
```
To deactivate color vision deficiency correction, call
```
ConsistentColor.deactivateDeficiencyCorrection();
```

View File

@ -1,145 +0,0 @@
Data Forms
==========
[Back](index.md)
Allows the exchange of structured data between users and applications for common
tasks such as registration and searching using Forms.
* Create a Form to fill out
* Answer a Form
**XEP related:** [XEP-4](http://www.xmpp.org/extensions/xep-0004.html)
Create a Form to fill out
-------------------------
**Description**
An XMPP entity may need to gather data from another XMPP entity. Therefore,
the data-gathering entity will need to create a new Form, specify the fields
that will conform to the Form and finally send the Form to the data-providing
entity.
**Usage**
In order to create a Form to fill out use the _**Form**_'s constructor passing
the constant **DataForm.type.form** as the parameter. The next step is to create
the form fields and add them to the form. In order to create and customize a
_**FormField**_ use the _**FormField**_'s constructor specifying the variable
name of the field as the parameter. Then use **setType(FormField.Type type)** to set
the field's type (e.g. FormField.Type.hidden, FormField.Type.text_single).
Once we have the _**Form**_ instance and the _**FormFields**_, the last step is
to send **addField(FormField field)** for each field that we want to add to
the form.
Once the form to fill out is finished we will want to send it in a message.
Send **getDataFormToSend()** to the form and add the answer as an extension to
the message to send.
**Examples**
In this example we can see how to create and send a form to fill out:
```
// Create a new form to gather data
Form formToSend = new Form(DataForm.Type.form);
formToSend.setInstructions("Fill out this form to report your case.\nThe case will be created automatically.");
formToSend.setTitle("Case configurations");
// Add a hidden variable to the form
FormField field = new FormField("hidden_var");
field.setType(FormField.Type.hidden);
field.addValue("Some value for the hidden variable");
formToSend.addField(field);
// Add a fixed variable to the form
field = new FormField();
field.addValue("Section 1: Case description");
formToSend.addField(field);
// Add a text-single variable to the form
field = new FormField("name");
field.setLabel("Enter a name for the case");
field.setType(FormField.Type.text_single);
formToSend.addField(field);
// Add a text-multi variable to the form
field = new FormField("description");
field.setLabel("Enter a description");
field.setType(FormField.Type.text_multi);
formToSend.addField(field);
// Create a chat with "user2@host.com"
Chat chat = ChatManager.getInstanceFor(conn1).chatWith("user2@host.com" );
Message msg = new Message();
msg.setBody("To enter a case please fill out this form and send it back");
// Add the form to fill out to the message to send
msg.addExtension(formToSend.getDataFormToSend());
// Send the message with the form to fill out
chat.send(msg);
```
Answer a Form
-------------
**Description**
Under many situations an XMPP entity could receive a form to fill out. For
example, some hosts may require to fill out a form in order to register new
users. Smack lets the data-providing entity to complete the form in an easy
way and send it back to the data-gathering entity.
**Usage**
The form to fill out contains useful information that could be used for
rendering the form. But it cannot be used to actually complete it. Instead
it's necessary to create a new form based on the original form whose purpose
is to hold all the answers.
In order to create a new _**Form**_ to complete based on the original
_**Form**_ just send **createAnswerForm()** to the original _**Form**_. Once
you have a valid form that can be completed, all you have to do is
send **setAnswer(String variable, String value)** to the form where variable
is the variable of the _**FormField**_ that you want to answer and value is
the String representation of the answer. If the answer consists of several
values you could then use **setAnswer(String variable, List values)** where
values is a List of Strings.
Once the form has been completed we will want to send it back in a message.
Send **getDataFormToSend()** to the form and add the answer as an extension to
the message to send back.
**Examples**
In this example we can see how to retrieve a form to fill out, complete the
form and send it back:
```
// Get the message with the form to fill out
Chat chat2 = ChatManager.getInstanceFor(conn).addIncomingListener(
new IncomingChatMessageListener() {
@Override public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
// Retrieve the form to fill out from the message
Form formToRespond = Form.getFormFrom(message);
// Obtain the form to send with the replies
Form completedForm = formToRespond.createAnswerForm();
// Add the answers to the form
completedForm.setAnswer("name", "Credit card number invalid");
completedForm.setAnswer("description", "The ATM says that my credit card number is invalid");
Message msg2 = new Message();
msg2.setBody("To enter a case please fill out this form and send it back");
// Add the completed form to the message to send back
msg2.addExtension(completedForm.getDataFormToSend());
// Send the message with the completed form
chat.send(msg2);
}
});
```

View File

@ -1,235 +0,0 @@
Service Discovery
=================
[Back](index.md)
The service discovery extension allows one to discover items and information about
XMPP entities. Follow these links to learn how to use this extension.
* Manage XMPP entity features
* Provide node information
* Discover items associated with an XMPP entity
* Discover information about an XMPP entity
* Publish publicly available items
**XEP related:** [XEP-30](http://www.xmpp.org/extensions/xep-0030.html)
Manage XMPP entity features
---------------------------
**Description**
Any XMPP entity may receive a discovery request and must answer with its
associated items or information. Therefore, your Smack client may receive a
discovery request that must respond to (i.e., if your client supports XHTML-
IM). This extension automatically responds to a discovery request with the
information that you previously configured.
**Usage**
In order to configure the supported features by your client you should first
obtain the ServiceDiscoveryManager associated with your XMPPConnection. To get
your ServiceDiscoveryManager send **getInstanceFor(connection)** to the class
_**ServiceDiscoveryManager**_ where connection is your XMPPConnection.
Once you have your ServiceDiscoveryManager you will be able to manage the
supported features. To register a new feature send **addFeature(feature)** to
your _**ServiceDiscoveryManager**_ where feature is a String that represents
the supported feature. To remove a supported feature send
**removeFeature(feature)** to your _**ServiceDiscoveryManager**_ where feature
is a String that represents the feature to remove.
**Examples**
In this example we can see how to add and remove supported features:
```
// Obtain the ServiceDiscoveryManager associated with my XMPP connection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
// Register that a new feature is supported by this XMPP entity
discoManager.addFeature(namespace1);
// Remove the specified feature from the supported features
discoManager.removeFeature(namespace2);
```
Provide node information
------------------------
**Description**
Your XMPP entity may receive a discovery request for items non-addressable as
a JID such as the MUC rooms where you are joined. In order to answer the
correct information it is necessary to configure the information providers
associated to the items/nodes within the Smack client.
**Usage**
In order to configure the associated nodes within the Smack client you will
need to create a NodeInformationProvider and register it with the
_**ServiceDiscoveryManager**_. To get your ServiceDiscoveryManager send
**getInstanceFor(connection)** to the class _**ServiceDiscoveryManager**_
where connection is your XMPPConnection.
Once you have your ServiceDiscoveryManager you will be able to register
information providers for the XMPP entity's nodes. To register a new node
information provider send **setNodeInformationProvider(String node,
NodeInformationProvider listener)** to your _**ServiceDiscoveryManager**_
where node is the item non-addressable as a JID and listener is the
_**NodeInformationProvider**_ to register. To unregister a
_**NodeInformationProvider**_ send **removeNodeInformationProvider(String
node)** to your _**ServiceDiscoveryManager**_ where node is the item non-
addressable as a JID whose information provider we want to unregister.
**Examples**
In this example we can see how to register a NodeInformationProvider with a
ServiceDiscoveryManager that will provide information concerning a node named
"http://jabber.org/protocol/muc#rooms":
```
// Set the NodeInformationProvider that will provide information about the
// joined rooms whenever a disco request is received
ServiceDiscoveryManager.getInstanceFor(connection).setNodeInformationProvider(
"http://jabber.org/protocol/muc#rooms",
new NodeInformationProvider() {
public List<DiscoverItems.Item> getNodeItems() {
MultiUserChatManager mucManager = MultiUserChatManager.getInstanceFor(connection);
List<DiscoverItems.Item> answer = new ArrayList<>();
Iterator<Jid> rooms = mucManager.getJoinedRooms().iterator();
while (rooms.hasNext()) {
answer.add(new DiscoverItems.Item(rooms.next()));
}
return answer;
}
public List<String> getNodeFeatures() {...}
public List<DiscoverInfo.Identity> getNodeIdentities() {...}
public List<ExtensionElement> getNodePacketExtensions() {...}
});
```
Discover items associated with an XMPP entity
---------------------------------------------
**Description**
In order to obtain information about a specific item you have to first
discover the items available in an XMPP entity.
**Usage**
Once you have your ServiceDiscoveryManager you will be able to discover items
associated with an XMPP entity. To discover the items of a given XMPP entity
send **discoverItems(entityID)** to your _**ServiceDiscoveryManager**_ where
entityID is the ID of the entity. The message **discoverItems(entityID)** will
answer an instance of _**DiscoverItems**_ that contains the discovered items.
**Examples**
In this example we can see how to discover the items associated with an online
catalog service:
```
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
// Get the items of a given XMPP entity
// This example gets the items associated with online catalog service
DiscoverItems discoItems = discoManager.discoverItems("plays.shakespeare.lit");
// Get the discovered items of the queried XMPP entity
Iterator it = discoItems.getItems().iterator();
// Display the items of the remote XMPP entity
while (it.hasNext()) {
DiscoverItems.Item item = (DiscoverItems.Item) it.next();
System.out.println(item.getEntityID());
System.out.println(item.getNode());
System.out.println(item.getName());
}
```
Discover information about an XMPP entity
-----------------------------------------
**Description**
Once you have discovered the entity ID and name of an item, you may want to
find out more about the item. The information desired generally is of two
kinds: 1) The item's identity and 2) The features offered by the item.
This information helps you determine what actions are possible with regard to
this item (registration, search, join, etc.) as well as specific feature types
of interest, if any (e.g., for the purpose of feature negotiation).
**Usage**
Once you have your ServiceDiscoveryManager you will be able to discover
information associated with an XMPP entity. To discover the information of a
given XMPP entity send **discoverInfo(entityID)** to your
_**ServiceDiscoveryManager**_ where entityID is the ID of the entity. The
message **discoverInfo(entityID)** will answer an instance of
_**DiscoverInfo**_ that contains the discovered information.
**Examples**
In this example we can see how to discover the information of a conference
room:
```
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
// Get the information of a given XMPP entity
// This example gets the information of a conference room
DiscoverInfo discoInfo = discoManager.discoverInfo("balconyscene@plays.shakespeare.lit");
// Get the discovered identities of the remote XMPP entity
Iterator it = discoInfo.getIdentities().iterator();
// Display the identities of the remote XMPP entity
while (it.hasNext()) {
DiscoverInfo.Identity identity = (DiscoverInfo.Identity) it.next();
System.out.println(identity.getName());
System.out.println(identity.getType());
System.out.println(identity.getCategory());
}
// Check if room is password protected
discoInfo.containsFeature("muc_passwordprotected");
```
Publish publicly available items
--------------------------------
**Description**
Publish your entity items to some kind of persistent storage. This enables
other entities to query that entity using the disco#items namespace and
receive a result even when the entity being queried is not online (or
available).
**Usage**
Once you have your ServiceDiscoveryManager you will be able to publish items
to some kind of persistent storage. To publish the items of a given XMPP
entity you have to first create an instance of _**DiscoverItems**_ and
configure it with the items to publish. Then you will have to send
**publishItems(Jid entityID, DiscoverItems discoverItems)** to your
_**ServiceDiscoveryManager**_ where entityID is the address of the XMPP entity
that will persist the items and discoverItems contains the items to publish.
**Examples**
In this example we can see how to publish new items:
```
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
// Create a DiscoverItems with the items to publish
DiscoverItems itemsToPublish = new DiscoverItems();
Jid jid = JidCreate.from("pubsub.shakespeare.lit");
DiscoverItems.Item itemToPublish = new DiscoverItems.Item(jid);
itemToPublish.setName("Avatar");
itemToPublish.setNode("romeo/avatar");
itemToPublish.setAction(DiscoverItems.Item.UPDATE_ACTION);
itemsToPublish.addItem(itemToPublish);
// Publish the new items by sending them to the server
Jid jid2 = JidCreate.from("host");
discoManager.publishItems(jid2, itemsToPublish);
```

View File

@ -1,155 +0,0 @@
File Transfer
=============
[Back](index.md)
The file transfer extension allows the user to transmit and receive files.
* Send a file to another user
* Receiving a file from another user
* Monitoring the progress of a file transfer
**XEP related:** [XEP-95](http://www.xmpp.org/extensions/xep-0095.html) [XEP-96](http://www.xmpp.org/extensions/xep-0096.html) [XEP-65](http://www.xmpp.org/extensions/xep-0065.html) [XEP-47](http://www.xmpp.org/extensions/xep-0047.html)
Send a file to another user
---------------------------
**Description**
A user may wish to send a file to another user. The other user has the option
of accepting, rejecting, or ignoring the users request. Smack provides a
simple interface in order to enable the user to easily send a file.
**Usage**
In order to send a file you must first construct an instance of the
**_FileTransferManager_** class. In order to instantiate the manager
you should call _FileTransferManager.getInstanceFor(connection)_, where connection is an XMPPConnection instance.
Once you have your **_FileTransferManager_** you will need to create an
outgoing file transfer to send a file. The method to use on the
**_FileTransferManager_** is the **createOutgoingFileTransfer(userID)**
method. The userID you provide to this method is the fully-qualified jabber ID
of the user you wish to send the file to. A fully-qualified jabber ID consists
of a node, a domain, and a resource. The user must be connected to the
resource in order to be able to receive the file transfer.
Now that you have your **_OutgoingFileTransfer_** instance you will want to
send the file. The method to send a file is **sendFile(file, description)**.
The file you provide to this method should be a readable file on the local
file system, and the description is a short description of the file to help
the user decide whether or not they would like to recieve the file.
For information on monitoring the progress of a file transfer see the
monitoring progress section of this document.
Other means to send a file are also provided as part of the
**_OutgoingFileTransfer_**. Please consult the Javadoc for more information.
**Examples**
In this example we can see how to send a file:
```
// Create the file transfer manager
FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
// Create the outgoing file transfer
OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(entityFullJid);
// Send the file
transfer.sendFile(new File("shakespeare_complete_works.txt"), "You won't believe this!");
```
Receiving a file from another user
----------------------------------
**Description**
The user may wish to receive files from another user. The process of receiving
a file is event driven, new file transfer requests are received from other
users via a listener registered with the file transfer manager.
**Usage**
In order to receive a file you must first construct an instance of the
**_FileTransferManager_** class. This class has one static factory method with one
parameter which is your XMPPConnection. In order to instantiate the manager
you should call _FileTransferManager.getInstanceFor(connection)_.
Once you have your **_FileTransferManager_** you will need to register a
listener with it. The FileTransferListener interface has one method,
**fileTransferRequest(request)**. When a request is received through this
method, you can either accept or reject the request. To help you make your
decision there are several methods in the **_FileTransferRequest_** class that
return information about the transfer request.
To accept the file transfer, call the **accept()** method. This method will create an
**_IncomingFileTransfer_**. After you have the file transfer you may start to
transfer the file by calling the **recieveFile(file)** method. The file
provided to this method will be where the data from the file transfer is saved.
Finally, to reject the file transfer the only method you need to call is
**reject()** on the **_FileTransferRequest_**.
For information on monitoring the progress of a file transfer see the
monitoring progress section of this document.
Other means to receive a file are also provided as part of the
**_IncomingFileTransfer_**. Please consult the Javadoc for more information.
**Examples**
In this example we can see how to approve or reject a file transfer request:
```
// Create the file transfer manager
final FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
// Create the listener
manager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(FileTransferRequest request) {
// Check to see if the request should be accepted
if (shouldAccept(request)) {
// Accept it
IncomingFileTransfer transfer = request.accept();
transfer.recieveFile(new File("shakespeare_complete_works.txt"));
} else {
// Reject it
request.reject();
}
}
});
```
Monitoring the progress of a file transfer
------------------------------------------
**Description**
While a file transfer is in progress you may wish to monitor the progress of a
file transfer.
**Usage**
Both the **_IncomingFileTransfer_** and the **_OutgoingFileTransfer_** extend
the **_FileTransfer_** class which provides several methods to monitor how a
file transfer is progressing:
* **getStatus()** - The file transfer can be in several states, negotiating, rejected, cancelled, in progress, error, and complete. This method will return which state the file transfer is currently in.
* **getProgress()** - If the status of the file transfer is in progress this method will return a number between 0 and 1, 0 being the transfer has not yet started and 1 being the transfer is complete. It may also return a -1 if the transfer is not in progress.
* **isDone()** - Similar to getProgress() except it returns a _boolean_. If the state is rejected, canceled, error, or complete then true will be returned and false otherwise.
* **getError()** - If there is an error during the file transfer this method will return the type of error that occured.
**Examples**
In this example we can see how to monitor a file transfer:
```
while(!transfer.isDone()) {
if (transfer.getStatus().equals(Status.error)) {
System.out.println("ERROR!!! " + transfer.getError());
} else {
System.out.println(transfer.getStatus());
System.out.println(transfer.getProgress());
}
sleep(1000);
}
```

View File

@ -1,114 +0,0 @@
HTTP over XMPP transport
========================
[Back](index.md)
Allows the transport of HTTP communication over XMPP peer-to-peer networks.
* Discover HOXT support
* IQ exchange
Discover HOXT support
---------------------
**Description**
Before using this extension you must ensure that your counterpart supports it
also.
**Usage**
Once you have your _**ServiceDiscoveryManager**_ you will be able to discover
information associated with an XMPP entity. To discover the information of a
given XMPP entity send **discoverInfo(entityID)** to your
_**ServiceDiscoveryManager**_ where entityID is the ID of the entity. The
message **discoverInfo(entityID)** will answer with an instance of
_**DiscoverInfo**_ that contains the discovered information.
**Examples**
In this example we can see how to check if the counterpart supports HOXT:
```
// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
// Get the information of a given XMPP entity, where entityID is a Jid
DiscoverInfo discoInfo = discoManager.discoverInfo(entityID);
// Check if room is HOXT is supported
boolean isSupported = discoInfo.containsFeature("urn:xmpp:http");
```
IQ exchange
-----------
**Description**
You can use IQ's to perform HTTP requests and responses. This is applicable to
relatively short requests and responses (due to the limitation of XMPP message
size).
**Usage**
First you need to register a _**StanzaListener**_ to be able to handle
intended IQs.
For the HTTP client you:
* You create and send _**HttpOverXmppReq**_ request.
* Then you handle the _**HttpOverXmppResp**_ response in your _**StanzaListener**_.
For the HTTP server you:
* You handle the _**HttpOverXmppReq**_ requests in your _**StanzaListener**_.
* And create and send _**HttpOverXmppResp**_ responses.
**Examples**
In this example we are an HTTP client, so we send a request (POST) and handle the
response:
```
// create a request body
String urlEncodedMessage = "I_love_you";
// prepare headers
List<Header> headers = new ArrayList<>();
headers.add(new Header("Host", "juliet.capulet.com"));
headers.add(new Header("Content-Type", "application/x-www-form-urlencoded"));
headers.add(new Header("Content-Length", Integer.toString(urlEncodedMessage.length())));
// provide body or request (not mandatory, - empty body is used for GET)
AbstractHttpOverXmpp.Text child = new AbstractHttpOverXmpp.Text(urlEncodedMessage);
AbstractHttpOverXmpp.Data data = new AbstractHttpOverXmpp.Data(child);
// create request
HttpOverXmppReq req = HttpOverXmppReq.buider()
.setMethod(HttpMethod.POST)
.setResource("/mailbox")
.setHeaders(headers)
.setVersion("1.1")
.setData(data)
.build();
// add to, where jid is the Jid of the individual the packet is sent to
req.setTo(jid);
// send it
connection.sendIqWithResponseCallback(req, new StanzaListener() {
public void processStanza(Stanza iq) {
HttpOverXmppResp resp = (HttpOverXmppResp) iq;
// check HTTP response code
if (resp.getStatusCode() == 200) {
// get content of the response
NamedElement child = resp.getData().getChild();
// check which type of content of the response arrived
if (child instanceof AbstractHttpOverXmpp.Xml) {
// print the message and anxiously read if from the console ;)
System.out.println(((AbstractHttpOverXmpp.Xml) child).getText());
} else {
// process other AbstractHttpOverXmpp data child subtypes
}
}
}
});
```

View File

@ -1,147 +0,0 @@
Smack Extensions User Manual
============================
The XMPP protocol includes a base protocol and many optional extensions
typically documented as "XEP's". Smack provides the org.jivesoftware.smack
package for the core XMPP protocol, and the org.jivesoftware.smackx package
for many of the protocol extensions.
This manual provides details about each of the "smackx" extensions, including
what it is, how to use it, and some simple example code.
Currently supported XEPs of Smack (all sub-projects)
---------------------------------------------------
| Name | XEP | Version | Description |
|---------------------------------------------|--------------------------------------------------------|-----------|----------------------------------------------------------------------------------------------------------|
| Discovering Alternative XMPP Connection Methods | [XEP-0156](https://xmpp.org/extensions/xep-0156.html) | 1.3.0 | Defines ways to discover alternative connection methods. |
| Nonzas | [XEP-0360](https://xmpp.org/extensions/xep-0360.html) | n/a | Defines the term "Nonza", describing every top level stream element that is not a Stanza. |
Currently supported XEPs of smack-tcp
-------------------------------------
| Name | XEP | Version | Description |
|---------------------------------------------|--------------------------------------------------------|-----------|----------------------------------------------------------------------------------------------------------|
| [Stream Management](streammanagement.md) | [XEP-0198](https://xmpp.org/extensions/xep-0198.html) | n/a | Allows active management of an XML Stream between two XMPP entities (stanza acknowledgement, stream resumption). |
Currently supported XEPs of smack-im
------------------------------------
| Name | XEP | Version | Description |
|---------------------------------------------|--------------------------------------------------------|-----------|-----------------------------------|
| Roster Versioning | [XEP-0237](https://xmpp.org/extensions/xep-0237.html) | n/a | Efficient roster synchronization. |
Smack Extensions and currently supported XEPs of smack-extensions
-----------------------------------------------------------------
| Name | XEP | Version | Description |
|---------------------------------------------|--------------------------------------------------------|-----------|----------------------------------------------------------------------------------------------------------|
| [Data Forms](dataforms.md) | [XEP-0004](https://xmpp.org/extensions/xep-0004.html) | n/a | Allows to gather data using Forms. |
| Last Activity | [XEP-0012](https://xmpp.org/extensions/xep-0012.html) | n/a | Communicating information about the last activity associated with an XMPP entity. |
| Flexible Offline Message Retrieval | [XEP-0013](https://xmpp.org/extensions/xep-0013.html) | n/a | Extension for flexible, POP3-like handling of offline messages. |
| [Privacy Lists](privacy.md) | [XEP-0016](https://xmpp.org/extensions/xep-0016.html) | n/a | Enabling or disabling communication with other entities. |
| [Service Discovery](disco.md) | [XEP-0030](https://xmpp.org/extensions/xep-0030.html) | n/a | Allows to discover services in XMPP entities. |
| Extended Stanza Addressing | [XEP-0033](https://xmpp.org/extensions/xep-0033.html) | n/a | Allows to include headers in stanzas in order to specifiy multiple recipients or sub-addresses. |
| [Multi User Chat](muc.md) | [XEP-0045](https://xmpp.org/extensions/xep-0045.html) | n/a | Allows configuration of, participation in, and administration of individual text-based conference rooms. |
| In-Band Bytestreams | [XEP-0047](https://xmpp.org/extensions/xep-0047.html) | n/a | Enables any two entities to establish a one-to-one bytestream between themselves using plain XMPP. |
| Bookmarks | [XEP-0048](https://xmpp.org/extensions/xep-0048.html) | n/a | Bookmarks, for e.g. MUC and web pages. |
| [Private Data](privatedata.md) | [XEP-0049](https://xmpp.org/extensions/xep-0049.html) | n/a | Manages private data. |
| Ad-Hoc Commands | [XEP-0050](https://xmpp.org/extensions/xep-0050.html) | n/a | Advertising and executing application-specific commands. |
| vcard-temp | [XEP-0054](https://xmpp.org/extensions/xep-0054.html) | n/a | The vCard-XML format currently in use. |
| Jabber Search | [XEP-0055](https://xmpp.org/extensions/xep-0055.html) | n/a | Search information repositories on the XMPP network. |
| Result Set Management | [XEP-0059](https://xmpp.org/extensions/xep-0059.html) | n/a | Page through and otherwise manage the receipt of large result sets |
| [PubSub](pubsub.md) | [XEP-0060](https://xmpp.org/extensions/xep-0060.html) | n/a | Generic publish and subscribe functionality. |
| SOCKS5 Bytestreams | [XEP-0065](https://xmpp.org/extensions/xep-0065.html) | n/a | Out-of-band bytestream between any two XMPP entities. |
| Field Standardization for Data Forms | [XEP-0068](https://xmpp.org/extensions/xep-0068.html) | n/a | Standardized field variables used in the context of jabber:x:data forms. |
| [XHTML-IM](xhtml.md) | [XEP-0071](https://xmpp.org/extensions/xep-0071.html) | n/a | Allows send and receiving formatted messages using XHTML. |
| In-Band Registration | [XEP-0077](https://xmpp.org/extensions/xep-0077.html) | n/a | In-band registration with XMPP services. |
| Advanced Message Processing | [XEP-0079](https://xmpp.org/extensions/xep-0079.html) | n/a | Enables entities to request, and servers to perform, advanced processing of XMPP message stanzas. |
| User Location | [XEP-0080](https://xmpp.org/extensions/xep-0080.html) | n/a | Enabled communicating information about the current geographical or physical location of an entity. |
| XMPP Date Time Profiles | [XEP-0082](https://xmpp.org/extensions/xep-0082.html) | n/a | Standardization of Date and Time representation in XMPP. |
| Chat State Notifications | [XEP-0085](https://xmpp.org/extensions/xep-0085.html) | n/a | Communicating the status of a user in a chat session. |
| [Time Exchange](time.md) | [XEP-0090](https://xmpp.org/extensions/xep-0090.html) | n/a | Allows local time information to be shared between users. |
| Software Version | [XEP-0092](https://xmpp.org/extensions/xep-0092.html) | n/a | Retrieve and announce the software application of an XMPP entity. |
| Stream Initiation | [XEP-0095](https://xmpp.org/extensions/xep-0095.html) | n/a | Initiating a data stream between any two XMPP entities. |
| [SI File Transfer](filetransfer.md) | [XEP-0096](https://xmpp.org/extensions/xep-0096.html) | n/a | Transfer files between two users over XMPP. |
| User Mood | [XEP-0107](https://xmpp.org/extensions/xep-0107.html) | 1.2.1 | Communicate the users current mood. |
| [Entity Capabilities](caps.md) | [XEP-0115](https://xmpp.org/extensions/xep-0115.html) | n/a | Broadcasting and dynamic discovery of entity capabilities. |
| User Tune | [XEP-0118](https://xmpp.org/extensions/xep-0118.html) | n/a | Defines a payload format for communicating information about music to which a user is listening. |
| Data Forms Validation | [XEP-0122](https://xmpp.org/extensions/xep-0122.html) | n/a | Enables an application to specify additional validation guidelines . |
| Stanza Headers and Internet Metadata (SHIM) | [XEP-0131](https://xmpp.org/extensions/xep-0131.html) | 1.2 | Add Metadata Headers to Stanzas. |
| Service Administration | [XEP-0133](https://xmpp.org/extensions/xep-0133.html) | n/a | Recommended best practices for service-level administration of servers and components using Ad-Hoc Commands. |
| Stream Compression | [XEP-0138](https://xmpp.org/extensions/xep-0138.html) | n/a | Support for optional compression of the XMPP stream.
| Data Forms Layout | [XEP-0141](https://xmpp.org/extensions/xep-0141.html) | n/a | Enables an application to specify form layouts. |
| Personal Eventing Protocol | [XEP-0163](https://xmpp.org/extensions/xep-0163.html) | n/a | Using the XMPP publish-subscribe protocol to broadcast state change events associated with an XMPP account. |
| [Jingle](jingle.html) | [XEP-0166](https://xmpp.org/extensions/xep-0166.html) | n/a | Initiate and manage sessions between two XMPP entities. |
| User Nickname | [XEP-0172](https://xmpp.org/extensions/xep-0172.html) | n/a | Communicate user nicknames. |
| Message Delivery Receipts | [XEP-0184](https://xmpp.org/extensions/xep-0184.html) | n/a | Extension for message delivery receipts. The sender can request notification that the message has been delivered. |
| [Blocking Command](blockingcommand.md) | [XEP-0191](https://xmpp.org/extensions/xep-0191.html) | n/a | Communications blocking that is intended to be simpler than privacy lists (XEP-0016). |
| XMPP Ping | [XEP-0199](https://xmpp.org/extensions/xep-0199.html) | n/a | Sending application-level pings over XML streams.
| Entity Time | [XEP-0202](https://xmpp.org/extensions/xep-0202.html) | n/a | Allows entities to communicate their local time |
| Delayed Delivery | [XEP-0203](https://xmpp.org/extensions/xep-0203.html) | n/a | Extension for communicating the fact that an XML stanza has been delivered with a delay. |
| XMPP Over BOSH | [XEP-0206](https://xmpp.org/extensions/xep-0206.html) | n/a | Use Bidirectional-streams Over Synchronous HTTP (BOSH) to transport XMPP stanzas. |
| Data Forms Media Element | [XEP-0221](https://xmpp.org/extensions/xep-0221.html) | n/a | Allows to include media data in XEP-0004 data forms. |
| Attention | [XEP-0224](https://xmpp.org/extensions/xep-0224.html) | n/a | Getting attention of another user. |
| Bits of Binary | [XEP-0231](https://xmpp.org/extensions/xep-0231.html) | n/a | Including or referring to small bits of binary data in an XML stanza. |
| Software Information | [XEP-0232](https://xmpp.org/extensions/xep-0232.html) | 0.3 | Allows an entity to provide detailed data about itself in Service Discovery responses. |
| Best Practices for Resource Locking | [XEP-0296](https://xmpp.org/extensions/xep-0296.html) | n/a | Specifies best practices to be followed by Jabber/XMPP clients about when to lock into, and unlock away from, resources. |
| Stanza Forwarding | [XEP-0297](https://xmpp.org/extensions/xep-0297.html) | n/a | Allows forwarding of Stanzas. |
| Last Message Correction | [XEP-0308](https://xmpp.org/extensions/xep-0308.html) | n/a | Provides a method for indicating that a message is a correction of the last sent message. |
| Last User Interaction in Presence | [XEP-0319](https://xmpp.org/extensions/xep-0319.html) | n/a | Communicate time of last user interaction via XMPP presence notifications. |
| Data Forms Geolocation Element | [XEP-0350](https://xmpp.org/extensions/xep-0350.html) | n/a | Allows to include XEP-0080 gelocation data in XEP-0004 data forms. |
| [Group Chat Invitations](invitation.md) | n/a | n/a | Send invitations to other users to join a group chat room. |
| [Jive Properties](properties.md) | n/a | n/a | TODO |
Experimental Smack Extensions and currently supported XEPs of smack-experimental
--------------------------------------------------------------------------------
| Name | XEP | Version | Description |
|-----------------------------------------------------------|--------------------------------------------------------|-----------|-------------------------------------------------------------------------------------------------------------------------|
| Message Carbons | [XEP-0280](https://xmpp.org/extensions/xep-0280.html) | n/a | Keep all IM clients for a user engaged in a conversation, by carbon-copy outbound messages to all interested resources. |
| [Message Archive Management](mam.md) | [XEP-0313](https://xmpp.org/extensions/xep-0313.html) | n/a | Query and control an archive of messages stored on a server. |
| Data Forms XML Element | [XEP-0315](https://xmpp.org/extensions/xep-0315.html) | n/a | Allows to include XML-data in XEP-0004 data forms. |
| [Internet of Things - Sensor Data](iot.md) | [XEP-0323](https://xmpp.org/extensions/xep-0323.html) | n/a | Sensor data interchange over XMPP. |
| [Internet of Things - Provisioning](iot.md) | [XEP-0324](https://xmpp.org/extensions/xep-0324.html) | n/a | Provisioning, access rights and user privileges for the Internet of Things. |
| [Internet of Things - Control](iot.md) | [XEP-0325](https://xmpp.org/extensions/xep-0325.html) | n/a | Describes how to control devices or actuators in an XMPP-based sensor network. |
| Jid Prep | [XEP-0328](https://xmpp.org/extensions/xep-0328.html) | 0.1 | Describes a way for an XMPP client to request an XMPP server to prep and normalize a given JID. |
| [HTTP over XMPP transport](hoxt.md) | [XEP-0332](https://xmpp.org/extensions/xep-0332.html) | n/a | Allows to transport HTTP communication over XMPP peer-to-peer networks. |
| Chat Markers | [XEP-0333](https://xmpp.org/extensions/xep-0333.html) | n/a | A solution of marking the last received, displayed and acknowledged message in a chat. |
| Message Processing Hints | [XEP-0334](https://xmpp.org/extensions/xep-0334.html) | n/a | Hints to entities routing or receiving a message. |
| JSON Containers | [XEP-0335](https://xmpp.org/extensions/xep-0335.html) | n/a | Encapsulation of JSON data within XMPP Stanzas. |
| [Internet of Things - Discovery](iot.md) | [XEP-0347](https://xmpp.org/extensions/xep-0347.html) | n/a | Describes how Things can be installed and discovered by their owners. |
| Client State Indication | [XEP-0352](https://xmpp.org/extensions/xep-0352.html) | n/a | A way for the client to indicate its active/inactive state. |
| [Push Notifications](pushnotifications.md) | [XEP-0357](https://xmpp.org/extensions/xep-0357.html) | n/a | Defines a way to manage push notifications from an XMPP Server. |
| Stable and Unique Stanza IDs | [XEP-0359](https://xmpp.org/extensions/xep-0359.html) | 0.5.0 | This specification describes unique and stable IDs for messages. |
| HTTP File Upload | [XEP-0363](https://xmpp.org/extensions/xep-0363.html) | 0.3.1 | Protocol to request permissions to upload a file to an HTTP server and get a shareable URL. |
| References | [XEP-0372](https://xmpp.org/extensions/xep-0363.html) | 0.2.0 | Add references like mentions or external data to stanzas. |
| Explicit Message Encryption | [XEP-0380](https://xmpp.org/extensions/xep-0380.html) | 0.3.0 | Mark a message as explicitly encrypted. |
| [OpenPGP for XMPP](ox.md) | [XEP-0373](https://xmpp.org/extensions/xep-0373.html) | 0.3.2 | Utilize OpenPGP to exchange encrypted and signed content. |
| [OpenPGP for XMPP: Instant Messaging](ox-im.md) | [XEP-0374](https://xmpp.org/extensions/xep-0374.html) | 0.2.0 | OpenPGP encrypted Instant Messaging. |
| [Spoiler Messages](spoiler.md) | [XEP-0382](https://xmpp.org/extensions/xep-0382.html) | 0.2.0 | Indicate that the body of a message should be treated as a spoiler. |
| [OMEMO Multi End Message and Object Encryption](omemo.md) | [XEP-0384](https://xmpp.org/extensions/xep-0384.html) | n/a | Encrypt messages using OMEMO encryption (currently only with smack-omemo-signal -> GPLv3). |
| [Consistent Color Generation](consistent_colors.md) | [XEP-0392](https://xmpp.org/extensions/xep-0392.html) | 0.6.0 | Generate consistent colors for identifiers like usernames to provide a consistent user experience. |
| [Message Markup](messagemarkup.md) | [XEP-0394](https://xmpp.org/extensions/xep-0394.html) | 0.1.0 | Style message bodies while keeping body and markup information separated. |
| DNS Queries over XMPP (DoX) | [XEP-0418](https://xmpp.org/extensions/xep-0418.html) | 0.1.0 | Send DNS queries and responses over XMPP. |
| Stanza Content Encryption | [XEP-0420](https://xmpp.org/extensions/xep-0420.html) | 0.3.0 | End-to-end encryption of arbitrary extension elements. Smack provides elements and providers to be used by encryption mechanisms. |
| Message Fastening | [XEP-0422](https://xmpp.org/extensions/xep-0422.html) | 0.1.1 | Mark payloads on a message to be logistically fastened to a previous message. |
| Message Retraction | [XEP-0424](https://xmpp.org/extensions/xep-0424.html) | 0.2.0 | Mark messages as retracted. |
| Fallback Indication | [XEP-0428](https://xmpp.org/extensions/xep-0428.html) | 0.1.0 | Declare body elements of a message as ignorable fallback for naive legacy clients. |
Unofficial XMPP Extensions
--------------------------
| Name | XEP | Version | Description |
|---------------------------------------------|--------------------------------------------------------|-----------|----------------------------------------------------------------------------------------------------------|
| [Multi-User Chat Light](muclight.md) | [XEP-xxxx](https://mongooseim.readthedocs.io/en/latest/open-extensions/xeps/xep-muc-light.html) | n/a | Multi-User Chats for mobile XMPP applications and specific environment. |
| Google GCM JSON payload | n/a | n/a | Semantically the same as XEP-0335: JSON Containers. |
Legacy Smack Extensions and currently supported XEPs of smack-legacy
--------------------------------------------------------------------
If a XEP becomes 'Deprecated' or 'Obsolete' the code will be moved to the *smack-legacy* subproject.
| Name | XEP | Version | Description |
|---------------------------------------------|--------------------------------------------------------|-----------|----------------------------------------------------------------------------------------------------------|
| [Message Events](messageevents.md) | [XEP-0022](https://xmpp.org/extensions/xep-0022.html) | n/a | Requests and responds to message events. |
| [Roster Item Exchange](rosterexchange.md) | [XEP-0093](https://xmpp.org/extensions/xep-0093.html) | n/a | Allows roster data to be shared between users. |

View File

@ -1,99 +0,0 @@
Smack Extensions Manual
Current Extensions
**Name**
**XEP #**
**Description**
[Private Data](privatedata.md)
[XEP-0049](http://www.xmpp.org/extensions/xep-0049.html)
Manages private data.
[XHTML Messages](xhtml.md)
[XEP-0071](http://www.xmpp.org/extensions/xep-0071.html)
Allows send and receiving formatted messages using XHTML.
[Message Events](messageevents.md)
[XEP-0022](http://www.xmpp.org/extensions/xep-0022.html)
Requests and responds to message events.
[Data Forms](dataforms.md)
[XEP-0004](http://www.xmpp.org/extensions/xep-0004.html)
Allows to gather data using Forms.
[Multi User Chat](muc.md)
[XEP-0045](http://www.xmpp.org/extensions/xep-0045.html)
Allows configuration of, participation in, and administration of individual
text-based conference rooms.
[Roster Item Exchange](rosterexchange.md)
[XEP-0093](http://www.xmpp.org/extensions/xep-0093.html)
Allows roster data to be shared between users.
[Time Exchange](time.md)
[XEP-0090](http://www.xmpp.org/extensions/xep-0090.html)
Allows local time information to be shared between users.
[Group Chat Invitations](invitation.md)
N/A
Send invitations to other users to join a group chat room.
[Service Discovery](disco.md)
[XEP-0030](http://www.xmpp.org/extensions/xep-0030.html)
Allows to discover services in XMPP entities.
[File Transfer](filetransfer.md)
[XEP-0096](http://www.xmpp.org/extensions/xep-0096.html)
Transfer files between two users over XMPP.
[PubSub](pubsub.md)
[XEP-0060](http://www.xmpp.org/extensions/xep-0060.html)
Generic publish and subscribe functionality.
[Entity Capabilities](caps.md)
[XEP-0115](http://www.xmpp.org/extensions/xep-0115.html)
Broadcasting and dynamic discovery of entity capabilities.
[Privacy Lists](privacy.md)
[XEP-0016](http://www.xmpp.org/extensions/xep-0016.html)
Enabling or disabling communication with other entities.
[HTTP over XMPP transport](hoxt.md)
[XEP-0332](http://www.xmpp.org/extensions/xep-0332.html)
Allows to transport HTTP communication over XMPP peer-to-peer networks.
[Jive Properties](properties.md)
N/A
TODO

View File

@ -1,43 +0,0 @@
Group Chat Invitations
======================
[Back](index.md)
The group chat invitation extension is used to invite other users to a
group chat room.
* Inviting Other Users
* Listen for Invitations
**XEP related:** N/A -- this protocol is outdated now that the Multi-User Chat (MUC) XEP is available ([XEP-45](http://www.xmpp.org/extensions/xep-0045.html)). However, most existing clients still use this older protocol. Once MUC support becomes more widespread, this API may be deprecated.
Inviting Other Users
--------------------
To use the GroupChatInvitation packet extension to invite another user to a
group chat room, address a new message to the user and set the room name
appropriately, as in the following code example:
```
Message message = new Message("user@chat.example.com", "Join me for a group chat!");
message.addExtension(new GroupChatInvitation("room@chat.example.com"));
con.sendStanza(message);
```
The XML generated for the invitation portion of the code above would be:
```
<x xmlns="jabber:x:conference" jid="room@chat.example.com"/>
```
Listening for Invitations
-------------------------
To listen for group chat invitations, use a StanzaExtensionFilter for the `x`
element name and `jabber:x:conference` namespace, as in the following code
example:
```
StanzaFilter filter = new StanzaExtensionFilter("x", "jabber:x:conference");
// Create a packet collector or packet listeners using the filter...
```

View File

@ -1,118 +0,0 @@
Internet of Things (XEP-0323, -0324, -0325, -0347)
==================================================
[Back](index.md)
The Internet of Things (IoT) XEPs are an experimental open standard how XMPP can be used for IoT. They currently consists of
- XEP-0323 Sensor Data
- XEP-0324 Provisioning
- XEP-0325 Control
- XEP-0326 Concentrators
- XEP-0347 Discovery
Smack only supports a subset of the functionality described by the XEPs!
Thing Builder
-------------
The `org.jivesoftware.smackx.iot.Thing` class acts as basic entity representing a single "Thing" which can be used to retrieve data from or to send control commands to. `Things` are constructed using a builder API.
Reading data from things
------------------------
For example, we can build a Thing which provides the current temperature with
```java
Thing dataThing = Thing.builder().setKey(key).setSerialNumber(sn).setMomentaryReadOutRequestHandler(new ThingMomentaryReadOutRequest() {
@Override
public void momentaryReadOutRequest(ThingMomentaryReadOutResult callback) {
int temp = getCurrentTemperature();
IoTDataField.IntField field = new IntField("temperature", temp);
callback.momentaryReadOut(Collections.singletonList(field));
}
}).build();
```
While not strictly required, most things are identified via a key and serial number. We also build the thing with a "momentary read out request handler" which when triggered, retrieves the current temperature and reports it back to the requestor.
After the `Thing` is built, it needs to be made available so that other entities within the federated XMPP network can use it. Right now we only install the Thing in the `IoTDataManager`, which means the thing will act on read out requests but not be managed by a provisioning server.
```java
IoTDataManager iotDataManager = IoTDataManager.getInstanceFor(connection);
iotDataManager.installThing(thing);
```
The data can be read out also by using the `IoTDataManager`:
```java
FullJid jid = …
List<IoTFieldsExtension> values = iotDataManager.requestMomentaryValuesReadOut(jid);
```
Now you have to unwrap the `IoTDataField` instances from the `IoTFieldsExtension`. Note that Smack currently only supports a subset of the specified data types.
Controlling a thing
-------------------
Things can also be controlled, e.g. to turn on a light. Let's create a thing which can be used to turn the light on and off.
```java
Thing controlThing = Thing.builder().setKey(key).setSerialNumber(sn).setControlRequestHandler(new ThingControlRequest() {
@Override
public void processRequest(Jid from, Collection<SetData> setData) throws XMPPErrorException {
for (final SetData data : setData) {
if (!data.getName().equals("light")) continue;
if (!(data instanceof SetBoolData)) continue;
SetBoolData boolData = (SetBoolData) data;
setLight(boolData.getBooleanValue());
}
}
}).build();
```
Now we have to install this thing into the `IoTControlManager`:
```java
IoTControlManager iotControlManager = IoTControlManager.getInstanceFor(connection);
iotControlManager.installThing(thing);
```
The `IoTControlManager` can also be used to control a thing:
```java
FullJid jid = …
SetData setData = new SetBoolData("light", true);
iotControlManager.setUsingIq(jid, setData);
```
Smack currently only supports a subset of the possible data types for set data.
Discovery
---------
You may have wondered how a full JIDs of things can be determined. One approach is using the discovery mechanisms specified in XEP-0347. Smack provides the `IoTDiscoveryManager` as an API for this.
For example, instead of just installing the previous things in the `IoTDataManager` and/or `IoTControlManager`, we could also use the `IoTDiscoveryManger` to register the thing with a registry. Doing this also installs the thing in the `IoTDataManager` and the `IoTControlManager`.
```java
IoTDiscoveryManager iotDiscoveryManager = IoTDiscoveryManager.getInstanceFor(connection);
iotDiscovyerManager.registerThing(thing);
```
The registry will now make the thing known to a broader audience, and available for a potential owner.
The `IoTDiscoveryManager` can also be used to claim, disown, remove and unregister a thing.
Provisioning
------------
Things can usually only be used by other things if they are friends. Since a thing normally can't decide on its own if an incoming friendship request should be granted or not, we can delegate this decision to a provisioning service. Smack provides the `IoTProvisinoManager` to deal with friendship and provisioning.
For example, if you want to befriend another thing:
```java
BareJid jid = …
IoTProvisioningManager iotProvisioningManager = IoTProvisioningManager.getInstanceFor(connection);
iotProvisioningManager.sendFriendshipRequest(jid);
```

View File

@ -1,72 +0,0 @@
Jingle
======
**XEP related:** [XEP-0116: Jingle](http://xmpp.org/extensions/xep-0166.html)
Jingle Element Structure
------------------------
```
jingle
│ action (REQUIRED, XEP-0166 § 7.2)
| content-accept
| content-add
| content-modify
| content-reject
| content-remove
| description-info
| security-info
| session-accept
| session-info
| session-initiate
| transport-accept
| transport-info
| transport-reject
| transport-replace
│ initator (RECOMMENDED for session initiate, NOT RECOMMENDED otherwise, full JID, XEP-0166 § 7.1)
│ responder (RECOMMENDED for session accept, NOT RECOMMENDED otherwise, full JID. XEP-0166 § 7.1)
│ sid (REQUIRED, SHOULD match XML Nmtoken production)
├── <reason/> (optional, XEP-0166 § 7.4)
│ │
│ └──(alternative─session│busy│..)
└── <content/> (one or more, XEP-0166 § 7.3)
│ creator (REQUIRED, must be one of)
| initiator
| responder
│ disposition (OPTIONAL)
│ name (REQUIRED)
│ senders (OPTIONAL, except when content-modify then REQUIRED)
| both (default)
| initiator
| none
| responder
├──description
│ │ media
│ │ xmlns
│ │
│ ├──payload─type
│ │
│ └──file (XEP─0234)
└──transport
│ xmlns
│ pwd (OPTIONAL, XEP-0176 Jingle ICE)
│ ufrag (OPTIONAL, XEP-0176 Jingle ICE)
│ mode (XEP-0234 Jingle File Transfer)
│ sid (XEP-0234 Jingle File Transfer)
└──candidate
component
foundation
generation
id
ip
network
port
priority
protocol
type
```

View File

@ -1,6 +0,0 @@
Message Archive Management
==========================
[Back](index.md)
See the javadoc of `MamManager` for details.

View File

@ -1,68 +0,0 @@
Message Markup
==============
[Back](index.md)
[Message Markup (XEP-0394)](https://xmpp.org/extensions/xep-0394.html) can be used as an alternative to XHTML-IM to style messages, while keeping the body and markup information strictly separated.
This implementation can *not* be used to render message bodies, but will offer a simple to use interface for creating ExtensionElements which encode the markup information.
## Usage
The most important class is the `MarkupElement` class, which contains a Builder.
To start creating a Message Markup Extension, call `MarkupElement.getBuilder()`.
(Almost) all method calls documented below will be made on the builder.
Whenever a method call receives a `start` and `end` index, `start` represents the first character, which is affected by the styling, while `end` is the character *after* the last affected character.
### Inline styling
Currently there are 3 styles available:
* *emphasis*, which should be rendered by a client as *italic*, or **bold**
* *code*, which should be rendered in `monospace`
* *deleted*, which should be rendered as ~~strikethrough~~.
Those styles are available by calling `builder.setEmphasis(int start, int end)`,
`builder.setDeleted(int start, int end)` and `builder.setCode(int start, int end)`.
If you want to apply multiple inline styles to a section, you can do the following:
```
Set<SpanElement.SpanStyle> spanStyles = new HashSet<>();
styles.add(SpanElement.SpanStyle.emphasis);
styles.add(SpanElement.SpanStyle.deleted);
builder.addSpan(start, end, spanStyles);
```
Note, that spans cannot overlap one another.
### Block Level Styling
Available block level styles are:
* Code blocks, which should be rendered as
```
blocks
of
code
```
* Itemized lists, which should render as
* Lists
* with possibly multiple
* entries
* Block Quotes, which should be rendered by the client
> as quotes, which
>> also can be nested
To mark a section as code block, call `builder.setCodeBlock(start, end)`.
To create a list, call `MarkupElement.Builder.ListBuilder lbuilder = builder.beginList()`, which will return a list builder.
On this you can call `lbuilder.addEntry(start, end)` to add an entry.
Note: If you add an entry, the start value MUST be equal to the end value of the previous added entry!
To end the list, call `lbuilder.endList()`, which will return the MessageElement builder.
To create a block quote, call `builder.setBlockQuote(start, end)`.
Note that block level elements MUST NOT overlap each other boundaries, but may be fully contained (nested) within each other.

View File

@ -1,650 +0,0 @@
Multi User Chat
===============
[Back](index.md)
Allows configuration of, participation in, and administration of individual
text-based conference rooms.
* Create a new Room
* Join a room
* Manage room invitations
* Discover MUC support
* Discover joined rooms
* Discover room information
* Start a private chat
* Manage changes on room subject
* Manage role modifications
* Manage affiliation modifications
**XEP related:** [XEP-45](http://www.xmpp.org/extensions/xep-0045.html)
For all examples in this document, assume that the following variables exists:
```java
// Create the XMPP address (JID) of the MUC.
EntityBareJid mucJid = JidCreate.bareFrom("myroom@conference.jabber.org");
// Create the nickname.
Resourcepart nickname = Resourcepart.from("testbot");
// A other use (we may invite him to a MUC).
FullJid otherJid = JidCreate.fullFrom("user3@host.org/Smack");
```
Create a new Room
-----------------
**Description**
Allowed users may create new rooms. There are two types of rooms that you can
create. **Instant rooms** which are available for immediate access and are
automatically created based on some default configuration and **Reserved
rooms** which are manually configured by the room creator before anyone is
allowed to enter.
**Usage**
In order to create a room you will need to first create an instance of
_**MultiUserChat**_.
In order to do so, get a instance of `MultiUserChatManager` and call `getMultiUserChat(String)` to retrieve a `MultiUserChat` instance.
The next step is to send **create(String nickname)** to
the _**MultiUserChat**_ instance where nickname is the nickname to use when
joining the room.
Depending on the type of room that you want to create you will have to use
different configuration forms. In order to create an Instant room just use
`MucCreateConfigFormHandle.makeInstant()`. But if you
want to create a Reserved room then you should first get the room's
configuration form, complete the form and finally send it back to the server.
**Examples**
In this example we can see how to create an instant room:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Get a MultiUserChat using MultiUserChatManager
MultiUserChat muc = manager.getMultiUserChat(mucJid);
// Create the room and send an empty configuration form to make this an instant room
muc.create(nickname).makeInstant();
```
In this example we can see how to create a reserved room. The form is
completed with default values:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat muc = manager.getMultiUserChat(mucJid);
// Prepare a list of owners of the new room
Set<Jid> owners = JidUtil.jidSetFrom(new String[] { "me@example.org", "juliet@example.org" });
// Create the room
muc.create(nickname)
.getConfigFormManger()
.setRoomOwners(owners)
.submitConfigurationForm();
```
Join a room
-----------
**Description**
Your usual first step in order to send messages to a room is to join the room.
Multi User Chat allows to specify several parameter while joining a room.
Basically you can control the amount of history to receive after joining the
room as well as provide your nickname within the room and a password if the
room is password protected.
**Usage**
In order to join a room you will need to first get an instance of
_**MultiUserChat**_.
In order to do so, get a instance of `MultiUserChatManager` and call `getMultiUserChat(String)` to retrieve a `MultiUserChat` instance.
The next step is to send **join(...)** to the
_**MultiUserChat**_ instance. But first you will have to decide which join
message to send. If you want to just join the room without a password and
without specifying the amount of history to receive then you could use
**join(String nickname)** where nickname if your nickname in the room. In case
the room requires a password in order to join you could then use **join(String
nickname, String password)**. And finally, the most complete way to join a
room is to send **join(String nickname, String password, DiscussionHistory
history, long timeout)** where nickname is your nickname in the room, ,
password is your password to join the room, history is an object that
specifies the amount of history to receive and timeout is the milliseconds to
wait for a response from the server.
**Examples**
In this example we can see how to join a room with a given nickname:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
// User2 joins the new room
// The room service will decide the amount of history to send
muc2.join(nickname);
```
In this example we can see how to join a room with a given nickname and
password:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
// User2 joins the new room using a password
// The room service will decide the amount of history to send
muc2.join(nickname, "password");
```
In this example we can see how to join a room with a given nickname specifying
the amount of history to receive:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
// User2 joins the new room using a password and specifying
// the amount of history to receive. In this example we are requesting the last 5 messages.
DiscussionHistory history = new DiscussionHistory();
history.setMaxStanzas(5);
muc2.join(nickname, "password", history, conn1.getPacketReplyTimeout());
```
Manage room invitations
-----------------------
**Description**
It can be useful to invite another user to a room in which one is an occupant.
Depending on the room's type the invitee could receive a password to use to
join the room and/or be added to the member list if the room is of type
members-only. Smack allows to send room invitations and let potential invitees
to listening for room invitations and inviters to listen for invitees'
rejections.
**Usage**
In order to invite another user to a room you must be already joined to the
room. Once you are joined just send **invite(String participant, String
reason)** to the _**MultiUserChat**_ where participant is the user to invite
to the room (e.g. hecate@shakespeare.lit) and reason is the reason why the
user is being invited.
If potential invitees want to listen for room invitations then the invitee
must add an _**InvitationListener**_ to the _**MultiUserChatManager**_ class. Since
the _**InvitationListener**_ is an _interface_, it is necessary to create a
class that implements this _interface_. If an inviter wants to listen for room
invitation rejections, just add an _**InvitationRejectionListener**_ to the
_**MultiUserChat**_. _**InvitationRejectionListener**_ is also an interface so
you will need to create a class that implements this interface.
**Examples**
In this example we can see how to invite another user to the room and lister
for possible rejections:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Create a MultiUserChat using an XMPPConnection for a room
MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
muc2.join(nickname);
// User2 listens for invitation rejections
muc2.addInvitationRejectionListener(new InvitationRejectionListener() {
public void invitationDeclined(String invitee, String reason) {
// Do whatever you need here...
}
});
// User2 invites user3 to join to the room
muc2.invite(otherJid, "Meet me in this excellent room");
```
In this example we can see how to listen for room invitations and decline
invitations:
```java
// User3 listens for MUC invitations
MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
public void invitationReceived(XMPPConnection conn, String room, EntityFullJid inviter, String reason, String password) {
// Reject the invitation
MultiUserChat.decline(conn, room, inviter.asBareJid()s, "I'm busy right now");
}
});
```
Discover MUC support
--------------------
**Description**
A user may want to discover if one of the user's contacts supports the Multi-
User Chat protocol.
**Usage**
In order to discover if one of the user's contacts supports MUC just send
**isServiceEnabled(String user)** to the
_**MultiUserChatManager**_ class where user is a fully qualified XMPP ID, e.g.
jdoe@example.com. You will receive a boolean indicating whether the user
supports MUC or not.
**Examples**
In this example we can see how to discover support of MUC:
```java
// Discover whether user3@host.org supports MUC or not
boolean supports = MultiUserChatManager.getInstanceFor(connection).isServiceEnabled(otherJid);
```
Discover joined rooms
---------------------
**Description**
A user may also want to query a contact regarding which rooms the contact is
in.
**Usage**
In order to get the rooms where a user is in just send
**getJoinedRooms(String user)** to the
_**MultiUserChatManager**_ class where user is a fully qualified XMPP ID, e.g.
jdoe@example.com. You will get an Iterator of Strings as an answer where each
String represents a room name.
**Examples**
In this example we can see how to get the rooms where a user is in:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Get the rooms where user3@host.org has joined
List<String> joinedRooms = manager.getJoinedRooms("user3@host.org/Smack");
```
Discover room information
-------------------------
**Description**
A user may need to discover information about a room without having to
actually join the room. The server will provide information only for public
rooms.
**Usage**
In order to discover information about a room just send
**getRoomInfo(String room)** to the
_**MultiUserChatManager**_ class where room is the XMPP ID of the room, e.g.
roomName@conference.myserver. You will get a RoomInfo object that contains the
discovered room information.
**Examples**
In this example we can see how to discover information about a room:
```java
// Get the MultiUserChatManager
MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
// Discover information about the room roomName@conference.myserver
RoomInfo info = manager.getRoomInfo("roomName@conference.myserver");
System.out.println("Number of occupants:" + info.getOccupantsCount());
System.out.println("Room Subject:" + info.getSubject());
```
Start a private chat
--------------------
**Description**
A room occupant may want to start a private chat with another room occupant
even though they don't know the fully qualified XMPP ID (e.g.
jdoe@example.com) of each other.
**Usage**
To create a private chat with another room occupant just send
**createPrivateChat(String participant)** to the _**MultiUserChat**_ that you
used to join the room. The parameter participant is the occupant unique room
JID (e.g. 'darkcave@macbeth.shakespeare.lit/Paul'). You will receive a regular
_**Chat**_ object that you can use to chat with the other room occupant.
**Examples**
In this example we can see how to start a private chat with another room
occupant:
```
// Start a private chat with another participant
Chat chat = muc2.createPrivateChat("myroom@conference.jabber.org/johndoe");
chat.sendMessage("Hello there");
```
Manage changes on room subject
------------------------------
**Description**
A common feature of multi-user chat rooms is the ability to change the subject
within the room. As a default, only users with a role of "moderator" are
allowed to change the subject in a room. Although some rooms may be configured
to allow a mere participant or even a visitor to change the subject.
Every time the room's subject is changed you may want to be notified of the
modification. The new subject could be used to display an in-room message.
**Usage**
In order to modify the room's subject just send **changeSubject(String
subject)** to the _**MultiUserChat**_ that you used to join the room where
subject is the new room's subject. On the other hand, if you want to be
notified whenever the room's subject is modified you should add a
_**SubjectUpdatedListener**_ to the _**MultiUserChat**_ by sending
**addSubjectUpdatedListener(SubjectUpdatedListener listener)** to the
_**MultiUserChat**_. Since the _**SubjectUpdatedListener**_ is an _interface_,
it is necessary to create a class that implements this _interface_.
**Examples**
In this example we can see how to change the room's subject and react whenever
the room's subject is modified:
```
// An occupant wants to be notified every time the room's subject is changed
muc3.addSubjectUpdatedListener(new SubjectUpdatedListener() {
public void subjectUpdated(String subject, String from) {
....
}
});
// A room's owner changes the room's subject
muc2.changeSubject("New Subject");
```
Manage role modifications
-------------------------
**Description**
There are four defined roles that an occupant can have:
1. Moderator
2. Participant
3. Visitor
4. None (the absence of a role)
These roles are temporary in that they do not persist across a user's visits
to the room and can change during the course of an occupant's visit to the
room.
A moderator is the most powerful occupant within the context of the room, and
can to some extent manage other occupants' roles in the room. A participant
has fewer privileges than a moderator, although he or she always has the right
to speak. A visitor is a more restricted role within the context of a
moderated room, since visitors are not allowed to send messages to all
occupants.
Roles are granted, revoked, and maintained based on the occupant's room
nickname or full JID. Whenever an occupant's role is changed Smack will
trigger specific events.
**Usage**
In order to grant voice (i.e. make someone a _participant_) just send the
message **grantVoice(String nickname)** to _**MultiUserChat**_. Use
**revokeVoice(String nickname)** to revoke the occupant's voice (i.e. make the
occupant a _visitor_).
In order to grant moderator privileges to a participant or visitor just send
the message **grantModerator(String nickname)** to _**MultiUserChat**_. Use
**revokeModerator(String nickname)** to revoke the moderator privilege from
the occupant thus making the occupant a participant.
Smack allows you to listen for role modification events. If you are interested
in listening role modification events of any occupant then use the listener
**_ParticipantStatusListener_**. But if you are interested in listening for
your own role modification events, use the listener **_UserStatusListener_**.
Both listeners should be added to the _**MultiUserChat**_ by using
**addParticipantStatusListener(ParticipantStatusListener listener)** or
**addUserStatusListener(UserStatusListener listener)** respectively. These
listeners include several notification events but you may be interested in
just a few of them. Smack provides default implementations for these listeners
avoiding you to implement all the interfaces' methods. The default
implementations are **_DefaultUserStatusListener_** and
**_DefaultParticipantStatusListener_**. Below you will find the sent messages
to the listeners whenever an occupant's role has changed.
These are the triggered events when the role has been upgraded:
| Old | New | Events |
|-----|-----|--------|
| None | Visitor | -- |
| Visitor | Participant | voiceGranted |
| Participant | Moderator | moderatorGranted |
| None | Participant | voiceGranted |
| None | Moderator | voiceGranted + moderatorGranted |
| Visitor | Moderator | voiceGranted + moderatorGranted |
These are the triggered events when the role has been downgraded:
| Old | New | Events |
|-----|-----|--------|
| Moderator | Participant | moderatorRevoked |
| Participant | Visitor | voiceRevoked |
| Visitor | None | kicked |
| Moderator | Visitor | voiceRevoked + moderatorRevoked |
| Moderator | None | kicked |
| Participant | None | kicked |
**Examples**
In this example we can see how to grant voice to a visitor and listen for the
notification events:
```java
// User1 creates a room
muc = manager.getMultiUserChat("myroom@conference.jabber.org");
muc.create("testbot");
// User1 (which is the room owner) configures the room as a moderated room
Form form = muc.getConfigurationForm();
FillableForm answerForm = configForm.getFillableForm();
answerForm.setAnswer("muc#roomconfig_moderatedroom", "1");
muc.sendConfigurationForm(answerForm);
// User2 joins the new room (as a visitor)
MultiUserChat muc2 = manager2.getMultiUserChat("myroom@conference.jabber.org");
muc2.join("testbot2");
// User2 will listen for his own "voice" notification events
muc2.addUserStatusListener(new DefaultUserStatusListener() {
public void voiceGranted() {
super.voiceGranted();
...
}
public void voiceRevoked() {
super.voiceRevoked();
...
}
});
// User3 joins the new room (as a visitor)
MultiUserChat muc3 = manager3.getMultiUserChat("myroom@conference.jabber.org");
muc3.join("testbot3");
// User3 will lister for other occupants "voice" notification events
muc3.addParticipantStatusListener(new DefaultParticipantStatusListener() {
public void voiceGranted(String participant) {
super.voiceGranted(participant);
...
}
public void voiceRevoked(String participant) {
super.voiceRevoked(participant);
...
}
});
// The room's owner grants voice to user2
muc.grantVoice("testbot2");
```
Manage affiliation modifications
--------------------------------
**Description**
There are five defined affiliations that a user can have in relation to a
room:
1. Owner
2. Admin
3. Member
4. Outcast
5. None (the absence of an affiliation)
These affiliations are semi-permanent in that they persist across a user's
visits to the room and are not affected by happenings in the room.
Affiliations are granted, revoked, and maintained based on the user's bare
JID.
If a user without a defined affiliation enters a room, the user's affiliation
is defined as "none"; however, this affiliation does not persist across
visits.
Owners and admins are by definition immune from certain actions. Specifically,
an owner or admin cannot be kicked from a room and cannot be banned from a
room. An admin must first lose his or her affiliation (i.e., have an
affiliation of "none" or "member") before such actions could be performed on
them.
The member affiliation provides a way for a room owner or admin to specify a
"whitelist" of users who are allowed to enter a members-only room. When a
member enters a members-only room, his or her affiliation does not change, no
matter what his or her role is. The member affiliation also provides a way for
users to effectively register with an open room and thus be permanently
associated with that room in some way (one result may be that the user's
nickname is reserved in the room).
An outcast is a user who has been banned from a room and who is not allowed to
enter the room. Whenever a user's affiliation is changed Smack will trigger
specific events.
**Usage**
In order to grant membership to a room, administrator privileges or owner
priveliges just send **grantMembership(String jid)**, **grantAdmin(String
jid)** or **grantOwnership(String jid)** to _**MultiUserChat**_ respectively.
Use **revokeMembership(String jid)**, **revokeAdmin(String jid)** or
**revokeOwnership(String jid)** to revoke the membership to a room,
administrator privileges or owner priveliges respectively.
In order to ban a user from the room just send the message **banUser(String
jid, String reason)** to _**MultiUserChat**_.
Smack allows you to listen for affiliation modification events. If you are
interested in listening affiliation modification events of any user then use
the listener **_ParticipantStatusListener_**. But if you are interested in
listening for your own affiliation modification events, use the listener
**_UserStatusListener_**. Both listeners should be added to the
_**MultiUserChat**_ by using
**addParticipantStatusListener(ParticipantStatusListener listener)** or
**addUserStatusListener(UserStatusListener listener)** respectively. These
listeners include several notification events but you may be interested in
just a few of them. Smack provides default implementations for these listeners
avoiding you to implement all the interfaces' methods. The default
implementations are **_DefaultUserStatusListener_** and
**_DefaultParticipantStatusListener_**. Below you will find the sent messages
to the listeners whenever a user's affiliation has changed.
These are the triggered events when the affiliation has been upgraded:
| Old | New | Events |
|-----|-----|--------|
| None | Member | membershipGranted |
| Member | Admin | membershipRevoked + adminGranted |
| Admin | Owner | adminRevoked + ownershipGranted |
| None | Admin | adminGranted |
| None | Owner | ownershipGranted |
| Member | Owner | membershipRevoked + ownershipGranted |
These are the triggered events when the affiliation has been downgraded:
| Old | New | Events |
|-----|-----|--------|
| Owner | Admin | ownershipRevoked + adminGranted |
| Admin | Member | adminRevoked + membershipGranted |
| Member | None | membershipRevoked |
| Owner | Member | ownershipRevoked + membershipGranted |
| Owner | None | ownershipRevoked |
| Admin | None | adminRevoked |
| _Anyone_ | Outcast | banned |
**Examples**
In this example we can see how to grant admin privileges to a user and listen
for the notification events:
```java
// User1 creates a room
muc = manager.getMultiUserChat("myroom@conference.jabber.org");
muc.create("testbot");
// User1 (which is the room owner) configures the room as a moderated room
Form form = muc.getConfigurationForm();
FillableForm answerForm = configForm.getFillableForm();
answerForm.setAnswer("muc#roomconfig_moderatedroom", "1");
muc.sendConfigurationForm(answerForm);
// User2 joins the new room (as a visitor)
MultiUserChat muc2 = manager2.getMultiUserChat("myroom@conference.jabber.org");
muc2.join("testbot2");
// User2 will listen for his own admin privileges
muc2.addUserStatusListener(new DefaultUserStatusListener() {
public void membershipRevoked() {
super.membershipRevoked();
...
}
public void adminGranted() {
super.adminGranted();
...
}
});
// User3 joins the new room (as a visitor)
MultiUserChat muc3 = manager3.getMultiUserChat("myroom@conference.jabber.org");
muc3.join("testbot3");
// User3 will lister for other users admin privileges
muc3.addParticipantStatusListener(new DefaultParticipantStatusListener() {
public void membershipRevoked(String participant) {
super.membershipRevoked(participant);
...
}
public void adminGranted(String participant) {
super.adminGranted(participant);
...
}
});
// The room's owner grants admin privileges to user2
muc.grantAdmin("user2@jabber.org");
```

View File

@ -1,358 +0,0 @@
Multi-User Chat Light
=====================
[Back](index.md)
Allows configuration of, participation in, and administration of presence­less Multi­-User Chats.
Its feature set is a response to mobile XMPP applications needs and specific environment.
* Obtain the MUC Light Manager
* Obtain a MUC Light
* Create a new Room
* Destroy a room
* Leave a room
* Change room name
* Change room subject
* Set room configurations
* Manage changes on room name, subject and other configurations
* Get room information
* Manage room occupants
* Manage occupants modifications
* Discover MUC Light support
* Get occupied rooms
* Start a private chat
* Send message to a room
* Manage blocking list
**XEP related:** [XEP-xxxx](http://mongooseim.readthedocs.io/en/latest/open-extensions/xeps/xep-muc-light.html)
Obtain the MUC Light Manager
----------------------------
```
MultiUserChatLightManager multiUserChatLightManager = MultiUserChatLightManager.getInstanceFor(connection);
```
Obtain a MUC Light
------------------
```
MultiUserChatLight multiUserChatLight = multiUserChatLightManager.getMultiUserChatLight(roomJid);
```
`roomJid` is a EntityBareJid
Create a new room
-----------------
```
multiUserChatLight.create(roomName, occupants);
```
or
```
multiUserChatLight.create(roomName, subject, customConfigs, occupants);
```
*roomName* is a `String`
*subject* is a `String`
*customConfigs* is a `HashMap<String, String>`
*occupants* is a `List<Jid>`
Destroy a room
---------------
```
multiUserChatLight.destroy();
```
Leave a room
-------------
```
multiUserChatLight.leave();
```
Change room name
----------------
```
multiUserChatLight.changeRoomName(roomName);
```
*roomName* is a `String`
Change subject
--------------
```
multiUserChatLight.changeSubject(subject);
```
*subject* is a `String`
Set room configurations
-----------------------
```
multiUserChatLight.setRoomConfigs(customConfigs);
```
or
```
multiUserChatLight.setRoomConfigs(roomName, customConfigs);
```
*customConfigs* is a `HashMap<String, String>` (which means [property name, value])
*roomName* is a `String`
Manage changes on room name, subject and other configurations
-------------------------------------------------------------
```
// check if the message is because of a configurations change
if (message.hasExtension(MUCLightElements.ConfigurationsChangeExtension.ELEMENT, MUCLightElements.ConfigurationsChangeExtension.NAMESPACE)) {
// Get the configurations extension
MUCLightElements.ConfigurationsChangeExtension configurationsChangeExtension = MUCLightElements.ConfigurationsChangeExtension.from(message);
// Get new room name
String roomName = configurationsChangeExtension.getRoomName();
// Get new subject
String subject = configurationsChangeExtension.getSubject();
// Get new custom configurations
HashMap<String, String> customConfigs = configurationsChangeExtension.getCustomConfigs();
}
```
Get room information
--------------------
**Get configurations**
```
MUCLightRoomConfiguration configuration = multiUserChatLight.getConfiguration(version);
```
*version* is a `String`
or
```
MUCLightRoomConfiguration configuration = multiUserChatLight.getConfiguration();
```
```
// Get room name
String roomName = configuration.getRoomName();
// Get subject
String subject = configuration.getSubject();
// Get custom configurations
HashMap<String, String> customConfigs = configuration.getCustomConfigs();
```
**Get affiliations**
```
HashMap<Jid, MUCLightAffiliation> affiliations = multiUserChatLight.getAffiliations(version);
```
*version* is a `String`
or
```
HashMap<Jid, MUCLightAffiliation> affiliations = multiUserChatLight.getAffiliations();
```
**Get full information**
```
MUCLightRoomInfo info = multiUserChatLight.getFullInfo(version);
```
*version* is a `String`
or
```
MUCLightRoomInfo info = multiUserChatLight.getFullInfo();
```
```
// Get version
String version = info.getVersion();
// Get room
Jid room = info.getRoom();
// Get configurations
MUCLightRoomConfiguration configuration = info.getConfiguration();
// Get occupants
HashMap<Jid, MUCLightAffiliation> occupants = info.getOccupants();
```
Manage room occupants
---------------------
To change room occupants:
```
multiUserChatLight.changeAffiliations(affiliations);
```
*affiliations* is a `HashMap<Jid, MUCLightAffiliation>`
Manage occupants modifications
------------------------------
```
// check if the message is because of an affiliations change
if (message.hasExtension(MUCLightElements.AffiliationsChangeExtension.ELEMENT, MUCLightElements.AffiliationsChangeExtension.NAMESPACE)) {
// Get the affiliations change extension
MUCLightElements.AffiliationsChangeExtension affiliationsChangeExtension = MUCLightElements.AffiliationsChangeExtension.from(message);
// Get the new affiliations
HashMap<EntityJid, MUCLightAffiliation> affiliations = affiliationsChangeExtension.getAffiliations();
}
```
Discover MUC Light support
--------------------------
**Check if MUC Light feature is supported by the server**
```
boolean isSupported = multiUserChatLightManager.isFeatureSupported(mucLightService);
```
*mucLightService* is a `DomainBareJid`
**Get MUC Light services domains**
```
List<DomainBareJid> domains = multiUserChatLightManager.getLocalServices();
```
Get occupied rooms
------------------
```
List<Jid> occupiedRooms = multiUserChatLightManager.getOccupiedRooms(mucLightService);
```
*mucLightService* is a `DomainBareJid`
Start a private chat
--------------------
```
Chat chat = multiUserChatLight.createPrivateChat(occupant, listener);
```
*occupant* is a `EntityJid`
*listener* is a `ChatMessageListener`
Send message to a room
----------------------
**Create message for an specific MUC Light**
```
Message message = multiUserChatLight.createMessage();
```
**Send a message to an specific MUC Light**
```
multiUserChatLight.sendMessage(message);
```
*message* is a `Message`
Manage blocking list
--------------------
**Get blocked list**
```
// Get users and rooms blocked
List<Jid> jids = multiUserChatLightManager.getUsersAndRoomsBlocked(mucLightService);
// Get rooms blocked
List<Jid> jids = multiUserChatLightManager.getRoomsBlocked(mucLightService);
// Get users blocked
List<Jid> jids = multiUserChatLightManager.getUsersBlocked(mucLightService);
```
*mucLightService* is a `DomainBareJid`
**Block rooms**
```
// Block one room
multiUserChatLightManager.blockRoom(mucLightService, roomJid);
// Block several rooms
multiUserChatLightManager.blockRooms(mucLightService, roomsJids);
```
*mucLightService* is a `DomainBareJid`
*roomJid* is a `Jid`
*roomsJids* is a `List<Jid>`
**Block users**
```
// Block one user
multiUserChatLightManager.blockUser(mucLightService, userJid);
// Block several users
multiUserChatLightManager.blockUsers(mucLightService, usersJids);
```
*mucLightService* is a `DomainBareJid`
*userJid* is a `Jid`
*usersJids* is a `List<Jid>`
**Unblock rooms**
```
// Unblock one room
multiUserChatLightManager.unblockRoom(mucLightService, roomJid);
// Unblock several rooms
multiUserChatLightManager.unblockRooms(mucLightService, roomsJids);
```
*mucLightService* is a `DomainBareJid`
*roomJid* is a `Jid`
*roomsJids* is a `List<Jid>`
**Unblock users**
```
// Unblock one user
multiUserChatLightManager.unblockUser(mucLightService, userJid);
// Unblock several users
multiUserChatLightManager.unblockUsers(mucLightService, usersJids);
```
*mucLightService* is a `DomainBareJid`
*userJid* is a `Jid`
*usersJids* is a `List<Jid>`

View File

@ -1,297 +0,0 @@
Encrypting messages with OMEMO
==============================
[Back](index.md)
About OMEMO
-----------
OMEMO ([XEP-0384](https://xmpp.org/extensions/xep-0384.html)) is an adaption
of the Signal protocol for XMPP. It provides an important set of
cryptographic properties including but not restricted to
* Confidentiality
* Integrity
* Authenticity
* Forward secrecy
* Future secrecy (break-in recovery)
* Plausible deniability
Contrary to OTR it is capable of multi-end-to-multi-end encryption and
message synchronization across multiple devices. It also allows the sender
to send a message while the recipient is offline.
It does NOT provide a server side message archive, so that a new device could
fetch old chat history.
Most implementations of OMEMO use the signal-protocol libraries provided by
OpenWhisperSystems. Unlike Smack, those libraries are licensed under the GPLv3,
which prevents a Apache licensed OMEMO implementation using those libraries (see
[licensing situation](https://github.com/igniterealtime/Smack/wiki/OMEMO-libsignal-Licensing-Situation)).
The module smack-omemo therefore contains no code related to signal-protocol.
However, almost all functionality is encapsulated in that module. If you want
to use OMEMO in a GPLv3 licensed client, you can use the smack-omemo-signal
Smack module, which binds the signal-protocol library to smack-omemo.
It is also possible, to port smack-omemo to other libraries implementing the
double ratchet algorithm.
Understanding the Double Ratchet Algorithm
------------------------------------------
In the context of OMEMO encryption, a *recipient* is a not a user, but a users *device* (a user might have
multiple devices of course).
Unlike in PGP, each device capable of OMEMO has its own identity key and publishes its own key bundle.
It is not advised to migrate OMEMO identities from one device to another, as it might damage the ratchet
if not done properly (more on that later). Sharing one identity key between multiple devices is not the purpose of
OMEMO. If a contact has three OMEMO capable devices, you will see three different OMEMO identities and their
fingerprints.
OMEMO utilizes multiple layers of encryption when encrypting a message.
The body of the message is encrypted with a symmetric message key (AES-128-GCM) producing a *payload*.
The message key is encrypted for each recipient using the double ratchet algorithm.
For that purpose, the sending device creates a session with the recipient device (if there was no session already).
Upon receiving a message, the recipient selects the encrypted key addressed to them and decrypts it with their
counterpart of the OMEMO session. The decrypted key gets then used to decrypt the message.
One important consequence of forward secrecy is, that whenever an OMEMO message gets decrypted,
the state of the ratchet changes and the key used to decrypt the message gets deleted.
There is no way to recover this key a second time. The result is, that every message can be decrypted
exactly once.
In order to provide the best user experience, it is therefore advised to implement a client side message archive,
since solutions like MAM cannot be used to fetch old, already once decrypted OMEMO messages.
Server-side Requirements
------------------------
In order to use OMEMO encryption, your server and the servers of your chat
partners must support PEP ([XEP-0163](http://xmpp.org/extensions/xep-0163.html))
to store and exchange key bundles.
Optionally your server should support Message Carbons ([XEP-0280](http://xmpp.org/extensions/xep-0280.html))
and Message Archive Management ([XEP-0313](http://xmpp.org/extensions/xep-0313.html))
to achieve message synchronization across all (on- and offline) devices.
Client-side Requirements
------------------------
If you are want to run smack-omemo related code on the Windows platform, you might have to install the
[Java Cryptography Extension](http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html).
This is needed to generate cryptographically strong keys.
Storing Keys
------------
smack-omemo needs to create, store and delete some information like keys and session states during operation.
For that purpose the `OmemoStore` class is used. There are multiple implementations with different properties.
* The `(Signal)FileBasedOmemoStore` stores all information in individual files organized in a directory tree.
While this is the most basic and easy to use implementation, it is not the best solution in terms of performance.
* The `(Signal)CachingOmemoStore` is a multi-purpose store implementation. It can be used to wrap another
`(Signal)OmemoStore` implementation to provide a caching layer (for example in order to reduce access to a database backend or
a the file system of the `FileBasedOmemoStore`. It is therefore advised to wrap persistent `(Signal)OmemoStore`
implementations with a `(Signal)CachingOmemoStore`.
On the other hand it can also be used standalone as an ephemeral `OmemoStore`, which "forgets" all stored information
once the program terminates. This comes in handy for testing purposes.
If you are unhappy with the `(Signal)FileBasedOmemoStore`, you can implement your own store (for example with a
SQL database) by extending the `(Signal)OmemoStore` class.
It most certainly makes sense to store the data of the used `OmemoStore` in a secure way (for example an
encrypted database).
Handling Trust Decisions
------------------------
In order for a cryptographic system to make sense, decisions must be made whether to *trust* an identity or not.
For technical reasons those decisions cannot be stored within the `OmemoStore`. Instead a client must implement
the `OmemoTrustCallback`. This interface provides methods to mark `OmemoFingerprints` as trusted or untrusted and to
query trust decisions.
In order to provide security, a client should communicate to the user, that it is important for them to compare
fingerprints through an external channel (reading it out on the phone, scanning QR codes...) before starting to chat.
While not implemented in smack-omemo, it is certainly for the client to implement different trust models like
[Blind Trust Before Verification](https://gultsch.de/trust.html).
Basic Setup
-----------
Before you can start to send and receive messages, some preconditions have to be met. These steps should be executed
in the order as presented below. In this example we will use components from the *smack-omemo-signal* module.
1. Register an OmemoService
The `OmemoService` class is responsible for handling incoming messages and manages access to the Double Ratchet.
```
SignalOmemoService.setup();
```
The `setup()` method registers the service as a singleton. You can later access the instance
by calling `SignalOmemoService.getInstace()`. The service can only be registered once.
Subsequent calls will throw an `IllegalStateException`.
2. Set an OmemoStore
Now you have to decide, what `OmemoStore` implementation you want to use to store and access
keys and session states. In this example we'll use the `SignalFileBasedOmemoStore` wrapped in a
`SignalCachingOmemoStore` for better performance.
```
SignalOmemoService service = SignalOmemoService.getInstace();
service.setOmemoStoreBackend(new SignalCachingOmemoStore(new SignalFileBasedOmemoStore(new File("/path/to/store"))));
```
Just like the `OmemoService` instance, the `OmemoStore` instance can only be set once.
3. Get an instance of the OmemoManager for your connection
For the greater part of OMEMO related actions, you'll use the `OmemoManager`. The `OmemoManager` represents
your OMEMO device. While it is possible to have multiple `OmemoManager`s per `XMPPConnection`, you really
only need one.
```
OmemoManager manager = OmemoManager.getInstanceFor(connection);
```
If for whatever reason you decide to use multiple `OmemoManager`s at once,
it is highly advised to get them like this:
```
OmemoManager first = OmemoManager.getInstanceFor(connection, firstId);
OmemoManager second = OmemoManager.getInstanceFor(connection, secondId);
```
4. Set an OmemoTrustCallback
As stated above, the `OmemoTrustCallback` is used to query trust decisions. Set the callback like this:
```
manager.setTrustCallback(trustCallback);
```
If you use multiple `OmemoManager`s each `OmemoManager` MUST have its own callback.
5. Set listeners for OMEMO messages.
To get notified of incoming OMEMO encrypted messages, you need to register corresponding listeners.
There are two types of listeners.
* `OmemoMessageListener` is used to listen for incoming encrypted OMEMO single chat messages and
KeyTransportMessages.
* `OmemoMucMessageListener` is used to listen for encrypted OMEMO messages sent in a MultiUserChat.
Note that an incoming message might not have a body. That might be the case for
[KeyTransportMessages](https://xmpp.org/extensions/xep-0384.html#usecases-keysend)
or messages sent to update the ratchet. You can check, whether a received message is such a message by calling
`OmemoMessage.Received.isKeyTransportMessage()`, which will return true if the message has no body.
The received message will include the senders device and fingerprint, which you can use in
`OmemoManager.isTrustedOmemoIdentity(device, fingerprint)` to determine, if the message was sent by a trusted device.
6. Initialize the manager(s)
Ideally all above steps should be executed *before* `connection.login()` gets called. That way you won't miss
any offline messages. If the connection is not yet logged in, now is the time to do so.
```
connection.login();
manager.initialize();
```
Since a lot of keys are generated in this step, this might take a little longer on older devices.
You might want to use the asynchronous call `OmemoManager.initializeAsync(initializationFinishedCallback)`
instead to prevent the thread from blocking.
Send Messages
-------------
Encrypting a message for a contact really means to encrypt the message for all trusted devices of the contact, as well
as all trusted devices of the user itself (except the sending device). The encryption process will fail if there are
devices for which the user has not yet made a trust decision.
### Make Trust Decisions
To get a list of all devices of a contact, you can do the following:
```
List<OmemoDevice> devices = manager.getDevicesOf(contactsBareJid);
```
To get the OmemoFingerprint of a device, you can call
```
OmemoFingerprint fingerprint = manager.getFingerprint(device);
```
This fingerprint can now be displayed to the user who can decide whether to trust the device, or not.
```
// Trust
manager.trustOmemoIdentity(device, fingerprint);
// Distrust
manager.distrustOmemoIdentity(device, fingerprint);
```
### Encrypt a Message
Currently only Message bodies can be encrypted.
```
String secret = "Mallory is a twerp!";
OmemoMessage.Sent encrypted = manager.encrypt(contactsBareJid, secret);
```
The encrypted message will contain some information about the message. It might for example happen, that the encryption
failed for some recipient devices. For that reason the encrypted message will contain a map of skipped devices and
the reasons.
### Encrypt a Message for a MultiUserChat
A MultiUserChat must fulfill some criteria in order to be OMEMO capable.
The MUC must be non-anonymous. Furthermore all members of the MUC must have subscribed to one another.
You can check for the non-anonymity like follows:
```
manager.multiUserChatSupportsOmemo(muc);
```
Encryption is then done analog to single message encryption:
```
OmemoMessage.Sent encrypted = manager.encrypt(multiUserChat, secret);
```
### Sending an encrypted Message
To send the message, it has to be wrapped in a `Message` object. That can conveniently be done like follows.
```
Message message = encrypted.asMessage(contactsJid);
connection.sendStanza(message):
```
This will add a [Message Processing Hint](https://xmpp.org/extensions/xep-0334.html) for MAM,
an [Explicit Message Encryption](https://xmpp.org/extensions/xep-0380.html) hint for OMEMO,
as well as an optional cleartext hint about OMEMO to the message.
Configuration
-------------
smack-omemo has some configuration options that can be changed on runtime via the `OmemoConfiguration` class:
* setIgnoreStaleDevices when set to true, smack-omemo will stop encrypting messages for **own** devices that have not send a message for some period of time (configurable in setIgnoreStaleDevicesAfterHours)
* setDeleteStaleDevices when set to true, smack-omemo will remove own devices from the device list, if no messages were received from them for a period of time (configurable in setDeleteStaleDevicesAfterHours)
* setRenewOldSignedPreKeys when set to true, smack-omemo will periodically generate and publish new signed prekeys. Via setRenewOldSignedPreKeysAfterHours you can configure, after what period of time new keys are generated and setMaxNumberOfStoredSignedPreKeys allows configuration of how many signed PreKeys are kept in storage for decryption of delayed messages.
* setAddOmemoBodyHint when set to true, a plaintext body with a hint about OMEMO encryption will be added to the message. This hint will be displayed by clients that do not support OMEMO. Note that this might not be desirable when communicating with clients that do not support EME.
* setRepairBrokenSessionsWithPreKeyMessages when set to true, whenever a message arrives, which cannot be decrypted, smack-omemo will respond with a preKeyMessage which discards the old session and builds a fresh one.
* setCompleteSessionWithEmptyMessage when set to true, whenever a preKeyMessage arrives, smack-omemo will respond with an empty message to complete the session.
Integration Tests
-----------------
smack-omemo comes with a set of integration tests. Lets say you want to run the integration test suite for smack-omemo-signal.
You can do so by using the following gradle task:
```
gradle omemoSignalIntTest
```

View File

@ -1,43 +0,0 @@
Migrating smack-omemo from 4.2.1 to 4.x.x
=========================================
The implementation of smack-omemo and smack-omemo-signal was originally started as an
academic project under pressure of time.
For that reason, the API was not perfect when OMEMO support was first introduced in
Smack in version 4.2.1.
Many issues of smack-omemo have been resolved over the course of the last year in
a major effort, which is why smack-omemo and smack-omemo-signalwere excluded from
the 4.2.2 release.
During this time major parts of the implementation were redone and the API changed
as a consequence of that. This guide will go through all notable changes in order
to make the process of upgrading as easy and straight forward as possible.
## Trust
One major change is, that the OmemoStore implementations no longer store trust decisions.
Methods related to trust have been removed from OmemoStore implementations.
Instead the client is now responsible to store those.
Upon startup, the client now must pass an `OmemoTrustCallback` to the `OmemoManager`
which is used to access and change trust decisions.
It is recommended for the client to store trust decisions as tuples of (omemo device,
fingerprint of identityKey, trust state).
When querying a trust decision (aka. "Is this fingerprint trusted for that device?),
the local fingerprint should be compared to the provided fingerprint.
The method signatures for setting and querying trust from inside the OmemoManager are
still the same. Internally they access the `OmemoTrustCallback` set by the client.
## Encryption
Message encryption in smack-omemo 4.2.1 was ugly. Encryption for multiple devices
could fail because session negotiation could go wrong, which resulted in an
exception, which contained all devices with working sessions.
That exception could then be used in
`OmemoManager.encryptForExistingSessions(CannotEstablishOmemoSessionException exception, String message)`,
to encrypt the message for all devices with a session.
The new API is

View File

@ -1,6 +0,0 @@
OpenPGP for XMPP: Instant Messaging
===================================
[Back](index.md)
See the javadoc of `OpenPgpManager` and `OXInstantMessagingManager` for details.

View File

@ -1,6 +0,0 @@
OpenPGP for XMPP
================
[Back](index.md)
See the javadoc of `OpenPgpManager` for details.

View File

@ -1,141 +0,0 @@
Privacy Lists
============
[Back](index.md)
[XEP-0016: Privacy Lists](http://xmpp.org/extensions/xep-0016.html)
What is it?
-----------
`Privacy` is a method for users to block communications from particular other
users. In XMPP this is done by managing one's privacy lists.
Server-side privacy lists enable successful completion of the following use
cases:
* Retrieving one's privacy lists.
* Adding, removing, and editing one's privacy lists.
* Setting, changing, or declining active lists.
* Setting, changing, or declining the default list (i.e., the list that is active by default).
* Allowing or blocking messages based on JID, group, or subscription type (or globally).
* Allowing or blocking inbound presence notifications based on JID, group, or subscription type (or globally).
* Allowing or blocking outbound presence notifications based on JID, group, or subscription type (or globally).
* Allowing or blocking IQ stanzas based on JID, group, or subscription type (or globally).
* Allowing or blocking all communications based on JID, group, or subscription type (or globally).
How can I use it?
-----------------
The API implementation releases three main public classes:
* `PrivacyListManager`: this is the main API class to retrieve and handle server privacy lists.
* `PrivacyList`: witch represents one privacy list, with a name, a set of privacy items. For example, the list with visible or invisible.
* `PrivacyItem`: block or allow one aspect of privacy. For example, to allow my friend to see my presence.
1. Right from the start, a client MAY **get his/her privacy list** that is stored in the server:
```
// Create a privacy manager for the current connection._
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
// Retrieve server privacy lists_
PrivacyList[] lists = privacyManager.getPrivacyLists();
```
Now the client is able to show every `PrivacyItem` of the server and also for
every list if it is active, default or none of them. The client is a listener
of privacy changes.
2. In order to **add a new list in the server**, the client MAY implement something like:
```
// Set the name of the list_
String listName = "newList";
// Create the list of PrivacyItem that will allow or deny some privacy aspect_
String user = "tybalt@example.com";
String groupName = "enemies";
ArrayList privacyItems = new ArrayList();
PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid, user, true, 1);
privacyItems.add(item);
item = new PrivacyItem(PrivacyItem.Type.subscription, PrivacyItem.SUBSCRIPTION_BOTH, true, 2);
privacyItems.add(item);
item = new PrivacyItem(PrivacyItem.Type.group, groupName, false, 3);
item.setFilterMessage(true);
privacyItems.add(item);
// Get the privacy manager for the current connection._
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
// Create the new list._
privacyManager.createPrivacyList(listName, privacyItems);
```
3. To **modify an existent list**, the client code MAY be like:
```
// Set the name of the list_
String listName = "existingList";
// Get the privacy manager for the current connection._
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
// Sent the new list to the server._
privacyManager.updatePrivacyList(listName, items);
```
Notice `items` was defined at the example 2 and MUST contain all the elements
in the list (not the "delta").
4. In order to **delete an existing list**, the client MAY perform something like:
```
// Set the name of the list_
String listName = "existingList";
// Get the privacy manager for the current connection._
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
// Remove the list._
privacyManager.deletePrivacyList(listName);
```
5. In order to **decline the use of an active list**, the client MAY perform something like:
```
// Get the privacy manager for the current connection._
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
// Decline the use of the active list._
privacyManager.declineActiveList();
```
6. In order to **decline the use of a default list**, the client MAY perform something like:
```
// Get the privacy manager for the current connection._
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
// Decline the use of the default list._
privacyManager.declineDefaultList();
```
Listening for Privacy Changes
In order to handle privacy changes, clients SHOULD listen manager's updates.
When a list is changed the manager notifies every added listener. Listeners
MUST implement the `PrivacyListListener` interface. Clients may need to react
when a privacy list is modified. The `PrivacyListManager` lets you add
listerners that will be notified when a list has been changed. Listeners
should implement the `PrivacyListListener` interface.
The most important notification is `updatedPrivacyList` that is performed when
a privacy list changes its privacy items.
The listener becomes notified after performing:
```
// Get the privacy manager for the current connection._
PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
// Add the listener (this) to get notified_
privacyManager.addListener(this);
```
Copyright (C) Jive Software 2002-2008

View File

@ -1,19 +0,0 @@
Private Data
============
[Back](index.md)
Manages private data, which is a mechanism to allow users to store arbitrary
XML data on an XMPP server. Each private data chunk is defined by a element
name and XML namespace. Example private data:
```
<color xmlns="http://example.com/xmpp/color">
<favorite>blue</blue>
<leastFavorite>puce</leastFavorite>
</color>
```
**XEP related:** [XEP-49](http://www.xmpp.org/extensions/xep-0049.html)
_More coming soon._

View File

@ -1,85 +0,0 @@
Stanza Properties
=================
[Back](index.md)
Smack provides an easy mechanism for attaching arbitrary properties to
packets. Each property has a String name, and a value that is a Java primitive
(int, long, float, double, boolean) or any Serializable object (a Java object
is Serializable when it implements the Serializable interface).
Using the API
-------------
All major objects have property support, such as Message objects. The
following code demonstrates how to set properties:
```
Message message = chat.createMessage();
JivePropertiesExtension jpe = new JivePropertiesExtension();
// Add a Color object as a property._
jpe.setProperty("favoriteColor", new Color(0, 0, 255));
// Add an int as a property._
jpe.setProperty("favoriteNumber", 4);
// Add the JivePropertiesExtension to the message packet_
message.addStanzaExtension(jpe);
chat.sendMessage(message);
```
Getting those same properties would use the following code:
```
Message message = chat.nextMessage();
// Get the JivePropertiesExtension_
JivePropertiesExtension jpe = message.getExtension(JivePropertiesExtension.NAMESPACE);
// Get a Color object property._
Color favoriteColor = (Color)jpe.getProperty("favoriteColor");
// Get an int property. Note that properties are always returned as
// Objects, so we must cast the value to an Integer, then convert
// it to an int._
int favoriteNumber = ((Integer)jpe.getProperty("favoriteNumber")).intValue();
```
For convenience `JivePropertiesManager` contains two helper methods namely
`addProperty(Stanza packet, String name, Object value)` and
`getProperty(Stanza packet, String name)`.
Objects as Properties
---------------------
Using objects as property values is a very powerful and easy way to exchange
data. However, you should keep the following in mind:
* When you send a Java object as a property, only clients running Java will be able to interpret the data. So, consider using a series of primitive values to transfer data instead.
* Objects sent as property values must implement Serialiable. Additionally, both the sender and receiver must have identical versions of the class, or a serialization exception will occur when de-serializing the object.
* Serialized objects can potentially be quite large, which will use more bandwidth and server resources.
XML Format
----------
The current XML format used to send property data is not a standard, so will
likely not be recognized by clients not using Smack. The XML looks like the
following (comments added for clarity):
<!-- All properties are in a x block. -->
<properties xmlns="http://www.jivesoftware.com/xmlns/xmpp/properties">
<!-- First, a property named "prop1" that's an integer. -->
<property>
<name>prop1</name>
<value type="integer">123</value>
<property>
<!-- Next, a Java object that's been serialized and then converted
from binary data to base-64 encoded text. -->
<property>
<name>blah2</name>
<value type="java-object">adf612fna9nab</value>
<property>
</properties>
The currently supported types are: `integer`, `long`, `float`, `double`,
`boolean`, `string`, and `java-object`.
Copyright (C) Jive Software 2002-2008

View File

@ -1,404 +0,0 @@
Pubsub
======
[Back](index.md)
This section details the usage of an API designed for accessing an XMPP based
implementation of a [publish and
subscribe](http://en.wikipedia.org/wiki/Publish/subscribe) based messaging
system. It has functionality for creation, configuration of, subscription and
publishing to pubsub nodes.
* Node creation and configuration
* Publishing to a node
* Receiving pubsub messages
* Retrieving persisted pubsub messages
* Discover pubsub information
**XEP related:** [XEP-0060](http://xmpp.org/extensions/xep-0060.html)
Node creation and configuration
-------------------------------
### Description
Allowed users may create and configure pubsub nodes. There are two types of
nodes that can be created, leaf nodes and collection nodes.
* Leaf Nodes - contains only messages
* Collection Nodes - contains only nodes (both Leaf and Collection are allowed), but no messages
The current version of this API only supports Leaf Nodes. There are many
configuration options available for nodes, but the two main options are
whether the node is **persistent** or not and whether it will deliver payload
or not.
### Usage
In order to create a node you will need to first create an instance of
_**PubSubManager**_. There are several options for node creation which range
from creating an instant node, default configuration, or a fully configured
node.
### Examples
Create an instant node:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = new PubSubManager(con);
// Create the node
LeafNode leaf = mgr.createNode();
```
Create a node with default configuration and then configure it:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Create the node
LeafNode leaf = mgr.createNode("testNode");
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(false);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
leaf.sendConfigurationForm(form);
```
Create and configure a node:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Create the node
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(false);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
LeafNode leaf = mgr.createNode("testNode", form);
```
Publishing to a node
--------------------
**Description**
This section deals with the **publish** portion of pubsub. Usage of a node
typically involves either sending or receiving data, referred to as items.
Depending on the context of the nodes usage, the item being sent to it can
have different properties. It can contain application data known as payload,
or the publisher may choose to supply meaningful unique id's. Determination of
an items acceptable properties is defined by a combination of node
configuration and its purpose.
**Usage**
To publish to a node, you will have to either create or retrieve an existing
node and then create and send items to that node. The ability for any given
person to publish to the node will be dependent on its configuration.
**Examples**
In this example we publish an item to a node that does not take payload:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
LeafNode node = mgr.getNode("testNode");
// Publish an Item, let service set the id
node.send(new Item());
// Publish an Item with the specified id
node.send(new Item("123abc"));
```
In this example we publish an item to a node that does take payload:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
LeafNode node = mgr.getNode("testNode");
// Publish an Item with payload
node.send(new PayloadItem("test" + System.currentTimeMillis(),
new SimplePayload("book", "pubsub:test:book", "Two Towers")));
```
Receiving pubsub messages
-------------------------
**Description**
This section deals with the **subscribe** portion of pubsub. As mentioned in
the last section, usage of a node typically involves either sending or
receiving items. Subscribers are interested in being notified when items are
published to the pubsub node. These items may or may not have application
specific data (payload), as that is dependent on the context in which the node
is being used.
**Usage**
To get messages asynchronously when items are published to a node, you will
have to
* Get a node.
* Create and register a listener.
* Subscribe to the node.
Please note that you should register the listener before subscribing so that
all messages sent after subscribing are received. If done in the reverse
order, messages that are sent after subscribing but before registering a
listener may not be processed as expected.
**Examples**
In this example we can see how to create a listener and register it and then
subscribe for messages.
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
LeafNode node = mgr.getNode("testNode");
node.addItemEventListener(new ItemEventCoordinator&ltItem;>());
node.subscribe(myJid);
```
Where the listener is defined like so:
```
class ItemEventCoordinator implements ItemEventListener {
@Override
public void handlePublishedItems(ItemPublishEvent items) {
System.out.println("Item count: " + System.out.println(items);
}
}
```
In addition to receiving published items, there are notifications for several
other events that occur on a node as well.
* Deleting items or purging all items from a node
* Changing the node configuration
In this example we can see how to create a listener, register it and then
subscribe for item deletion messages.
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
LeafNode node = mgr.getNode("testNode");
node.addItemDeleteListener(new ItemDeleteCoordinator&ltItem;>());
node.subscribe(myJid);
node.deleteItem("id_one");
```
Where the handler is defined like so:
```
class ItemDeleteCoordinator implements ItemDeleteListener {
@Override
public void handleDeletedItems(ItemDeleteEvent items) {
System.out.println("Item count: " + items.getItemIds().size());
System.out.println(items);
}
@Override
public void handlePurge() {
System.out.println("All items have been deleted from node");
}
}
```
In this example we can see how to create a listener, register it and then
subscribe for node configuration messages.
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
Node node = mgr.getNode("testNode");
node.addConfigurationListener(new NodeConfigCoordinator());
node.subscribe(myJid);
ConfigureForm form = new ConfigureForm(FormType.submit);
form.setAccessModel(AccessModel.open);
form.setDeliverPayloads(false);
form.setNotifyRetract(true);
form.setPersistentItems(true);
form.setPublishModel(PublishModel.open);
node.sendConfigurationForm(form);
```
Where the handler is defined like so:
```
class NodeConfigCoordinator implements NodeConfigListener {
@Override
public void handleNodeConfiguration(ConfigurationEvent config) {
System.out.println("New configuration");
System.out.println(config.getConfiguration());
}
}
```
Retrieving persisted pubsub messages
------------------------------------
**Description**
When persistent nodes are used, the subscription and registration methods
described in the last section will not enable the retrieval of items that
already exist in the node. This section deals with the specific methods for
retrieving these items. There are several means of retrieving existing items.
You can retrieve all items at once, the last N items, or the items specified
by a collection of id's. Please note that the service may, according to the
pubsub specification, reply with a list of items that contains only the item
id's (no payload) to save on bandwidth. This will not occur when the id's are
specified since this is the means of guaranteeing retrieval of payload.
**Usage**
To synchronously retrieve existing items from a persistent node, you will have
to get an instance of a _**LeafNode**_ and call one of the retrieve methods.
**Examples**
In this example we can see how to retrieve the existing items from a node:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
LeafNode node = mgr.getNode("testNode");
Collection<? extends Item> items = node.getItems();
```
In this example we can see how to retrieve the last N existing items:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
LeafNode node = mgr.getNode("testNode");
List<? extends Item> items = node.getItems(100);
```
In this example we can see how to retrieve the specified existing items:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the node
LeafNode node = mgr.getNode("testNode");
Collection&ltString;> ids = new ArrayList&ltString;>(3);
ids.add("1");
ids.add("3");
ids.add("4");
List<? extends Item> items = node.getItems(ids);
```
Discover pubsub information
---------------------------
**Description**
A user may want to query a server or node for a variety of pubsub related
information.
**Usage**
To retrieve information, a user will simply use either the _**PubSubManager**_
or _**Node**_ classes depending on what type of information is required.
**Examples**
In this example we can see how to get pubsub capabilities:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the pubsub features that are supported
DiscoverInfo supportedFeatures = mgr.getSupportedFeatures();
```
In this example we can see how to get pubsub subscriptions for all nodes:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get all the subscriptions in the pubsub service
List&ltSubscription;> subscriptions = mgr.getSubscriptions();
```
In this example we can see how to get all affiliations for the users bare JID
on the pubsub service:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
// Get the affiliations for the users bare JID
List&ltAffiliation;> affiliations = mgr.getAffiliations();
```
In this example we can see how to get information about the node:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
Node node = mgr.getNode("testNode");
// Get the node information
DiscoverInfo nodeInfo = node.discoverInfo();
```
In this example we can see how to discover the node items:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
Node node = mgr.getNode("testNode");
// Discover the node items
DiscoverItems nodeItems = node.discoverItems();
```
In this example we can see how to get node subscriptions:
```
// Create a pubsub manager using an existing XMPPConnection
PubSubManager mgr = PubSubManager.getInstanceFor(con);
Node node = mgr.getNode("testNode");
// Discover the node subscriptions
List&ltSubscription;> subscriptions = node.getSubscriptions();
```

View File

@ -1,84 +0,0 @@
Push Notifications
==================
[Back](index.md)
Allows to manage how XMPP servers deliver information for use in push notifications to mobile and other devices.
* Check push notifications support
* Enable push notifications
* Disable push notifications
* Remote disabling of push notifications
**XEP related:** [XEP-0357](http://xmpp.org/extensions/xep-0357.html)
Get push notifications manager
------------------------------
```
PushNotificationsManager pushNotificationsManager = PushNotificationsManager.getInstanceFor(connection);
```
Check push notifications support
--------------------------------
```
boolean isSupported = pushNotificationsManager.isSupportedByServer();
```
Enable push notifications
-----------------------
```
pushNotificationsManager.enable(pushJid, node);
```
or
```
pushNotificationsManager.enable(pushJid, node, publishOptions);
```
*pushJid* is a `Jid`
*node* is a `String`
*publishOptions* is a `HashMap<String, String>` (which means [option name, value])
Disable push notifications
--------------------------
```
pushNotificationsManager.disable(pushJid, node);
```
*pushJid* is a `Jid`
*node* is a `String`
**Disable all**
```
pushNotificationsManager.disableAll(pushJid);
```
*pushJid* is a `Jid`
Remote disabling of push notifications
--------------------------------------
```
// check if the message is because remote disabling of push notifications
if (message.hasExtension(PushNotificationsElements.RemoteDisablingExtension.ELEMENT, PushNotificationsElements.RemoteDisablingExtension.NAMESPACE)) {
// Get the remote disabling extension
PushNotificationsElements.RemoteDisablingExtension remoteDisablingExtension = PushNotificationsElements.RemoteDisablingExtension.from(message);
// Get the user Jid
Jid userJid = remoteDisablingExtension.getUserJid();
// Get the node
String node = remoteDisablingExtension.getNode();
}
```

View File

@ -1,19 +0,0 @@
References
==========
[Back](index.md)
References are a way to refer to other entities like users, other messages or external data from within a message.
Typical use-cases are mentioning other users by name, but referencing to their BareJid, or linking to a sent file.
## Usage
Mention a user and link to their bare jid.
```
Message message = new Message("Alice is a realy nice person.");
BareJid alice = JidCreate.bareFrom("alice@capulet.lit");
ReferenceManager.addMention(message, 0, 5, alice);
```
TODO: Add more use cases (for example for MIX, SIMS...)

View File

@ -1,162 +0,0 @@
Roster Item Exchange
====================
[Back](index.md)
This extension is used to send rosters, roster groups and roster entries from
one XMPP Entity to another. It also provides an easy way to hook up custom
logic when entries are received from other XMPP clients.
Follow these links to learn how to send and receive roster items:
* Send a complete roster
* Send a roster's group
* Send a roster's entry
* Receive roster entries
**XEP related:** [XEP-93](http://www.xmpp.org/extensions/xep-0093.html)
Send a entire roster
-------------------
**Description**
Sometimes it is useful to send a whole roster to another user. Smack provides
a very easy way to send a complete roster to another XMPP client.
**Usage**
Create an instance of _**RosterExchangeManager**_ and use the **#send(Roster,
String)** message to send a roster to a given user. The first parameter is the
roster to send and the second parameter is the id of the user that will
receive the roster entries.
**Example**
In this example we can see how user1 sends his roster to user2.
```
XMPPConnection conn1 = …
// Create a new roster exchange manager on conn1
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
// Send user1's roster to user2
rosterExchangeManager.send(Roster.getInstanceFor(conn1), user2);
```
Send a roster group
-------------------
**Description**
It is also possible to send a roster group to another XMPP client. A roster
group groups a set of roster entries under a name.
**Usage**
Create an instance of _**RosterExchangeManager**_ and use the
**#send(RosterGroup, String)** message to send a roster group to a given user.
The first parameter is the roster group to send and the second parameter is
the id of the user that will receive the roster entries.
**Example**
In this example we can see how user1 sends his roster groups to user2.
```
XMPPConnection conn1 = …
// Create a new roster exchange manager on conn1
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
// Send user1's RosterGroups to user2
for (Iterator it = Roster.getInstanceFor(conn1).getGroups(); it.hasNext(); )
rosterExchangeManager.send((RosterGroup)it.next(), user2);
```
Send a roster entry
-------------------
**Description**
Sometimes you may need to send a single roster entry to another XMPP client.
Smack also lets you send items at this granularity level.
**Usage**
Create an instance of _**RosterExchangeManager**_ and use the
**#send(RosterEntry, String)** message to send a roster entry to a given user.
The first parameter is the roster entry to send and the second parameter is
the id of the user that will receive the roster entries.
**Example**
In this example we can see how user1 sends a roster entry to user2.
```
XMPPConnection conn1 = …
// Create a new roster exchange manager on conn1
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
// Send a roster entry (any) to user2
rosterExchangeManager1.send((RosterEntry)Roster.getInstanceFor(conn1).getEntries().next(), user2);
```
Receive roster entries
----------------------
**Description**
Since roster items are sent between XMPP clients, it is necessary to listen to
possible roster entries receptions. Smack provides a mechanism that you can
use to execute custom logic when roster entries are received.
**Usage**
1. Create a class that implements the _**RosterExchangeListener**_ interface.
2. Implement the method **entriesReceived(String, Iterator)** that will be called when new entries are received with custom logic.
3. Add the listener to the _RosterExchangeManager_ that works on the desired _XMPPConnection_.
**Example**
In this example we can see how user1 sends a roster entry to user2 and user2
adds the received entries to his roster.
```
// Connect to the server and log in the users
XMPPConnection conn1 = …
XMPPConnection conn2 = …
final Roster user2_roster = Roster.getInstanceFor(conn2);
// Create a RosterExchangeManager that will help user2 to listen and accept
the entries received
RosterExchangeManager rosterExchangeManager2 = new RosterExchangeManager(conn2);
// Create a RosterExchangeListener that will iterate over the received roster entries
RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
public void entriesReceived(String from, Iterator remoteRosterEntries) {
while (remoteRosterEntries.hasNext()) {
try {
// Get the received entry
RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) remoteRosterEntries.next();
// Display the remote entry on the console
System.out.println(remoteRosterEntry);
// Add the entry to the user2's roster
user2_roster.createEntry(
remoteRosterEntry.getUser(),
remoteRosterEntry.getName(),
remoteRosterEntry.getGroupArrayNames());
}
catch (XMPPException e) {
e.printStackTrace();
}
}
}
};
// Add the RosterExchangeListener to the RosterExchangeManager that user2 is using
rosterExchangeManager2.addRosterListener(rosterExchangeListener);
// Create a RosterExchangeManager that will help user1 to send his roster
RosterExchangeManager rosterExchangeManager1 = new RosterExchangeManager(conn1);
// Send user1's roster to user2
rosterExchangeManager1.send(Roster.getInstanceFor(conn1), user2);
```

View File

@ -1,33 +0,0 @@
Spoiler Messages
================
[Back](index.md)
Spoiler Messages can be used to indicate that the body of a message is a spoiler and should be displayed as such.
## Usage
To get an instance of the SpoilerManager, call
```
SpoilerManager manager = SpoilerManager.getInstanceFor(connection);
```
This will automatically add Spoilers to the list of supported features of your client.
The manager can then be used to add SpoilerElements to messages like follows:
```
Message message = new Message();
// spoiler without hint
SpoilerElement.addSpoiler(message);
// spoiler with hint about content
SpoilerElement.addSpoiler(message, "End of Love Story");
// spoiler with localized hint
SpoilerElement.addSpoiler(message, "de", "Der Kuchen ist eine Lüge");
```
To get Spoilers from a message call
```
Map<String, String> spoilers = SpoilerElement.getSpoilers(message);
```

View File

@ -1,39 +0,0 @@
Stream Management
=================
[Back](index.md)
XMPPTCPConnection comes with support for Stream Management (SM).
**XEP related:** [XEP-0198](http://xmpp.org/extensions/xep-0198.html)
Known interoperability issues
-----------------------------
- SM resumption failes on prosody when compression in sync flush mode is used with prosody. See [Prosody issue #433](https://code.google.com/p/lxmppd/issues/detail?id=433).
Enabling stream management
------------------------
TODO
Getting notifications about acknowledges stanzas
------------------------------------------------
TODO
Requisting stanza acknowledgements from the server
--------------------------------------------------
### By using predicates
TODO
### Manually
TODO
Enable stream resumption
------------------------
TODO

View File

@ -1,12 +0,0 @@
Entity Time Exchange
====================
[Back](index.md)
Supports a protocol that XMPP clients use to exchange their respective local
times and time zones.
**XEP related:** [XEP-90](http://www.xmpp.org/extensions/xep-0090.html)
_More coming soon._

View File

@ -1,205 +0,0 @@
XHTML Messages
==============
[Back](index.md)
Provides the ability to send and receive formatted messages using XHTML.
Follow these links to learn how to compose, send, receive and discover support
for XHTML messages:
* Compose an XHTML Message
* Send an XHTML Message
* Receive an XHTML Message
* Discover support for XHTML Messages
**XEP related:** [XEP-71](http://www.xmpp.org/extensions/xep-0071.html)
Compose an XHTML Message
------------------------
**Description**
The first step in order to send an XHTML message is to compose it. Smack
provides a special class that helps to build valid XHTML messages hiding any
low level complexity. For special situations, advanced users may decide not to
use the helper class and generate the XHTML by themselves. Even for these
situations Smack provides a well defined entry point in order to add the
generated XHTML content to a given message.
Note: not all clients are able to view XHTML formatted messages. Therefore,
it's recommended that you include a normal body in that message that is either
an unformatted version of the text or a note that XHTML support is required to
view the message contents.
**Usage**
Create an instance of _**XHTMLText**_ specifying the style and language of the
body. You can add several XHTML bodies to the message but each body should be
for a different language. Once you have an XHTMLText you can start to append
tags and text to it. In order to append tags there are several messages that
you can use. For each XHTML defined tag there is a message that you can send.
In order to add text you can send the message **#append(String
textToAppend)**.
After you have configured the XHTML text, the last step you have to do is to
add the XHTML text to the message you want to send. If you decided to create
the XHTML text by yourself, you will have to follow this last step too. In
order to add the XHTML text to the message send the message **#addBody(Message
message, String body)** to the _**XHTMLManager**_ class where _message_ is the
message that will receive the XHTML body and _body_ is the string to add as an
XHTML body to the message.**
**Example**
In this example we can see how to compose the following XHTML message:
```
<body>
<p style='font-size:large'>Hey John, this is my new
<span style='color:green'>green</span>
<em>!!!!</em>
</p>
</body>
```
```
// Create a message to send
Message msg = chat.createMessage();
msg.setSubject("Any subject you want");
msg.setBody("Hey John, this is my new green!!!!");
// Create an XHTMLText to send with the message
XHTMLText xhtmlText = new XHTMLText(null, null);
xhtmlText.appendOpenParagraphTag("font-size:large");
xhtmlText.append("Hey John, this is my new ");
xhtmlText.appendOpenSpanTag("color:green");
xhtmlText.append("green");
xhtmlText.appendCloseSpanTag();
xhtmlText.appendOpenEmTag();
xhtmlText.append("!!!!");
xhtmlText.appendCloseEmTag();
xhtmlText.appendCloseParagraphTag();
xhtmlText.appendCloseBodyTag();
// Add the XHTML text to the message
XHTMLManager.addBody(msg, xhtmlText);
```
Send an XHTML Message
---------------------
**Description**
After you have composed an XHTML message you will want to send it. Once you
have added the XHTML content to the message you want to send you are almost
done. The last step is to send the message as you do with any other message.
**Usage**
An XHTML message is like any regular message, therefore to send the message
you can follow the usual steps you do in order to send a message. For example,
to send a message as part of a chat just use the message **#sendMessage(Message)** of
_**Chat**_ or you can use the message **#sendStanza(Stanza)** of
_**XMPPConnection**_.
**Example**
In this example we can see how to send a message with XHTML content as part of
a chat.
```
// Create a message to send
Message msg = chat.createMessage();
// Obtain the XHTML text to send from somewhere
XHTMLText xhtmlBody = getXHTMLTextToSend();
// Add the XHTML text to the message
XHTMLManager.addBody(msg, xhtmlBody);
// Send the message that contains the XHTML
chat.sendMessage(msg);
```
Receive an XHTML Message
------------------------
**Description**
It is also possible to obtain the XHTML content from a received message.
Remember that the specification defines that a message may contain several
XHTML bodies where each body should be for a different language.
**Usage**
To get the XHTML bodies of a given message just send the message
**#getBodies(Message)** to the class _**XHTMLManager**_. The answer of this
message will be an _**List**_ with the different XHTML bodies of the
message or null if none.
**Example**
In this example we can see how to create a PacketListener that obtains the
XHTML bodies of any received message.
```
// Create a listener for the chat and display any XHTML content
IncomingChatMessageListener listener = new IncomingChatMessageListener() {
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
// Obtain the XHTML bodies of the message
List<CharSequence> bodies = XHTMLManager.getBodies(message);
if (bodies == null) {
return;
// Display the bodies on the console
for (CharSequence body : bodies) {
System.out.println(body);
}
}
};
chatManager.addListener(listener);
```
Discover support for XHTML Messages
-----------------------------------
**Description**
Before you start to send XHTML messages to a user you should discover if the
user supports XHTML messages. There are two ways to achieve the discovery,
explicitly and implicitly. Explicit is when you first try to discover if the
user supports XHTML before sending any XHTML message. Implicit is when you
send XHTML messages without first discovering if the conversation partner's
client supports XHTML and depenging on the answer (normal message or XHTML
message) you find out if the user supports XHTML messages or not. This section
explains how to explicitly discover for XHTML support.
**Usage**
In order to discover if a remote user supports XHTML messages send
**#isServiceEnabled(XMPPConnection connection, String userID)** to the class
_**XHTMLManager**_ where connection is the connection to use to perform the
service discovery and userID is the user to check (A fully qualified xmpp ID,
e.g. jdoe@example.com). This message will return true if the specified user
handles XHTML messages.
**Example**
In this example we can see how to discover if a remote user supports XHTML
Messages.
```
Message msg = chat.createMessage();
// Include a normal body in the message
msg.setBody(getTextToSend());
// Check if the other user supports XHTML messages
if (XHTMLManager.isServiceEnabled(connection, chat.getParticipant())) {
// Obtain the XHTML text to send from somewhere
String xhtmlBody = getXHTMLTextToSend();
// Include an XHTML body in the message
qHTMLManager.addBody(msg, xhtmlBody);
}
// Send the message
chat.sendMessage(msg);
```

View File

@ -1,119 +0,0 @@
Smack: Getting Started
======================
[Back](index.md)
This document will introduce you to the Smack API and provide an overview of
important classes and concepts.
Smack Modules and Requirements
-------------------------------
Smack is meant to be easily embedded into any existing Java application. The
library ships as several modules to provide more flexibility over which
features applications require:
* `smack-core` -- provides core XMPP functionality. All XMPP features that are part of the XMPP RFCs are included.
* `smack-im` -- provides functionality defined in RFC 6121 (XMPP-IM), like the Roster.
* `smack-tcp` -- support for XMPP over TCP. Includes XMPPTCPConnection class, which you usually want to use
* `smack-extensions` -- support for many of the extensions (XEPs) defined by the XMPP Standards Foundation, including multi-user chat, file transfer, user search, etc. The extensions are documented in the [extensions manual](extensions/index.md).
* `smack-experimental` -- support for experimental extensions (XEPs) defined by the XMPP Standards Foundation. The API and functionality of those extensions should be considered as unstable.
* `smack-legacy` -- support for legacy extensions (XEPs) defined by the XMPP Standards Foundation.
* `smack-bosh` -- support for BOSH (XEP-0124). This code should be considered as beta.
* `smack-resolver-minidns` -- support for resolving DNS SRV records with the help of MiniDNS. Ideal for platforms that do not support the javax.naming API. Also supports [DNSSEC](dnssec.md).
* `smack-resolver-dnsjava` -- support for resolving DNS SRV records with the help of dnsjava.
* `smack-resolver-javax` -- support for resolving DNS SRV records with the javax namespace API.
* `smack-debug` -- an enhanced GUI debugger for protocol traffic. It will automatically be used when found in the classpath and when [debugging](debugging.md) is enabled.
Configuration
-------------
Smack has an initialization process that involves 2 phases.
* Initializing system properties - Initializing all the system properties accessible through the class **SmackConfiguration**. These properties are retrieved by the _getXXX_ methods on that class.
* Initializing startup classes - Initializing any classes meant to be active at startup by instantiating the class, and then calling the _initialize_ method on that class if it extends **SmackInitializer**. If it does not extend this interface, then initialization will have to take place in a static block of code which is automatically executed when the class is loaded.
Initialization is accomplished via a configuration file. By default, Smack
will load the one embedded in the Smack jar at _org.jivesoftware.smack/smack-
config.xml_. This particular configuration contains a list of initializer
classes to load. All manager type classes that need to be initialized are
contained in this list of initializers.
Establishing a Connection
-------------------------
The `XMPPTCPConnection` class is used to create a connection to an XMPP
server. Below are code examples for making a connection:
```
// Create a connection and login to the example.org XMPP service.
AbstractXMPPConnection conn1 = new XMPPTCPConnection("username", "password", "example.org");
conn1.connect().login();
```
Further connection parameters can be configured by using a configuration builder:
```
// Create a connection to the jabber.org server on a specific port.
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("username", "password")
.setXmppDomain("jabber.org")
.setHost("earl.jabber.org")
.setPort(8222)
.build();
AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
conn2.connect().login();
```
Note that maximum security will be used when connecting to the server by
default (and when possible), including use of TLS encryption. The
ConnectionConfiguration class provides advanced control over the connection
created, such as the ability to disable or require encryption. See
[XMPPConnection Management](connections.md) for full details.
Once you've created a connection, you should login with the
`XMPPConnection.login()` method. Once you've logged in, you can begin
chatting with other users by creating new `Chat` or `MultiUserChat`
objects.
Working with the Roster
----------------------
The roster lets you keep track of the availability (presence) of other users.
Users can be organized into groups such as "Friends" and "Co-workers", and
then you discover whether each user is online or offline.
Retrieve the roster using the `Roster.getInstanceFor(XMPPConnection)` method. The roster
class allows you to find all the roster entries, the groups they belong to,
and the current presence status of each entry.
Reading and Writing Stanzas
Each message to the XMPP server from a client is called a packet and is sent
as XML. The `org.jivesoftware.smack.packet` package contains classes that
encapsulate the three different basic packet types allowed by XMPP (message,
presence, and IQ). Classes such as `Chat` and `GroupChat` provide higher-level
constructs that manage creating and sending packets automatically, but you can
also create and send packets directly. Below is a code example for changing
your presence to let people know you're unavailable and "out fishing":
```
// Create a new presence. Pass in false to indicate we're unavailable._
Presence presence = new Presence(Presence.Type.unavailable);
presence.setStatus("Gone fishing");
// Send the stanza (assume we have an XMPPConnection instance called "con").
con.sendStanza(presence);
```
Smack provides two ways to read incoming packets: `StanzaListener`, and
`StanzaCollector`. Both use `StanzaFilter` instances to determine which
stanzas should be processed. A stanza listener is used for event style
programming, while a stanza collector has a result queue of packets that you
can do polling and blocking operations on. So, a stanza listener is useful
when you want to take some action whenever a stanza happens to come in, while
a stanza collector is useful when you want to wait for a specific packet to
arrive. Stanza collectors and listeners can be created using an Connection
instance.
Copyright (C) Jive Software 2002-2008

View File

@ -1,16 +0,0 @@
**Smack Documentation**
**Contents:**
* [Overview](overview.md)
* [Getting Started Guide](gettingstarted.md)
* [Managing Connections](connections.md)
* [Messaging Basics](messaging.md)
* [Roster and Presence](roster.md)
* [Processing Incoming Stanzas](processing.md)
* [Provider Architecture](providers.md)
* [DNSSEC and DANE](dnssec.md)
* [Debugging with Smack](debugging.md)
* [Smack Extensions Manual](extensions/index.md)
* [Smack's Modular Connection Architecture](connection-modules.md)

View File

@ -1,15 +0,0 @@
<html>
<head>
<title>Smack Legacy User Manual</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<frameset cols="200,*">
<frame src="toc.html" name="navFrame" target="mainFrame">
<frame src="intro.html" name="mainFrame">
</frameset>
<noframes>
<H2>Smack Legacy User Manual</H2>
<a href="toc.html">Smack Extensions User Manual</a></noframes></html>

View File

@ -1,26 +0,0 @@
<html>
<head>
<title>Smack Extensions User Manual</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="header">Smack Legacy Manual</div>
<p>The XMPP protocol includes a base protocol and many optional extensions
typically documented as "XEP's". Smack provides the smack-legacy artifcate, with
implementations of now <b>obsolete</b> XEPs. You should no longer use this code!</p>
<div class="subheader">Legacy Extensions</div><p>
<table border="0" width="85%" cellspacing="0" cellpadding="3" style="border:1px #bbb solid;">
<tr bgcolor="#ddeeff">
<td><b>Name</b></td><td><b>XEP #</b></td><td><b>Description</b></td>
</tr>
<tr>
<td><a href="messageevents.html">Message Events</a></td>
<td><a href="http://www.xmpp.org/extensions/xep-0022.html">XEP-0022</a></td>
<td>Requests and responds to message events.</td>
</tr>
</table>
</body>
</html>

View File

@ -1,244 +0,0 @@
<html>
<head>
<title>Message Events</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div class="header">Message Events</div><p>
This extension is used to request and respond to events relating to the delivery,
display, and composition of messages. There are three stages in this extension:<ol>
<li>Request for event notifications,
<li>Receive the event notification requests and send event notifications, and
<li>Receive the event notifications.</ol>
<p>For more information on each stage please follow these links:</p>
<ul>
<li><a href="#reqevnot">Requesting Event Notifications</a></li>
<li><a href="#lstevnotreq">Reacting to Event Notification Requests</a></li>
<li><a href="#lstevnot">Reacting to Event Notifications</a></li>
</ul>
<b>XEP related:</b> <a href="http://www.xmpp.org/extensions/xep-0022.html">XEP-22</a>
<hr>
<div class="subheader"><a name="reqevnot">Requesting Event Notifications</a></div><p>
<b>Description</b><p>
In order to receive event notifications for a given message you first have to specify
which events are you interested in. Each message that you send has to request its own event
notifications. Therefore, every message that you send as part of a chat should request its own event
notifications.</p>
<b>Usage</b><p>
The class <i>MessageEventManager</i> provides an easy way for requesting event notifications. All you have to do is specify
the message that requires the event notifications and the events that you are interested in.
<p>Use the static method <i><b>MessageEventManager.addNotificationsRequests(Message message, boolean offline, boolean
delivered, boolean displayed, boolean composing)</b></i> for requesting event notifications.
</p>
<b>Example</b><p>
Below you can find an example that logs in a user to the server, creates a message, adds the requests
for notifications and sends the message.
<blockquote>
<pre> <font color="#3f7f5f">// Connect to the server and log in</font>
conn1 = new XMPPConnection(host);
conn1.login(server_user1, pass1);
<font color="#3f7f5f">// Create a chat with user2</font>
Chat chat1 = conn1.createChat(user2);
<font color="#3f7f5f">// Create a message to send</font>
Message msg = chat1.createMessage();
msg.setSubject(<font color="#0000FF">"Any subject you want"</font>);
msg.setBody(<font color="#0000FF">"An interesting body comes here..."</font>);
<font color="#3f7f5f">// Add to the message all the notifications requests (offline, delivered, displayed,</font>
<font color="#3f7f5f">// composing)</font>
MessageEventManager.addNotificationsRequests(msg, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>);
<font color="#3f7f5f">// Send the message that contains the notifications request</font>
chat1.sendMessage(msg);
</pre>
</blockquote>
<hr>
<div class="subheader"><a name="lstevnotreq">Reacting to Event Notification Requests</a></div><p>
<b>Description</b><p>
You can receive notification requests for the following events: delivered, displayed, composing and offline. You
<b>must</b> listen for these requests and react accordingly.</p>
<b>Usage</b><p>
The general idea is to create a new <i>DefaultMessageEventRequestListener</i> that will listen to the event notifications
requests and react with custom logic. Then you will have to add the listener to the
<i>MessageEventManager</i> that works on
the desired <i>XMPPConnection</i>.
<p>Note that <i>DefaultMessageEventRequestListener</i> is a default implementation of the
<i>MessageEventRequestListener</i> interface.
The class <i>DefaultMessageEventRequestListener</i> automatically sends a delivered notification to the sender of the message
if the sender has requested to be notified when the message is delivered. If you decide to create a new class that
implements the <i>MessageEventRequestListener</i> interface, please remember to send the delivered notification.</p>
<ul>
<li>To create a new <i>MessageEventManager</i> use the <i><b>MessageEventManager(XMPPConnection)</b></i> constructor.
</li>
<li>To create an event notification requests listener create a subclass of <i><b>DefaultMessageEventRequestListener</b></i> or
create a class that implements the <i><b>MessageEventRequestListener</b></i> interface.
</li>
<li>To add a listener to the messageEventManager use the MessageEventManager's message
<i><b>addMessageEventRequestListener(MessageEventRequestListener)</b></i>.</li>
</ul></p>
<b>Example</b><p>
Below you can find an example that connects two users to the server. One user will create a message, add the requests
for notifications and will send the message to the other user. The other user will add a
<i>DefaultMessageEventRequestListener</i>
to a <i>MessageEventManager</i> that will listen and react to the event notification requested by the other user.
<blockquote>
<pre> <font color="#3f7f5f">// Connect to the server and log in the users</font>
conn1 = new XMPPTCPConnection(host);
conn1.login(server_user1, pass1);
conn2 = new XMPPTCPConnection(host);
conn2.login(server_user2, pass2);
<font color="#3f7f5f">// User2 creates a MessageEventManager</font>
MessageEventManager messageEventManager = new MessageEventManager(conn2);
<font color="#3f7f5f">// User2 adds the listener that will react to the event notifications requests</font>
messageEventManager.addMessageEventRequestListener(new DefaultMessageEventRequestListener() {
public void deliveredNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.deliveredNotificationRequested(from, packetID, messageEventManager);
<font color="#3f7f5f">// DefaultMessageEventRequestListener automatically responds that the message was delivered when receives this request</font>
System.out.println(<font color="#0000FF">"Delivered Notification Requested (" + from + ", " + packetID + ")"</font>);
}
public void displayedNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.displayedNotificationRequested(from, packetID, messageEventManager);
<font color="#3f7f5f">// Send to the message's sender that the message was displayed</font>
messageEventManager.sendDisplayedNotification(from, packetID);
}
public void composingNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.composingNotificationRequested(from, packetID, messageEventManager);
<font color="#3f7f5f">// Send to the message's sender that the message's receiver is composing a reply</font>
messageEventManager.sendComposingNotification(from, packetID);
}
public void offlineNotificationRequested(
String from,
String packetID,
MessageEventManager messageEventManager) {
super.offlineNotificationRequested(from, packetID, messageEventManager);
<font color="#3f7f5f">// The XMPP server should take care of this request. Do nothing.</font>
System.out.println(<font color="#0000FF">"Offline Notification Requested (" + from + ", " + packetID + ")"</font>);
}
});
<font color="#3f7f5f">// User1 creates a chat with user2</font>
Chat chat1 = conn1.createChat(user2);
<font color="#3f7f5f">// User1 creates a message to send to user2</font>
Message msg = chat1.createMessage();
msg.setSubject(<font color="#0000FF">"Any subject you want"</font>);
msg.setBody(<font color="#0000FF">"An interesting body comes here..."</font>);
<font color="#3f7f5f">// User1 adds to the message all the notifications requests (offline, delivered, displayed,</font>
<font color="#3f7f5f">// composing)</font>
MessageEventManager.addNotificationsRequests(msg, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>);
<font color="#3f7f5f">// User1 sends the message that contains the notifications request</font>
chat1.sendMessage(msg);
Thread.sleep(500);
<font color="#3f7f5f">// User2 sends to the message's sender that the message's receiver cancelled composing a reply</font>
messageEventManager.sendCancelledNotification(user1, msg.getPacketID());
</pre>
</blockquote>
<hr>
<div class="subheader"><a name="lstevnot">Reacting to Event Notifications</a></div><p>
<b>Description</b><p>
Once you have requested for event notifications you will start to receive notifications of events. You can
receive notifications of the following events: delivered, displayed, composing, offline and cancelled. You
will probably want to react to some or all of these events.</p>
<b>Usage</b><p>
The general idea is to create a new <i>MessageEventNotificationListener</i> that will listen to the event notifications
and react with custom logic. Then you will have to add the listener to the <i>MessageEventManager</i> that works on
the desired <i>XMPPConnection</i>.
<ul>
<li>To create a new <i>MessageEventManager</i> use the <i><b>MessageEventManager(XMPPConnection)</b></i> constructor.
</li>
<li>To create an event notifications listener create a class that implements the <i><b>MessageEventNotificationListener</b></i>
interface.
</li>
<li>To add a listener to the messageEventManager use the MessageEventManager's message
<i><b>addMessageEventNotificationListener(MessageEventNotificationListener)</b></i>.</li>
</ul></p>
<b>Example</b><p>
Below you can find an example that logs in a user to the server, adds a <i>MessageEventNotificationListener</i>
to a <i>MessageEventManager</i> that will listen and react to the event notifications, creates a message, adds
the requests for notifications and sends the message.
<blockquote>
<pre> <font color="#3f7f5f">// Connect to the server and log in</font>
conn1 = new XMPPTCPConnection(host);
conn1.login(server_user1, pass1);
<font color="#3f7f5f">// Create a MessageEventManager</font>
MessageEventManager messageEventManager = new MessageEventManager(conn1);
<font color="#3f7f5f">// Add the listener that will react to the event notifications</font>
messageEventManager.addMessageEventNotificationListener(new MessageEventNotificationListener() {
public void deliveredNotification(String from, String packetID) {
System.out.println(<font color="#0000FF">"The message has been delivered (" + from + ", " + packetID + ")"</font>);
}
public void displayedNotification(String from, String packetID) {
System.out.println(<font color="#0000FF">"The message has been displayed (" + from + ", " + packetID + ")"</font>);
}
public void composingNotification(String from, String packetID) {
System.out.println(<font color="#0000FF">"The message's receiver is composing a reply (" + from + ", " + packetID + ")"</font>);
}
public void offlineNotification(String from, String packetID) {
System.out.println(<font color="#0000FF">"The message's receiver is offline (" + from + ", " + packetID + ")"</font>);
}
public void cancelledNotification(String from, String packetID) {
System.out.println(<font color="#0000FF">"The message's receiver cancelled composing a reply (" + from + ", " + packetID + ")"</font>);
}
});
<font color="#3f7f5f">// Create a chat with user2</font>
Chat chat1 = conn1.createChat(user2);
<font color="#3f7f5f">// Create a message to send</font>
Message msg = chat1.createMessage();
msg.setSubject(<font color="#0000FF">"Any subject you want"</font>);
msg.setBody(<font color="#0000FF">"An interesting body comes here..."</font>);
<font color="#3f7f5f">// Add to the message all the notifications requests (offline, delivered, displayed,</font>
<font color="#3f7f5f">// composing)</font>
MessageEventManager.addNotificationsRequests(msg, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>, <font COLOR="#7f0055"><b>true</b></font>);
<font color="#3f7f5f">// Send the message that contains the notifications request</font>
chat1.sendMessage(msg);
</pre>
</blockquote>
</body>
</html>

View File

@ -1,19 +0,0 @@
<html>
<head>
<title>Smack Legacy User Manual</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<base target="mainFrame">
</head>
<body>
<a href="intro.html">Introduction</a><p>
<div class="subheader">Smack Legacy Extensions</div><p>
<p>
<a href="messageevents.html">Message Events</a><br>
</p>
</body>
</html>

View File

@ -1,60 +0,0 @@
Messaging using Chats
=====================
[Back](index.md)
Sending messages back and forth is at the core of instant messaging. Although
individual messages can be sent and received as packets, it's generally easier
to treat the string of messages as a chat using the
`org.jivesoftware.smack.chat2.Chat` class.
Chat
----
A chat creates a new thread of messages (using a thread ID) between two users.
The following code snippet demonstrates how to create a new Chat with a user
and then send them a text message:
```
// Assume we've created an XMPPConnection name "connection"._
ChatManager chatManager = ChatManager.getInstanceFor(connection);
chatManager.addIncomingListener(new IncomingChatMessageListener() {
@Override
void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
System.out.println("New message from " + from + ": " + message.getBody());
}
});
EntityBareJid jid = JidCreate.entityBareFrom("jsmith@jivesoftware.com");
Chat chat = chatManager.chatWith(jid);
chat.send("Howdy!");
}
```
The `Chat.send(String)` method is a convenience method that creates a
Message object, sets the body using the String parameter, then sends the
message. In the case that you wish to set additional values on a Message
before sending it, use the
`Chat.send(Message)` method, as in the following code snippet:
```
Message newMessage = new Message();
newMessage.setBody("Howdy!");
// Additional modifications to the message Stanza.
JivePropertiesManager.addProperty(newMessage, "favoriteColor", "red");
chat.send(newMessage);
```
You'll also notice in the example above that we specified an IncomingChatMessageListener.
The listener is notified any time a new chat message arrives.
The following code snippet uses the listener
as a parrot-bot -- it echoes back everything the other user types.
```
// Assume a IncomingChatMessageListener we've setup with a ChatManager
public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
// Send back the same text the other user sent us.
chat.send(message.getBody());
}
```
Copyright (C) Jive Software 2002-2008

View File

@ -1,46 +0,0 @@
Smack Overview
==============
[Back](index.md)
Smack is a library for communicating with XMPP servers to perform real-time
communications, including instant messaging and group chat.
Smack Key Advantages
--------------------
* Extremely simple to use, yet powerful API. Sending a text message to a user can be accomplished in only a few lines of code:
```java
AbstractXMPPConnection connection = new XMPPTCPConnection("mtucker", "password", "jabber.org");
connection.connect().login();
Message message = connection.getStanzaFactory()
.buildMessageStanza()
.to("jsmith@jivesoftware.com")
.setBody("Howdy! How are you?")
.build();
connection.sendStanza(message);
```
* Doesn't force you to code at the XMPP protocol level, as other libraries do. Smack provides intelligent higher level constructs such as the `Chat` and `Roster` classes, which let you program more efficiently.
* Does not require that you're familiar with the XMPP XML format, or even that you're familiar with XML.
* Provides easy machine to machine communication. Smack lets you set any number of properties on each message, including properties that are Java objects.
* Open Source under the Apache License 2.0, which means you can incorporate Smack into your commercial or non-commercial applications.
About XMPP
----------
XMPP (eXtensible Messaging and Presence Protocol) is an open protocol
standardized by the IETF and supported and extended by the XMPP Standards
Foundation (XSF, [http://www.xmpp.org](http://www.xmpp.org)).
How To Use This Documentation
-----------------------------
This documentation assumes that you're already familiar with the main features
of XMPP instant messaging. It's also highly recommended that you open the
Javadoc API guide and use that as a reference while reading through this
documentation.
Copyright (C) Jive Software 2002-2008

View File

@ -1,60 +0,0 @@
Processing Incoming Stanzas
===========================
[Back](index.md)
Smack provides a flexible framework for processing incoming stanzas using two
constructs:
* `org.jivesoftware.smack.StanzaCollector` -- a class that lets you synchronously wait for new stanzas.
* `org.jivesoftware.smack.StanzaListener` -- an interface for asynchronously notifying you of incoming stanzas. A stanza listener is used for event style programming, while a stanza collector has a result queue of stanzas that you can do polling and blocking operations on. So, a stanza listener is useful when you want to take some action whenever a stanza happens to come in, while a stanza collector is useful when you want to wait for a specific stanza to arrive. Stanza collectors and listeners can be created using an `XMPPConnection` instance.
The `org.jivesoftware.smack.filter.StanzaFilter` interface determines which
specific stanzas will be delivered to a `StanzaCollector` or `StanzaListener`.
Many pre-defined filters can be found in the `org.jivesoftware.smack.filter`
package.
The following code snippet demonstrates registering both a stanza collector
and a stanza listener:
```
// Create a stanza filter to listen for new messages from a particular
// user. We use an AndFilter to combine two other filters._
StanzaFilter filter = new AndFilter(StanzaTypeFilter.MESSAGE,
FromMatchesFilter.create(JidCreate.entityBareFrom("mary@jivesoftware.com")));
// Assume we've created an XMPPConnection named "connection".
// First, register a stanza collector using the filter we created.
StanzaCollector myCollector = connection.createStanzaCollector(filter);
// Normally, you'd do something with the collector, like wait for new packets.
// Next, create a stanza listener. We use an anonymous inner class for brevity.
StanzaListener myListener = new StanzaListener() {
public void processStanza(Stanza stanza) {
// Do something with the incoming stanza here._
}
};
// Register the listener._
connection.addAsyncStanzaListener(myListener, filter);
// or for a synchronous stanza listener use
connection.addSyncStanzaListener(myListener, filter);
```
Standard Stanza Filters
-----------------------
A rich set of stanza filters are included with Smack, or you can create your
own filters by coding to the `StanzaFilter` interface. The default set of
filters includes:
* `StanzaTypeFilter` -- filters for stanzas that are a particular Class type.
* `StanzaIdFilter` -- filters for stanzas with a particular packet ID.
* `ThreadFilter` -- filters for message stanzas with a particular thread ID.
* `ToMatchesFilter` -- filters for stanzas that are sent to a particular address.
* `FromMatchesFilter` -- filters for stanzas that are sent from a particular address.
* `StanzaExtensionFilter` -- filters for stanzas that have a particular stanza extension.
* `AndFilter` -- implements the logical AND operation over two filters.
* `OrFilter` -- implements the logical OR operation over two filters.
* `NotFilter` -- implements the logical NOT operation on a filter.
Copyright (C) Jive Software 2002-2008

View File

@ -1,350 +0,0 @@
Provider Architecture: Stanza Extensions and Custom IQ's
========================================================
[Back](index.md)
Introduction
------------
The Smack provider architecture is a system for plugging in custom XML parsing
of packet extensions and IQ packets. The standard [Smack
Extensions](extensions/index.md) are built using the provider architecture.
There are two types of providers:
* `IQProvider` -- parses IQ requests into Java objects.
* `Extension Provider` -- parses XML sub-documents attached to packets into ExtensionElement instances. By default, Smack only knows how to process a few standard packets and sub-packets that are in a few namespaces such as:
* jabber:iq:auth
* jabber:iq:roster
* jabber:iq:register
There are many more IQ types and extensions that are part of XMPP standards, and of course an endless number that can be added as custom extensions. To support this, an extensible parsing mechanism is provided via Smack and user build providers.
Whenever a packet extension is found in a packet, parsing will be
passed to the correct provider. Each provider must extend the
ExtensionElementProvider abstract class. Each extension provider is
responsible for parsing the raw XML stream, via the
Smack's `XmlPullParser` interface, to construct an object.
You can also create an introspection provider
(`provider.IntrospectionProvider.PacketExtensionIntrospectionProvider`). Here,
bean introspection is used to try to automatically set the properties
of the class using the values in the packet extension sub-element.
When no extension provider is registered for an element name and namespace
combination, Smack will store all top-level elements of the sub-packet in the
StandardExtensionElement object and then attach it to the packet.
Management of these providers is accomplished via the [ProviderManager]()
class. There are multiple ways to add providers to the manager.
* Call addXXProvider methods - You can call the appropriate add methods directly.
```
ProviderManager.addIQProvider("element", "namespace", new MyIQProvider());
ProviderManager.addExtensionProvider("element", "namespace", new MyExtProvider());
```
* Add a loader - You can add a ProviderLoader which will inject a means of loading multiple providers (both types) into the manager. This is the mechanism used by Smack to load from the Smack specific file format (via ProviderFileLoader). Implementers can provide the means to load providers from any source they wish, or simply reuse the ProviderFileLoader to load from their own provider files.
```
ProviderManager.addLoader(new ProviderFileLoader(FileUtils.getStreamForUrl("classpath:com/myco/provider/myco_custom.providers", null)));
```
* VM Argument - You can add a provider file via the VM argument _smack.provider.file_. This will load the file at the specified URL during startup when Smack initializes. This also assumes the default configuration, since it requires that the **VmArgInitializer** was part of the startup configuration.
`-Dsmack.provider.file=classpath:com/myco/provider/myco_custom.providers`
or
`-Dsmack.provider.file=file:///c:/myco/provider/myco_custom.providers`
IQ Providers
------------
The IQ provider class must extend the IQProvider abstract class. Each
IQProvider is responsible for parsing the raw XML stream to create an
IQ instance.
You can also create an introspection provider
(`provider.IntrospectionProvider.IQIntrospectionProvider`). Which
uses bean introspection to try to automatically set properties of the
IQ instance using the values found in the IQ packet XML. For example,
an XMPP time packet resembles the following:
### Introspection
_Time Stanza_
<iq type='result' to='joe@example.com' from='mary@example.com' id='time_1'>
<query xmlns='jabber:iq:time'>
<utc>20020910T17:58:35</utc>
<tz>MDT</tz>
<display>Tue Sep 10 12:58:35 2002</display>
</query>
</iq>
_Time IQ Class_
class Time extends IQ {
private Date utc;
private TimeZone timeZone;
private String display;
@Override
public String getChildElementXML() {
return null;
}
public void setUtc(String utcString) {
try {
utc = StringUtils.parseDate(utcString);
} catch (ParseException e) {
}
}
public void setTimeZone(String zone) {
timeZone = TimeZone.getTimeZone(zone);
}
public void setDisplay(String timeDisplay) {
display = timeDisplay;
}
}
_Time Provider_
```java
public class TimeProvider extends IQIntrospectionProvider<Time> {
public TimeProvider() {
super(Time.class);
}
}
```
The introspection service will automatically try to convert the String value
from the XML into a boolean, int, long, float, double, or Class depending on
the type the IQ instance expects.
### Custom IQProvider example
Let's assume you want to write a provider for a new, unsupported IQ in Smack.
_Custom IQ_
```
<iq type='set' from='juliet@capulet.example/balcony' to='romeo@montage.example'>
<myiq xmlns='example:iq:foo' token='secret'>
<user age='42'>John Doe</user>
<location>New York</location>
</myiq>
</iq>
```
_Custom IQ Provider_
```java
public class MyIQProvider extends IQProvider<MyIQ> {
@Override
public MyIQ parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException {
// Define the data we are trying to collect with sane defaults
int age = -1;
String user = null;
String location = null;
// Start parsing loop
outerloop: while(true) {
XmlPullParser.Event eventType = parser.next();
switch(eventType) {
case START_ELEMENT:
String elementName = parser.getName();
switch (elementName) {
case "user":
age = ParserUtils.getIntegerAttribute(parser, "age");
user = parser.nextText();
break;
case "location"
location = parser.nextText();
break;
}
break;
case END_ELEMENT:
// Abort condition: if the are on a end tag (closing element) of the same depth
if (parser.getDepth() == initialDepth) {
break outerloop;
}
break;
default:
// Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
break;
}
}
// Construct the IQ instance at the end of parsing, when all data has been collected
return new MyIQ(user, age, location);
}
}
```
### DiscoItemsProvider
_Disco Items Stanza_
<iq type='result' from='shakespeare.lit' to='romeo@montague.net/orchard' id='items1'>
<query xmlns='http://jabber.org/protocol/disco#items'>
<item jid='people.shakespeare.lit' name='Directory of Characters'/>
<item jid='plays.shakespeare.lit' name='Play-Specific Chatrooms'/>
<item jid='mim.shakespeare.lit' name='Gateway to Marlowe IM'/>
<item jid='words.shakespeare.lit' name='Shakespearean Lexicon'/>
<item jid='globe.shakespeare.lit' name='Calendar of Performances'/>
<item jid='headlines.shakespeare.lit' name='Latest Shakespearean News'/>
<item jid='catalog.shakespeare.lit' name='Buy Shakespeare Stuff!'/>
<item jid='en2fr.shakespeare.lit' name='French Translation Service'/>
</query>
</iq>
_Disco Items IQProvider_
public class DiscoverItemsProvider implements IQProvider<DiscoverItems> {
public DiscoverItems parseIQ(XmlPullParser parser, int initialDepth) throw XmlPullParserException, IOException {
DiscoverItems discoverItems = new DiscoverItems();
DiscoverItems.Item item;
String jid = "";
String name = "";
String action = "";
String node = "";
discoverItems.setNode(parser.getAttributeValue("", "node"));
outerloop: while (true) {
XmlPullParser.Event eventType = parser.next();
switch (eventType) {
case START_ELEMENT:
String elementName = parser.getName();
switch (elementName) {
case "item":
// Initialize the variables from the parsed XML
jid = parser.getAttributeValue("", "jid");
name = parser.getAttributeValue("", "name");
node = parser.getAttributeValue("", "node");
action = parser.getAttributeValue("", "action");
break;
}
break;
case END_ELEMENT:
String elementName = parser.getName();
switch (elementName) {
case "item":
// Create a new Item and add it to DiscoverItems.
item = new DiscoverItems.Item(jid);
item.setName(name);
item.setNode(node);
item.setAction(action);
discoverItems.addItem(item);
break;
case "query":
if (parser.getDepth() == initialDepth) {
break outerloop;
}
break;
}
}
}
return discoverItems;
}
}
Extension Providers
-------------------
Stanza extension providers are responsible for parsing packet extensions,
which are child elements in a custom namespace of IQ, message and presence
packets.
_Pubsub Subscription Stanza_
<iq type='result' from='pubsub.shakespeare.lit' to='francisco@denmark.lit/barracks' id='sub1'>
<pubsub xmlns='http://jabber.org/protocol/pubsub'>
<subscription node='princely_musings' jid='francisco@denmark.lit' subscription='unconfigured'>
<subscribe-options>
<required/>
</subscribe-options>
</subscription>
</pubsub>
</iq>
_Subscription PacketExtensionProvider Implementation_
public class SubscriptionProvider extends ExtensionElementProvider<ExtensionElement> {
public ExtensionElement parse(XmlPullParser parser) throws Exception {
String jid = parser.getAttributeValue(null, "jid");
String nodeId = parser.getAttributeValue(null, "node");
String subId = parser.getAttributeValue(null, "subid");
String state = parser.getAttributeValue(null, "subscription");
boolean isRequired = false;
XmlPullParser.Event tag = parser.next();
if ((tag == XmlPullParser.START_ELEMENT) && parser.getName().equals("subscribe-options")) {
tag = parser.next();
if ((tag == XmlPullParser.START_ELEMENT) && parser.getName().equals("required"))
isRequired = true;
while (parser.next() != XmlPullParser.END_ELEMENT && parser.getName() != "subscribe-options");
}
while (parser.getEventType() != XmlPullParser.END_ELEMENT) parser.next();
return new Subscription(jid, nodeId, subId, state == null ? null : Subscription.State.valueOf(state), isRequired);
}
}
Provider file format
--------------------
This is the format for a provider file which can be parsed by the
**ProviderFileLoader**.
<?xml version="1.0"?>
<smackProviders>
<iqProvider>
<elementName>query</elementName>
<namespace>jabber:iq:time</namespace>
<className>org.jivesoftware.smack.packet.Time</className>
</iqProvider>
<iqProvider>
<elementName>query</elementName>
<namespace>http://jabber.org/protocol/disco#items</namespace>
<className>org.jivesoftware.smackx.provider.DiscoverItemsProvider</className>
</iqProvider>
<extensionProvider>
<elementName>subscription</elementName>
<namespace>http://jabber.org/protocol/pubsub</namespace>
<className>org.jivesoftware.smackx.pubsub.provider.SubscriptionProvider</className>
</extensionProvider>
</smackProviders>
Each provider is associated with an element name and a namespace. If multiple
provider entries attempt to register to handle the same namespace, the last
entry added to the **ProviderManager** will overwrite any other that was
loaded before it.
Copyright (C) Jive Software 2002-2008

View File

@ -1,101 +0,0 @@
Roster and Presence
===================
[Back](index.md)
The roster lets you keep track of the availability ("presence") of other
users. A roster also allows you to organize users into groups such as
"Friends" and "Co-workers". Other IM systems refer to the roster as the buddy
list, contact list, etc.
A `Roster` instance is obtained using the `Roster.getInstanceFor(XMPPConnection)` method.
A detailed descriptrion of the protcol behind the Roster and Presence
semantics can be found in [RFC
6120](https://tools.ietf.org/html/rfc6121).
Roster Entries
--------------
Every user in a roster is represented by a RosterEntry, which consists of:
* An XMPP address, aka. JID (e.g. jsmith@example.com).
* A name you've assigned to the user (e.g. "Joe").
* The list of groups in the roster that the entry belongs to. If the roster entry belongs to no groups, it's called an "unfiled entry". The following code snippet prints all entries in the roster:
```
Roster roster = Roster.getInstanceFor(connection);
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
System.out.println(entry);
}
```
Methods also exist to get individual entries, the list of unfiled entries, or
to get one or all roster groups.
Presence
![Roster](images/roster.png)
Every entry in the roster has presence associated with it. The
`Roster.getPresence(BareJid user)` method will return a Presence object with
the user's presence or `null` if the user is not online or you are not
subscribed to the user's presence. _Note:_ Presence subscription is
nnot tied to the user being on the roster, and vice versa: You could
be subscriped to a remote users presence without the user in your roster, and
a remote user can be in your roster without any presence subscription relation.
A user either has a presence of online or offline. When a user is online,
their presence may contain extended information such as what they are
currently doing, whether they wish to be disturbed, etc. See the Presence
class for further details.
Listening for Roster and Presence Changes
-----------------------------------------
The typical use of the roster class is to display a tree view of groups and
entries along with the current presence value of each entry. As an example,
see the image showing a Roster in the Exodus XMPP client to the right.
The presence information will likely change often, and it's also possible for
the roster entries to change or be deleted. To listen for changing roster and
presence data, a RosterListener should be used. To be informed about all
changes to the roster the RosterListener should be registered before logging
into the XMPP server. The following code snippet registers a RosterListener
with the Roster that prints any presence changes in the roster to standard
out. A normal client would use similar code to update the roster UI with the
changing information.
```
Roster roster = Roster.getInstanceFor(con);
roster.addRosterListener(new RosterListener() {
// Ignored events public void entriesAdded(Collection<String> addresses) {}
public void entriesDeleted(Collection<String> addresses) {}
public void entriesUpdated(Collection<String> addresses) {}
public void presenceChanged(Presence presence) {
System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
}
});
```
Note that in order to receive presence changed events you need to be subscribed
to the users presence. See the following section.
Adding Entries to the Roster
----------------------------
Rosters and presence use a permissions-based model where users must give
permission before someone else can see their presence. This protects a
user's privacy by making sure that only approved users are able to view their
presence information. Therefore, when you add a new roster entry, you will not
see the presence information until the other user accepts your request.
If another user requests a presence subscription, you must accept or reject
that request. Smack handles presence subscription requests in one of three ways:
* Automatically accept all presence subscription requests.
* Automatically reject all presence subscription requests.
* Process presence subscription requests manually. The mode can be set using the `Roster.setSubscriptionMode(Roster.SubscriptionMode)` method. Simple clients normally use one of the automated subscription modes, while full-featured clients should manually process subscription requests and let the end-user accept or reject each request. If using the manual mode, a PacketListener should be registered that listens for Presence packets that have a type of `Presence.Type.subscribe`.
Copyright (C) Jive Software 2002-2008

View File

@ -2,15 +2,15 @@
<h1>Overview</h1>
<p>Smack is a library for client-to-server XMPP connections to perform real-time communications and data exchange. This includes, but is not limited to, instant messaging and group chat. More genericly speaking, it allows you to easily exchange data in various ways: For example fire-and-forget, publish-subscribe, between human and non-human endpoints. The use cases include M2M, IoT, and many more.</p>
<p>Smack is a library for client-to-server XMPP connections to perform real-time communications and data exchange. This includes, but is not limited to, instant messaging and group chat. More generically speaking, it allows you to easily exchange data in various ways: For example fire-and-forget, publish-subscribe, between human and non-human endpoints. The use cases include M2M, IoT, and many more.</p>
<p>Smack is a pure Java library, open-source and highly modular. It runs on Android and Java SE. The API strives to be easy to use but yet powerful.</p>
<h2>Key Advantages</h2>
Smack is extremely simple to use. Sending a text message to a user can be accomplished in only a few lines of code.
Smack is extremely simple to use, yet provides a powerful API. Sending a text message to a user can be accomplished in only a few lines of code.
<pre>
<pre>{@code
AbstractXMPPConnection connection = new XMPPTCPConnection("mtucker", "password", "jabber.org");
connection.connect().login();
@ -23,7 +23,7 @@ Message message = connection.getStanzaFactory()
connection.sendStanza(message);
connection.disconnect();
</pre>
}</pre>
<p>Smack doesn't force you to code at the protcol level of XMPP. The library provides intelligent higher level constructs, often called {@link org.jivesoftware.smack.Manager}, which let you program more efficiently. Other examples of those constructs are the Chat and Roster classes.</p>
@ -48,4 +48,74 @@ connection.disconnect();
<p>XMPP (eXtensible Messaging and Presence Protocol) is an open protocol standardized by the <a href="https://ietf.org/">Internet Engineering Task Force (IETF)</a> and supported and extended by the <a href="https://www.xmpp.org/">XMPP Standards Foundation (XSF)</a>.</p>
<h2>Smack Modules</h2>
<p>Smack is meant to be easily embedded into any existing Java
application. The library ships as several modules to provide more
flexibility over which features applications require.</p>
<ul>
<li>smack-core -- provides core XMPP functionality. All XMPP features that are part of the XMPP RFCs are included.</li>
<li>smack-im -- provides functionality defined in RFC 6121 (XMPP-IM), like the Roster.</li>
<li>{@link org.jivesoftware.smack.tcp smack-tcp} -- support for XMPP over TCP. Includes XMPPTCPConnection class, which you usually want to use</li>
<li>smack-extensions -- support for many of the extensions (XEPs) defined by the XMPP Standards Foundation, including multi-user chat, file transfer, user search, etc. The extensions are documented in the [extensions manual](extensions/index.md).</li>
<li>smack-experimental -- support for experimental extensions (XEPs) defined by the XMPP Standards Foundation. The API and functionality of those extensions should be considered as unstable.</li>
<li>smack-legacy -- support for legacy extensions (XEPs) defined by the XMPP Standards Foundation.
<li>smack-bosh -- support for BOSH (XEP-0124). This code should be considered as beta.</li>
<li>smack-resolver-minidns -- support for resolving DNS SRV records with the help of <a href="https://minidns.org">MiniDNS</a>. Ideal for platforms that do not support the javax.naming API. Also supports [DNSSEC](dnssec.md) TODO: Fix link.</li>
<li>smack-resolver-dnsjava -- support for resolving DNS SRV records with the help of dnsjava.</li>
<li>smack-resolver-javax -- support for resolving DNS SRV records with the javax namespace API.</li>
<li>smack-debug -- an enhanced GUI debugger for protocol traffic. It will automatically be used when found in the classpath and when [debugging](debugging.md) is enabled.</li>
</ul>
<h2>Main API Entry Points</h2>
<ul>
<li>{@link org.jivesoftware.smack.XMPPConnection}</li>
<li>{@link org.jivesoftware.smack.tcp.XMPPTCPConnection}</li>
<li>{@link org.jivesoftware.smack.roster.Roster}</li>
<!-- <li>{@link org.jivesoftware.smack.chat2.Chat}</li> -->
<!-- More form index.md -->
</ul>
<h2>Smack Extensions</h2>
<p>
Since the X in XMPP stands for eXstensible, Smack comes with many
built-in extensions for XMPP. Click
</p>
<blockquote><b>{@link org.jivesoftware.smackx}</b></blockquote>
<p>
for an overview of all supporteted XMPP extensions of Smack.
</p>
Some selected extensions are
<ul>
<li>{@link org.jivesoftware.smackx.muc.MultiUserChat Multi-User Chat (XEP-0045)}</li>
<li>{@link org.jivesoftware.smackx.carbons.CarbonManager Message Carbons (XEP-0289)}</li>
<li>{@link org.jivesoftware.smackx.omemo OMEMO (XEP-0384)}</li>
<!-- <li>{@link org.jivesoftware.smack.chat2.Chat}</li> -->
<!-- More form index.md -->
</ul>
<h2>Configuration</h2>
<p>Smack has an initialization process that involves 2 phases.</p>
<ul>
<li>Initializing system properties - Initializing all the system properties accessible through the class **SmackConfiguration**. These properties are retrieved by the _getXXX_ methods on that class.</li>
<li>Initializing startup classes - Initializing any classes meant to be active at startup by instantiating the class, and then calling the _initialize_ method on that class if it extends **SmackInitializer**. If it does not extend this interface, then initialization will have to take place in a static block of code which is automatically executed when the class is loaded.</li>
</ul>
<p>
Initialization is accomplished via a configuration file.
By default, Smack
will load the one embedded in the Smack jar at _org.jivesoftware.smack/smack-
config.xml_.
This particular configuration contains a list of initializer
classes to load.
All manager type classes that need to be initialized are
contained in this list of initializers.
</p>
</body>

View File

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

Before

Width:  |  Height:  |  Size: 33 KiB

After

Width:  |  Height:  |  Size: 33 KiB

View File

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

View File

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

View File

@ -1 +1 @@
../../../../../../../smack-extensions/src/main/java/org/jivesoftware/smackx/package-info.java
../../../../../../../smack-java8-full/src/main/java/org/jivesoftware/smackx/package-info.java

View File

@ -1 +1 @@
../../../../../../../smack-extensions/src/main/java/org/jivesoftware/smackx/package-info.java
../../../../../../../smack-java8-full/src/main/java/org/jivesoftware/smackx/package-info.java

View File

@ -45,35 +45,34 @@ import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.EntityFullJid;
/**
* The XMPPConnection interface provides an interface for connections to an XMPP server and
* The XMPPConnection interface provides an interface for connections from a client to an XMPP server and
* implements shared methods which are used by the different types of connections (e.g.
* <code>XMPPTCPConnection</code> or <code>XMPPBOSHConnection</code>). To create a connection to an XMPP server
* {@link org.jivesoftware.smack.c2s.ModularXmppClientToServerConnection} or <code>XMPPTCPConnection</code>). To create a connection to an XMPP server
* a simple usage of this API might look like the following:
*
* <pre>
* // Create a connection to the igniterealtime.org XMPP server.
* XMPPTCPConnection con = new XMPPTCPConnection("igniterealtime.org");
* // Connect to the server
* con.connect();
* // Most servers require you to login before performing other tasks.
* con.login("jsmith", "mypass");
* // Start a new conversation with John Doe and send him a message.
* ChatManager chatManager = ChatManager.getInstanceFor(con);
* chatManager.addIncomingListener(new IncomingChatMessageListener() {
* public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
* // Print out any messages we get back to standard out.
* System.out.println("Received message: " + message);
* }
* });
* Chat chat = chatManager.chatWith("jdoe@igniterealtime.org");
* chat.send("Howdy!");
* // Disconnect from the server
* con.disconnect();
* </pre>
* <pre>{@code
* // Create the configuration for this new connection
* XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
* configBuilder.setUsernameAndPassword("username", "password");
* configBuilder.setXmppDomain("jabber.org");
*
* AbstractXMPPConnection connection = new XMPPTCPConnection(configBuilder.build());
* connection.connect();
* connection.login();
*
* Message message = connection.getStanzaFactory().buildMessageStanza()
* .to("mark@example.org)
* .setBody("Hi, how are you?")
* .build();
* connection.sendStanza(message);
*
* connection.disconnect();
* }</pre>
* <p>
* Note that the XMPPConnection interface does intentionally not declare any methods that manipulate
* the connection state, e.g. <code>connect()</code>, <code>disconnect()</code>. You should use the
* most specific connection type, e.g. <code>XMPPTCPConnection</code> as declared type and use the
* most-generic superclass connection type that is able to provide the methods you require. In most cases
* this should be {@link AbstractXMPPConnection}. And use or hand out instances of the
* XMPPConnection interface when you don't need to manipulate the connection state.
* </p>
* <p>
@ -81,6 +80,13 @@ import org.jxmpp.jid.EntityFullJid;
* disconnected and then connected again. Listeners of the XMPPConnection will be retained across
* connections.
* </p>
* <h2>Processing Incoming Stanzas</h2>
* Smack provides a flexible framework for processing incoming stanzas using two constructs:
* <ul>
* <li>{@link StanzaCollector}: lets you synchronously wait for new stanzas</li>
* <li>{@link StanzaListener}: an interface for asynchronously notifying you of incoming stanzas</li>
* </ul>
*
* <h2>Incoming Stanza Listeners</h2>
* Most callbacks (listeners, handlers, ) than you can add to a connection come in three different variants:
* <ul>
@ -102,9 +108,22 @@ import org.jxmpp.jid.EntityFullJid;
* exact order of how events happen there, most importantly the arrival order of incoming stanzas. You should only
* use synchronous callbacks in rare situations.
* </p>
* <h2>Stanza Filters</h2>
* Stanza filters allow you to define the predicates for which listeners or collectors should be invoked. For more
* information about stanza filters, see {@link org.jivesoftware.smack.filter}.
* <h2>Provider Architecture</h2>
* XMPP is an extensible protocol. Smack allows for this extensible with its provider architecture that allows to
* plug-in providers that are able to parse the various XML extension elements used for XMPP's extensibility. For
* more information see {@link org.jivesoftware.smack.provider}.
* <h2>Debugging</h2>
* See {@link org.jivesoftware.smack.debugger} for Smack's API to debug XMPP connections.
* <h2>Modular Connection Architecture</h2>
* Smack's new modular connection architecture will one day replace the monolithic architecture. Its main entry
* point {@link org.jivesoftware.smack.c2s.ModularXmppClientToServerConnection} has more information.
*
* @author Matt Tucker
* @author Guenther Niess
* @author Florian Schmaus
*/
public interface XMPPConnection {

View File

@ -86,9 +86,55 @@ import org.jxmpp.jid.DomainBareJid;
import org.jxmpp.jid.parts.Resourcepart;
import org.jxmpp.util.XmppStringUtils;
/**
* The superclass of Smack's Modular Connection Architecture.
* <p>
* <b>Note:</b> Everything related to the modular connection architecture is currently considered experimental and
* should not be used in production. Use the mature {@code XMPPTCPConnection} if you do not feel adventurous.
* </p>
* <p>
* Smack's modular connection architecture allows to extend a XMPP c2s (client-to-server) connection with additional
* functionality by adding modules. Those modules extend the Finite State Machine (FSM) within the connection with new
* states. Connection modules can either be
* <ul>
* <li>Transports</li>
* <li>Extensions</li>
* </ul>
* <p>
* Transports bind the XMPP XML stream to an underlying transport like TCP, WebSockets, BOSH, and allow for the
* different particularities of transports like DirectTLS
* (<a href="https://xmpp.org/extensions/xep-0368.html">XEP-0368</a>). This eventually means that a single transport
* module can implement multiple transport mechanisms. For example the TCP transport module implements the RFC6120 TCP
* and the XEP-0368 direct TLS TCP transport bindings.
* </p>
* <p>
* Extensions allow for a richer functionality of the connection. Those include
* <ul>
* <li>Compression</li>
* <li><ul>
* <li>zlib ([XEP-0138](https://xmpp.org/extensions/xep-0138.html))</li>
* <li>[Efficient XML Interchange (EXI)](https://www.w3.org/TR/exi/)</li>
* </ul></li>
* <li>Instant Stream Resumption ([XEP-0397](https://xmpp.org/extensions/xep-0397.html)</li>
* <li>Bind2</li>
* <li>Stream Management</li>
* </ul>
* Note that not all extensions work with every transport. For example compression only works with TCP-based transport
* bindings.
* <p>
* Connection modules are plugged into the the modular connection via their constructor. and they usually declare
* backwards edges to some common, generic connection state of the FSM.
* </p>
* <p>
* Modules and states always have an accompanying *descriptor* type. `ModuleDescriptor` and `StateDescriptor` exist
* without an connection instance. They describe the module and state metadata, while their modules and states are
* Instantiated once a modular connection is instantiated.
* </p>
*/
public final class ModularXmppClientToServerConnection extends AbstractXMPPConnection {
private static final Logger LOGGER = Logger.getLogger(ModularXmppClientToServerConnectionConfiguration.class.getName());
private static final Logger LOGGER = Logger.getLogger(
ModularXmppClientToServerConnectionConfiguration.class.getName());
private final ArrayBlockingQueueWithShutdown<TopLevelStreamElement> outgoingElementsQueue = new ArrayBlockingQueueWithShutdown<>(
100, true);
@ -126,7 +172,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
this.configuration = configuration;
// Construct the internal connection API.
connectionInternal = new ModularXmppClientToServerConnectionInternal(this, getReactor(), debugger, outgoingElementsQueue) {
connectionInternal = new ModularXmppClientToServerConnectionInternal(this, getReactor(), debugger,
outgoingElementsQueue) {
@Override
public void parseAndProcessElement(String wrappedCompleteElement) {
@ -180,13 +227,14 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
@Override
public void waitForFeaturesReceived(String waitFor) throws InterruptedException, SmackException, XMPPException {
public void waitForFeaturesReceived(String waitFor)
throws InterruptedException, SmackException, XMPPException {
ModularXmppClientToServerConnection.this.waitForFeaturesReceived(waitFor);
}
@Override
public void newStreamOpenWaitForFeaturesSequence(String waitFor) throws InterruptedException,
SmackException, XMPPException {
public void newStreamOpenWaitForFeaturesSequence(String waitFor)
throws InterruptedException, SmackException, XMPPException {
ModularXmppClientToServerConnection.this.newStreamOpenWaitForFeaturesSequence(waitFor);
}
@ -196,9 +244,11 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
@Override
public <SN extends Nonza, FN extends Nonza> SN sendAndWaitForResponse(Nonza nonza, Class<SN> successNonzaClass,
Class<FN> failedNonzaClass) throws NoResponseException, NotConnectedException, FailedNonzaException, InterruptedException {
return ModularXmppClientToServerConnection.this.sendAndWaitForResponse(nonza, successNonzaClass, failedNonzaClass);
public <SN extends Nonza, FN extends Nonza> SN sendAndWaitForResponse(Nonza nonza,
Class<SN> successNonzaClass, Class<FN> failedNonzaClass) throws NoResponseException,
NotConnectedException, FailedNonzaException, InterruptedException {
return ModularXmppClientToServerConnection.this.sendAndWaitForResponse(nonza, successNonzaClass,
failedNonzaClass);
}
@Override
@ -234,7 +284,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
// modules are sometimes used to construct the states.
for (ModularXmppClientToServerConnectionModuleDescriptor moduleDescriptor : configuration.moduleDescriptors) {
Class<? extends ModularXmppClientToServerConnectionModuleDescriptor> moduleDescriptorClass = moduleDescriptor.getClass();
ModularXmppClientToServerConnectionModule<? extends ModularXmppClientToServerConnectionModuleDescriptor> connectionModule = moduleDescriptor.constructXmppConnectionModule(connectionInternal);
ModularXmppClientToServerConnectionModule<? extends ModularXmppClientToServerConnectionModuleDescriptor> connectionModule = moduleDescriptor.constructXmppConnectionModule(
connectionInternal);
connectionModules.put(moduleDescriptorClass, connectionModule);
XmppClientToServerTransport transport = connectionModule.getTransport();
@ -265,7 +316,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
private WalkStateGraphContext.Builder buildNewWalkTo(Class<? extends StateDescriptor> finalStateClass) {
return WalkStateGraphContext.builder(currentStateVertex.getElement().getStateDescriptor().getClass(), finalStateClass);
return WalkStateGraphContext.builder(currentStateVertex.getElement().getStateDescriptor().getClass(),
finalStateClass);
}
/**
@ -316,7 +368,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
List<GraphVertex<State>> outgoingStateEdges = initialStateVertex.getOutgoingEdges();
// See if we need to handle mandatory intermediate states.
GraphVertex<State> mandatoryIntermediateStateVertex = walkStateGraphContext.maybeReturnMandatoryImmediateState(outgoingStateEdges);
GraphVertex<State> mandatoryIntermediateStateVertex = walkStateGraphContext.maybeReturnMandatoryImmediateState(
outgoingStateEdges);
if (mandatoryIntermediateStateVertex != null) {
StateTransitionResult reason = attemptEnterState(mandatoryIntermediateStateVertex, walkStateGraphContext);
@ -340,7 +393,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
// state.
if (walkStateGraphContext.wouldCauseCycle(successorStateVertex)) {
// Ignore this successor.
invokeConnectionStateMachineListener(new ConnectionStateEvent.TransitionIgnoredDueCycle(initialStateVertex, successorStateVertex));
invokeConnectionStateMachineListener(new ConnectionStateEvent.TransitionIgnoredDueCycle(
initialStateVertex, successorStateVertex));
} else {
StateTransitionResult result = attemptEnterState(successorStateVertex, walkStateGraphContext);
@ -348,9 +402,11 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
break;
}
// If attemptEnterState did not throw and did not return a value of type TransitionSuccessResult, then we
// If attemptEnterState did not throw and did not return a value of type TransitionSuccessResult, then
// we
// just record this value and go on from there. Note that reason may be null, which is returned by
// attemptEnterState in case the state was already successfully handled. If this is the case, then we don't
// attemptEnterState in case the state was already successfully handled. If this is the case, then we
// don't
// record it.
if (result != null) {
walkStateGraphContext.recordFailedState(successorState, result);
@ -379,8 +435,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
* @throws InterruptedException if the calling thread was interrupted.
*/
private StateTransitionResult attemptEnterState(GraphVertex<State> successorStateVertex,
WalkStateGraphContext walkStateGraphContext) throws SmackException, XMPPException,
IOException, InterruptedException {
WalkStateGraphContext walkStateGraphContext)
throws SmackException, XMPPException, IOException, InterruptedException {
final GraphVertex<State> initialStateVertex = currentStateVertex;
final State initialState = initialStateVertex.getElement();
final State successorState = successorStateVertex.getElement();
@ -396,8 +452,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
if (successorStateDescriptor.isNotImplemented()) {
StateTransitionResult.TransitionImpossibleBecauseNotImplemented transtionImpossibleBecauseNotImplemented = new StateTransitionResult.TransitionImpossibleBecauseNotImplemented(
successorStateDescriptor);
invokeConnectionStateMachineListener(new ConnectionStateEvent.TransitionNotPossible(initialState, successorState,
transtionImpossibleBecauseNotImplemented));
invokeConnectionStateMachineListener(new ConnectionStateEvent.TransitionNotPossible(initialState,
successorState, transtionImpossibleBecauseNotImplemented));
return transtionImpossibleBecauseNotImplemented;
}
@ -406,12 +462,13 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
StateTransitionResult.TransitionImpossible transitionImpossible = successorState.isTransitionToPossible(
walkStateGraphContext);
if (transitionImpossible != null) {
invokeConnectionStateMachineListener(new ConnectionStateEvent.TransitionNotPossible(initialState, successorState,
transitionImpossible));
invokeConnectionStateMachineListener(new ConnectionStateEvent.TransitionNotPossible(initialState,
successorState, transitionImpossible));
return transitionImpossible;
}
invokeConnectionStateMachineListener(new ConnectionStateEvent.AboutToTransitionInto(initialState, successorState));
invokeConnectionStateMachineListener(
new ConnectionStateEvent.AboutToTransitionInto(initialState, successorState));
transitionAttemptResult = successorState.transitionInto(walkStateGraphContext);
} catch (SmackException | IOException | InterruptedException | XMPPException e) {
// Unwind the state here too, since this state will not be unwound by walkStateGraph(), as it will not
@ -421,8 +478,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
if (transitionAttemptResult instanceof StateTransitionResult.Failure) {
StateTransitionResult.Failure transitionFailureResult = (StateTransitionResult.Failure) transitionAttemptResult;
invokeConnectionStateMachineListener(
new ConnectionStateEvent.TransitionFailed(initialState, successorState, transitionFailureResult));
invokeConnectionStateMachineListener(new ConnectionStateEvent.TransitionFailed(initialState, successorState,
transitionFailureResult));
return transitionAttemptResult;
}
@ -566,8 +623,7 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
featuresReceived = false;
}
private void waitForFeaturesReceived(String waitFor)
throws InterruptedException, SmackException, XMPPException {
private void waitForFeaturesReceived(String waitFor) throws InterruptedException, SmackException, XMPPException {
waitForConditionOrThrowConnectionException(() -> featuresReceived, waitFor);
}
@ -577,8 +633,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
return streamOpenAndCloseFactory.createStreamOpen(to, from, id, lang);
}
private void newStreamOpenWaitForFeaturesSequence(String waitFor) throws InterruptedException,
SmackException, XMPPException {
private void newStreamOpenWaitForFeaturesSequence(String waitFor)
throws InterruptedException, SmackException, XMPPException {
prepareToWaitForFeaturesReceived();
// Create StreamOpen from StreamOpenAndCloseFactory via underlying transport.
@ -589,7 +645,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
if (localpart != null) {
from = XmppStringUtils.completeJidFrom(localpart, xmppServiceDomain);
}
AbstractStreamOpen streamOpen = streamOpenAndCloseFactory.createStreamOpen(xmppServiceDomain, from, getStreamId(), getConfiguration().getXmlLang());
AbstractStreamOpen streamOpen = streamOpenAndCloseFactory.createStreamOpen(xmppServiceDomain, from,
getStreamId(), getConfiguration().getXmlLang());
sendStreamOpen(streamOpen);
waitForFeaturesReceived(waitFor);
@ -609,7 +666,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
private final class DisconnectedState extends State {
private DisconnectedState(StateDescriptor stateDescriptor, ModularXmppClientToServerConnectionInternal connectionInternal) {
private DisconnectedState(StateDescriptor stateDescriptor,
ModularXmppClientToServerConnectionInternal connectionInternal) {
super(stateDescriptor, connectionInternal);
}
@ -648,7 +706,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
private final class LookupRemoteConnectionEndpointsState extends State {
boolean outgoingElementsQueueWasShutdown;
private LookupRemoteConnectionEndpointsState(StateDescriptor stateDescriptor, ModularXmppClientToServerConnectionInternal connectionInternal) {
private LookupRemoteConnectionEndpointsState(StateDescriptor stateDescriptor,
ModularXmppClientToServerConnectionInternal connectionInternal) {
super(stateDescriptor, connectionInternal);
}
@ -757,7 +816,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
private final class ConnectedButUnauthenticatedState extends State {
private ConnectedButUnauthenticatedState(StateDescriptor stateDescriptor, ModularXmppClientToServerConnectionInternal connectionInternal) {
private ConnectedButUnauthenticatedState(StateDescriptor stateDescriptor,
ModularXmppClientToServerConnectionInternal connectionInternal) {
super(stateDescriptor, connectionInternal);
}
@ -788,7 +848,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
private final class SaslAuthenticationState extends State {
private SaslAuthenticationState(StateDescriptor stateDescriptor, ModularXmppClientToServerConnectionInternal connectionInternal) {
private SaslAuthenticationState(StateDescriptor stateDescriptor,
ModularXmppClientToServerConnectionInternal connectionInternal) {
super(stateDescriptor, connectionInternal);
}
@ -837,14 +898,16 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
private final class ResourceBindingState extends State {
private ResourceBindingState(StateDescriptor stateDescriptor, ModularXmppClientToServerConnectionInternal connectionInternal) {
private ResourceBindingState(StateDescriptor stateDescriptor,
ModularXmppClientToServerConnectionInternal connectionInternal) {
super(stateDescriptor, connectionInternal);
}
@Override
public StateTransitionResult.AttemptResult transitionInto(WalkStateGraphContext walkStateGraphContext)
throws IOException, SmackException, InterruptedException, XMPPException {
// Calling bindResourceAndEstablishSession() below requires the lastFeaturesReceived sync point to be signaled.
// Calling bindResourceAndEstablishSession() below requires the lastFeaturesReceived sync point to be
// signaled.
// Since we entered this state, the FSM has decided that the last features have been received, hence signal
// the sync point.
lastFeaturesReceived = true;
@ -901,13 +964,12 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
if (walkFromDisconnectToAuthenticated != null) {
// If there was already a previous walk to ConnectedButUnauthenticated, then the context of the current
// walk must not start from the 'Disconnected' state.
assert walkStateGraphContext.getWalk().get(0).getStateDescriptor().getClass()
!= DisconnectedStateDescriptor.class;
assert walkStateGraphContext.getWalk().get(
0).getStateDescriptor().getClass() != DisconnectedStateDescriptor.class;
// Append the current walk to the previous one.
walkStateGraphContext.appendWalkTo(walkFromDisconnectToAuthenticated);
} else {
walkFromDisconnectToAuthenticated = new ArrayList<>(
walkStateGraphContext.getWalkLength() + 1);
walkFromDisconnectToAuthenticated = new ArrayList<>(walkStateGraphContext.getWalkLength() + 1);
walkStateGraphContext.appendWalkTo(walkFromDisconnectToAuthenticated);
}
walkFromDisconnectToAuthenticated.add(this);
@ -937,7 +999,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
@Override
public StateTransitionResult.TransitionImpossible isTransitionToPossible(WalkStateGraphContext walkStateGraphContext) {
public StateTransitionResult.TransitionImpossible isTransitionToPossible(
WalkStateGraphContext walkStateGraphContext) {
ensureNotOnOurWayToAuthenticatedAndResourceBound(walkStateGraphContext);
return null;
}
@ -968,7 +1031,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
XmppInputOutputFilter filter = it.next();
try {
filter.waitUntilInputOutputClosed();
} catch (IOException | CertificateException | InterruptedException | SmackException | XMPPException e) {
} catch (IOException | CertificateException | InterruptedException | SmackException
| XMPPException e) {
LOGGER.log(Level.WARNING, "waitUntilInputOutputClosed() threw", e);
}
}
@ -991,12 +1055,14 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
}
private static final class InstantShutdownState extends NoOpState {
private InstantShutdownState(ModularXmppClientToServerConnection connection, StateDescriptor stateDescriptor, ModularXmppClientToServerConnectionInternal connectionInternal) {
private InstantShutdownState(ModularXmppClientToServerConnection connection, StateDescriptor stateDescriptor,
ModularXmppClientToServerConnectionInternal connectionInternal) {
super(connection, stateDescriptor, connectionInternal);
}
@Override
public StateTransitionResult.TransitionImpossible isTransitionToPossible(WalkStateGraphContext walkStateGraphContext) {
public StateTransitionResult.TransitionImpossible isTransitionToPossible(
WalkStateGraphContext walkStateGraphContext) {
ensureNotOnOurWayToAuthenticatedAndResourceBound(walkStateGraphContext);
return null;
}
@ -1057,8 +1123,8 @@ public final class ModularXmppClientToServerConnection extends AbstractXMPPConne
@Override
protected void connectInternal() throws SmackException, IOException, XMPPException, InterruptedException {
WalkStateGraphContext walkStateGraphContext = buildNewWalkTo(ConnectedButUnauthenticatedStateDescriptor.class)
.build();
WalkStateGraphContext walkStateGraphContext = buildNewWalkTo(
ConnectedButUnauthenticatedStateDescriptor.class).build();
walkStateGraph(walkStateGraphContext);
}

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2002-2008 Jive Software, 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,18 @@
*/
/**
* Core debugger functionality.
* Smack includes built-in debugging consoles that will let you track all XML traffic between the client and server.
* Further debuggers, besides those provide by smack-core, can be found in org.jivesoftware.smackx.debugger (note, that
* this uses the smackx namespace, and not smack) provided by smack-debug.
*
* Debugging mode can be enabled in two different ways.
*
* Add the following line of code before creating new connections
*
* {@code SmackConfiguration.DEBUG = true;}
*
* Set the Java system property smack.debugEnabled to {@code true}. The system property can be set on the command line such as
*
* <pre>java -Dsmack.debugEnabled=true SomeApp</pre>
*/
package org.jivesoftware.smack.debugger;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -17,5 +17,16 @@
/**
* Allows {@link org.jivesoftware.smack.StanzaCollector} and {@link org.jivesoftware.smack.StanzaListener} instances to filter for stanzas with particular attributes.
* <h2>Selected Filter Types</h2>
* <ul>
* <li>{@link StanzaTypeFilter}: filters for stanzas that are a stanza type (Message, Presence, or IQ)</li>
* <li>{@link StanzaIdFilter}: filters for stanzas with a particular stanza ID</li>
* <li>{@link ToMatchesFilter}: filters for stanzas that are sent to a particular address</li>
* <li>{@link FromMatchesFilter}: filters for stanzas that are sent from a particular address</li>
* <li>{@link ExtensionElementFilter}: filters for stanzas that have a particular stanza exentsion element</li>
* <li>{@link AndFilter}: implements the logical AND operation over two or more filters</li>
* <li>{@link OrFilter}: implements the logical OR operation over two or more filters</li>
* <li>{@link NotFilter}: implements the logical NOT operation on a filter</li>
* </ul>
*/
package org.jivesoftware.smack.filter;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2019-2021 Florian Schmaus
* Copyright 2019-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -31,6 +31,62 @@ import org.jivesoftware.smack.xml.XmlPullParserException;
* An abstract class for parsing custom {@link IQ} packets. Each IqProvider must be registered with the {@link
* ProviderManager} for it to be used. Every implementation of this abstract class <b>must</b> have a public,
* no-argument constructor.
* <h2>Custom IQ Provider Example</h2>
* <p>
* Let us assume you want to write a provider for a new, unsupported IQ in Smack.
* </p>
* <pre>{@code
* <iq type='set' from='juliet@capulet.example/balcony' to='romeo@montage.example'>
* <myiq xmlns='example:iq:foo' token='secret'>
* <user age='42'>John Doe</user>
* <location>New York</location>
* </myiq>
* </iq>
* }</pre>
* The custom IQ provider may look like the follows
* <pre>{@code
* public class MyIQProvider extends IQProvider<MyIQ> {
*
* {@literal @}Override
* public MyIQ parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException {
* // Define the data we are trying to collect with sane defaults
* int age = -1;
* String user = null;
* String location = null;
*
* // Start parsing loop
* outerloop: while(true) {
* XmlPullParser.Event eventType = parser.next();
* switch(eventType) {
* case START_ELEMENT:
* String elementName = parser.getName();
* switch (elementName) {
* case "user":
* age = ParserUtils.getIntegerAttribute(parser, "age");
* user = parser.nextText();
* break;
* case "location"
* location = parser.nextText();
* break;
* }
* break;
* case END_ELEMENT:
* // Abort condition: if the are on a end tag (closing element) of the same depth
* if (parser.getDepth() == initialDepth) {
* break outerloop;
* }
* break;
* default:
* // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
* break;
* }
* }
*
* // Construct the IQ instance at the end of parsing, when all data has been collected
* return new MyIQ(user, age, location);
* }
* }
* }</pre>
*
* @param <I> the {@link IQ} that is parsed by implementations.
*/

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,29 @@
*/
/**
* Provides pluggable parsing of incoming IQ's and extensions elements.
* The Smack provider architecture is a system for plugging in custom XML parsing of staza extensions
* ({@link org.jivesoftware.smack.packet.ExtensionElement}, {@link org.jivesoftware.smack.packet.IQ} stanzas and
* {@link org.jivesoftware.smack.packet.Nonza}. Hence, there are the the following providers:
* <ul>
* <li>{@link ExtensionElementProvider}</li>
* <li>{@link IqProvider}</li>
* <li>{@link NonzaProvider}</li>
* </ul>
* For most users, only extension element and IQ providers should be relevant.
* <h2>Architecture</h2>
* <p>
* Providers are registered with the {@link ProviderManager}. XML elements identified by their
* {@link javax.xml.namespace.QName}, that is, their qualified name consistent of the XML elements name and its
* namespace. The QName is hence used to map XML elements to their provider Whenever a stanza extension is found in a
* stanza, parsing will be passed to the correct provider. Each provider is responsible for parsing the XML stream via
* Smack's {@link org.jivesoftware.smack.xml.XmlPullParser}.
* </p>
* <h2>Unknown Extension Elements</h2>
* <p>
* If no extension element provider is registered for an element, then Smack will fall back to parse the "unknown"
* element to a {@link org.jivesoftware.smack.packet.StandardExtensionElement}.
* </p>
* <h2>Custom Provider Example</h2>
* See {@link IqProvider} for examples.
*/
package org.jivesoftware.smack.provider;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,56 @@
*/
/**
* Utilities for DNS related tasks.
* Smack's API for DNS related tasks.
* <h2>DNSSEC and DANE</h2>
* <h3>About</h3>
* <p>
* DNSSEC (<a href="https://tools.ietf.org/html/rfc4033">RFC 4033</a>, and others) authenticates DNS answers, positive
* and negative ones. This means that if a DNS response secured by DNSSEC turns out to be authentic, then you can be
* sure that the domain either exists, and that the returned resource records (RRs) are the ones the domain owner
* authorized, or that the domain does not exists and that nobody tried to fake its non existence.
* </p>
* <p>
* The tricky part is that an application using DNSSEC can not determine whether a domain uses DNSSEC, does not use
* DNSSEC or if someone downgraded your DNS query using DNSSEC to a response without DNSSEC.
* </p>
* <p>
* DANE (<a href="https://tools.ietf.org/html/rfc6698">RFC 6698</a>) allows the verification of a TLS certificate with
* information stored in the DNS system and secured by DNSSEC. Thus DANE requires DNSSEC.
* </p>
* <h3>Prerequisites</h3>
* <p>
* From the three DNS resolver providers (MiniDNS, javax, dnsjava) supported by Smack we currently only support DNSSEc
* with <a href="https://github.com/minidns/minidns">MiniDNS</a>. MiniDNS is the default resolver when smack-android is
* used. For other configurations, make sure to add smack-resolver-minidns to your dependencies and call
* `MiniDnsResolver.setup()` prior using Smack (e.g. in a `static {}` code block).
* </p>
* <h3>DNSSEC API</h3>
* <p>
* Smack's DNSSEC API is very simple. Just use
* {@link org.jivesoftware.smack.ConnectionConfiguration.Builder#setDnssecMode(org.jivesoftware.smack.ConnectionConfiguration.DnssecMode)}
* to enable DNSSEC. The argument, {@link org.jivesoftware.smack.ConnectionConfiguration.DnssecMode}, can be one of
* <ul>
* <li>{@link org.jivesoftware.smack.ConnectionConfiguration.DnssecMode#disabled}</li>
* <li>{@link org.jivesoftware.smack.ConnectionConfiguration.DnssecMode#needsDnssec}</li>
* <li>{@link org.jivesoftware.smack.ConnectionConfiguration.DnssecMode#needsDnssecAndDane}</li>
* </ul>
* The default is disabled.
* <p>
* If {@link org.jivesoftware.smack.ConnectionConfiguration.DnssecMode#needsDnssec} is used, then then Smack will only
* connect if the DNS results required to determine a host for the XMPP domain could be verified using DNSSEC.
* </p>
* <p>
* If set to {@link org.jivesoftware.smack.ConnectionConfiguration.DnssecMode#needsDnssecAndDane}, then then DANE will
* be used to verify the XMPP service's TLS certificate if STARTTLS is used.
* </p>
* <h2>Best Practices</h2>
* <p>
* We recommend that applications using Smack's DNSSEC API do not ask the user if DNSSEC is avaialble. Instead they
* should check for DNSSEC suport on every connection attempt. Once DNSSEC support has been discovered, the application
* should use the `needsDnssec` mode for all future connection attempts. The same scheme can be applied when using DANE.
* This approach is similar to the scheme established by to <a href="https://tools.ietf.org/html/rfc6797">HTTP Strict
* Transport Security" (HSTS, RFC 6797</a>.
* </p>
*/
package org.jivesoftware.smack.util.dns;

View File

@ -1 +1 @@
../../../../../../../smack-extensions/src/main/java/org/jivesoftware/smackx/package-info.java
../../../../../../../smack-java8-full/src/main/java/org/jivesoftware/smackx/package-info.java

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,6 @@
*/
/**
* Smack optional Debuggers.
* Smack optional Debuggers, which include {@link EnhancedDebugger} and {@link LiteDebugger}.
*/
package org.jivesoftware.smackx.debugger;

View File

@ -1 +1 @@
../../../../../../../smack-extensions/src/main/java/org/jivesoftware/smackx/package-info.java
../../../../../../../smack-java8-full/src/main/java/org/jivesoftware/smackx/package-info.java

View File

@ -22,7 +22,19 @@ import org.jivesoftware.smack.util.SHA1;
import org.hsluv.HUSLColorConverter;
/**
* Implementation of XEP-0392: Consistent Color Generation version 0.6.0.
* Smack API for Consistent Color Generation (XEP-0392).
* <p>
* Since XMPP can be used on multiple platforms at the same time, it might be a
* good idea to render given Strings like nicknames in the same color on all
* platforms to provide a consistent user experience.
* </p>
* <h2>Usage</h2>
*
* <h2>Color Deficiency Corrections</h2>
* <p>
* Some users might suffer from color vision deficiencies. To compensate those
* deficiencies, the API allows for color correction.
* </p>
*
* @author Paul Schaub
*/

View File

@ -17,5 +17,122 @@
/**
* Smack's API for XEP-0332: HTTP over XMPP transport.
* <h2 id="discover-hoxt-support">Discover HOXT support</h2>
* <p>
* <strong>Description</strong>
* </p>
* <p>
* Before using this extension you must ensure that your counterpart supports it also.
* </p>
* <p>
* <strong>Usage</strong>
* </p>
* <p>
* Once you have your <em><strong>ServiceDiscoveryManager</strong></em> you will be able to discover information
* associated with an XMPP entity. To discover the information of a given XMPP entity send
* <strong>discoverInfo(entityID)</strong> to your <em><strong>ServiceDiscoveryManager</strong></em> where entityID is
* the ID of the entity. The message <strong>discoverInfo(entityID)</strong> will answer with an instance of
* <em><strong>DiscoverInfo</strong></em> that contains the discovered information.
* </p>
* <p>
* <strong>Examples</strong>
* </p>
* <p>
* In this example we can see how to check if the counterpart supports HOXT:
* </p>
*
* <pre>
* <code>// Obtain the ServiceDiscoveryManager associated with my XMPPConnection
* ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
* // Get the information of a given XMPP entity, where entityID is a Jid
* DiscoverInfo discoInfo = discoManager.discoverInfo(entityID);
* // Check if room is HOXT is supported
* boolean isSupported = discoInfo.containsFeature(&quot;urn:xmpp:http&quot;);</code>
* </pre>
*
* <h2 id="iq-exchange">IQ exchange</h2>
* <p>
* <strong>Description</strong>
* </p>
* <p>
* You can use IQs to perform HTTP requests and responses. This is applicable to relatively short requests and
* responses (due to the limitation of XMPP message size).
* </p>
* <p>
* <strong>Usage</strong>
* </p>
* <p>
* First you need to register a <em><strong>StanzaListener</strong></em> to be able to handle intended IQs.
* </p>
* <p>
* For the HTTP client you:
* </p>
* <ul>
* <li>You create and send <em><strong>HttpOverXmppReq</strong></em> request.</li>
* <li>Then you handle the <em><strong>HttpOverXmppResp</strong></em> response in your
* <em><strong>StanzaListener</strong></em>.</li>
* </ul>
* <p>
* For the HTTP server you:
* </p>
* <ul>
* <li>You handle the <em><strong>HttpOverXmppReq</strong></em> requests in your
* <em><strong>StanzaListener</strong></em>.</li>
* <li>And create and send <em><strong>HttpOverXmppResp</strong></em> responses.</li>
* </ul>
* <p>
* <strong>Examples</strong>
* </p>
* <p>
* In this example we are an HTTP client, so we send a request (POST) and handle the response:
* </p>
*
* <pre>
* <code>
* // create a request body
* String urlEncodedMessage = &quot;I_love_you&quot;;
*
* // prepare headers
* List&lt;Header&gt; headers = new ArrayList&lt;&gt;();
* headers.add(new Header(&quot;Host&quot;, &quot;juliet.capulet.com&quot;));
* headers.add(new Header(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;));
* headers.add(new Header(&quot;Content-Length&quot;, Integer.toString(urlEncodedMessage.length())));
*
* // provide body or request (not mandatory, - empty body is used for GET)
* AbstractHttpOverXmpp.Text child = new AbstractHttpOverXmpp.Text(urlEncodedMessage);
* AbstractHttpOverXmpp.Data data = new AbstractHttpOverXmpp.Data(child);
*
* // create request
* HttpOverXmppReq req = HttpOverXmppReq.buider()
* .setMethod(HttpMethod.POST)
* .setResource(&quot;/mailbox&quot;)
* .setHeaders(headers)
* .setVersion(&quot;1.1&quot;)
* .setData(data)
* .build();
*
* // add to, where jid is the Jid of the individual the packet is sent to
* req.setTo(jid);
*
* // send it
* connection.sendIqWithResponseCallback(req, new StanzaListener() {
* public void processStanza(Stanza iq) {
* HttpOverXmppResp resp = (HttpOverXmppResp) iq;
* // check HTTP response code
* if (resp.getStatusCode() == 200) {
* // get content of the response
* NamedElement child = resp.getData().getChild();
* // check which type of content of the response arrived
* if (child instanceof AbstractHttpOverXmpp.Xml) {
* // print the message and anxiously read if from the console ;)
* System.out.println(((AbstractHttpOverXmpp.Xml) child).getText());
* } else {
* // process other AbstractHttpOverXmpp data child subtypes
* }
* }
* }
* });
* </code>
* </pre>
*/
package org.jivesoftware.smackx.hoxt;

View File

@ -16,6 +16,167 @@
*/
/**
* Smack's API for XMPP IoT.
* Smack's API for XMPP IoT (XEP-0323, -0324, -0325, -0347).
* <p>
* The Internet of Things (IoT) XEPs are an experimental open standard how XMPP
* can be used for IoT. They currently consists of
* </p>
* <ul>
* <li>XEP-0323 Sensor Data</li>
* <li>XEP-0324 Provisioning</li>
* <li>XEP-0325 Control</li>
* <li>XEP-0326 Concentrators</li>
* <li>XEP-0347 Discovery</li>
* </ul>
* <p>
* Smack only supports a subset of the functionality described by the XEPs!
* </p>
* <h2>Thing Builder</h2>
* <p>
* The {@link org.jivesoftware.smackx.iot.Thing} class acts as basic entity
* representing a single "Thing" which can be used to retrieve data from or to
* send control commands to. `Things` are constructed using a builder API.
* </p>
* <h2>Reading data from things</h2>
* <p>
* For example, we can build a Thing which provides the current temperature with
* </p>
*
* <pre><code>
* Thing dataThing = Thing.builder().setKey(key).setSerialNumber(sn).setMomentaryReadOutRequestHandler(new ThingMomentaryReadOutRequest() {
* {@literal @}Override
* public void momentaryReadOutRequest(ThingMomentaryReadOutResult callback) {
* int temp = getCurrentTemperature();
* IoTDataField.IntField field = new IntField("temperature", temp);
* callback.momentaryReadOut(Collections.singletonList(field));
* }
* }).build();
* </code></pre>
* <p>
* While not strictly required, most things are identified via a key and serial
* number. We also build the thing with a "momentary read out request handler"
* which when triggered, retrieves the current temperature and reports it back
* to the requestor.
* </p>
* <p>
* After the `Thing` is built, it needs to be made available so that other
* entities within the federated XMPP network can use it. Right now we only
* install the Thing in the `IoTDataManager`, which means the thing will act on
* read out requests but not be managed by a provisioning server.
* </p>
*
* <pre>
* <code>
* IoTDataManager iotDataManager = IoTDataManager.getInstanceFor(connection);
* iotDataManager.installThing(thing);
* </code>
* </pre>
* <p>
* The data can be read out also by using the <code>IoTDataManager</code>:
* </p>
*
* <pre>{@code
* FullJid jid =
* List<IoTFieldsExtension> values = iotDataManager.requestMomentaryValuesReadOut(jid);
* }</pre>
* <p>
* Now you have to unwrap the `IoTDataField` instances from the
* `IoTFieldsExtension`. Note that Smack currently only supports a subset of the
* specified data types.
* </p>
* <h2>Controlling a thing</h2>
* <p>
* Things can also be controlled, e.g. to turn on a light. Let's create a thing
* which can be used to turn the light on and off.
* </p>
*
* <pre>
* <code>
* Thing controlThing = Thing.builder().setKey(key).setSerialNumber(sn).setControlRequestHandler(new ThingControlRequest() {
* {@literal @}Override
* public void processRequest(Jid from, Collection&lt;SetData&gt;} setData) throws XMPPErrorException {
* for (final SetData data : setData) {
* if (!data.getName().equals("light")) continue;
* if (!(data instanceof SetBoolData)) continue;
* SetBoolData boolData = (SetBoolData) data;
* setLight(boolData.getBooleanValue());
* }
* }
* }).build();
* </code>
* </pre>
* <p>
* Now we have to install this thing into the `IoTControlManager`:
* </p>
*
* <pre>
* <code>
* IoTControlManager iotControlManager = IoTControlManager.getInstanceFor(connection);
* iotControlManager.installThing(thing);
* </code>
* </pre>
* <p>
* The `IoTControlManager` can also be used to control a thing:
* </p>
*
* <pre>
* <code>
* FullJid jid =
* SetData setData = new SetBoolData("light", true);
* iotControlManager.setUsingIq(jid, setData);
* </code>
* </pre>
* <p>
* Smack currently only supports a subset of the possible data types for set
* data.
* </p>
* <h2>Discovery</h2>
* <p>
* You may have wondered how a full JIDs of things can be determined. One
* approach is using the discovery mechanisms specified in XEP-0347. Smack
* provides the `IoTDiscoveryManager` as an API for this.
* </p>
* <p>
* For example, instead of just installing the previous things in the
* `IoTDataManager` and/or `IoTControlManager`, we could also use the
* `IoTDiscoveryManger` to register the thing with a registry. Doing this also
* installs the thing in the `IoTDataManager` and the `IoTControlManager`.
* </p>
*
* <pre>
* <code>
* IoTDiscoveryManager iotDiscoveryManager = IoTDiscoveryManager.getInstanceFor(connection);
* iotDiscovyerManager.registerThing(thing);
* </code>
* </pre>
* <p>
* The registry will now make the thing known to a broader audience, and
* available for a potential owner.
* </p>
* <p>
* The `IoTDiscoveryManager` can also be used to claim, disown, remove and
* unregister a thing.
* </p>
* <h2>Provisioning</h2>
* <p>
* Things can usually only be used by other things if they are friends. Since a
* thing normally can't decide on its own if an incoming friendship request
* should be granted or not, we can delegate this decision to a provisioning
* service. Smack provides the `IoTProvisinoManager` to deal with friendship and
* provisioning.
* </p>
* <p>
* For example, if you want to befriend another thing:
* </p>
*
* <pre>
* <code>
* BareJid jid =
* IoTProvisioningManager iotProvisioningManager = IoTProvisioningManager.getInstanceFor(connection);
* iotProvisioningManager.sendFriendshipRequest(jid);
* </code>
* </pre>
*
*
*/
package org.jivesoftware.smackx.iot;

View File

@ -16,10 +16,89 @@
*/
/**
* XEP-0394: Message Markup.
* Smack's API for XEP-0394: Message Markup, which can be used to style message. Message Markup is an alternative to
* XHTML-im to style message, which keeps the message body and the markup information strictly separated.
* <h2>Usage</h2>
* <p>
* The most important class is the {@link org.jivesoftware.smackx.message_markup.element.MarkupElement} class, which
* contains a Builder to construct message markup..
* </p>
* <p>
* To start creating a Message Markup Extension, call
* {@link org.jivesoftware.smackx.message_markup.element.MarkupElement#getBuilder}. (Almost) all method calls documented
* below will be made on the builder.
* </p>
* <p>
* Whenever a method call receives a `start` and `end` index, `start` represents the first character, which is affected
* by the styling, while `end` is the character *after* the last affected character.
* </p>
* <h2>Inline styling</h2>
* <p>
* Currently there are 3 styles available:
* <ul>
* <li>*emphasis*, which should be rendered by a client as *italic*, or **bold**</li>
* <li>*code*, which should be rendered in `monospace`</li>
* <li>*deleted*, which should be rendered as ~~strikethrough~~.</li>
* </ul>
* <p>
* Those styles are available by calling `builder.setEmphasis(int start, int end)`, `builder.setDeleted(int start, int
* end)` and `builder.setCode(int start, int end)`.
* </p>
* <p>
* If you want to apply multiple inline styles to a section, you can do the following:
* </p>
*
* @see <a href="http://xmpp.org/extensions/xep-0394.html">XEP-0394: Message
* Markup</a>
* <pre>
* {@code
* Set<SpanElement.SpanStyle> spanStyles = new HashSet<>();
* styles.add(SpanElement.SpanStyle.emphasis);
* styles.add(SpanElement.SpanStyle.deleted);
* builder.addSpan(start, end, spanStyles);
* }
* </pre>
* <p>
* Note, that spans cannot overlap one another.
* </p>
* <h2 id="block-level-styling">Block Level Styling</h2>
* <p>
* Available block level styles are: * Code blocks, which should be rendered as
* </p>
*
* <pre>
* <code>blocks
* of
* code</code>
* </pre>
* <ul>
* <li>Itemized lists, which should render as
* <ul>
* <li>Lists</li>
* <li>with possibly multiple</li>
* <li>entries</li>
* </ul>
* </li>
* <li>Block Quotes, which should be rendered by the client &gt; as quotes, which &gt;&gt; also can be nested</li>
* </ul>
* <p>
* To mark a section as code block, call <code>builder.setCodeBlock(start, end)</code>.
* </p>
* <p>
* To create a list, call <code>MarkupElement.Builder.ListBuilder lbuilder = builder.beginList()</code>, which will
* return a list builder. On this you can call <code>lbuilder.addEntry(start, end)</code> to add an entry.
* </p>
* <p>
* Note: If you add an entry, the start value MUST be equal to the end value of the previous added entry!
* </p>
* <p>
* To end the list, call <code>lbuilder.endList()</code>, which will return the MessageElement builder.
* </p>
* <p>
* To create a block quote, call <code>builder.setBlockQuote(start, end)</code>.
* </p>
* <p>
* Note that block level elements MUST NOT overlap each other boundaries, but may be fully contained (nested) within
* each other.
* </p>
* @see <a href="http://xmpp.org/extensions/xep-0394.html">XEP-0394: Message Markup</a>
*/
package org.jivesoftware.smackx.message_markup.element;

View File

@ -1,25 +0,0 @@
/**
*
* Copyright 2018 Paul Schaub
*
* 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.
*/
/**
* XEP-0394: Message Markup.
*
* @see <a href="http://xmpp.org/extensions/xep-0394.html">XEP-0394: Message
* Markup</a>
*
*/
package org.jivesoftware.smackx.message_markup;

View File

@ -16,5 +16,23 @@
*/
/**
* Smack's API for XEP-0372: References.
*/
* <p>
* References are a way to refer to other entities like users, other messages or external data from within a message.
* </p>
* <p>
* Typical use-cases are mentioning other users by name, but referencing to their BareJid, or linking to a sent file.
* </p>
* <h2 id="usage">Usage</h2>
* <p>
* Mention a user and link to their bare jid.
* </p>
*
* <pre>
* <code>
* Message message = new Message(&quot;Alice is a realy nice person.&quot;);
* BareJid alice = JidCreate.bareFrom(&quot;alice@capulet.lit&quot;);
* ReferenceManager.addMention(message, 0, 5, alice);
* </code>
* </pre>
*/
package org.jivesoftware.smackx.reference;

View File

@ -15,6 +15,24 @@
* limitations under the License.
*/
/**
* Smack's API for XEP-0382: Spoiler Messages.
*/
* Smack's API for XEP-0382: Spoiler Messages, that can be used to indicate that
* the body of a message is a spoiler and should be displayed as such.
* <h2>Usage</h2>
* <p>
* Invoke {@link SpoilerManager#startAnnounceSupport()} to announce support for
* spoiler messages.
* </p>
* <p>
* Add spoilers to messages via
* {@link org.jivesoftware.smackx.spoiler.element.SpoilerElement#addSpoiler(Message)},
* {@link org.jivesoftware.smackx.spoiler.element.SpoilerElement#addSpoiler(Message, String)},
* or
* {@link org.jivesoftware.smackx.spoiler.element.SpoilerElement#addSpoiler(Message, String, String)}.
* To get spoilers use
* {@link org.jivesoftware.smackx.spoiler.element.SpoilerElement#getSpoilers(Message)}.
* </p>
*
* @see <a href="https://xmpp.org/extensions/xep-0382.html">XEP-0382: Spoiler
* Messages</a>
*/
package org.jivesoftware.smackx.spoiler;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2016-2017 Fernando Ramirez, 2016-2020 Florian Schmaus
* Copyright 2016-2017 Fernando Ramirez, 2016-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -44,7 +44,15 @@ import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
import org.jxmpp.jid.Jid;
/**
* Blocking command manager class.
* Block communications with contancts and other entities using XEP-0191.
* Allows to
* <ul>
* <li>Check push notifications support</li>
* <li>Get blocking list</li>
* <li>Block contact</li>
* <li>Unblock conact</li>
* <li>Unblock all</li>
* </ul>
*
* @author Fernando Ramirez
* @author Florian Schmaus

View File

@ -1,6 +1,6 @@
/**
*
* Copyright © 2009 Jonas Ådahl, 2011-2021 Florian Schmaus
* Copyright © 2009 Jonas Ådahl, 2011-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -77,7 +77,41 @@ import org.jxmpp.jid.Jid;
import org.jxmpp.util.cache.LruCache;
/**
* Keeps track of entity capabilities.
* Manages own and others Entity Capabilities (XEP-0115).
* <p>
* Entity Capabilities is an XMPP extension which, in order to minimize network impact, caches the capabilities of
* remote XMPP entities. Those capabilities are determine with the help of the Service Discovery Protocol
* (<a href="https://xmpp.org/extensions/xep-0030.html">XEP-0030</a>, {@link ServiceDiscoveryManager}).
* </p>
*
* <h2>Usage</h2>
* <p>
* Entity Capabilities work silently in the background when enabled. If the remote XMPP entity does not support XEP-0115
* but XEP-0030 then XEP-0030 mechanisms are transparently used.
* </p>
* <p>
* The caches used by Smack for Entity Capabilities is non-persisent per default. However, it is is also possible to set
* a persistent Entity Capabilities cache, which is recommended.
* </p>
* <h2>Examples</h2>
*
* <h3>Enable Entity Capabilities</h3>
* <pre>{@code
* // Get an instance of entity caps manager for the specified connection
* EntityCapsManager mgr = EntityCapsManager.getInstanceFor(connection);
* // Enable entity capabilities
* mgr.enableEntityCaps();
* }</pre>
*
* <h3>Configure a persistent cache for Entity Capabilities</h3>
* <pre>{@code
* // Get an instance of entity caps manager for the specified connection
* EntityCapsManager mgr = EntityCapsManager.getInstanceFor(connection);
* // Create an cache, see smackx.entitycaps.cache for pre-defined cache implementations
* EntityCapsPersistentCache cache = new SimpleDirectoryPersistentCache(new File("/foo/cachedir"));
* // Set the cache
* mgr.setPersistentCache(cache);
* }</pre>
*
* @author Florian Schmaus
* @see <a href="http://www.xmpp.org/extensions/xep-0115.html">XEP-0115: Entity Capabilities</a>

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,6 @@
*/
/**
* Smacks implementation of XEP-0115: Entity Capabilities.
* Smacks implementation of XEP-0115: Entity Capabilities, see {@link EntityCapsManager} for more information.
*/
package org.jivesoftware.smackx.caps;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,193 @@
*/
/**
* Smacks implementation of XEP-0030: Service Discovery.
* Smack's API for Service Discovery (XEP-0030). The service discovery extension allows one to discover items
* and information about XMPP entities.
* <h2>Manage XMPP entity features</h2>
* <h3>Description</h3>
* <p>
* Any XMPP entity may receive a discovery request and must answer with its associated items or information. Therefore,
* your Smack client may receive a discovery request that must respond to (i.e., if your client supports XHTML- IM).
* This extension automatically responds to a discovery request with the information that you previously configured.
* </p>
* <h3>Usage</h3>
* <p>
* In order to configure the supported features by your client you should first obtain the ServiceDiscoveryManager
* associated with your XMPPConnection. To get your ServiceDiscoveryManager send **getInstanceFor(connection)** to the
* class _**ServiceDiscoveryManager**_ where connection is your XMPPConnection.
* </p>
* <p>
* Once you have your ServiceDiscoveryManager you will be able to manage the supported features. To register a new
* feature send **addFeature(feature)** to your _**ServiceDiscoveryManager**_ where feature is a String that represents
* the supported feature. To remove a supported feature send removeFeature(feature)** to your
* _**ServiceDiscoveryManager**_ where feature is a String that represents the feature to remove.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to add and remove supported features:
* </p>
*
* <pre>{@code
* // Obtain the ServiceDiscoveryManager associated with my XMPP connection
* ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
* // Register that a new feature is supported by this XMPP entity
* discoManager.addFeature(namespace1);
* // Remove the specified feature from the supported features
* discoManager.removeFeature(namespace2);
* }</pre>
*
* <h2>Provide node information</h2>
* <h3>Description</h3>
* <p>
* Your XMPP entity may receive a discovery request for items non-addressable as a JID such as the MUC rooms where you
* are joined. In order to answer the correct information it is necessary to configure the information providers
* associated to the items/nodes within the Smack client.
* </p>
* <h3>Usage</h3>
* <p>
* In order to configure the associated nodes within the Smack client you will need to create a NodeInformationProvider
* and register it with the _**ServiceDiscoveryManager**_. To get your ServiceDiscoveryManager send
** getInstanceFor(connection)** to the class _**ServiceDiscoveryManager**_ where connection is your XMPPConnection.
* </p>
* <p>
* Once you have your ServiceDiscoveryManager you will be able to register information providers for the XMPP entity's
* nodes. To register a new node information provider send **setNodeInformationProvider(String node,
* NodeInformationProvider listener)** to your _**ServiceDiscoveryManager**_ where node is the item non-addressable as a
* JID and listener is the _**NodeInformationProvider**_ to register. To unregister a _**NodeInformationProvider**_ send
* **removeNodeInformationProvider(String node)** to your _**ServiceDiscoveryManager**_ where node is the item non-
* addressable as a JID whose information provider we want to unregister.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to register a NodeInformationProvider with a ServiceDiscoveryManager that will provide
* information concerning a node named "http://jabber.org/protocol/muc#rooms":
* </p>
*
* <pre>{@code
* // Obtain the ServiceDiscoveryManager associated with my XMPPConnection
* ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
* // Get the items of a given XMPP entity
* // This example gets the items associated with online catalog service
* DiscoverItems discoItems = discoManager.discoverItems("plays.shakespeare.lit");
* // Get the discovered items of the queried XMPP entity
* Iterator it = discoItems.getItems().iterator();
* // Display the items of the remote XMPP entity
* while (it.hasNext()) {
* DiscoverItems.Item item = (DiscoverItems.Item) it.next();
* System.out.println(item.getEntityID());
* System.out.println(item.getNode());
* System.out.println(item.getName());
* }
* }</pre>
*
* <h2>Discover items associated with an XMPP entity</h2>
* <h3>Description</h3>
* <p>
* In order to obtain information about a specific item you have to first discover the items available in an XMPP
* entity.
* </p>
* <h3>Usage</h3>
* <p>
* Once you have your ServiceDiscoveryManager you will be able to discover items associated with an XMPP entity. To
* discover the items of a given XMPP entity send **discoverItems(entityID)** to your _**ServiceDiscoveryManager**_
* where entityID is the ID of the entity. The message **discoverItems(entityID)** will answer an instance of
* _**DiscoverItems**_ that contains the discovered items.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to discover the items associated with an online catalog service:
* </p>
*
* <pre>{@code
* // Obtain the ServiceDiscoveryManager associated with my XMPPConnection
* ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
* // Get the items of a given XMPP entity
* // This example gets the items associated with online catalog service
* DiscoverItems discoItems = discoManager.discoverItems("plays.shakespeare.lit");
* // Get the discovered items of the queried XMPP entity
* Iterator it = discoItems.getItems().iterator();
* // Display the items of the remote XMPP entity
* while (it.hasNext()) {
* DiscoverItems.Item item = (DiscoverItems.Item) it.next();
* System.out.println(item.getEntityID());
* System.out.println(item.getNode());
* System.out.println(item.getName());
* }
* }</pre>
*
* <h2>Discover information about an XMPP entity</h2>
* <h3>Description</h3>
* <p>
* Once you have discovered the entity ID and name of an item, you may want to find out more about the item. The
* information desired generally is of two kinds: 1) The item's identity and 2) The features offered by the item.
* </p>
* <p>
* This information helps you determine what actions are possible with regard to this item (registration, search, join,
* etc.) as well as specific feature types of interest, if any (e.g., for the purpose of feature negotiation).
* </p>
* <h3>Usage</h3>
* <p>
* Once you have your ServiceDiscoveryManager you will be able to discover information associated with an XMPP entity.
* To discover the information of a given XMPP entity send **discoverInfo(entityID)** to your
* _**ServiceDiscoveryManager**_ where entityID is the ID of the entity. The message **discoverInfo(entityID)** will
* answer an instance of _**DiscoverInfo**_ that contains the discovered information.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to discover the information of a conference room:
* </p>
*
* <pre>{@code
* // Obtain the ServiceDiscoveryManager associated with my XMPPConnection
* ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
* // Get the information of a given XMPP entity
* // This example gets the information of a conference room
* DiscoverInfo discoInfo = discoManager.discoverInfo("balconyscene@plays.shakespeare.lit");
* // Get the discovered identities of the remote XMPP entity
* Iterator it = discoInfo.getIdentities().iterator();
* // Display the identities of the remote XMPP entity
* while (it.hasNext()) {
* DiscoverInfo.Identity identity = (DiscoverInfo.Identity) it.next();
* System.out.println(identity.getName());
* System.out.println(identity.getType());
* System.out.println(identity.getCategory());
* }
* // Check if room is password protected
* discoInfo.containsFeature("muc_passwordprotected");
* }</pre>
*
* <h2>Publish publicly available items</h2>
* <h3>Description</h3>
* <p>
* Publish your entity items to some kind of persistent storage. This enables other entities to query that entity using
* the disco#items namespace and receive a result even when the entity being queried is not online (or available).
* </p>
* <h3>Usage</h3>
* <p>
* Once you have your ServiceDiscoveryManager you will be able to publish items to some kind of persistent storage. To
* publish the items of a given XMPP entity you have to first create an instance of _**DiscoverItems**_ and configure it
* with the items to publish. Then you will have to send publishItems(Jid entityID, DiscoverItems discoverItems)** to
* your _**ServiceDiscoveryManager**_ where entityID is the address of the XMPP entity that will persist the items and
* discoverItems contains the items to publish.
* </p>
* <h3>Examples</h3> In this example we can see how to publish new items:
*
* <pre>{@code
* // Obtain the ServiceDiscoveryManager associated with my XMPPConnection
* ServiceDiscoveryManager discoManager = ServiceDiscoveryManager.getInstanceFor(connection);
* // Create a DiscoverItems with the items to publish
* DiscoverItems itemsToPublish = new DiscoverItems();
* Jid jid = JidCreate.from("pubsub.shakespeare.lit");
* DiscoverItems.Item itemToPublish = new DiscoverItems.Item(jid);
* itemToPublish.setName("Avatar");
* itemToPublish.setNode("romeo/avatar");
* itemToPublish.setAction(DiscoverItems.Item.UPDATE_ACTION);
* itemsToPublish.addItem(itemToPublish);
* // Publish the new items by sending them to the server
* Jid jid2 = JidCreate.from("host");
* discoManager.publishItems(jid2, itemsToPublish);
* }</pre>
*
* @see <a href="https://www.xmpp.org/extensions/xep-0030.html">XEP-0030: Service Discovery</a>
*/
package org.jivesoftware.smackx.disco;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,156 @@
*/
/**
* File Transfers via XEP-0095: Stream Initialization.
* Smack's API for File Transfers. The file transfer extension allows the user to transmit and receive files.
* <ul>
* <li>Send a file to another user</li>
* <li>Receiving a file from another user</li>
* <li>Monitoring the progress of a file transfer</li>
* </ul>
* <h2>Send a file to another user</h2>
* <h3>Description</h3>
* <p>
* A user may wish to send a file to another user. The other user has the option of accepting, rejecting, or ignoring
* the users request. Smack provides a simple interface in order to enable the user to easily send a file.
* </p>
* <h3>Usage</h3>
* <p>
* In order to send a file you must first construct an instance of the _FileTransferManager_** class. In order to
* instantiate the manager you should call _FileTransferManager.getInstanceFor(connection)_, where connection is an
* XMPPConnection instance.
* </p>
* <p>
* Once you have your **_FileTransferManager_** you will need to create an outgoing file transfer to send a file. The
* method to use on the _FileTransferManager_** is the **createOutgoingFileTransfer(userID)** method. The userID you
* provide to this method is the fully-qualified jabber ID of the user you wish to send the file to. A fully-qualified
* jabber ID consists of a node, a domain, and a resource. The user must be connected to the resource in order to be
* able to receive the file transfer.
* </p>
* <p>
* Now that you have your **_OutgoingFileTransfer_** instance you will want to send the file. The method to send a file
* is **sendFile(file, description)**. The file you provide to this method should be a readable file on the local file
* system, and the description is a short description of the file to help the user decide whether or not they would like
* to receive the file.
* </p>
* <p>
* For information on monitoring the progress of a file transfer see the monitoring progress section of this document.
* </p>
* <p>
* Other means to send a file are also provided as part of the _OutgoingFileTransfer_**. Please consult the Javadoc for
* more information.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to send a file:
* </p>
*
* <pre>{@code
* // Create the file transfer manager
* FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
* // Create the outgoing file transfer
* OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(entityFullJid);
* // Send the file
* transfer.sendFile(new File("shakespeare_complete_works.txt"), "You won't believe this!");
* }</pre>
*
* <h2>Receiving a file from another user</h2>
* <h3>Description</h3>
* <p>
* The user may wish to receive files from another user. The process of receiving a file is event driven, new file
* transfer requests are received from other users via a listener registered with the file transfer manager.
* </p>
* <h3>Usage</h3>
* <p>
* In order to receive a file you must first construct an instance of the _FileTransferManager_** class. This class has
* one static factory method with one parameter which is your XMPPConnection. In order to instantiate the manager you
* should call _FileTransferManager.getInstanceFor(connection)_.
* </p>
* <p>
* Once you have your **_FileTransferManager_** you will need to register a listener with it. The FileTransferListener
* interface has one method, fileTransferRequest(request)**. When a request is received through this method, you can
* either accept or reject the request. To help you make your decision there are several methods in the
* **_FileTransferRequest_** class that return information about the transfer request.
* </p>
* <p>
* To accept the file transfer, call the **accept()** method. This method will create an _IncomingFileTransfer_**. After
* you have the file transfer you may start to transfer the file by calling the **recieveFile(file)** method. The file
* provided to this method will be where the data from the file transfer is saved.
* </p>
* <p>
* Finally, to reject the file transfer the only method you need to call is reject()** on the **_FileTransferRequest_**.
* </p>
* <p>
* For information on monitoring the progress of a file transfer see the monitoring progress section of this document.
* </p>
* <p>
* Other means to receive a file are also provided as part of the _IncomingFileTransfer_**. Please consult the Javadoc
* for more information.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to approve or reject a file transfer request:
* </p>
*
* <pre>{@code
* // Create the file transfer manager
* final FileTransferManager manager = FileTransferManager.getInstanceFor(connection);
* // Create the listener
* manager.addFileTransferListener(new FileTransferListener() {
* public void fileTransferRequest(FileTransferRequest request) {
* // Check to see if the request should be accepted
* if (shouldAccept(request)) {
* // Accept it
* IncomingFileTransfer transfer = request.accept();
* transfer.recieveFile(new File("shakespeare_complete_works.txt"));
* } else {
* // Reject it
* request.reject();
* }
* }
* });
* }</pre>
*
* <h2>Monitoring the progress of a file transfer</h2>
* <h3>Description</h3>
* <p>
* While a file transfer is in progress you may wish to monitor the progress of a file transfer.
* </p>
* <h3>Usage</h3>
* <p>
* Both the **_IncomingFileTransfer_** and the **_OutgoingFileTransfer_** extend the **_FileTransfer_** class which
* provides several methods to monitor how a file transfer is progressing:
* </p>
* <ul>
* <li>**getStatus()** - The file transfer can be in several states, negotiating, rejected, cancelled, in progress,
* error, and complete. This method will return which state the file transfer is currently in.</li>
* <li>**getProgress()** - If the status of the file transfer is in progress this method will return a number between 0
* and 1, 0 being the transfer has not yet started and 1 being the transfer is complete. It may also return a -1 if the
* transfer is not in progress.</li>
* <li>**isDone()** - Similar to getProgress() except it returns a _boolean_. If the state is rejected, canceled, error,
* or complete then true will be returned and false otherwise.</li>
* <li>**getError()** - If there is an error during the file transfer this method will return the type of error that
* occured.</li>
* </ul>
* <h3>Examples</h3>
* <p>
* In this example we can see how to monitor a file transfer:
* </p>
*
* <pre>{@code
* while (!transfer.isDone()) {
* if (transfer.getStatus().equals(Status.error)) {
* System.out.println("ERROR!!! " + transfer.getError());
* } else {
* System.out.println(transfer.getStatus());
* System.out.println(transfer.getProgress());
* }
* sleep(1000);
* }
* }</pre>
*
* @see <a href="https://xmpp.org/extensions/xep-0047.html">XEP-0047: In-Band Bytestreams</a>
* @see <a href="https://xmpp.org/extensions/xep-0065.html">XEP-0065: SOCKS5 Bytestreams</a> *
* @see <a href="https://xmpp.org/extensions/xep-0095.html">XEP-0095: Stream Initiation</a> *
* @see <a href="https://xmpp.org/extensions/xep-0096.html">XEP-0096: SI File Transfer</a> *
*/
package org.jivesoftware.smackx.filetransfer;

View File

@ -17,5 +17,19 @@
/**
* Smacks implementation of XEP-0049: Private XML Storage.
* <p>
* Manages private data, which is a mechanism to allow users to store arbitrary XML data on an XMPP server. Each private
* data chunk is defined by a element name and XML namespace. Example private data:
* </p>
*
* <pre>
* <code>
* &lt;color xmlns=&quot;http://example.com/xmpp/color&quot;&gt;
* &lt;favorite&gt;blue&lt;/blue&gt;
* &lt;leastFavorite&gt;puce&lt;/leastFavorite&gt;
* &lt;/color&gt;
* </code>
* </pre>
* @see <a href="https://xmpp.org/extensions/xep-0049.html">XEP-0049: Private XML Storage</a>
*/
package org.jivesoftware.smackx.iqprivate;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2003-2007 Jive Software, 2014-2021 Florian Schmaus
* Copyright 2003-2007 Jive Software, 2014-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -34,6 +34,72 @@ import org.jxmpp.jid.FullJid;
/**
* The Jingle element.
*
* <h2>Jingle Element Structure</h2>
* <pre>{@code
* jingle
* action (REQUIRED, XEP-0166 § 7.2)
* | content-accept
* | content-add
* | content-modify
* | content-reject
* | content-remove
* | description-info
* | security-info
* | session-accept
* | session-info
* | session-initiate
* | transport-accept
* | transport-info
* | transport-reject
* | transport-replace
* initator (RECOMMENDED for session initiate, NOT RECOMMENDED otherwise, full JID, XEP-0166 § 7.1)
* responder (RECOMMENDED for session accept, NOT RECOMMENDED otherwise, full JID. XEP-0166 § 7.1)
* sid (REQUIRED, SHOULD match XML Nmtoken production)
*
* <reason/> (optional, XEP-0166 § 7.4)
*
* (alternativesessionbusy..)
*
* <content/> (one or more, XEP-0166 § 7.3)
* creator (REQUIRED, must be one of)
* | initiator
* | responder
* disposition (OPTIONAL)
* name (REQUIRED)
* senders (OPTIONAL, except when content-modify then REQUIRED)
* | both (default)
* | initiator
* | none
* | responder
*
* description
* media
* xmlns
*
* payloadtype
*
* file (XEP0234)
*
* transport
* xmlns
* pwd (OPTIONAL, XEP-0176 Jingle ICE)
* ufrag (OPTIONAL, XEP-0176 Jingle ICE)
* mode (XEP-0234 Jingle File Transfer)
* sid (XEP-0234 Jingle File Transfer)
*
* candidate
* component
* foundation
* generation
* id
* ip
* network
* port
* priority
* protocol
* type
* }</pre>
*
* @author Florian Schmaus
*/
public final class Jingle extends IQ {

View File

@ -18,5 +18,89 @@
/**
* Smacks implementation for attaching arbitrary properties to packets according to
* https://docs.jivesoftware.com/smack/latest/documentation/properties.html.
* <p>
* Smack provides an easy mechanism for attaching arbitrary properties to packets. Each property has a String name, and
* a value that is a Java primitive (int, long, float, double, boolean) or any Serializable object (a Java object is
* Serializable when it implements the Serializable interface).
* </p>
* <h2 id="using-the-api">Using the API</h2>
* <p>
* All major objects have property support, such as Message objects. The following code demonstrates how to set
* properties:
* </p>
*
* <pre>
* <code>Message message = chat.createMessage();
JivePropertiesExtension jpe = new JivePropertiesExtension();
// Add a Color object as a property._
jpe.setProperty(&quot;favoriteColor&quot;, new Color(0, 0, 255));
// Add an int as a property._
jpe.setProperty(&quot;favoriteNumber&quot;, 4);
// Add the JivePropertiesExtension to the message packet_
message.addStanzaExtension(jpe);
chat.sendMessage(message);</code>
* </pre>
* <p>
* Getting those same properties would use the following code:
* </p>
*
* <pre>
* <code>
* Message message = chat.nextMessage();
* // Get the JivePropertiesExtension_
* JivePropertiesExtension jpe = message.getExtension(JivePropertiesExtension.NAMESPACE);
* // Get a Color object property._
* Color favoriteColor = (Color)jpe.getProperty(&quot;favoriteColor&quot;);
* // Get an int property. Note that properties are always returned as
* // Objects, so we must cast the value to an Integer, then convert
* // it to an int._
* int favoriteNumber = ((Integer)jpe.getProperty(&quot;favoriteNumber&quot;)).intValue();
* </code>
* </pre>
* <p>
* For convenience <code>JivePropertiesManager</code> contains two helper methods namely
* <code>addProperty(Stanza packet, String name, Object value)</code> and
* <code>getProperty(Stanza packet, String name)</code>.
* </p>
* <h2 id="objects-as-properties">Objects as Properties</h2>
* <p>
* Using objects as property values is a very powerful and easy way to exchange data. However, you should keep the
* following in mind:
* </p>
* <ul>
* <li>When you send a Java object as a property, only clients running Java will be able to interpret the data. So,
* consider using a series of primitive values to transfer data instead.</li>
* <li>Objects sent as property values must implement Serialiable. Additionally, both the sender and receiver must have
* identical versions of the class, or a serialization exception will occur when de-serializing the object.</li>
* <li>Serialized objects can potentially be quite large, which will use more bandwidth and server resources.</li>
* </ul>
* <h2 id="xml-format">XML Format</h2>
* <p>
* The current XML format used to send property data is not a standard, so will likely not be recognized by clients not
* using Smack. The XML looks like the following (comments added for clarity):
* </p>
*
* <pre>
* <code>
* &lt;!-- All properties are in a x block. --&gt;
* &lt;properties xmlns=&quot;http://www.jivesoftware.com/xmlns/xmpp/properties&quot;&gt;
* &lt;!-- First, a property named &quot;prop1&quot; that&#39;s an integer. --&gt;
* &lt;property&gt;
* &lt;name&gt;prop1&lt;/name&gt;
* &lt;value type=&quot;integer&quot;&gt;123&lt;/value&gt;
* &lt;property&gt;
* &lt;!-- Next, a Java object that&#39;s been serialized and then converted
* from binary data to base-64 encoded text. --&gt;
* &lt;property&gt;
* &lt;name&gt;blah2&lt;/name&gt;
* &lt;value type=&quot;java-object&quot;&gt;adf612fna9nab&lt;/value&gt;
* &lt;property&gt;
* &lt;/properties&gt;
* </code>
* </pre>
* <p>
* The currently supported types are: <code>integer</code>, <code>long</code>, <code>float</code>, <code>double</code>,
* <code>boolean</code>, <code>string</code>, and <code>java-object</code>.
* </p>
*/
package org.jivesoftware.smackx.jiveproperties;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2023 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,674 @@
*/
/**
* Classes and Interfaces that implement Multi-User Chat (MUC) as defined in XEP-0045.
* Smack API for Multi-User Chat (MUC, XEP-0045). This API allows configuration of, participation in, and administration
* of individual text-based conference rooms. The two key API classes are {@link MultiUserChatManager} and
* {@link MultiUserChat}.
* <h2>Create a new Room</h2>
* <h3>Description</h3>
* <p>
* Allowed users may create new rooms. There are two types of rooms that you can create. **Instant rooms** which are
* available for immediate access and are automatically created based on some default configuration and **Reserved
* rooms** which are manually configured by the room creator before anyone is allowed to enter.
* </p>
* <h3>Usage</h3>
* <p>
* In order to create a room you will need to first create an instance of _* *MultiUserChat**_. In order to do so, get a
* instance of `MultiUserChatManager` and call `getMultiUserChat(String)` to retrieve a `MultiUserChat` instance. The
* next step is to send **create(String nickname)** to the _**MultiUserChat**_ instance where nickname is the nickname
* to use when joining the room. Depending on the type of room that you want to create you will have to use different
* configuration forms. In order to create an Instant room just use `MucCreateConfigFormHandle.makeInstant()`. But if
* you want to create a Reserved room then you should first get the room's configuration form, complete the form and
* finally send it back to the server.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to create an instant room:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
* // Get a MultiUserChat using MultiUserChatManager
* MultiUserChat muc = manager.getMultiUserChat(mucJid);
* // Create the room and send an empty configuration form to make this an instant room
* muc.create(nickname).makeInstant();
* }</pre>
* <p>
* In this example we can see how to create a reserved room. The form is completed with default values:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
* // Create a MultiUserChat using an XMPPConnection for a room
* MultiUserChat muc = manager.getMultiUserChat(mucJid);
* // Prepare a list of owners of the new room
* Set<Jid> owners = JidUtil.jidSetFrom(new String[] { "me@example.org", "juliet@example.org" });
* // Create the room
* muc.create(nickname).getConfigFormManger().setRoomOwners(owners).submitConfigurationForm();
* }</pre>
*
* <h2>Join a room</h2>
* <h3>Description</h3>
* <p>
* Your usual first step in order to send messages to a room is to join the room. Multi User Chat allows to specify
* several parameter while joining a room. Basically you can control the amount of history to receive after joining the
* room as well as provide your nickname within the room and a password if the room is password protected.
* </p>
* <h3>Usage</h3>
* <p>
* In order to join a room you will need to first get an instance of _**MultiUserChat**_. In order to do so, get a
* instance of `MultiUserChatManager` and call `getMultiUserChat(String)` to retrieve a `MultiUserChat` instance. The
* next step is to send **join(...)** to the _**MultiUserChat**_ instance. But first you will have to decide which join
* message to send. If you want to just join the room without a password and without specifying the amount of history to
* receive then you could use join(String nickname)** where nickname if your nickname in the room. In case the room
* requires a password in order to join you could then use **join(String nickname, String password)**. And finally, the
* most complete way to join a room is to send **join(String nickname, String password, DiscussionHistory history, long
* timeout)** where nickname is your nickname in the room, , password is your password to join the room, history is an
* object that specifies the amount of history to receive and timeout is the milliseconds to wait for a response from
* the server.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to join a room with a given nickname:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
* // Create a MultiUserChat using an XMPPConnection for a room
* MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
* // User2 joins the new room
* // The room service will decide the amount of history to send
* muc2.join(nickname);
* }</pre>
* <p>
* In this example we can see how to join a room with a given nickname and password:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
* // Create a MultiUserChat using an XMPPConnection for a room
* MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
* // User2 joins the new room using a password
* // The room service will decide the amount of history to send
* muc2.join(nickname, "password");
* }</pre>
* <p>
* In this example we can see how to join a room with a given nickname specifying the amount of history to receive:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
*
* // Create a MultiUserChat using an XMPPConnection for a room
* MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
*
* // User2 joins the new room using a password and specifying
* // the amount of history to receive. In this example we are requesting the last 5 messages.
* DiscussionHistory history = new DiscussionHistory();
* history.setMaxStanzas(5);
* muc2.join(nickname, "password", history, conn1.getPacketReplyTimeout());
* }</pre>
*
* <h2>Manage room invitations</h2>
* <h3>Description</h3>
* <p>
* It can be useful to invite another user to a room in which one is an occupant. Depending on the room's type the
* invitee could receive a password to use to join the room and/or be added to the member list if the room is of type
* members-only. Smack allows to send room invitations and let potential invitees to listening for room invitations and
* inviters to listen for invitees' rejections.
* </p>
* <h3>Usage</h3>
* <p>
* In order to invite another user to a room you must be already joined to the room. Once you are joined just send
* **invite(String participant, String reason)** to the _**MultiUserChat**_ where participant is the user to invite to
* the room (e.g. hecate@shakespeare.lit) and reason is the reason why the user is being invited.
* </p>
* <p>
* If potential invitees want to listen for room invitations then the invitee must add an _**InvitationListener**_ to
* the _**MultiUserChatManager**_ class. Since the _**InvitationListener**_ is an _interface_, it is necessary to create
* a class that implements this _interface_. If an inviter wants to listen for room invitation rejections, just add an
* _**InvitationRejectionListener**_ to the _**MultiUserChat**_. _**InvitationRejectionListener**_ is also an interface
* so you will need to create a class that implements this interface.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to invite another user to the room and lister for possible rejections:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
*
* // Create a MultiUserChat using an XMPPConnection for a room
* MultiUserChat muc2 = manager.getMultiUserChat(mucJid);
*
* muc2.join(nickname);
* // User2 listens for invitation rejections
* muc2.addInvitationRejectionListener(new InvitationRejectionListener() {
* public void invitationDeclined(String invitee, String reason) {
* // Do whatever you need here...
* }
* });
* // User2 invites user3 to join to the room
* muc2.invite(otherJid, "Meet me in this excellent room");
* }</pre>
* <p>
* In this example we can see how to listen for room invitations and decline invitations:
* </p>
*
* <pre>{@code
* // User3 listens for MUC invitations
* MultiUserChatManager.getInstanceFor(connection).addInvitationListener(new InvitationListener() {
* public void invitationReceived(XMPPConnection conn, String room, EntityFullJid inviter, String reason,
* String password) {
* // Reject the invitation
* MultiUserChat.decline(conn, room, inviter.asBareJid(), "I'm busy right now");
* }
* });
* }</pre>
*
* <h2>Discover MUC support</h2>
* <h3>Description</h3>
* <p>
* A user may want to discover if one of the user's contacts supports the Multi-User Chat protocol.
* </p>
* <h3>Usage</h3>
* <p>
* In order to discover if one of the user's contacts supports MUC just send isServiceEnabled(String user)** to the
* _**MultiUserChatManager**_ class where user is a fully qualified XMPP ID, e.g. jdoe@example.com. You will receive a
* boolean indicating whether the user supports MUC or not.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to discover support of MUC:
* </p>
*
* <pre>{@code
* // Discover whether user3@host.org supports MUC or not
* boolean supportsMuc = MultiUserChatManager.getInstanceFor(connection).isServiceEnabled(otherJid);
* }</pre>
*
* <h2>Discover joined rooms</h2>
* <h3>Description</h3>
* <p>
* A user may also want to query a contact regarding which rooms the contact is in.
* </p>
* <h3>Usage</h3>
* <p>
* In order to get the rooms where a user is in just send getJoinedRooms(String user)** to the
* _**MultiUserChatManager**_ class where user is a fully qualified XMPP ID, e.g. jdoe@example.com. You will get an
* Iterator of Strings as an answer where each String represents a room name.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to get the rooms where a user is in:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
*
* // Get the rooms where user3@host.org has joined
* List<String> joinedRooms = manager.getJoinedRooms("user3@host.org/Smack");
* }</pre>
*
* <h2>Discover room information</h2>
* <h3>Description</h3>
* <p>
* A user may need to discover information about a room without having to actually join the room. The server will
* provide information only for public rooms.
* </p>
* <h3>Usage</h3>
* <p>
* In order to discover information about a room just send getRoomInfo(String room)** to the _**MultiUserChatManager**_
* class where room is the XMPP ID of the room, e.g. roomName@conference.myserver. You will get a RoomInfo object that
* contains the discovered room information.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to discover information about a room:
* </p>
*
* <pre>{@code
* // Get the MultiUserChatManager
* MultiUserChatManager manager = MultiUserChatManager.getInstanceFor(connection);
*
* // Discover information about the room roomName@conference.myserver
* RoomInfo info = manager.getRoomInfo("roomName@conference.myserver");
* System.out.println("Number of occupants:" + info.getOccupantsCount());
* System.out.println("Room Subject:" + info.getSubject());
* }</pre>
*
* <h2>Start a private chat</h2>
* <h3>Description</h3>
* <p>
* A room occupant may want to start a private chat with another room occupant even though they don't know the fully
* qualified XMPP address (e.g. jdoe@example.com) of each other.
* </p>
* <h3>Usage</h3>
* <p>
* To create a private chat with another room occupant just send createPrivateChat(String participant)** to the
* _**MultiUserChat**_ that you used to join the room. The parameter participant is the occupant unique room JID (e.g.
* 'darkcave@macbeth.shakespeare.lit/Paul'). You will receive a regular _**Chat**_ object that you can use to chat with
* the other room occupant.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to start a private chat with another room occupant:
* </p>
*
* <pre>{@code
* // Start a private chat with another participant
* Chat chat = muc2.createPrivateChat("myroom@conference.jabber.org/johndoe");
* chat.sendMessage("Hello there");
* }</pre>
*
* <h2>Manage changes on room subject</h2>
* <h3>Description</h3>
* <p>
* A common feature of multi-user chat rooms is the ability to change the subject within the room. As a default, only
* users with a role of "moderator" are allowed to change the subject in a room. Although some rooms may be configured
* to allow a mere participant or even a visitor to change the subject.
* </p>
* <p>
* Every time the room's subject is changed you may want to be notified of the modification. The new subject could be
* used to display an in-room message.
* </p>
* <h3>Usage</h3>
* <p>
* In order to modify the room's subject just send **changeSubject(String subject)** to the _**MultiUserChat**_ that you
* used to join the room where subject is the new room's subject. On the other hand, if you want to be notified whenever
* the room's subject is modified you should add a _**SubjectUpdatedListener**_ to the _**MultiUserChat**_ by sending
** addSubjectUpdatedListener(SubjectUpdatedListener listener)** to the _**MultiUserChat**_. Since the
* _**SubjectUpdatedListener**_ is an _interface_, it is necessary to create a class that implements this _interface_.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to change the room's subject and react whenever the room's subject is modified:
* </p>
*
* <pre>{@code
* // An occupant wants to be notified every time the room's subject is changed
* muc3.addSubjectUpdatedListener(new SubjectUpdatedListener() {
* public void subjectUpdated(String subject, String from) {
* ....
* }
* });
* // A room's owner changes the room's subject
* muc2.changeSubject("New Subject");
* }</pre>
*
* <h2></h2>
* <h3>Description</h3>
* <p>
* There are four defined roles that an occupant can have:
* </p>
* <ol>
* <li>Moderator</li>
* <li>Participant</li>
* <li>Visitor</li>
* <li>None (the absence of a role)</li>
* </ol>
* <p>
* These roles are temporary in that they do not persist across a user's visits to the room and can change during the
* course of an occupant's visit to the room.
* </p>
* <p>
* A moderator is the most powerful occupant within the context of the room, and can to some extent manage other
* occupants' roles in the room. A participant has fewer privileges than a moderator, although he or she always has the
* right to speak. A visitor is a more restricted role within the context of a moderated room, since visitors are not
* allowed to send messages to all occupants.
* </p>
* <p>
* Roles are granted, revoked, and maintained based on the occupant's room nickname or full JID. Whenever an occupant's
* role is changed Smack will trigger specific events.
* </p>
* <h3>Usage</h3>
* <p>
* In order to grant voice (i.e. make someone a _participant_) just send the message **grantVoice(String nickname)** to
* _**MultiUserChat**_. Use revokeVoice(String nickname)** to revoke the occupant's voice (i.e. make the occupant a
* _visitor_).
* </p>
* <p>
* In order to grant moderator privileges to a participant or visitor just send the message **grantModerator(String
* nickname)** to _**MultiUserChat**_. Use revokeModerator(String nickname)** to revoke the moderator privilege from the
* occupant thus making the occupant a participant.
* </p>
* <p>
* Smack allows you to listen for role modification events. If you are interested in listening role modification events
* of any occupant then use the listener _ParticipantStatusListener_**. But if you are interested in listening for your
* own role modification events, use the listener **_UserStatusListener_**. Both listeners should be added to the
* _**MultiUserChat**_ by using addParticipantStatusListener(ParticipantStatusListener listener)** or
** addUserStatusListener(UserStatusListener listener)** respectively. These listeners include several notification
* events but you may be interested in just a few of them. Smack provides default implementations for these listeners
* avoiding you to implement all the interfaces' methods. The default implementations are
* **_DefaultUserStatusListener_** and _DefaultParticipantStatusListener_**. Below you will find the sent messages to
* the listeners whenever an occupant's role has changed.
* </p>
* <p>
* These are the triggered events when the role has been upgraded:
* </p>
* <table border="1">
* <caption>Role Upgrade paths</caption>
* <tr>
* <th>Old</th>
* <th>New</th>
* <th>Events</th>
* </tr>
* <tr>
* <td>None</td>
* <td>Visitor</td>
* <td>--</td>
* </tr>
* <tr>
* <td>Visitor</td>
* <td>Participant</td>
* <td>voiceGranted</td>
* </tr>
* <tr>
* <td>Participant</td>
* <td>Moderator</td>
* <td>moderatorGranted</td>
* </tr>
* <tr>
* <td>None</td>
* <td>Participant</td>
* <td>voiceGranted</td>
* </tr>
* <tr>
* <td>None</td>
* <td>Moderator</td>
* <td>voiceGranted + moderatorGranted</td>
* </tr>
* <tr>
* <td>Visitor</td>
* <td>Moderator</td>
* <td>voiceGranted + moderatorGranted</td>
* </tr>
* </table>
* <p>
* These are the triggered events when the role has been downgraded:
* </p>
* <table border="1">
* <caption>Role Downgrade paths</caption>
* <tr>
* <th>Old</th>
* <th>New</th>
* <th>Events</th>
* </tr>
* <tr>
* <td>Moderator</td>
* <td>Participant</td>
* <td>moderatorRevoked</td>
* </tr>
* <tr>
* <td>Participant</td>
* <td>Vistor</td>
* <td>voiceRevoked</td>
* </tr>
* <tr>
* <td>Visitor</td>
* <td>None</td>
* <td>kicked</td>
* </tr>
* <tr>
* <td>Moderator</td>
* <td>Visitor</td>
* <td>voiceRevoked + moderatorRevoked</td>
* </tr>
* <tr>
* <td>Moderator</td>
* <td>None</td>
* <td>kicked</td>
* </tr>
* <tr>
* <td>Participant</td>
* <td>None</td>
* <td>kicked</td>
* </tr>
* </table>
* <h3>Examples</h3>
* <p>
* In this example we can see how to grant voice to a visitor and listen for the notification events:
* </p>
*
* <pre>{@code
* // User1 creates a room
* muc = manager.getMultiUserChat("myroom@conference.jabber.org");
* muc.create("testbot");
* // User1 (which is the room owner) configures the room as a moderated room
* Form form = muc.getConfigurationForm();
* FillableForm answerForm = configForm.getFillableForm();
* answerForm.setAnswer("muc#roomconfig_moderatedroom", "1");
* muc.sendConfigurationForm(answerForm);
*
* // User2 joins the new room (as a visitor)
* MultiUserChat muc2 = manager2.getMultiUserChat("myroom@conference.jabber.org");
* muc2.join("testbot2");
* // User2 will listen for his own "voice" notification events
* muc2.addUserStatusListener(new DefaultUserStatusListener() {
* public void voiceGranted() {
* super.voiceGranted();
* ...
* }
* public void voiceRevoked() {
* super.voiceRevoked();
* ...
* }
* });
*
* // User3 joins the new room (as a visitor)
* MultiUserChat muc3 = manager3.getMultiUserChat("myroom@conference.jabber.org");
* muc3.join("testbot3");
* // User3 will lister for other occupants "voice" notification events
* muc3.addParticipantStatusListener(new DefaultParticipantStatusListener() {
* public void voiceGranted(String participant) {
* super.voiceGranted(participant);
* ...
* }
* public void voiceRevoked(String participant) {
* super.voiceRevoked(participant);
* ...
* }
* });
*
* // The room's owner grants voice to user2
* muc.grantVoice("testbot2");
* }</pre>
*
* <h2>Manage affiliation modifications</h2>
* <h3>Description</h3>
* <p>
* There are five defined affiliations that a user can have in relation to a room:
* </p>
* <ol>
* <li>Owner</li>
* <li>Admin</li>
* <li>Member</li>
* <li>Outcast</li>
* <li>None (the absence of an affiliation)</li>
* </ol>
* <p>
* These affiliations are semi-permanent in that they persist across a user's visits to the room and are not affected by
* happenings in the room. Affiliations are granted, revoked, and maintained based on the user's bare JID.
* </p>
* <p>
* If a user without a defined affiliation enters a room, the user's affiliation is defined as "none"; however, this
* affiliation does not persist across visits.
* </p>
* <p>
* Owners and admins are by definition immune from certain actions. Specifically, an owner or admin cannot be kicked
* from a room and cannot be banned from a room. An admin must first lose his or her affiliation (i.e., have an
* affiliation of "none" or "member") before such actions could be performed on them.
* </p>
* <p>
* The member affiliation provides a way for a room owner or admin to specify a "whitelist" of users who are allowed to
* enter a members-only room. When a member enters a members-only room, his or her affiliation does not change, no
* matter what his or her role is. The member affiliation also provides a way for users to effectively register with an
* open room and thus be permanently associated with that room in some way (one result may be that the user's nickname
* is reserved in the room).
* </p>
* <p>
* An outcast is a user who has been banned from a room and who is not allowed to enter the room. Whenever a user's
* affiliation is changed Smack will trigger specific events.
* </p>
* <h3>Usage</h3>
* <p>
* In order to grant membership to a room, administrator privileges or owner priveliges just send
* **grantMembership(String jid)**, **grantAdmin(String jid)** or **grantOwnership(String jid)** to _**MultiUserChat**_
* respectively. Use **revokeMembership(String jid)**, **revokeAdmin(String jid)** or revokeOwnership(String jid)** to
* revoke the membership to a room, administrator privileges or owner priveliges respectively.
* </p>
* <p>
* In order to ban a user from the room just send the message **banUser(String jid, String reason)** to
* _**MultiUserChat**_.
* </p>
* <p>
* Smack allows you to listen for affiliation modification events. If you are interested in listening affiliation
* modification events of any user then use the listener **_ParticipantStatusListener_**. But if you are interested in
* listening for your own affiliation modification events, use the listener _UserStatusListener_**. Both listeners
* should be added to the _**MultiUserChat**_ by using addParticipantStatusListener(ParticipantStatusListener
* listener)** or addUserStatusListener(UserStatusListener listener)** respectively. These listeners include several
* notification events but you may be interested in just a few of them. Smack provides default implementations for these
* listeners avoiding you to implement all the interfaces' methods. The default implementations are
* **_DefaultUserStatusListener_** and _DefaultParticipantStatusListener_**. Below you will find the sent messages to
* the listeners whenever a user's affiliation has changed.
* </p>
* <p>
* These are the triggered events when the affiliation has been upgraded:
* </p>
* <table border="1">
* <caption>Affiliation Upgrade paths</caption>
* <tr>
* <th>Old</th>
* <th>New</th>
* <th>Events</th>
* </tr>
* <tr>
* <td>None</td>
* <td>Member</td>
* <td>membershipGranted</td>
* </tr>
* <tr>
* <td>Member</td>
* <td>Admin</td>
* <td>membershipRevoked + adminGranted</td>
* </tr>
* <tr>
* <td>Admin</td>
* <td>Owner</td>
* <td>adminRevoked + ownershipGranted</td>
* </tr>
* <tr>
* <td>None</td>
* <td>Admin</td>
* <td>adminGranted</td>
* </tr>
* <tr>
* <td>None</td>
* <td>Owner</td>
* <td>ownershipGranted</td>
* </tr>
* <tr>
* <td>Member</td>
* <td>Owner</td>
* <td>membershipRevoked + ownershipGranted</td>
* </tr>
* </table>
* <p>
* These are the triggered events when the affiliation has been downgraded:
* </p>
* <table border="1">
* <caption>Affiliation Downgrade paths</caption>
* <tr>
* <th>Owner</th>
* <th>Admin</th>
* <th>ownershipRevoked + adminGranted</th>
* </tr>
* <tr>
* <td>Admin</td>
* <td>Member</td>
* <td>adminRevoked + membershipGranted</td>
* </tr>
* <tr>
* <td>Member</td>
* <td>None</td>
* <td>membershipRevoked</td>
* </tr>
* <tr>
* <td>Owner</td>
* <td>Member</td>
* <td>ownershipRevoked + membershipGranted</td>
* </tr>
* <tr>
* <td>Owner</td>
* <td>None</td>
* <td>ownershipRevoked</td>
* </tr>
* <tr>
* <td>Admin</td>
* <td>None</td>
* <td>adminRevoked</td>
* </tr>
* <tr>
* <td>Anyone</td>
* <td>Outcast</td>
* <td>banned</td>
* </tr>
* </table>
* <h3>Examples</h3>
* <p>
* In this example we can see how to grant admin privileges to a user and listen for the notification events:
* </p>
*
* <pre>{@code
* // User1 creates a room
* muc = manager.getMultiUserChat("myroom@conference.jabber.org");
* muc.create("testbot");
* // User1 (which is the room owner) configures the room as a moderated room
* Form form = muc.getConfigurationForm();
* FillableForm answerForm = configForm.getFillableForm();
* answerForm.setAnswer("muc#roomconfig_moderatedroom", "1");
* muc.sendConfigurationForm(answerForm);
*
* // User2 joins the new room (as a visitor)
* MultiUserChat muc2 = manager2.getMultiUserChat("myroom@conference.jabber.org");
* muc2.join("testbot2");
* // User2 will listen for his own admin privileges
* muc2.addUserStatusListener(new DefaultUserStatusListener() {
* public void membershipRevoked() {
* super.membershipRevoked();
* ...
* }
* public void adminGranted() {
* super.adminGranted();
* ...
* }
* });
*
* // User3 joins the new room (as a visitor)
* MultiUserChat muc3 = manager3.getMultiUserChat("myroom@conference.jabber.org");
* muc3.join("testbot3");
* // User3 will lister for other users admin privileges
* muc3.addParticipantStatusListener(new DefaultParticipantStatusListener() {
* public void membershipRevoked(String participant) {
* super.membershipRevoked(participant);
* ...
* }
* public void adminGranted(String participant) {
* super.adminGranted(participant);
* ...
* }
* });
* // The room's owner grants admin privileges to user2
* muc.grantAdmin("user2@jabber.org");
* }</pre>
*
* @see <a href="https://xmpp.org/extensions/xep-0045.html">XEP-0045: Multi-User Chat</a>
*/
package org.jivesoftware.smackx.muc;

View File

@ -17,5 +17,163 @@
/**
* Smacks implementation of XEP-0016: Privacy Lists.
* <h2 id="what-is-it">What is it?</h2>
* <p>
* <code>Privacy</code> is a method for users to block communications from particular other users. In XMPP this is done
* by managing ones privacy lists.
* </p>
* <p>
* Server-side privacy lists enable successful completion of the following use cases:
* </p>
* <ul>
* <li>Retrieving ones privacy lists.</li>
* <li>Adding, removing, and editing ones privacy lists.</li>
* <li>Setting, changing, or declining active lists.</li>
* <li>Setting, changing, or declining the default list (i.e., the list that is active by default).</li>
* <li>Allowing or blocking messages based on JID, group, or subscription type (or globally).</li>
* <li>Allowing or blocking inbound presence notifications based on JID, group, or subscription type (or globally).</li>
* <li>Allowing or blocking outbound presence notifications based on JID, group, or subscription type (or
* globally).</li>
* <li>Allowing or blocking IQ stanzas based on JID, group, or subscription type (or globally).</li>
* <li>Allowing or blocking all communications based on JID, group, or subscription type (or globally).</li>
* </ul>
* <h2 id="how-can-i-use-it">How can I use it?</h2>
* <p>
* The API implementation releases three main public classes:
* </p>
* <ul>
* <li><code>PrivacyListManager</code>: this is the main API class to retrieve and handle server privacy lists.</li>
* <li><code>PrivacyList</code>: witch represents one privacy list, with a name, a set of privacy items. For example,
* the list with visible or invisible.</li>
* <li><code>PrivacyItem</code>: block or allow one aspect of privacy. For example, to allow my friend to see my
* presence.</li>
* </ul>
* <ol type="1">
* <li>Right from the start, a client MAY <strong>get his/her privacy list</strong> that is stored in the server:</li>
* </ol>
*
* <pre>
* <code>
* // Create a privacy manager for the current connection._
* PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
* // Retrieve server privacy lists_
* PrivacyList[] lists = privacyManager.getPrivacyLists();
* </code>
* </pre>
* <p>
* Now the client is able to show every <code>PrivacyItem</code> of the server and also for every list if it is active,
* default or none of them. The client is a listener of privacy changes.
* </p>
* <ol start="2" type="1">
* <li>In order to <strong>add a new list in the server</strong>, the client MAY implement something like:</li>
* </ol>
*
* <pre>
* <code>
* // Set the name of the list_
* String listName = &quot;newList&quot;;
*
* // Create the list of PrivacyItem that will allow or deny some privacy aspect_
* String user = &quot;tybalt@example.com&quot;;
* String groupName = &quot;enemies&quot;;
* ArrayList privacyItems = new ArrayList();
*
* PrivacyItem item = new PrivacyItem(PrivacyItem.Type.jid, user, true, 1);
* privacyItems.add(item);
*
* item = new PrivacyItem(PrivacyItem.Type.subscription, PrivacyItem.SUBSCRIPTION_BOTH, true, 2);
* privacyItems.add(item);
*
* item = new PrivacyItem(PrivacyItem.Type.group, groupName, false, 3);
* item.setFilterMessage(true);
* privacyItems.add(item);
*
* // Get the privacy manager for the current connection._
* PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
* // Create the new list._
* privacyManager.createPrivacyList(listName, privacyItems);
* </code>
* </pre>
* <ol start="3" type="1">
* <li>To <strong>modify an existent list</strong>, the client code MAY be like:</li>
* </ol>
*
* <pre>
* <code>
* // Set the name of the list_
* String listName = &quot;existingList&quot;;
* // Get the privacy manager for the current connection._
* PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
* // Sent the new list to the server._
* privacyManager.updatePrivacyList(listName, items);
* </code>
* </pre>
* <p>
* Notice <code>items</code> was defined at the example 2 and MUST contain all the elements in the list (not the
* delta).
* </p>
* <ol start="4" type="1">
* <li>In order to <strong>delete an existing list</strong>, the client MAY perform something like:</li>
* </ol>
*
* <pre>
* <code>
* // Set the name of the list_
* String listName = &quot;existingList&quot;;
* // Get the privacy manager for the current connection._
* PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
* // Remove the list._
* privacyManager.deletePrivacyList(listName);
* </code>
* </pre>
* <ol start="5" type="1">
* <li>In order to <strong>decline the use of an active list</strong>, the client MAY perform something like:</li>
* </ol>
*
* <pre>
* <code>
* // Get the privacy manager for the current connection._
* PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
* // Decline the use of the active list._
* privacyManager.declineActiveList();
* </code>
* </pre>
* <ol start="6" type="1">
* <li>In order to <strong>decline the use of a default list</strong>, the client MAY perform something like:</li>
* </ol>
*
* <pre>
* <code>
* // Get the privacy manager for the current connection._
* PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
* // Decline the use of the default list._
* privacyManager.declineDefaultList();
* </code>
* </pre>
* <p>
* Listening for Privacy Changes
* </p>
* <p>
* In order to handle privacy changes, clients SHOULD listen managers updates. When a list is changed the manager
* notifies every added listener. Listeners MUST implement the <code>PrivacyListListener</code> interface. Clients may
* need to react when a privacy list is modified. The <code>PrivacyListManager</code> lets you add listerners that will
* be notified when a list has been changed. Listeners should implement the <code>PrivacyListListener</code> interface.
* </p>
* <p>
* The most important notification is <code>updatedPrivacyList</code> that is performed when a privacy list changes its
* privacy items.
* </p>
* <p>
* The listener becomes notified after performing:
* </p>
*
* <pre>
* <code>
* // Get the privacy manager for the current connection._
* PrivacyListManager privacyManager = PrivacyListManager.getInstanceFor(myConnection);
* // Add the listener (this) to get notified_
* privacyManager.addListener(this);
* </code>
* </pre>
*/
package org.jivesoftware.smackx.privacy;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2023 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,390 @@
*/
/**
* Smack's API for XEP-0060: Publish-Subscribe.
* Smack's API for XEP-0060: Publish-Subscribe. XMPP based
* <a href="https://en.wikipedia.org/wiki/Publish/subscribe">publish and subscribe</a> is based around nodes to which
* items can be published. Subscribers of those nodes will be notified about new items.
* <h2>Node creation and configuration</h2>
* <h3>Description</h3>
* <p>
* Allowed users may create and configure pubsub nodes. There are two types of nodes that can be created, leaf nodes and
* collection nodes.
* </p>
* <ul>
* <li>Leaf Nodes - contains only messages</li>
* <li>Collection Nodes - contains only nodes (both Leaf and Collection are allowed), but no messages The current
* version of this API only supports Leaf Nodes. There are many configuration options available for nodes, but the two
* main options are whether the node is **persistent** or not and whether it will deliver payload or not.</li>
* </ul>
* <h3>Usage</h3>
* <p>
* In order to create a node you will need to first create an instance of _**PubSubManager**_. There are several options
* for node creation which range from creating an instant node, default configuration, or a fully configured node.
* </p>
* <h3>Examples</h3>
* <p>
* Create an instant node:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = new PubSubManager(con);
*
* // Create the node
* LeafNode leaf = mgr.createNode();
* }</pre>
* <p>
* Create a node with default configuration and then configure it:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Create the node
* LeafNode leaf = mgr.createNode("testNode");
* ConfigureForm form = new ConfigureForm(FormType.submit);
* form.setAccessModel(AccessModel.open);
* form.setDeliverPayloads(false);
* form.setNotifyRetract(true);
* form.setPersistentItems(true);
* form.setPublishModel(PublishModel.open);
*
* leaf.sendConfigurationForm(form);
* }</pre>
* <p>
* Create and configure a node:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Create the node
* ConfigureForm form = new ConfigureForm(FormType.submit);
* form.setAccessModel(AccessModel.open);
* form.setDeliverPayloads(false);
* form.setNotifyRetract(true);
* form.setPersistentItems(true);
* form.setPublishModel(PublishModel.open);
* LeafNode leaf = mgr.createNode("testNode", form);
* }</pre>
*
* <h2>Publishing to a node</h2>
* <h3>Description</h3>
* <p>
* This section deals with the **publish** portion of pubsub. Usage of a node typically involves either sending or
* receiving data, referred to as items. Depending on the context of the nodes usage, the item being sent to it can have
* different properties. It can contain application data known as payload, or the publisher may choose to supply
* meaningful unique id's. Determination of an items acceptable properties is defined by a combination of node
* configuration and its purpose.
* </p>
* <h3>Usage</h3>
* <p>
* To publish to a node, you will have to either create or retrieve an existing node and then create and send items to
* that node. The ability for any given person to publish to the node will be dependent on its configuration.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we publish an item to a node that does not take payload:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* LeafNode node = mgr.getNode("testNode");
*
* // Publish an Item, let service set the id
* node.send(new Item());
*
* // Publish an Item with the specified id
* node.send(new Item("123abc"));
* }</pre>
* <p>
* In this example we publish an item to a node that does take payload:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* LeafNode node = mgr.getNode("testNode");
*
* // Publish an Item with payload
* node.send(new PayloadItem("test" + System.currentTimeMillis(),
* new SimplePayload("book", "pubsub:test:book", "Two Towers")));
* }</pre>
*
* <h2>Receiving pubsub messages</h2>
* <h3>Description</h3>
* <p>
* This section deals with the **subscribe** portion of pubsub. As mentioned in the last section, usage of a node
* typically involves either sending or receiving items. Subscribers are interested in being notified when items are
* published to the pubsub node. These items may or may not have application specific data (payload), as that is
* dependent on the context in which the node is being used.
* </p>
* <h3>Usage</h3>
* <p>
* To get messages asynchronously when items are published to a node, you will have to
* </p>
* <ul>
* <li>Get a node.</li>
* <li>Create and register a listener.</li>
* <li>Subscribe to the node.</li>
* </ul>
* <p>
* Please note that you should register the listener before subscribing so that all messages sent after subscribing are
* received. If done in the reverse order, messages that are sent after subscribing but before registering a listener
* may not be processed as expected.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to create a listener and register it and then subscribe for messages.
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* LeafNode node = mgr.getNode("testNode");
*
* node.addItemEventListener(new ItemEventCoordinator<Item>());
* node.subscribe(myJid);
* }</pre>
* <p>
* Where the listener is defined like so:
* </p>
*
* <pre><code>
* class ItemEventCoordinator implements ItemEventListener {
* {@literal @}@Override
* public void handlePublishedItems(ItemPublishEvent items) {
* System.out.println("Item count: " + System.out.println(items));
* }
* }
* </code></pre>
* <p>
* In addition to receiving published items, there are notifications for several other events that occur on a node as
* well.
* </p>
* <ul>
* <li>Deleting items or purging all items from a node</li>
* <li>Changing the node configuration</li>
* </ul>
* <p>
* In this example we can see how to create a listener, register it and then subscribe for item deletion messages.
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* LeafNode node = mgr.getNode("testNode");
*
* node.addItemDeleteListener(new ItemDeleteCoordinator<Item>());
* node.subscribe(myJid);
* node.deleteItem("id_one");
* }</pre>
* <p>
* Where the handler is defined like so:
* </p>
*
* <pre><code>
* class ItemDeleteCoordinator implements ItemDeleteListener {
* {@literal @}Override
* public void handleDeletedItems(ItemDeleteEvent items) {
* System.out.println("Item count: " + items.getItemIds().size());
* System.out.println(items);
* }
*
* {@literal @}Override
* public void handlePurge() {
* System.out.println("All items have been deleted from node");
* }
* }
* </code></pre>
* <p>
* In this example we can see how to create a listener, register it and then subscribe for node configuration messages.
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* Node node = mgr.getNode("testNode");
*
* node.addConfigurationListener(new NodeConfigCoordinator());
* node.subscribe(myJid);
*
* ConfigureForm form = new ConfigureForm(FormType.submit);
* form.setAccessModel(AccessModel.open);
* form.setDeliverPayloads(false);
* form.setNotifyRetract(true);
* form.setPersistentItems(true);
* form.setPublishModel(PublishModel.open);
*
* node.sendConfigurationForm(form);
* }</pre>
* <p>
* In this example we can see how to create a listener, register it and then subscribe for node configuration messages.
* </p>
*
* <pre><code>
* class NodeConfigCoordinator implements NodeConfigListener {
* {@literal @}Override
* public void handleNodeConfiguration(ConfigurationEvent config) {
* System.out.println("New configuration");
* System.out.println(config.getConfiguration());
* }
* </code></pre>
*
* <h2>Retrieving persisted pubsub messages</h2>
* <h3>Description</h3>
* <p>
* When persistent nodes are used, the subscription and registration methods described in the last section will not
* enable the retrieval of items that already exist in the node. This section deals with the specific methods for
* retrieving these items. There are several means of retrieving existing items. You can retrieve all items at once, the
* last N items, or the items specified by a collection of id's. Please note that the service may, according to the
* pubsub specification, reply with a list of items that contains only the item id's (no payload) to save on bandwidth.
* This will not occur when the id's are specified since this is the means of guaranteeing retrieval of payload.
* </p>
* <h3>Usage</h3>
* <p>
* To synchronously retrieve existing items from a persistent node, you will have to get an instance of a _**LeafNode**_
* and call one of the retrieve methods.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to retrieve the existing items from a node:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* LeafNode node = mgr.getNode("testNode");
*
* Collection<? extends Item> items = node.getItems();
* }</pre>
* <p>
* In this example we can see how to retrieve the last N existing items:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* LeafNode node = mgr.getNode("testNode");
*
* List<? extends Item> items = node.getItems(100);
* }</pre>
* <p>
* In this example we can see how to retrieve the specified existing items:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the node
* LeafNode node = mgr.getNode("testNode");
* Collection<String> ids = new ArrayList<String>(3);
* ids.add("1");
* ids.add("3");
* ids.add("4");
*
* List<? extends Item> items = node.getItems(ids);
* }</pre>
*
* <h2>Discover pubsub information</h2>
* <h3>Description</h3>
* <p>
* A user may want to query a server or node for a variety of pubsub related information.
* </p>
* <h3>Usage</h3>
* <p>
* To retrieve information, a user will simply use either the _**PubSubManager**_ or _**Node**_ classes depending on
* what type of information is required.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to get pubsub capabilities:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the pubsub features that are supported
* DiscoverInfo supportedFeatures = mgr.getSupportedFeatures();
* }</pre>
* <p>
* In this example we can see how to get pubsub subscriptions for all nodes:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get all the subscriptions in the pubsub service
* List<Subscription> subscriptions = mgr.getSubscriptions();
* }</pre>
* <p>
* In this example we can see how to get all affiliations for the users bare JID on the pubsub service:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
*
* // Get the affiliations for the users bare JID
* List<Affiliation> affiliations = mgr.getAffiliations();
* }</pre>
* <p>
* In this example we can see how to get information about the node:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
* Node node = mgr.getNode("testNode");
*
* // Get the node information
* DiscoverInfo nodeInfo = node.discoverInfo();
* }</pre>
* <p>
* In this example we can see how to discover the node items:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
* Node node = mgr.getNode("testNode");
*
* // Discover the node items
* DiscoverItems nodeItems = node.discoverItems();
* }</pre>
* <p>
* In this example we can see how to get node subscriptions:
* </p>
*
* <pre>{@code
* // Create a pubsub manager using an existing XMPPConnection
* PubSubManager mgr = PubSubManager.getInstanceFor(con);
* Node node = mgr.getNode("testNode");
*
* // Discover the node subscriptions
* List<Subscription> subscriptions = node.getSubscriptions();
* }</pre>
*
* @see <a href="https://xmpp.org/extensions/xep-0060.html">XEP-0060: Publish-Subscribe</a>
*/
package org.jivesoftware.smackx.pubsub;

View File

@ -17,5 +17,9 @@
/**
* Smacks implementation of XEP-0202: Entity Time.
* <p>
* Supports a protocol that XMPP clients use to exchange their respective local times and time zones.
* </p>
* @see <a href="https://xmpp.org/extensions/xep-0090.html">XEP-0090: Legacy Entity Time</a>
*/
package org.jivesoftware.smackx.time;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,31 @@
*/
/**
* Smacks implementation of XEP-0004: Data Forms.
* Smacks API for Data Forms (XEP-0004).
* <p>
* XMPP data forms allow the exchange of structured data between users and applications for common tasks such as
* registration, searching user forms, or answering a questionnaire.
* </p>
* <h2>Create a Form to fill out</h2>
* <h3>Description</h3>
* <p>
* An XMPP entity may need to gather data from another XMPP entity. Therefore, the data-gathering entity will need to
* create a new Form, specify the fields that will conform to the Form and finally send the Form to the data-providing
* entity.
* </p>
* <h3>Usage</h3> TODO
* <h3>Example</h3>
*
* <h2>Answer a Form</h2>
* <h3>Description</h3>
* <p>
* Under many situations an XMPP entity could receive a form to fill out. For example, some hosts may require to fill
* out a form in order to register new users. Smack lets the data-providing entity to complete the form in an easy way
* and send it back to the data-gathering entity.
* </p>
* <h3>Usage</h3> TODO
* <h3>Example</h3>
*
* @see <a href="https://xmpp.org/extensions/xep-0004.html">XEP-0004: Data Forms</a>
*/
package org.jivesoftware.smackx.xdata;

View File

@ -16,6 +16,174 @@
*/
/**
* Smacks implementation of XEP-0071: XHTML-IM.
* Smacks implementation of XHTML-IM (XEP-0071), which provides the ability to send and receive formatted messages using
* XHTML.
* <h2></h2>
* <h3>Description</h3>
* <p>
* The first step in order to send an XHTML message is to compose it. Smack provides a special class that helps to build
* valid XHTML messages hiding any low level complexity. For special situations, advanced users may decide not to use
* the helper class and generate the XHTML by themselves. Even for these situations Smack provides a well defined entry
* point in order to add the generated XHTML content to a given message.
* </p>
* <p>
* Note: not all clients are able to view XHTML formatted messages. Therefore, it's recommended that you include a
* normal body in that message that is either an unformatted version of the text or a note that XHTML support is
* required to view the message contents.
* </p>
* <h3>Usage</h3>
* <p>
* Create an instance of _**XHTMLText**_ specifying the style and language of the body. You can add several XHTML bodies
* to the message but each body should be for a different language. Once you have an XHTMLText you can start to append
* tags and text to it. In order to append tags there are several messages that you can use. For each XHTML defined tag
* there is a message that you can send. In order to add text you can send the message **#append(String textToAppend)**.
* </p>
* <p>
* After you have configured the XHTML text, the last step you have to do is to add the XHTML text to the message you
* want to send. If you decided to create the XHTML text by yourself, you will have to follow this last step too. In
* order to add the XHTML text to the message send the message **#addBody(Message message, String body)** to the
* _**XHTMLManager**_ class where _message_ is the message that will receive the XHTML body and _body_ is the string to
* add as an XHTML body to the message.**
* </p>
* <h3>Example</h3>
* <p>
* In this example we can see how to compose the following XHTML message:
* </p>
*
* <pre>{@code
* <body>
* <p style='font-size:large'>Hey John, this is my new
* <span style='color:green'>green</span>
* <em>!!!!</em>
* </p>
* </body>
* }</pre>
*
* <pre>{@code
* // Create a message to send
* Message msg = chat.createMessage();
* msg.setSubject("Any subject you want");
* msg.setBody("Hey John, this is my new green!!!!");
*
* // Create an XHTMLText to send with the message
* XHTMLText xhtmlText = new XHTMLText(null, null);
* xhtmlText.appendOpenParagraphTag("font-size:large");
* xhtmlText.append("Hey John, this is my new ");
* xhtmlText.appendOpenSpanTag("color:green");
* xhtmlText.append("green");
* xhtmlText.appendCloseSpanTag();
* xhtmlText.appendOpenEmTag();
* xhtmlText.append("!!!!");
* xhtmlText.appendCloseEmTag();
* xhtmlText.appendCloseParagraphTag();
* xhtmlText.appendCloseBodyTag();
*
* // Add the XHTML text to the message
* XHTMLManager.addBody(msg, xhtmlText);
* }</pre>
*
* <h2>Send an XHTML Message</h2>
* <h3>Description</h3>
* <p>
* After you have composed an XHTML message you will want to send it. Once you have added the XHTML content to the
* message you want to send you are almost done. The last step is to send the message as you do with any other message.
* </p>
* <h3>Usage</h3>
* <p>
* An XHTML message is like any regular message, therefore to send the message you can follow the usual steps you do in
* order to send a message. For example, to send a message as part of a chat just use the message
* **#sendMessage(Message)** of _**Chat**_ or you can use the message **#sendStanza(Stanza)** of _**XMPPConnection**_.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to send a message with XHTML content as part of a chat.
* </p>
*
* <pre>{@code
* // Create a message to send
* Message msg = chat.createMessage();
* // Obtain the XHTML text to send from somewhere
* XHTMLText xhtmlBody = getXHTMLTextToSend();
*
* // Add the XHTML text to the message
* XHTMLManager.addBody(msg, xhtmlBody);
*
* // Send the message that contains the XHTML
* chat.sendMessage(msg);
* }</pre>
*
* <h2>Receive an XHTML Message</h2>
* <h3>Description</h3>
* <p>
* It is also possible to obtain the XHTML content from a received message. Remember that the specification defines that
* a message may contain several XHTML bodies where each body should be for a different language.
* </p>
* <h3>Usage</h3>
* <p>
* To get the XHTML bodies of a given message just send the message #getBodies(Message)** to the class
* _**XHTMLManager**_. The answer of this message will be an _**List**_ with the different XHTML bodies of the message
* or null if none.
* </p>
* <h3>Example</h3>
* <p>
* In this example we can see how to create a PacketListener that obtains the XHTML bodies of any received message.
* </p>
* <pre>{@code
* // Create a listener for the chat and display any XHTML content
* IncomingChatMessageListener listener = new IncomingChatMessageListener() {
* public void newIncomingMessage(EntityBareJid from, Message message, Chat chat) {
* // Obtain the XHTML bodies of the message
* List&lt;CharSequence&gt; bodies = XHTMLManager.getBodies(message);
* if (bodies == null) {
* return;
*
* // Display the bodies on the console
* for (CharSequence body : bodies) {
* System.out.println(body);
* }
* }
* };
* chatManager.addListener(listener);
* }
* }</pre>
* <h2>Discover support for XHTML Messages</h2>
* <h3>Description</h3>
* <p>
* Before you start to send XHTML messages to a user you should discover if the user supports XHTML messages. There are
* two ways to achieve the discovery, explicitly and implicitly. Explicit is when you first try to discover if the user
* supports XHTML before sending any XHTML message. Implicit is when you send XHTML messages without first discovering
* if the conversation partner's client supports XHTML and depenging on the answer (normal message or XHTML message) you
* find out if the user supports XHTML messages or not. This section explains how to explicitly discover for XHTML
* support.
* </p>
* <h3>Usage</h3>
* <p>
* In order to discover if a remote user supports XHTML messages send #isServiceEnabled(XMPPConnection connection,
* String userID)** to the class _**XHTMLManager**_ where connection is the connection to use to perform the service
* discovery and userID is the user to check (A fully qualified xmpp ID, e.g. jdoe@example.com). This message will
* return true if the specified user handles XHTML messages.
* </p>
* <h3>Examples</h3>
* <p>
* In this example we can see how to discover if a remote user supports XHTML Messages.
* </p>
*
* <pre>{@code
* Message msg = chat.createMessage();
* // Include a normal body in the message
* msg.setBody(getTextToSend());
* // Check if the other user supports XHTML messages
* if (XHTMLManager.isServiceEnabled(connection, chat.getParticipant())) {
* // Obtain the XHTML text to send from somewhere
* String xhtmlBody = getXHTMLTextToSend();
* // Include an XHTML body in the message
* qHTMLManager.addBody(msg, xhtmlBody);
* }
*
* // Send the message
* chat.sendMessage(msg);
* }</pre>
*
* @see <a href="https://www.xmpp.org/extensions/xep-0071.html">XEP-0071: XHTML-IM</a>
*/
package org.jivesoftware.smackx.xhtmlim;

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2003-2007 Jive Software, 2016-2021 Florian Schmaus.
* Copyright 2003-2007 Jive Software, 2016-2022 Florian Schmaus.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -78,15 +78,122 @@ import org.jxmpp.jid.parts.Resourcepart;
import org.jxmpp.util.cache.LruCache;
/**
* Represents a user's roster, which is the collection of users a person receives
* presence updates for. Roster items are categorized into groups for easier management.
* <p>
* The roster lets you keep track of the availability ("presence") of other
* users. A roster also allows you to organize users into groups such as
* "Friends" and "Co-workers". Other IM systems refer to the roster as the buddy
* list, contact list, etc.
* </p>
* <p>
* You can obtain a Roster instance for your connection via
* {@link #getInstanceFor(XMPPConnection)}. A detailed description of the
* protocol behind the Roster and Presence semantics can be found in
* <a href="https://tools.ietf.org/html/rfc6121">RFC 6120</a>.
* </p>
*
* Other users may attempt to subscribe to this user using a subscription request. Three
* modes are supported for handling these requests: <ul>
* <li>{@link SubscriptionMode#accept_all accept_all} -- accept all subscription requests.</li>
* <li>{@link SubscriptionMode#reject_all reject_all} -- reject all subscription requests.</li>
* <li>{@link SubscriptionMode#manual manual} -- manually process all subscription requests.</li>
* <h2>Roster Entries</h2>
* Every user in a roster is represented by a RosterEntry, which consists
* of:
* <ul>
* <li>An XMPP address, aka. JID (e.g. jsmith@example.com).</li>
* <li>A name you've assigned to the user (e.g. "Joe").</li>
* <li>The list of groups in the roster that the entry belongs to. If the roster
* entry belongs to no groups, it's called an "unfiled entry".</li>
* </ul>
* The following code snippet prints all entries in the roster:
*
* <pre>{@code
* Roster roster = Roster.getInstanceFor(connection);
* Collection<RosterEntry> entries = roster.getEntries();
* for (RosterEntry entry : entries) {
* System.out.println(entry);
* }
* }</pre>
*
* Methods also exist to get individual entries, the list of unfiled entries, or
* to get one or all roster groups.
*
* <h2>Presence</h2>
* <p>
* Every entry in the roster has presence associated with it. The
* {@link #getPresence(BareJid)} method will return a Presence object with the
* user's presence or `null` if the user is not online or you are not subscribed
* to the user's presence. _Note:_ Presence subscription is nnot tied to the
* user being on the roster, and vice versa: You could be subscriped to a remote
* users presence without the user in your roster, and a remote user can be in
* your roster without any presence subscription relation.
* </p>
* <p>
* A user either has a presence of online or offline. When a user is online,
* their presence may contain extended information such as what they are
* currently doing, whether they wish to be disturbed, etc. See the Presence
* class for further details.
* </p>
*
* <h2>Listening for Roster and Presence Changes</h2>
* <p>
* The typical use of the roster class is to display a tree view of groups and
* entries along with the current presence value of each entry. As an example,
* see the image showing a Roster in the Exodus XMPP client to the right.
* </p>
* <p>
* The presence information will likely change often, and it's also possible for
* the roster entries to change or be deleted. To listen for changing roster and
* presence data, a RosterListener should be used. To be informed about all
* changes to the roster the RosterListener should be registered before logging
* into the XMPP server. The following code snippet registers a RosterListener
* with the Roster that prints any presence changes in the roster to standard
* out. A normal client would use similar code to update the roster UI with the
* changing information.
* </p>
*
* <pre>{@code
* Roster roster = Roster.getInstanceFor(con);
* roster.addRosterListener(new RosterListener() {
* // Ignored events public void entriesAdded(Collection<String> addresses) {}
* public void entriesDeleted(Collection<String> addresses) {
* }
*
* public void entriesUpdated(Collection<String> addresses) {
* }
*
* public void presenceChanged(Presence presence) {
* System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
* }
* });
* }</pre>
*
* Note that in order to receive presence changed events you need to be
* subscribed to the users presence. See the following section.
*
* <h2>Adding Entries to the Roster</h2>
*
* <p>
* Rosters and presence use a permissions-based model where users must give
* permission before someone else can see their presence. This protects a user's
* privacy by making sure that only approved users are able to view their
* presence information. Therefore, when you add a new roster entry, you will
* not see the presence information until the other user accepts your request.
* </p>
* <p>
* If another user requests a presence subscription, you must accept or reject
* that request. Smack handles presence subscription requests in one of three
* ways:
* </p>
* <ul>
* <li>Automatically accept all presence subscription requests
* ({@link SubscriptionMode#accept_all accept_all})</li>
* <li>Automatically reject all presence subscription requests
* ({@link SubscriptionMode#reject_all reject_all})</li>
* <li>Process presence subscription requests manually.
* ({@link SubscriptionMode#manual manual})</li>
* </ul>
* <p>
* The mode can be set using {@link #setSubscriptionMode(SubscriptionMode)}.
* Simple clients normally use one of the automated subscription modes, while
* full-featured clients should manually process subscription requests and let
* the end-user accept or reject each request.
* </p>
*
* @author Matt Tucker
* @see #getInstanceFor(XMPPConnection)

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2015-2023 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -16,6 +16,293 @@
*/
/**
* The Smack Integration Test Framework.
* The Smack Integration Test Framework (sinttest) used to run a set of tests against a real XMPP service. The framework
* discovers on start-up the available tests by reflection.
* <h2>Quickstart</h2>
* <p>
* You can run the framework against an XMPP service with
* </p>
*
* <pre>
* $ gradle integrationTest -Dsinttest.service=my.xmppservice.org
* </pre>
* <p>
* Note that the service needs to have In-Band Registration (IBR) enabled.
* </p>
* <p>
* A better alternative to IBR is using XEP-0133: Service Administration to create the throw away accounts used by the
* integration test framework. Simply use
* </p>
*
* <pre>
* $ gradle integrationTest -Dsinttest.service=my.xmppservice.org \
* -Dsinttest.adminAccountUsername=admin \
* -Dsinttest.adminAccountPassword=aeR0Wuub
* </pre>
* <p>
* to run Smack's integration test framework against my.xmppservice.org with an admin account named 'admin' and
* 'aeR0Wuub' as password.
* </p>
* <h2>Configuration</h2>
* <p>
* The framework is configured with a standard Java properties file. This file simply contains key/value pairs, which
* are separated by an equals sign ("="). The most important configuration value is the `service` value, it's also the
* only required setting.
* </p>
* <p>
* The file properties can be overridden with Java system properties. The name of a system property that is used by the
* framework needs to be prefixed with 'sinttest.' (*S*mack *Int*egration *Test* Framework). For example the `service`
* property becomes `sinttest.service`.
* </p>
* <h3>Minimal example 'properties' file</h3>
*
* <pre>
* service = example.org
* </pre>
*
* <h3>Another example 'properties' file</h3>
*
* <pre>
* service=example.org
* serviceTlsPin=CERTSHA256:2F:92:C9:4D:30:58:E1:05:21:9A:57:59:5F:6E:25:9A:0F:BF:FF:64:1A:C3:4B:EC:06:7D:4A:6F:0A:D5:21:85
* debugger=console
* </pre>
*
* <h3>Framework properties</h3>
* <table border="1">
* <caption>Properties of the Smack Integration Test Framework</caption>
* <tr>
* <th>Name</th>
* <th>Description</th>
* </tr>
* <tr>
* <td>service</td>
* <td>XMPP service to run the tests on</td>
* </tr>
* <tr>
* <td>serviceTlsPin</td>
* <td>TLS Pin (used by <a href="https://github.com/Flowdalic/java-pinning">java-pinning</a>)</td>
* </tr>
* <tr>
* <td>securityMode</td>
* <td>Either required or disabled</td>
* </tr>
* <tr>
* <td>replyTimeout</td>
* <td>In milliseconds</td>
* </tr>
* <tr>
* <td>adminAccountUsername</td>
* <td>Username of the XEP-0133 Admin account</td>
* </tr>
* <tr>
* <td>adminAccountPassword</td>
* <td>Password of the XEP-0133 Admin account</td>
* </tr>
* <tr>
* <td>accountOneUsername</td>
* <td>Username of the first XMPP account</td>
* </tr>
* <tr>
* <td>accountOnePassword</td>
* <td>Password of the first XMPP account</td>
* </tr>
* <tr>
* <td>accountTwoUsername</td>
* <td>Username of the second XMPP account</td>
* </tr>
* <tr>
* <td>accountTwoPassword</td>
* <td>Password of the second XMPP account</td>
* </tr>
* <tr>
* <td>accountThreeUsername</td>
* <td>Username of the third XMPP account</td>
* </tr>
* <tr>
* <td>accountThreePassword</td>
* <td>Password of the third XMPP account</td>
* </tr>
* <tr>
* <td>debugger</td>
* <td>console for console debugger, enhanced for the enhanced debugger</td>
* </tr>
* <tr>
* <td>enabledTests</td>
* <td>List of enabled tests</td>
* </tr>
* <tr>
* <td>disabledTests</td>
* <td>List of disabled tests</td>
* </tr>
* <tr>
* <td>defaultConnection</td>
* <td>Nickname of the default connection</td>
* </tr>
* <tr>
* <td>enabledConnections</td>
* <td>List of enabled connections nicknames</td>
* </tr>
* <tr>
* <td>disabledConnections</td>
* <td>List of disabled connections nicknames</td>
* </tr>
* <tr>
* <td>testPackages</td>
* <td>List of packages with tests</td>
* </tr>
* <tr>
* <td>verbose</td>
* <td>If <code>true</code> set output to verbose</td>
* </tr>
* <tr>
* <td>dnsResolver</td>
* <td>One of minidns, javax or dnsjava. Defaults to minidns.</td>
* </tr>
* </table>
* <h3>Where to place the properties file</h3>
* <p>
* The framework will first load the properties file from <code>~/.config/smack-integration-test/properties</code>.
* </p>
* <h3>Running selected tests only</h3>
* <p>
* Using <code>enabledTests</code> is is possible to run only selected tests. The tests can be selected on a per class
* base or by specifying concrete test methods. In the latter case, the methods must be qualified by a (simple) class
* name.
* </p>
* <p>
* For example:
* </p>
*
* <pre>
* $ gradle integrationTest -Dsinttest.enabledTests=SoftwareInfoIntegrationTest.test
* </pre>
* <p>
* will only run the <code>test()</code> method of <code>SoftwareInfoIntegrationTest</code>, whereas
* </p>
*
* <pre>
* $ gradle integrationTest -Dsinttest.enabledTests=SoftwareInfoIntegrationTest
* </pre>
* <p>
* would run all tests defined in the <code>SoftwareInfoIntegrationTest</code> class.
* </p>
* <h2>Overview of the components</h2>
* <p>
* Package <code>org.igniterealtime.smack.inttest</code>
* </p>
* <h3>SmackIntegrationTestFramework</h3>
* <p>
* Contains <code>public static void main</code> method, i.e. the entry point for the framework. Here the available
* integration tests are discovered by means of reflection, the configuration is read and a
* <code>IntegrationTestEnvironment</code> instance created, which includes the XMPP connections.
* </p>
* <h3>AbstractSmackIntegrationTest</h3>
* <p>
* The base class that integration tests need to subclass.
* </p>
* <h3>AbstractSmackLowLevelIntegrationTest</h3>
* <p>
* Allows low level integration test, i.e. every test method will have its own exclusive XMPPTCPConnection instances.
* </p>
* <h3>AbstractSmackSpecificLowLevelIntegrationTest</h3>
* <p>
* Operates, like <code>AbstractSmackLowLevelIntegrationTest</code>, on its own <code>XMPPConnection</code> instances,
* but is limited to a particular type of <code>XMPPConnection</code>.
* </p>
* <h3>IntegrationTestEnvironment</h3>
* <p>
* The environment, e.g. the `XMPPConnections` provided to the integration tests by the framework. Note that for
* convenience `AbstractSmackIntegrationTest` contains some of those as protected members.
* </p>
* <h3>SmackIntegrationTest</h3>
* <p>
* An annotation that needs to be added to all methods that represent a single integration test. Annotated integration
* test methods must not take any arguments, i.e., their parameter count is 0, and should return void as it's not
* evaluated in any way. The methods are supposed to throw an exception if their integration test fails.
* </p>
* <h3>TestNotPossibleException</h3>
* <p>
* Can be thrown by test methods or constructors to signal that their test is not possible, e.g. because the service
* does not support the required feature.
* </p>
* <h2>Running the integration tests</h2>
* <p>
* Smack's Gradle build system is configured with a special task called `integrationTest`, which means you can run the
* tests simply with
* </p>
*
* <pre>{@code
* $ gradle integrationTest -Dsinttest.service=my.xmppservice.org
* }</pre>
* <p>
* If one of <code>accountOneUsername</code>, <code>accountOnePassword</code>, <code>accountTwoUsername</code> or
* <code>accountTwoPassword</code> is not configured, then the framework will automatically create the accounts on the
* service. Of course this requires account registration (IBR) to be enabled. If the accounts got created automatically
* by the framework, then they will also be deleted at the end of the test.
* </p>
* <h2>Implementing Integration Tests</h2>
* <p>
* Create a new class which extends <code>AbstractSmackIntegrationTest</code>. Every non-static method, including the
* constructor, of this class will have two XMPPConnections available to perform the integration tests with:
* <code>conOne</code> and <code>conTwo</code>. You can use the constructor to check if the XMPP service does provide
* the required XMPP feature. If it does not, simply throw a <code>TestNotPossibleException</code>.
* </p>
* <p>
* Test methods must be <code>public</code>, take zero arguments i.e. declare no parameters and be annoated with
* <code>@SmackIntegrationTest</code>. If the test method is not able to perform a test then it should throw a
* <code>TestNotPossibleException</code>.
* </p>
* <h3>Rules for integration tests</h3>
* <p>
* Tests should not leave any traces on the service if they are finished, i.e. the service state at the end of the test
* must be equal to the state of the beginning. It must be possible to run the tests in parallel.
* </p>
* <h3>Why are there two mechanisms to signal that the test is not possible?</h3>
* <p>
* Because the XMPP service may provide a component that is required to perform a certain integration test, but that
* component may not support all features. For example, the XMPP service may provides a PubSub (XEP-0060) component, but
* this component may not support all features of XEP-0060.
* </p>
* <h3>Low-Level Integration Tests</h3>
* <p>
* Classes that implement low-level integration tests need to sublcass
* {@link org.igniterealtime.smack.inttest.AbstractSmackLowLevelIntegrationTest}. The test methods can declare as many
* parameters as they need to, but every parameter must be of type <code>XMPPTCPConnection</code>. The framework will
* automatically create, register and login the connections. After the test is finished, the connections will be
* unregistered with the XMPP service and terminated.
* </p>
* <h2>Debugging Integration Tests</h2>
* <p>
* A test, like any other code, may not be perfect on the first attempt, and you may require more information in order
* to ascertain quite what's wrong.
* </p>
* <h3>Smack Debugger Options</h3>
* <p>
* As described in the package documentation of org.jivesoftware.smack.debugger, there are two built-in debuggers that
* could surface you more information. Using the 'enhanced' debugger config option listed above, you'll get the Smack
* Debug Window launching when your tests launch, and you'll get a stanza-by-stanza account of what happened on each
* connection, hopefully enough to diagnose what went wrong.
* </p>
* <h3>Debugging in the IDE</h3>
* <p>
* If the output isn't enough, you may need to debug and inspect running code within the IDE. Depending on the IDE, in
* order to get execution to pause at your breakpoints, you may need to switch your configuration. Instead of running
* `gradle integrationTest`, instead run the `SmackIntegrationTestFramework` class directly with the same command-line
* options.
* </p>
* <h2>Running Your Own Integration Tests</h2>
* <p>
* The framework can be used to run your own tests residing outside of the framework's default package scope. Simply set
* the <code>testPackages</code> property to a comma separated list of package names where the framework should look for
* integration tests.
* </p>
* <p>
* Example:
* </p>
*
* <pre>{@code
* $ gradle integrationTest -Dsinttest.service=my.xmppserivce.org -Dsinttest.testPackages=org.mypackage,org.otherpackage
* }</pre>
*/
package org.igniterealtime.smack.inttest;

View File

@ -1 +1 @@
../../../../../../../smack-extensions/src/main/java/org/jivesoftware/smackx/package-info.java
../../../../../../../smack-java8-full/src/main/java/org/jivesoftware/smackx/package-info.java

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2015 Florian Schmaus
* Copyright 2022 Florian Schmaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -14,8 +14,13 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.smackx;
/**
* Integration tests.
* This is just a dummy class, please head over to {@link org.jivesoftware.smackx} for more information on Smack
* extensions. The dummy class causes javadoc generate the HTML for smackx.pacakge-info.java, which would otherwise be
* not generated, as org.jivesoftware.smackx is an empty package (see
* <a href="https://bugs.openjdk.org/browse/JDK-4492654">JDK-4492654</a>).
*/
package org.jivesoftware.smackx;
public class SmackExtensions {
}

View File

@ -0,0 +1,595 @@
/**
*
* Copyright 2015-2023 Florian Schmaus
*
* 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.
*/
/**
* Smack's API for XMPP extensions.
* <p>
* The XMPP protocol includes a base protocol and many optional extensions typically documented as "XEPs". Smack
* provides the {@link org.jivesoftware.smack} package for the core XMPP protocol and the {@link org.jivesoftware.smackx
* package} for many of the protocol extensions.
* </p>
* <table>
* <caption>XEPs supported by Smack</caption> <thead>
* <tr>
* <th>Name</th>
* <th>XEP</th>
* <th>Smack API</th>
* <th>Description</th>
* </tr>
* </thead> <tbody>
* <tr>
* <td>Data Forms</td>
* <td><a href="https://xmpp.org/extensions/xep-0004.html">XEP-0004</a></td>
* <td>{@link org.jivesoftware.smackx.xdata}</td>
* <td>Allows to gather data using Forms.</td>
* </tr>
* <tr>
* <td>Last Activity</td>
* <td><a href="https://xmpp.org/extensions/xep-0012.html">XEP-0012</a></td>
* <td></td>
* <td>Communicating information about the last activity associated with an XMPP entity.</td>
* </tr>
* <tr>
* <td>Flexible Offline Message Retrieval</td>
* <td><a href="https://xmpp.org/extensions/xep-0013.html">XEP-0013</a></td>
* <td></td>
* <td>Extension for flexible, POP3-like handling of offline messages.</td>
* </tr>
* <tr>
* <td>Privacy Lists</td>
* <td><a href="https://xmpp.org/extensions/xep-0016.html">XEP-0016</a></td>
* <td>{@link org.jivesoftware.smackx.privacy}</td>
* <td>Enabling or disabling communication with other entities.</td>
* </tr>
* <tr>
* <td>Message Events</td>
* <td><a href="https://xmpp.org/extensions/xep-0022.html">XEP-0022</a></td>
* <td></td>
* <td>Requests and responds to message events.</td>
* </tr>
* <tr>
* <td>Service Discovery</td>
* <td><a href="https://xmpp.org/extensions/xep-0030.html">XEP-0030</a></td>
* <td></td>
* <td>Allows to discover services in XMPP entities.</td>
* </tr>
* <tr>
* <td>Extended Stanza Addressing</td>
* <td><a href="https://xmpp.org/extensions/xep-0033.html">XEP-0033</a></td>
* <td></td>
* <td>Allows to include headers in stanzas in order to specifiy multiple recipients or sub-addresses.</td>
* </tr>
* <tr>
* <td>Multi User Chat</td>
* <td><a href="https://xmpp.org/extensions/xep-0045.html">XEP-0045</a></td>
* <td>{@link org.jivesoftware.smackx.muc}</td>
* <td>Allows configuration of, participation in, and administration of individual text-based conference rooms.</td>
* </tr>
* <tr>
* <td>In-Band Bytestreams</td>
* <td><a href="https://xmpp.org/extensions/xep-0047.html">XEP-0047</a></td>
* <td></td>
* <td>Enables any two entities to establish a one-to-one bytestream between themselves using plain XMPP.</td>
* </tr>
* <tr>
* <td>Bookmarks</td>
* <td><a href="https://xmpp.org/extensions/xep-0048.html">XEP-0048</a></td>
* <td></td>
* <td>Bookmarks, for e.g. MUC and web pages.</td>
* </tr>
* <tr>
* <td>Private Data</td>
* <td><a href="https://xmpp.org/extensions/xep-0049.html">XEP-0049</a></td>
* <td></td>
* <td>Manages private data.</td>
* </tr>
* <tr>
* <td>Ad-Hoc Commands</td>
* <td><a href="https://xmpp.org/extensions/xep-0050.html">XEP-0050</a></td>
* <td></td>
* <td>Advertising and executing application-specific commands.</td>
* </tr>
* <tr>
* <td>vcard-temp</td>
* <td><a href="https://xmpp.org/extensions/xep-0054.html">XEP-0054</a></td>
* <td></td>
* <td>The vCard-XML format currently in use.</td>
* </tr>
* <tr>
* <td>Jabber Search</td>
* <td><a href="https://xmpp.org/extensions/xep-0055.html">XEP-0055</a></td>
* <td></td>
* <td>Search information repositories on the XMPP network.</td>
* </tr>
* <tr>
* <td>Result Set Management</td>
* <td><a href="https://xmpp.org/extensions/xep-0059.html">XEP-0059</a></td>
* <td></td>
* <td>Page through and otherwise manage the receipt of large result sets</td>
* </tr>
* <tr>
* <td>PubSub</td>
* <td><a href="https://xmpp.org/extensions/xep-0060.html">XEP-0060</a></td>
* <td></td>
* <td>Generic publish and subscribe functionality.</td>
* </tr>
* <tr>
* <td>SOCKS5 Bytestreams</td>
* <td><a href="https://xmpp.org/extensions/xep-0065.html">XEP-0065</a></td>
* <td></td>
* <td>Out-of-band bytestream between any two XMPP entities.</td>
* </tr>
* <tr>
* <td>Field Standardization for Data Forms</td>
* <td><a href="https://xmpp.org/extensions/xep-0068.html">XEP-0068</a></td>
* <td></td>
* <td>Standardized field variables used in the context of jabber:x:data forms.</td>
* </tr>
* <tr>
* <td>XHTML-IM</td>
* <td><a href="https://xmpp.org/extensions/xep-0071.html">XEP-0071</a></td>
* <td></td>
* <td>Allows send and receiving formatted messages using XHTML.</td>
* </tr>
* <tr>
* <td>In-Band Registration</td>
* <td><a href="https://xmpp.org/extensions/xep-0077.html">XEP-0077</a></td>
* <td></td>
* <td>In-band registration with XMPP services.</td>
* </tr>
* <tr>
* <td>Advanced Message Processing</td>
* <td><a href="https://xmpp.org/extensions/xep-0079.html">XEP-0079</a></td>
* <td></td>
* <td>Enables entities to request, and servers to perform, advanced processing of XMPP message stanzas.</td>
* </tr>
* <tr>
* <td>User Location</td>
* <td><a href="https://xmpp.org/extensions/xep-0080.html">XEP-0080</a></td>
* <td></td>
* <td>Enabled communicating information about the current geographical or physical location of an entity.</td>
* </tr>
* <tr>
* <td>XMPP Date Time Profiles</td>
* <td><a href="https://xmpp.org/extensions/xep-0082.html">XEP-0082</a></td>
* <td></td>
* <td>Standardization of Date and Time representation in XMPP.</td>
* </tr>
* <tr>
* <td>Chat State Notifications</td>
* <td><a href="https://xmpp.org/extensions/xep-0085.html">XEP-0085</a></td>
* <td></td>
* <td>Communicating the status of a user in a chat session.</td>
* </tr>
* <tr>
* <td>Time Exchange</td>
* <td><a href="https://xmpp.org/extensions/xep-0090.html">XEP-0090</a></td>
* <td></td>
* <td>Allows local time information to be shared between users.</td>
* </tr>
* <tr>
* <td>Software Version</td>
* <td><a href="https://xmpp.org/extensions/xep-0092.html">XEP-0092</a></td>
* <td></td>
* <td>Retrieve and announce the software application of an XMPP entity.</td>
* </tr>
* <tr>
* <td>Roster Item Exchange</td>
* <td><a href="https://xmpp.org/extensions/xep-0093.html">XEP-0093</a></td>
* <td></td>
* <td>Allows roster data to be shared between users.</td>
* </tr>
* <tr>
* <td>Stream Initiation</td>
* <td><a href="https://xmpp.org/extensions/xep-0095.html">XEP-0095</a></td>
* <td></td>
* <td>Initiating a data stream between any two XMPP entities.</td>
* </tr>
* <tr>
* <td>SI File Transfer</td>
* <td><a href="https://xmpp.org/extensions/xep-0096.html">XEP-0096</a></td>
* <td></td>
* <td>Transfer files between two users over XMPP.</td>
* </tr>
* <tr>
* <td>User Mood</td>
* <td><a href="https://xmpp.org/extensions/xep-0107.html">XEP-0107</a></td>
* <td></td>
* <td>Communicate the users current mood.</td>
* </tr>
* <tr>
* <td>Entity Capabilities</td>
* <td><a href="https://xmpp.org/extensions/xep-0115.html">XEP-0115</a></td>
* <td>{@link org.jivesoftware.smackx.caps.EntityCapsManager}</td>
* <td>Broadcasting and dynamic discovery of entity capabilities.</td>
* </tr>
* <tr>
* <td>User Tune</td>
* <td><a href="https://xmpp.org/extensions/xep-0118.html">XEP-0118</a></td>
* <td></td>
* <td>Defines a payload format for communicating information about music to which a user is listening.</td>
* </tr>
* <tr>
* <td>Data Forms Validation</td>
* <td><a href="https://xmpp.org/extensions/xep-0122.html">XEP-0122</a></td>
* <td></td>
* <td>Enables an application to specify additional validation guidelines.</td>
* </tr>
* <tr>
* <td>Stanza Headers and Internet Metadata (SHIM)</td>
* <td><a href="https://xmpp.org/extensions/xep-0131.html">XEP-0131</a></td>
* <td></td>
* <td>Add Metadata Headers to Stanzas.</td>
* </tr>
* <tr>
* <td>Service Administration</td>
* <td><a href="https://xmpp.org/extensions/xep-0133.html">XEP-0133</a></td>
* <td></td>
* <td>Recommended best practices for service-level administration of servers and components using Ad-Hoc Commands.</td>
* </tr>
* <tr>
* <td>Stream Compression</td>
* <td><a href="https://xmpp.org/extensions/xep-0138.html">XEP-0138</a></td>
* <td></td>
* <td>Support for optional compression of the XMPP stream.</td>
* </tr>
* <tr>
* <td>Data Forms Layout</td>
* <td><a href="https://xmpp.org/extensions/xep-0141.html">XEP-0141</a></td>
* <td></td>
* <td>Enables an application to specify form layouts.</td>
* </tr>
* <tr>
* <td>Discovering Alternative XMPP Connection Methods</td>
* <td><a href="https://xmpp.org/extensions/xep-0156.html">XEP-0156</a></td>
* <td></td>
* <td>Defines ways to discover alternative connection methods.</td>
* </tr>
* <tr>
* <td>Personal Eventing Protocol</td>
* <td><a href="https://xmpp.org/extensions/xep-0163.html">XEP-0163</a></td>
* <td></td>
* <td>Using the XMPP publish-subscribe protocol to broadcast state change events associated with an XMPP account.</td>
* </tr>
* <tr>
* <td><a href="jingle.html">Jingle</a></td>
* <td><a href="https://xmpp.org/extensions/xep-0166.html">XEP-0166</a></td>
* <td></td>
* <td>Initiate and manage sessions between two XMPP entities.</td>
* </tr>
* <tr>
* <td>User Nickname</td>
* <td><a href="https://xmpp.org/extensions/xep-0172.html">XEP-0172</a></td>
* <td></td>
* <td>Communicate user nicknames.</td>
* </tr>
* <tr>
* <td>Message Delivery Receipts</td>
* <td><a href="https://xmpp.org/extensions/xep-0184.html">XEP-0184</a></td>
* <td></td>
* <td>Extension for message delivery receipts. The sender can request notification that the message has been
* delivered.</td>
* </tr>
* <tr>
* <td>Blocking Command</td>
* <td><a href="https://xmpp.org/extensions/xep-0191.html">XEP-0191</a></td>
* <td>{@link org.jivesoftware.smackx.blocking.BlockingCommandManager}</td>
* <td>Communications blocking that is intended to be simpler than privacy lists (XEP-0016).</td>
* </tr>
* <tr>
* <td>Stream Management</td>
* <td><a href="https://xmpp.org/extensions/xep-0198.html">XEP-0198</a></td>
* <td></td>
* <td>Allows active management of an XML Stream between two XMPP entities (stanza acknowledgement, stream
* resumption).</td>
* </tr>
* <tr>
* <td>XMPP Ping</td>
* <td><a href="https://xmpp.org/extensions/xep-0199.html">XEP-0199</a></td>
* <td></td>
* <td>Sending application-level pings over XML streams.</td>
* </tr>
* <tr>
* <td>Entity Time</td>
* <td><a href="https://xmpp.org/extensions/xep-0202.html">XEP-0202</a></td>
* <td></td>
* <td>Allows entities to communicate their local time</td>
* </tr>
* <tr>
* <td>Delayed Delivery</td>
* <td><a href="https://xmpp.org/extensions/xep-0203.html">XEP-0203</a></td>
* <td></td>
* <td>Extension for communicating the fact that an XML stanza has been delivered with a delay.</td>
* </tr>
* <tr>
* <td>XMPP Over BOSH</td>
* <td><a href="https://xmpp.org/extensions/xep-0206.html">XEP-0206</a></td>
* <td></td>
* <td>Use Bidirectional-streams Over Synchronous HTTP (BOSH) to transport XMPP stanzas.</td>
* </tr>
* <tr>
* <td>Data Forms Media Element</td>
* <td><a href="https://xmpp.org/extensions/xep-0221.html">XEP-0221</a></td>
* <td></td>
* <td>Allows to include media data in XEP-0004 data forms.</td>
* </tr>
* <tr>
* <td>Attention</td>
* <td><a href="https://xmpp.org/extensions/xep-0224.html">XEP-0224</a></td>
* <td></td>
* <td>Getting attention of another user.</td>
* </tr>
* <tr>
* <td>Bits of Binary</td>
* <td><a href="https://xmpp.org/extensions/xep-0231.html">XEP-0231</a></td>
* <td></td>
* <td>Including or referring to small bits of binary data in an XML stanza.</td>
* </tr>
* <tr>
* <td>Software Information</td>
* <td><a href="https://xmpp.org/extensions/xep-0232.html">XEP-0232</a></td>
* <td></td>
* <td>Allows an entity to provide detailed data about itself in Service Discovery responses.</td>
* </tr>
* <tr>
* <td>Roster Versioning</td>
* <td><a href="https://xmpp.org/extensions/xep-0237.html">XEP-0237</a></td>
* <td></td>
* <td>Efficient roster synchronization.</td>
* </tr>
* <tr>
* <td>Message Carbons</td>
* <td><a href="https://xmpp.org/extensions/xep-0280.html">XEP-0280</a></td>
* <td>{@link org.jivesoftware.smackx.carbons}</td>
* <td>Keep all IM clients for a user engaged in a conversation, by carbon-copy outbound messages to all interested
* resources.</td>
* </tr>
* <tr>
* <td>Best Practices for Resource Locking</td>
* <td><a href="https://xmpp.org/extensions/xep-0296.html">XEP-0296</a></td>
* <td></td>
* <td>Specifies best practices to be followed by Jabber/XMPP clients about when to lock into, and unlock away from,
* resources.</td>
* </tr>
* <tr>
* <td>Stanza Forwarding</td>
* <td><a href="https://xmpp.org/extensions/xep-0297.html">XEP-0297</a></td>
* <td></td>
* <td>Allows forwarding of Stanzas.</td>
* </tr>
* <tr>
* <td>Last Message Correction</td>
* <td><a href="https://xmpp.org/extensions/xep-0308.html">XEP-0308</a></td>
* <td></td>
* <td>Provides a method for indicating that a message is a correction of the last sent message.</td>
* </tr>
* <tr>
* <td>Message Archive Management</td>
* <td><a href="https://xmpp.org/extensions/xep-0313.html">XEP-0313</a></td>
* <td></td>
* <td>Query and control an archive of messages stored on a server.</td>
* </tr>
* <tr>
* <td>Data Forms XML Element</td>
* <td><a href="https://xmpp.org/extensions/xep-0315.html">XEP-0315</a></td>
* <td></td>
* <td>Allows to include XML-data in XEP-0004 data forms.</td>
* </tr>
* <tr>
* <td>Last User Interaction in Presence</td>
* <td><a href="https://xmpp.org/extensions/xep-0319.html">XEP-0319</a></td>
* <td></td>
* <td>Communicate time of last user interaction via XMPP presence notifications.</td>
* </tr>
* <tr>
* <td>Internet of Things - Sensor Data</td>
* <td><a href="https://xmpp.org/extensions/xep-0323.html">XEP-0323</a></td>
* <td></td>
* <td>Sensor data interchange over XMPP.</td>
* </tr>
* <tr>
* <td>Internet of Things - Provisioning</td>
* <td><a href="https://xmpp.org/extensions/xep-0324.html">XEP-0324</a></td>
* <td></td>
* <td>Provisioning, access rights and user privileges for the Internet of Things.</td>
* </tr>
* <tr>
* <td>Internet of Things - Control</td>
* <td><a href="https://xmpp.org/extensions/xep-0325.html">XEP-0325</a></td>
* <td></td>
* <td>Describes how to control devices or actuators in an XMPP-based sensor network.</td>
* </tr>
* <tr>
* <td>Jid Prep</td>
* <td><a href="https://xmpp.org/extensions/xep-0328.html">XEP-0328</a></td>
* <td></td>
* <td>Describes a way for an XMPP client to request an XMPP server to prep and normalize a given JID.</td>
* </tr>
* <tr>
* <td>HTTP over XMPP transport</td>
* <td><a href="https://xmpp.org/extensions/xep-0332.html">XEP-0332</a></td>
* <td>{@link org.jivesoftware.smackx.hoxt}</td>
* <td>Allows to transport HTTP communication over XMPP peer-to-peer networks.</td>
* </tr>
* <tr>
* <td>Chat Markers</td>
* <td><a href="https://xmpp.org/extensions/xep-0333.html">XEP-0333</a></td>
* <td></td>
* <td>A solution of marking the last received, displayed and acknowledged message in a chat.</td>
* </tr>
* <tr>
* <td>Message Processing Hints</td>
* <td><a href="https://xmpp.org/extensions/xep-0334.html">XEP-0334</a></td>
* <td></td>
* <td>Hints to entities routing or receiving a message.</td>
* </tr>
* <tr>
* <td>JSON Containers</td>
* <td><a href="https://xmpp.org/extensions/xep-0335.html">XEP-0335</a></td>
* <td></td>
* <td>Encapsulation of JSON data within XMPP Stanzas.</td>
* </tr>
* <tr>
* <td>Internet of Things - Discovery</td>
* <td><a href="https://xmpp.org/extensions/xep-0347.html">XEP-0347</a></td>
* <td></td>
* <td>Describes how Things can be installed and discovered by their owners.</td>
* </tr>
* <tr>
* <td>Data Forms Geolocation Element</td>
* <td><a href="https://xmpp.org/extensions/xep-0350.html">XEP-0350</a></td>
* <td></td>
* <td>Allows to include XEP-0080 gelocation data in XEP-0004 data forms.</td>
* </tr>
* <tr>
* <td>Client State Indication</td>
* <td><a href="https://xmpp.org/extensions/xep-0352.html">XEP-0352</a></td>
* <td></td>
* <td>A way for the client to indicate its active/inactive state.</td>
* </tr>
* <tr>
* <td>Push Notifications</td>
* <td><a href="https://xmpp.org/extensions/xep-0357.html">XEP-0357</a></td>
* <td></td>
* <td>Defines a way to manage push notifications from an XMPP Server.</td>
* </tr>
* <tr>
* <td>Stable and Unique Stanza IDs</td>
* <td><a href="https://xmpp.org/extensions/xep-0359.html">XEP-0359</a></td>
* <td></td>
* <td>This specification describes unique and stable IDs for messages.</td>
* </tr>
* <tr>
* <td>Nonzas</td>
* <td><a href="https://xmpp.org/extensions/xep-0360.html">XEP-0360</a></td>
* <td>{@link org.jivesoftware.smack.packet.Nonza}</td>
* <td>Defines the term Nonza, describing every top level stream element that is not a Stanza.</td>
* </tr>
* <tr>
* <td>HTTP File Upload</td>
* <td><a href="https://xmpp.org/extensions/xep-0363.html">XEP-0363</a></td>
* <td></td>
* <td>Protocol to request permissions to upload a file to an HTTP server and get a shareable URL.</td>
* </tr>
* <tr>
* <td>References</td>
* <td><a href="https://xmpp.org/extensions/xep-0363.html">XEP-0372</a></td>
* <td></td>
* <td>Add references like mentions or external data to stanzas.</td>
* </tr>
* <tr>
* <td>Explicit Message Encryption</td>
* <td><a href="https://xmpp.org/extensions/xep-0380.html">XEP-0380</a></td>
* <td></td>
* <td>Mark a message as explicitly encrypted.</td>
* </tr>
* <tr>
* <td>OpenPGP for XMPP</td>
* <td><a href="https://xmpp.org/extensions/xep-0373.html">XEP-0373</a></td>
* <td></td>
* <td>Utilize OpenPGP to exchange encrypted and signed content.</td>
* </tr>
* <tr>
* <td>OpenPGP for XMPP: Instant Messaging</td>
* <td><a href="https://xmpp.org/extensions/xep-0374.html">XEP-0374</a></td>
* <td></td>
* <td>OpenPGP encrypted Instant Messaging.</td>
* </tr>
* <tr>
* <td>Spoiler Messages</td>
* <td><a href="https://xmpp.org/extensions/xep-0382.html">XEP-0382</a></td>
* <td></td>
* <td>Indicate that the body of a message should be treated as a spoiler.</td>
* </tr>
* <tr>
* <td>OMEMO Multi End Message and Object Encryption</td>
* <td><a href="https://xmpp.org/extensions/xep-0384.html">XEP-0384</a></td>
* <td></td>
* <td>Encrypt messages using OMEMO encryption (currently only with smack-omemo-signal -&gt; GPLv3).</td>
* </tr>
* <tr>
* <td>Consistent Color Generation</td>
* <td><a href="https://xmpp.org/extensions/xep-0392.html">XEP-0392</a></td>
* <td>{@link org.jivesoftware.smackx.colors.ConsistentColor}</td>
* <td>Generate consistent colors for identifiers like usernames to provide a consistent user experience.</td>
* </tr>
* <tr>
* <td>Message Markup</td>
* <td><a href="https://xmpp.org/extensions/xep-0394.html">XEP-0394</a></td>
* <td>{@link org.jivesoftware.smackx.message_markup.element}</td>
* <td>Style message bodies while keeping body and markup information separated.</td>
* </tr>
* <tr>
* <td>DNS Queries over XMPP (DoX)</td>
* <td><a href="https://xmpp.org/extensions/xep-0418.html">XEP-0418</a></td>
* <td></td>
* <td>Send DNS queries and responses over XMPP.</td>
* </tr>
* <tr>
* <td>Stanza Content Encryption</td>
* <td><a href="https://xmpp.org/extensions/xep-0420.html">XEP-0420</a></td>
* <td></td>
* <td>End-to-end encryption of arbitrary extension elements. Smack provides elements and providers to be used by
* encryption mechanisms.</td>
* </tr>
* <tr>
* <td>Message Fastening</td>
* <td><a href="https://xmpp.org/extensions/xep-0422.html">XEP-0422</a></td>
* <td></td>
* <td>Mark payloads on a message to be logistically fastened to a previous message.</td>
* </tr>
* <tr>
* <td>Message Retraction</td>
* <td><a href="https://xmpp.org/extensions/xep-0424.html">XEP-0424</a></td>
* <td></td>
* <td>Mark messages as retracted.</td>
* </tr>
* <tr>
* <td>Fallback Indication</td>
* <td><a href="https://xmpp.org/extensions/xep-0428.html">XEP-0428</a></td>
* <td></td>
* <td>Declare body elements of a message as ignorable fallback for naive legacy clients.</td>
* </tr>
* <tr>
* <td>Google GCM JSON payload</td>
* <td></td>
* <td></td>
* <td>Semantically the same as XEP-0335: JSON Containers.</td>
* </tr>
* <tr>
* <td>Multi-User Chat Light</td>
* <td><a href=
* "https://mongooseim.readthedocs.io/en/latest/open-extensions/xeps/xep-muc-light.html">XEP-MUCLIGHT</a></td>
* <td></td>
* <td>Multi-User Chats for mobile XMPP applications and specific environment.</td>
* </tr>
* <tr>
* <td>Group Chat Invitations</td>
* <td></td>
* <td></td>
* <td>Send invitations to other users to join a group chat room.</td>
* </tr>
* <tr>
* <td><a href="properties.md">Jive Properties</a></td>
* <td></td>
* <td></td>
* <td>TODO</td>
* </tr>
* </tbody>
* </table>
*/
package org.jivesoftware.smackx;

View File

@ -1 +1 @@
../../../../../../../smack-extensions/src/main/java/org/jivesoftware/smackx/package-info.java
../../../../../../../smack-java8-full/src/main/java/org/jivesoftware/smackx/package-info.java

View File

@ -1 +1 @@
../../../../../../../smack-extensions/src/main/java/org/jivesoftware/smackx/package-info.java
../../../../../../../smack-java8-full/src/main/java/org/jivesoftware/smackx/package-info.java

View File

@ -16,6 +16,183 @@
*/
/**
* TODO describe me.
* This extension is used to send rosters, roster groups and roster entries from one XMPP Entity to another. It also
* provides an easy way to hook up custom logic when entries are received from other XMPP clients.
* <p>
* Follow these links to learn how to send and receive roster items:
* </p>
* <ul>
* <li>Send a complete roster</li>
* <li>Send a rosters group</li>
* <li>Send a rosters entry</li>
* <li>Receive roster entries</li>
* </ul>
* <p>
* <strong>XEP related:</strong> <a href="http://www.xmpp.org/extensions/xep-0093.html">XEP-93</a>
* </p>
* <h2 id="send-a-entire-roster">Send a entire roster</h2>
* <p>
* <strong>Description</strong>
* </p>
* <p>
* Sometimes it is useful to send a whole roster to another user. Smack provides a very easy way to send a complete
* roster to another XMPP client.
* </p>
* <p>
* <strong>Usage</strong>
* </p>
* <p>
* Create an instance of <em><strong>RosterExchangeManager</strong></em> and use the <strong>#send(Roster,
* String)</strong> message to send a roster to a given user. The first parameter is the roster to send and the second
* parameter is the id of the user that will receive the roster entries.
* </p>
* <p>
* <strong>Example</strong>
* </p>
* <p>
* In this example we can see how user1 sends his roster to user2.
* </p>
*
* <pre>
* <code>XMPPConnection conn1 =
// Create a new roster exchange manager on conn1
RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
// Send user1&#39;s roster to user2
rosterExchangeManager.send(Roster.getInstanceFor(conn1), user2);</code>
* </pre>
*
* <h2 id="send-a-roster-group">Send a roster group</h2>
* <p>
* <strong>Description</strong>
* </p>
* <p>
* It is also possible to send a roster group to another XMPP client. A roster group groups a set of roster entries
* under a name.
* </p>
* <p>
* <strong>Usage</strong>
* </p>
* <p>
* Create an instance of <em><strong>RosterExchangeManager</strong></em> and use the <strong>#send(RosterGroup,
* String)</strong> message to send a roster group to a given user. The first parameter is the roster group to send and
* the second parameter is the id of the user that will receive the roster entries.
* </p>
* <p>
* <strong>Example</strong>
* </p>
* <p>
* In this example we can see how user1 sends his roster groups to user2.
* </p>
*
* <pre>
* <code>
* XMPPConnection conn1 =
* // Create a new roster exchange manager on conn1
* RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
* // Send user1&#39;s RosterGroups to user2
* for (Iterator it = Roster.getInstanceFor(conn1).getGroups(); it.hasNext(); )
* rosterExchangeManager.send((RosterGroup)it.next(), user2);
* </code>
* </pre>
*
* <h2 id="send-a-roster-entry">Send a roster entry</h2>
* <p>
* <strong>Description</strong>
* </p>
* <p>
* Sometimes you may need to send a single roster entry to another XMPP client. Smack also lets you send items at this
* granularity level.
* </p>
* <p>
* <strong>Usage</strong>
* </p>
* <p>
* Create an instance of <em><strong>RosterExchangeManager</strong></em> and use the <strong>#send(RosterEntry,
* String)</strong> message to send a roster entry to a given user. The first parameter is the roster entry to send and
* the second parameter is the id of the user that will receive the roster entries.
* </p>
* <p>
* <strong>Example</strong>
* </p>
* <p>
* In this example we can see how user1 sends a roster entry to user2.
* </p>
*
* <pre>
* <code>
* XMPPConnection conn1 =
* // Create a new roster exchange manager on conn1
* RosterExchangeManager rosterExchangeManager = new RosterExchangeManager(conn1);
* // Send a roster entry (any) to user2
* rosterExchangeManager1.send((RosterEntry)Roster.getInstanceFor(conn1).getEntries().next(), user2);</code>
* </pre>
*
* <h2 id="receive-roster-entries">Receive roster entries</h2>
* <p>
* <strong>Description</strong>
* </p>
* <p>
* Since roster items are sent between XMPP clients, it is necessary to listen to possible roster entries receptions.
* Smack provides a mechanism that you can use to execute custom logic when roster entries are received.
* </p>
* <p>
* <strong>Usage</strong>
* </p>
* <ol type="1">
* <li>Create a class that implements the <em><strong>RosterExchangeListener</strong></em> interface.</li>
* <li>Implement the method <strong>entriesReceived(String, Iterator)</strong> that will be called when new entries are
* received with custom logic.</li>
* <li>Add the listener to the <em>RosterExchangeManager</em> that works on the desired <em>XMPPConnection</em>.</li>
* </ol>
* <p>
* <strong>Example</strong>
* </p>
* <p>
* In this example we can see how user1 sends a roster entry to user2 and user2 adds the received entries to his roster.
* </p>
*
* <pre>
* <code>
* // Connect to the server and log in the users
* XMPPConnection conn1 =
* XMPPConnection conn2 =
*
* final Roster user2_roster = Roster.getInstanceFor(conn2);
*
* // Create a RosterExchangeManager that will help user2 to listen and accept
* the entries received
* RosterExchangeManager rosterExchangeManager2 = new RosterExchangeManager(conn2);
* // Create a RosterExchangeListener that will iterate over the received roster entries
* RosterExchangeListener rosterExchangeListener = new RosterExchangeListener() {
* public void entriesReceived(String from, Iterator remoteRosterEntries) {
* while (remoteRosterEntries.hasNext()) {
* try {
* // Get the received entry
* RemoteRosterEntry remoteRosterEntry = (RemoteRosterEntry) remoteRosterEntries.next();
* // Display the remote entry on the console
* System.out.println(remoteRosterEntry);
* // Add the entry to the user2&#39;s roster
* user2_roster.createEntry(
* remoteRosterEntry.getUser(),
* remoteRosterEntry.getName(),
* remoteRosterEntry.getGroupArrayNames());
* }
* catch (XMPPException e) {
* e.printStackTrace();
* }
* }
* }
* };
* // Add the RosterExchangeListener to the RosterExchangeManager that user2 is using
* rosterExchangeManager2.addRosterListener(rosterExchangeListener);
*
* // Create a RosterExchangeManager that will help user1 to send his roster
* RosterExchangeManager rosterExchangeManager1 = new RosterExchangeManager(conn1);
* // Send user1&#39;s roster to user2
* rosterExchangeManager1.send(Roster.getInstanceFor(conn1), user2);
* </code>
* </pre>
* @see <a href="https://xmpp.org/extensions/xep-0093.html">XEP-0093: Roster Item Exchange</a>
*/
package org.jivesoftware.smackx.xroster;

View File

@ -15,10 +15,320 @@
* limitations under the License.
*/
/**
* Classes and interfaces for OMEMO Encryption. This module consists of the
* XMPP logic and some abstract crypto classes that have to be implemented
* using concrete crypto libraries (like signal-protocol-java or olm).
* See smack-omemo-signal for a concrete implementation (GPL licensed).
* Classes and interfaces for OMEMO Encryption. This module consists of the XMPP logic and some abstract crypto classes
* that have to be implemented using concrete crypto libraries (like signal-protocol-java or olm). See
* smack-omemo-signal for a concrete implementation (GPL licensed).
* <h2>About OMEMO</h2>
* <p>
* OMEMO (<a href="https://xmpp.org/extensions/xep-0384.html">XEP-0384</a>) is an adaption of the Signal protocol for
* XMPP. It provides an important set of cryptographic properties including but not restricted to
* </p>
* <ul>
* <li>Confidentiality</li>
* <li>Integrity</li>
* <li>Authenticity</li>
* <li>Forward Secrecy</li>
* <li>Future Secrecy (break-in recovery)</li>
* <li>Plausible Deniability</li>
* </ul>
* <p>
* Contrary to OTR it is capable of multi-end-to-multi-end encryption and message synchronization across multiple
* devices. It also allows the sender to send a message while the recipient is offline.
* </p>
* <p>
* It does <b>not</b> provide a server side message archive, so that a new device could fetch old chat history.
* </p>
* <p>
* Most implementations of OMEMO use the signal-protocol libraries provided by OpenWhisperSystems. Unlike Smack, those
* libraries are licensed under the GPLv3, which prevents a Apache licensed OMEMO implementation using those libraries
* (see <a href="https://github.com/igniterealtime/Smack/wiki/OMEMO-libsignal-Licensing-Situation">licensing
* situation</a>). The module smack-omemo therefore contains no code related to signal-protocol. However, almost all
* functionality is encapsulated in that module. If you want to use OMEMO in a GPLv3 licensed client, you can use the
* smack-omemo-signal Smack module, which binds the signal-protocol library to smack-omemo. It is also possible, to port
* smack-omemo to other libraries implementing the double ratchet algorithm.
* </p>
* <h2>Understanding the Double Ratchet Algorithm</h2>
* <p>
* In the context of OMEMO encryption, a *recipient* is a not a user, but a users *device* (a user might have multiple
* devices of course). Unlike in PGP, each device capable of OMEMO has its own identity key and publishes its own key
* bundle. It is not advised to migrate OMEMO identities from one device to another, as it might damage the ratchet if
* not done properly (more on that later). Sharing one identity key between multiple devices is not the purpose of
* OMEMO. If a contact has three OMEMO capable devices, you will see three different OMEMO identities and their
* fingerprints.
* </p>
* <p>
* OMEMO utilizes multiple layers of encryption when encrypting a message. The body of the message is encrypted with a
* symmetric message key (AES-128-GCM) producing a *payload*. The message key is encrypted for each recipient using the
* double ratchet algorithm. For that purpose, the sending device creates a session with the recipient device (if there
* was no session already). Upon receiving a message, the recipient selects the encrypted key addressed to them and
* decrypts it with their counterpart of the OMEMO session. The decrypted key gets then used to decrypt the message.
* </p>
* <p>
* One important consequence of forward secrecy is, that whenever an OMEMO message gets decrypted, the state of the
* ratchet changes and the key used to decrypt the message gets deleted. There is no way to recover this key a second
* time. The result is, that every message can be decrypted exactly once.
* </p>
* <p>
* In order to provide the best user experience, it is therefore advised to implement a client side message archive,
* since solutions like MAM cannot be used to fetch old, already once decrypted OMEMO messages.
* </p>
* <h2>Server-Side Requirements</h2>
* <p>
* In order to use OMEMO encryption, your server and the servers of your chat partners must support PEP
* (<a href="https://xmpp.org/extensions/xep-0163.html">XEP-0163</a>) to store and exchange key bundles. Optionally your
* server should support Message Carbons (<a href="https://xmpp.org/extensions/xep-0280.html">XEP-0280</a>) and Message
* Archive Management (<a href="http://xmpp.org/extensions/xep-0313.html">XEP-0313</a>) to achieve message
* synchronization across all (on- and offline) devices.
* </p>
* <h2>Client-side Requirements</h2>
* <p>
* If you are want to run smack-omemo related code on the Windows platform, you might have to install the
* <a href="http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html">Java Cryptography
* Extension</a>). This is needed to generate cryptographically strong keys.
* </p>
* <h2>Storing Keys</h2>
* <p>
* smack-omemo needs to create, store and delete some information like keys and session states during operation. For
* that purpose the `OmemoStore` class is used. There are multiple implementations with different properties.
* </p>
* <p>
* The `(Signal)FileBasedOmemoStore` stores all information in individual files organized in a directory tree. While
* this is the most basic and easy to use implementation, it is not the best solution in terms of performance.
* </p>
* <p>
* The `(Signal)CachingOmemoStore` is a multi-purpose store implementation. It can be used to wrap another
* `(Signal)OmemoStore` implementation to provide a caching layer (for example in order to reduce access to a database
* backend or a the file system of the `FileBasedOmemoStore`. It is therefore advised to wrap persistent
* `(Signal)OmemoStore` implementations with a `(Signal)CachingOmemoStore`. On the other hand it can also be used
* standalone as an ephemeral `OmemoStore`, which "forgets" all stored information once the program terminates. This
* comes in handy for testing purposes.
* </p>
* <p>
* If you are unhappy with the `(Signal)FileBasedOmemoStore`, you can implement your own store (for example with a SQL
* database) by extending the `(Signal)OmemoStore` class.
* </p>
* <p>
* It most certainly makes sense to store the data of the used `OmemoStore` in a secure way (for example an encrypted
* database).
* </p>
* <h2>Handling Trust Decisions</h2>
* <p>
* In order for a cryptographic system to make sense, decisions must be made whether to *trust* an identity or not. For
* technical reasons those decisions cannot be stored within the `OmemoStore`. Instead a client must implement the
* `OmemoTrustCallback`. This interface provides methods to mark `OmemoFingerprints` as trusted or untrusted and to
* query trust decisions.
* </p>
* <p>
* In order to provide security, a client should communicate to the user, that it is important for them to compare
* fingerprints through an external channel (reading it out on the phone, scanning QR codes...) before starting to chat.
* </p>
* <p>
* While not implemented in smack-omemo, it is certainly for the client to implement different trust models like
* <a href="https://gultsch.de/trust.html">Blind Trust Before Verification</a>.
* </p>
* <h2>Basic Setup</h2>
* <p>
* Before you can start to send and receive messages, some preconditions have to be met. These steps should be executed
* in the order as presented below. In this example we will use components from the *smack-omemo-signal* module.
* </p>
* <h3>1. Register an OmemoService</h3>
* <p>
* The `OmemoService` class is responsible for handling incoming messages and manages access to the Double Ratchet.
* </p>
*
* <pre>
* <code>
* SignalOmemoService.setup();
* </code>
* </pre>
* <p>
* The `setup()` method registers the service as a singleton. You can later access the instance by calling
* `SignalOmemoService.getInstace()`. The service can only be registered once. Subsequent calls will throw an
* {@link IllegalStateException}.
* </p>
* <h3>2. Set an OmemoStore</h3>
* <p>
* Now you have to decide, what `OmemoStore` implementation you want to use to store and access keys and session states.
* In this example we'll use the `SignalFileBasedOmemoStore` wrapped in a `SignalCachingOmemoStore` for better
* performance.
* </p>
*
* <pre>
* <code>
* SignalOmemoService service = SignalOmemoService.getInstace();
* service.setOmemoStoreBackend(new SignalCachingOmemoStore(new SignalFileBasedOmemoStore(new File("/path/to/store"))));
* </code>
* </pre>
* <p>
* Just like the `OmemoService` instance, the `OmemoStore` instance can only be set once.
* </p>
* <h3>3. Get an instance of the OmemoManager for your connection</h3>
* <p>
* For the greater part of OMEMO related actions, you'll use the `OmemoManager`. The `OmemoManager` represents
* your OMEMO device. While it is possible to have multiple `OmemoManager`s per `XMPPConnection`, you really
* only need one.
* </p>
* <pre>
* <code>
* OmemoManager manager = OmemoManager.getInstanceFor(connection);
* </code>
* </pre>
* <p>
* If for whatever reason you decide to use multiple `OmemoManager`s at once, it is highly advised to get them like this:
* </p>
* <pre>
* <code>
* OmemoManager first = OmemoManager.getInstanceFor(connection, firstId);
* OmemoManager second = OmemoManager.getInstanceFor(connection, secondId);
* </code>
* </pre>
* <h3>Set an OmemoTrustCallback</h3>
* <p>
* As stated above, the `OmemoTrustCallback` is used to query trust decisions. Set the callback like this:
* </p>
* <pre>
* <code>
* manager.setTrustCallback(trustCallback);
* </code>
* </pre>
* <p>
* If you use multiple `OmemoManager`s each `OmemoManager` MUST have its own callback.
* </p>
* <h3>Set listeners for OMEMO messages.</h3>
* <p>
* To get notified of incoming OMEMO encrypted messages, you need to register corresponding listeners.
* There are two types of listeners.
* </p>
* <ul>
* <li>`OmemoMessageListener` is used to listen for incoming encrypted OMEMO single chat messages and KeyTransportMessages.</li>
* <li>`OmemoMucMessageListener` is used to listen for encrypted OMEMO messages sent in a MultiUserChat.</li>
* </ul>
* <p>
* Note that an incoming message might not have a body. That might be the case for KeyTransportMessages or or messages sent to update the ratchet. You can check, whether a received message is such a message by calling `OmemoMessage.Received.isKeyTransportMessage()`, which will return true if the message has no body.
* </p>
* <p>
* The received message will include the senders device and fingerprint, which you can use in
* `OmemoManager.isTrustedOmemoIdentity(device, fingerprint)` to determine, if the message was sent by a trusted device.
* </p>
* <h3>Initialize the manager(s)</h3>
* <p>
* Ideally all above steps should be executed *before* `connection.login()` gets called. That way you won't miss
* any offline messages. If the connection is not yet logged in, now is the time to do so.
* </p>
* <pre>
* <code>
* connection.login();
* manager.initialize();
* </code>
* </pre>
* <p>
* Since a lot of keys are generated in this step, this might take a little longer on older devices.
* You might want to use the asynchronous call `OmemoManager.initializeAsync(initializationFinishedCallback)`
* instead to prevent the thread from blocking.
* </p>
* <h2>Send Messages</h2>
* <p>
* Encrypting a message for a contact really means to encrypt the message for all trusted devices of the contact, as well
* as all trusted devices of the user itself (except the sending device). The encryption process will fail if there are
* devices for which the user has not yet made a trust decision.
* </p>
* <h3>Make Trust Decisions</h3>
* <p>
* To get a list of all devices of a contact, you can do the following:
* </p>
* <pre>
* {@code
* List<OmemoDevice> devices = manager.getDevicesOf(contactsBareJid);
* }
* </pre>
* <p>
* To get the OmemoFingerprint of a device, you can call
* </p>
* <pre>
* <code>
* OmemoFingerprint fingerprint = manager.getFingerprint(device);
* </code>
* </pre>
* <p>
* This fingerprint can now be displayed to the user who can decide whether to trust the device, or not.
* </p>
* <pre>
* <code>
* // Trust
* manager.trustOmemoIdentity(device, fingerprint);
*
* // Distrust
* manager.distrustOmemoIdentity(device, fingerprint);
* </code>
* </pre>
* <h3>Encrypt a Message</h3>
* <p>
* Currently only Message bodies can be encrypted.
* </p>
* <pre>
* <code>
* String secret = "Mallory is a twerp!";
* OmemoMessage.Sent encrypted = manager.encrypt(contactsBareJid, secret);
* </code>
* </pre>
* <p>
* The encrypted message will contain some information about the message. It might for example happen, that the encryption failed for some recipient devices. For that reason the encrypted message will contain a map of skipped devices and the reasons.
* </p>
* <h3>Encrypt a Message for a MultiUserChat</h3>
* <p>
* A MultiUserChat must fulfill some criteria in order to be OMEMO capable.
* The MUC must be non-anonymous. Furthermore all members of the MUC must have subscribed to one another.
* You can check for the non-anonymity like follows:
* </p>
* <pre>
* <code>
* manager.multiUserChatSupportsOmemo(muc);
* </code>
* </pre>
* <p>
* Encryption is then done analog to single message encryption:
* </p>
* <pre>
* <code>
* OmemoMessage.Sent encrypted = manager.encrypt(multiUserChat, secret);
* </code>
* </pre>
* <h3>Sending an encrypted Message</h3>
* <p>
* To send the message, it has to be wrapped in a `Message` object. That can conveniently be done like follows.
* </p>
* <pre>
* <code>
* Message message = encrypted.asMessage(contactsJid);
* connection.sendStanza(message):
* </code>
* </pre>
* <p>
* This will add a <a href="https://xmpp.org/extensions/xep-0334.html">Message Processing Hint</a> for MAM,
* an <a href="https://xmpp.org/extensions/xep-0380.html">Explicit Message Encryption</a> hint for OMEMO,
* as well as an optional cleartext hint about OMEMO to the message.
* </p>
* <h2>Configuration</h2>
* <p>
* smack-omemo has some configuration options that can be changed on runtime via the `OmemoConfiguration` class:
* </p>
* <ul>
* <li>setIgnoreStaleDevices when set to true, smack-omemo will stop encrypting messages for **own** devices that have not send a message for some period of time (configurable in setIgnoreStaleDevicesAfterHours)</li>
* <li>setDeleteStaleDevices when set to true, smack-omemo will remove own devices from the device list, if no messages were received from them for a period of time (configurable in setDeleteStaleDevicesAfterHours)</li>
* <li>setRenewOldSignedPreKeys when set to true, smack-omemo will periodically generate and publish new signed prekeys. Via setRenewOldSignedPreKeysAfterHours you can configure, after what period of time new keys are generated and setMaxNumberOfStoredSignedPreKeys allows configuration of how many signed PreKeys are kept in storage for decryption of delayed messages.</li>
* <li>setAddOmemoBodyHint when set to true, a plaintext body with a hint about OMEMO encryption will be added to the message. This hint will be displayed by clients that do not support OMEMO. Note that this might not be desirable when communicating with clients that do not support EME.</li>
* <li>setRepairBrokenSessionsWithPreKeyMessages when set to true, whenever a message arrives, which cannot be decrypted, smack-omemo will respond with a preKeyMessage which discards the old session and builds a fresh one.</li>
* <li>setCompleteSessionWithEmptyMessage when set to true, whenever a preKeyMessage arrives, smack-omemo will respond with an empty message to complete the session.</li>
* </ul>
* <h2>Integration Tests</h2>
* <p>
* smack-omemo comes with a set of integration tests. Lets say you want to run the integration test suite for smack-omemo-signal. You can do so by using the following gradle task:
* </p>
* <pre>
* <code>
* gradle omemoSignalIntTest
* </code>
* </pre>
*
* @author Paul Schaub
* @see <a href="https://conversations.im/xeps/multi-end.html">XEP-0384: OMEMO</a>

View File

@ -1,6 +1,6 @@
/**
*
* Copyright 2017 Florian Schmaus, 2018 Paul Schaub.
* Copyright 2017-2023 Florian Schmaus, 2018 Paul Schaub.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -15,6 +15,6 @@
* limitations under the License.
*/
/**
* Smack API for XEP-0373: OpenPGP for XMPP.
* Smack API for XEP-0373: OpenPGP for XMPP. See {@link OpenPgpManager} for more information.
*/
package org.jivesoftware.smackx.ox;

Some files were not shown because too many files have changed in this diff Show More