org.jivesoftware.smackx.delay.packet.DelayInformation Java Examples

The following examples show how to use org.jivesoftware.smackx.delay.packet.DelayInformation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KonMessageListener.java    From desktopclient-java with GNU General Public License v3.0 6 votes vote down vote up
private static Date getDelay(Message m) {
    // first: new XEP-0203 specification
    ExtensionElement delay = DelayInformation.from(m);

    // fallback: obsolete XEP-0091 specification
    if (delay == null) {
        delay = m.getExtension("x", "jabber:x:delay");
    }

    if (delay instanceof DelayInformation) {
        Date date = ((DelayInformation) delay).getStamp();
        if (date.after(new Date()))
            LOGGER.warning("delay time is in future: "+date);
        return date;
    }

    return null;
}
 
Example #2
Source File: AbstractDelayInformationProvider.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Override
public final DelayInformation parse(XmlPullParser parser,
                int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException,
                IOException, SmackTextParseException {
    String stampString = parser.getAttributeValue("", "stamp");
    String from = parser.getAttributeValue("", "from");
    final String reason;
    XmlPullParser.Event event = parser.next();
    switch (event) {
    case TEXT_CHARACTERS:
        reason = parser.getText();
        parser.next();
        break;
    case END_ELEMENT:
        reason = null;
        break;
    default:
        // TODO: Should be SmackParseException.
        throw new IOException("Unexpected event: " + event);
    }

    Date stamp = parseDate(stampString);
    return new DelayInformation(stamp, from, reason);
}
 
Example #3
Source File: QueryArchiveTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void checkMamQueryResults() throws Exception {
    Message message = StanzaBuilder.buildMessage("iasd207")
            .from("[email protected]")
            .to("[email protected]/pda")
            .build();

    GregorianCalendar calendar = new GregorianCalendar(2002, 10 - 1, 13, 23, 58, 37);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = calendar.getTime();

    DelayInformation delay = new DelayInformation(date);
    Message forwardedMessage = StanzaBuilder.buildMessage("162BEBB1-F6DB-4D9A-9BD8-CFDCC801A0B2")
                    .from(JidCreate.from("[email protected]/firstwitch"))
                    .ofType(Type.chat)
                    .setBody("Thrice the brinded cat hath mew.")
                    .build();

    Forwarded forwarded = new Forwarded(delay, forwardedMessage);

    message.addExtension(new MamResultExtension("g27", "34482-21985-73620", forwarded));

    assertEquals(mamQueryResultExample, message.toXML(StreamOpen.CLIENT_NAMESPACE).toString());

    MamResultExtension mamResultExtension = MamResultExtension.from(message);

    assertEquals(mamResultExtension.getId(), "34482-21985-73620");
    assertEquals(mamResultExtension.getForwarded().getDelayInformation().getStamp(), date);

    Message resultMessage = (Message) mamResultExtension.getForwarded().getForwardedStanza();
    assertEquals(resultMessage.getFrom(), JidCreate.from("[email protected]/firstwitch"));
    assertEquals(resultMessage.getStanzaId(), "162BEBB1-F6DB-4D9A-9BD8-CFDCC801A0B2");
    assertEquals(resultMessage.getType(), Type.chat);
    assertEquals(resultMessage.getBody(), "Thrice the brinded cat hath mew.");
}
 
Example #4
Source File: SoundPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChatRoom room, Message message) {

       // Do not play sounds on history updates.
       DelayInformation inf = message.getExtension("delay", "urn:xmpp:delay");
       if (inf != null) {
           return;
       }

       SoundPreferences preferences = soundPreference.getPreferences();
       if (preferences.isPlayIncomingSound()) {
           File incomingFile = new File(preferences.getIncomingSound());
           SparkManager.getSoundManager().playClip(incomingFile);
       }
   }
 
Example #5
Source File: BroadcastPlugin.java    From Spark with Apache License 2.0 5 votes vote down vote up
@Override
public void processStanza(final Stanza stanza) {
    SwingUtilities.invokeLater( () -> {
        try {
            final Message message = (Message)stanza;

            // Do not handle errors or offline messages
            final DelayInformation offlineInformation = message.getExtension("delay", "urn:xmpp:delay");
            if (offlineInformation != null || message.getError() != null) {
                return;
            }

            final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension( JivePropertiesExtension.NAMESPACE ));
            final boolean broadcast = extension != null && extension.getProperty( "broadcast" ) != null;

            if ((broadcast || message.getType() == Type.normal
                || message.getType() == Type.headline) && message.getBody() != null) {
                showAlert((Message)stanza);
            }
            else {
                String host = SparkManager.getSessionManager().getServerAddress();
                String from = stanza.getFrom() != null ? stanza.getFrom().toString() : "";
                if (host.equalsIgnoreCase(from) || !ModelUtil.hasLength(from)) {
                    showAlert((Message)stanza);
                }
            }
        }
        catch (Exception e) {
            Log.error(e);
        }
    } );

}
 
Example #6
Source File: TranscriptWindow.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a text message this transcript window.
 *
 * @param nickname   the nickname of the author of the message.
 * @param message    the message to insert.
 * @param foreground the color to use for the nickname (excluding the message text) foreground.
 * @param background the color to use for the entire background (eg, to highlight).
 */
public void insertMessage( CharSequence nickname, Message message, Color foreground, Color background )
{
    for ( TranscriptWindowInterceptor interceptor : SparkManager.getChatManager().getTranscriptWindowInterceptors() )
    {
        try
        {
            boolean handled = interceptor.isMessageIntercepted( this, nickname.toString(), message );
            if ( handled )
            {
                // Do nothing.
                return;
            }
        }
        catch ( Exception e )
        {
            Log.error( "A TranscriptWindowInterceptor ('" + interceptor + "') threw an exception while processing a chat message (current user: '" + nickname + "').", e );
        }
    }

    String body = message.getBody();

    // Verify the timestamp of this message. Determine if it is a 'live' message, or one that was sent earlier.
    final DelayInformation inf = message.getExtension( "delay", "urn:xmpp:delay" );
    final ZonedDateTime sentDate;
    final boolean isDelayed;
    if ( inf != null )
    {
        sentDate = inf.getStamp().toInstant().atZone( ZoneOffset.UTC );
        body = "(" + Res.getString( "offline" ) + ") " + body;
        isDelayed = true;
    }
    else
    {
        sentDate = ZonedDateTime.now();
        isDelayed = false;
    }
    add( new MessageEntry( sentDate, isDelayed, nickname.toString(), foreground, body, (Color) UIManager.get( "Message.foreground" ), background ) );
}
 
Example #7
Source File: ForwardedTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void forwardedWithDelayTest() throws Exception {
    XmlPullParser parser;
    String control;
    Forwarded fwd;

    // @formatter:off
    control = XMLBuilder.create("forwarded").a("xmlns", "urn:xmpp:forwarded:0")
                    .e("message").a("from", "[email protected]").up()
                    .e("delay").ns(DelayInformation.NAMESPACE).a("stamp", "2010-07-10T23:08:25Z")
              .asString(outputProperties);
    // @formatter:on

    parser = PacketParserUtils.getParserFor(control);
    fwd = new ForwardedProvider().parse(parser);

    // assert there is delay information in packet
    DelayInformation delay = fwd.getDelayInformation();
    assertNotNull(delay);

    // check message
    assertThat("[email protected]", equalsCharSequence(fwd.getForwardedStanza().getFrom()));

    // check end of tag
    assertEquals(XmlPullParser.Event.END_ELEMENT, parser.getEventType());
    assertEquals("forwarded", parser.getName());
}
 
Example #8
Source File: DelayInformationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void parsePresenceWithInvalidLegacyDelayed() throws Exception {
    String stanza = "<presence from='[email protected]' to='[email protected]'>"
                    + "<x xmlns='jabber:x:delay'/></presence>";

    Presence presence = PacketParserUtils.parsePresence(PacketParserUtils.getParserFor(stanza));
    DelayInformation delay = DelayInformationManager.getXep203DelayInformation(presence);
    assertNull(delay);
}
 
Example #9
Source File: DelayInformationTest.java    From Smack with Apache License 2.0 5 votes vote down vote up
@Test
public void validatePresenceWithDelayedDelivery() throws Exception {
    String stanza = "<presence from='[email protected]' to='[email protected]'>"
            + "<delay xmlns='urn:xmpp:delay' stamp='2002-09-10T23:41:07Z'/></presence>";

    Presence presence = PacketParserUtils.parsePresence(PacketParserUtils.getParserFor(stanza));

    DelayInformation delay = DelayInformationManager.getXep203DelayInformation(presence);
    assertNotNull(delay);
    Date date = XmppDateTime.parseDate("2002-09-10T23:41:07Z");
    assertEquals(date, delay.getStamp());
}
 
Example #10
Source File: DelayInformationManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Get the Delayed Delivery timestamp or <code>null</code>.
 *
 * @param packet TODO javadoc me please
 * @return the Delayed Delivery timestamp or <code>null</code>
 */
public static Date getDelayTimestamp(Stanza packet) {
    DelayInformation delayInformation = getDelayInformation(packet);
    if (delayInformation == null) {
        return null;
    }
    return delayInformation.getStamp();
}
 
Example #11
Source File: DelayInformationManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Get Delayed Delivery information. This method first looks for a PacketExtension with the
 * XEP-203 namespace and falls back to the XEP-91 namespace.
 *
 * @param packet TODO javadoc me please
 * @return the Delayed Delivery information or <code>null</code>
 */
public static DelayInformation getDelayInformation(Stanza packet) {
    DelayInformation delayInformation = getXep203DelayInformation(packet);
    if (delayInformation != null) {
        return delayInformation;
    }
    return getLegacyDelayInformation(packet);
}
 
Example #12
Source File: DelayInformationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void delayInformationTest() throws Exception {
    DelayInformationProvider p = new DelayInformationProvider();
    DelayInformation delayInfo;
    XmlPullParser parser;
    String control;
    GregorianCalendar calendar = new GregorianCalendar(2002, 9 - 1, 10, 23, 8, 25);
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date date = calendar.getTime();

    control = XMLBuilder.create("x")
        .a("xmlns", "jabber:x:delay")
        .a("from", "capulet.com")
        .a("stamp", "2002-09-10T23:08:25Z")
        .t("Offline Storage")
        .asString(outputProperties);

    parser = PacketParserUtils.getParserFor(control);
    delayInfo = p.parse(parser);

    assertEquals("capulet.com", delayInfo.getFrom());
    assertEquals(date, delayInfo.getStamp());
    assertEquals("Offline Storage", delayInfo.getReason());

    assertEquals(XmlPullParser.Event.END_ELEMENT, parser.getEventType());
    assertEquals("x", parser.getName());

    control = XMLBuilder.create("x")
        .a("xmlns", "jabber:x:delay")
        .a("from", "capulet.com")
        .a("stamp", "2002-09-10T23:08:25Z")
        .asString(outputProperties);

    parser = PacketParserUtils.getParserFor(control);
    delayInfo = p.parse(parser);

    assertEquals("capulet.com", delayInfo.getFrom());
    assertEquals(date, delayInfo.getStamp());
    assertNull(delayInfo.getReason());

    assertEquals(XmlPullParser.Event.END_ELEMENT, parser.getEventType());
    assertEquals("x", parser.getName());

}
 
Example #13
Source File: DelayInformationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void dateFormatsTest() throws Exception {
    DelayInformationProvider p = new DelayInformationProvider();
    DelayInformation delayInfo;
    String control;

    // XEP-0082 date format
    control = XMLBuilder.create("delay")
        .a("xmlns", "urn:xmpp:delay")
        .a("from", "capulet.com")
        .a("stamp", "2002-09-10T23:08:25.12Z")
        .asString(outputProperties);

    delayInfo = p.parse(PacketParserUtils.getParserFor(control));

    GregorianCalendar cal = (GregorianCalendar) calendar.clone();
    cal.add(Calendar.MILLISECOND, 120);
    assertEquals(cal.getTime(), delayInfo.getStamp());

    // XEP-0082 date format without milliseconds
    control = XMLBuilder.create("delay")
        .a("xmlns", "urn:xmpp:delay")
        .a("from", "capulet.com")
        .a("stamp", "2002-09-10T23:08:25Z")
        .asString(outputProperties);

    delayInfo = p.parse(PacketParserUtils.getParserFor(control));

    assertEquals(calendar.getTime(), delayInfo.getStamp());

    // XEP-0082 date format without milliseconds and leading 0 in month
    control = XMLBuilder.create("delay")
        .a("xmlns", "urn:xmpp:delay")
        .a("from", "capulet.com")
        .a("stamp", "2002-9-10T23:08:25Z")
        .asString(outputProperties);

    delayInfo = p.parse(PacketParserUtils.getParserFor(control));

    assertEquals(calendar.getTime(), delayInfo.getStamp());
}
 
Example #14
Source File: DelayInformationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void legacyDateFormatsTest() throws FactoryConfigurationError, XmlPullParserException, IOException, Exception {
    LegacyDelayInformationProvider p = new LegacyDelayInformationProvider();
    DelayInformation delayInfo;

    String control;

    // XEP-0091 date format
    control = XMLBuilder.create("x")
        .a("xmlns", "jabber:x:delay")
        .a("from", "capulet.com")
        .a("stamp", "20020910T23:08:25")
        .asString(outputProperties);

    delayInfo = p.parse(PacketParserUtils.getParserFor(control));

    assertEquals(calendar.getTime(), delayInfo.getStamp());

    // XEP-0091 date format without leading 0 in month
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMd'T'HH:mm:ss");
    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
    GregorianCalendar dateInPast = new GregorianCalendar();
    if (dateInPast.get(Calendar.MONTH) >= 10) {
        dateInPast.set(Calendar.MONTH, dateInPast.get(Calendar.MONTH) - 3);
    }
    dateInPast.add(Calendar.DAY_OF_MONTH, -3);
    dateInPast.set(Calendar.MILLISECOND, 0);

    control = XMLBuilder.create("x")
        .a("xmlns", "jabber:x:delay")
        .a("from", "capulet.com")
        .a("stamp", dateFormat.format(dateInPast.getTime()))
        .asString(outputProperties);

    delayInfo = p.parse(PacketParserUtils.getParserFor(control));

    assertEquals(dateInPast.getTime(), delayInfo.getStamp());

    // XEP-0091 date format from SMACK-243
    control = XMLBuilder.create("x")
        .a("xmlns", "jabber:x:delay")
        .a("from", "capulet.com")
        .a("stamp", "200868T09:16:20")
        .asString(outputProperties);

    delayInfo = p.parse(PacketParserUtils.getParserFor(control));
    Date controlDate = XmppDateTime.parseDate("2008-06-08T09:16:20.0Z");

    assertEquals(controlDate, delayInfo.getStamp());
}
 
Example #15
Source File: ForwardedProvider.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Override
public Forwarded parse(XmlPullParser parser, int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException, IOException, SmackParsingException {
    DelayInformation di = null;
    Stanza packet = null;

    outerloop: while (true) {
        XmlPullParser.Event eventType = parser.next();
        switch (eventType) {
        case START_ELEMENT:
            String name = parser.getName();
            String namespace = parser.getNamespace();
            switch (name) {
            case DelayInformation.ELEMENT:
                if (DelayInformation.NAMESPACE.equals(namespace)) {
                    di = DelayInformationProvider.INSTANCE.parse(parser, parser.getDepth(), null);
                } else {
                    LOGGER.warning("Namespace '" + namespace + "' does not match expected namespace '"
                                    + DelayInformation.NAMESPACE + "'");
                }
                break;
            case Message.ELEMENT:
                packet = PacketParserUtils.parseMessage(parser);
                break;
            default:
                LOGGER.warning("Unsupported forwarded packet type: " + name);
            }
            break;
        case END_ELEMENT:
            if (parser.getDepth() == initialDepth) {
                break outerloop;
            }
            break;
        default:
            // Catch all for incomplete switch (MissingCasesInEnumSwitch) statement.
            break;
        }
    }

    if (packet == null) {
        // TODO: Should be SmackParseException.
        throw new IOException("forwarded extension must contain a packet");
    }
    return new Forwarded(di, packet);
}
 
Example #16
Source File: Workspace.java    From Spark with Apache License 2.0 4 votes vote down vote up
private void handleIncomingPacket(Stanza stanza) throws SmackException.NotConnectedException, InterruptedException
{
    // We only handle message packets here.
    if (stanza instanceof Message) {
        final Message message = (Message)stanza;
        boolean isGroupChat = message.getType() == Message.Type.groupchat;

        // Check if Conference invite. If so, do not handle here.
        if (message.getExtension("x", "jabber:x:conference") != null) {
            return;
        }

        final String body = message.getBody();
        final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension( JivePropertiesExtension.NAMESPACE ));
        final boolean broadcast = extension != null && extension.getProperty( "broadcast" ) != null;

        // Handle offline message.
        DelayInformation offlineInformation = message.getExtension("delay", "urn:xmpp:delay");
        if (offlineInformation != null && (Message.Type.chat == message.getType() ||
            Message.Type.normal == message.getType())) {
            handleOfflineMessage(message);
        }

        if (body == null ||
            isGroupChat ||
            broadcast ||
            message.getType() == Message.Type.normal ||
            message.getType() == Message.Type.headline ||
            message.getType() == Message.Type.error) {
            return;
        }

        // Create new chat room for Agent Invite.
        final Jid from = stanza.getFrom();
        final String host = SparkManager.getSessionManager().getServerAddress();

        // Don't allow workgroup notifications to come through here.
        final BareJid bareJID = from.asBareJid();
        if (host.equalsIgnoreCase(from.toString()) || from == null) {
            return;
        }


        ChatRoom room = null;
        try {
            room = SparkManager.getChatManager().getChatContainer().getChatRoom(bareJID);
        }
        catch (ChatRoomNotFoundException e) {
            // Ignore
        }

        // Check for non-existent rooms.
        if (room == null) {
            EntityBareJid entityBareJid = bareJID.asEntityBareJidIfPossible();
            if (entityBareJid != null) {
                createOneToOneRoom(entityBareJid, message);
            }
        }
    }
}
 
Example #17
Source File: Forwarded.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * get the timestamp of the forwarded packet.
 *
 * @return the {@link DelayInformation} representing the time when the original stanza was sent. May be null.
 */
public DelayInformation getDelayInformation() {
    return delay;
}
 
Example #18
Source File: Forwarded.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new Forwarded stanza extension.
 *
 * @param delay an optional {@link DelayInformation} timestamp of the packet.
 * @param fwdPacket the stanza that is forwarded (required).
 */
public Forwarded(DelayInformation delay, Stanza fwdPacket) {
    this.delay = delay;
    this.forwardedPacket = fwdPacket;
}
 
Example #19
Source File: DelayInformationManager.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Get Delayed Delivery information as defined in XEP-91
 * <p>
 * Prefer {@link #getDelayInformation(Stanza)} over this method for backwards compatibility.
 * </p>
 * @param packet TODO javadoc me please
 * @return the Delayed Delivery information or <code>null</code>
 */
public static DelayInformation getLegacyDelayInformation(Stanza packet) {
    return packet.getExtension(DelayInformation.class);
}
 
Example #20
Source File: DelayInformationManager.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Get Delayed Delivery information as defined in XEP-203
 * <p>
 * Prefer {@link #getDelayInformation(Stanza)} over this method for backwards compatibility.
 * </p>
 * @param packet TODO javadoc me please
 * @return the Delayed Delivery information or <code>null</code>
 */
public static DelayInformation getXep203DelayInformation(Stanza packet) {
    return DelayInformation.from(packet);
}