Java Code Examples for org.jivesoftware.smack.packet.Message#getExtension()

The following examples show how to use org.jivesoftware.smack.packet.Message#getExtension() . 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: MucChatService.java    From xyTalk-pc with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void join(Message message) {
	// TODO 收到加入群的离线消息,被邀请进入群
	MucInvitation mi = message.getExtension("x", "xytalk:muc:invitation");
	String jid = mi.getRoomid();
	String roomname = mi.getRoomName();
	MultiUserChat muc;
	try {
		muc = MultiUserChatManager.getInstanceFor(Launcher.connection)
				.getMultiUserChat(JidCreate.entityBareFrom(jid));
		muc.join(Resourcepart.from(UserCache.CurrentUserName + "-" + UserCache.CurrentUserRealName));
		// 更新左侧panel,将群组UI新建出来
		createNewRoomByInvitation(jid, roomname);
	} catch (NotAMucServiceException | NoResponseException | XMPPErrorException | NotConnectedException
			| XmppStringprepException | InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 2
Source File: GeoLocationProviderTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void testGeoLocationWithoutAccuracySetAndWithErrorSet() throws Exception {

    // @formatter:off
    final String geoLocationString = "<message from='[email protected]'"
    + " to='[email protected]'>"
    + "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
    + "<error>90</error>"
    + "</geoloc>"
    + "</message>";
    // @formatter:on

    Message messageWithGeoLocation = PacketParserUtils.parseStanza(geoLocationString);

    GeoLocation geoLocation = messageWithGeoLocation.getExtension(GeoLocation.class);

    @SuppressWarnings("deprecation")
    Double error = geoLocation.getError();
    assertEquals((Double) 90d, error);
}
 
Example 3
Source File: WorkgroupManager.java    From Spark with Apache License 2.0 6 votes vote down vote up
@Override
public boolean handleInvitation(final XMPPConnection conn, final MultiUserChat room, final EntityBareJid inviter, final String reason, final String password, final Message message) {
    invites.add(inviter);

    if (message.getExtension("workgroup", "http://jabber.org/protocol/workgroup") != null) {
        Localpart workgroupName = inviter.getLocalpart();
        GroupChatRoom groupChatRoom = ConferenceUtils.enterRoomOnSameThread(workgroupName, room.getRoom(), password);

        int tabLocation = SparkManager.getChatManager().getChatContainer().indexOfComponent(groupChatRoom);
        groupChatRoom.setTabIcon(FastpathRes.getImageIcon(FastpathRes.FASTPATH_IMAGE_16x16));
        if (tabLocation != -1) {
            SparkTab tab = SparkManager.getChatManager().getChatContainer().getTabAt(tabLocation);
            tab.setIcon(FastpathRes.getImageIcon(FastpathRes.FASTPATH_IMAGE_16x16));
        }
        return true;
    }

    return false;
}
 
Example 4
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 5
Source File: RoarPopupHelper.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the Nickname of the person sending the message
 * 
 * @param room
 *            the ChatRoom the message was sent in
 * @param message
 *            the actual message
 * @return nickname
 */
public static String getNickname(ChatRoom room, Message message) {
    String nickname = SparkManager.getUserManager().getUserNicknameFromJID(message.getFrom());
    if (room.getChatType() == Message.Type.groupchat) {
        nickname = XmppStringUtils.parseResource(nickname);
    }

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

    if ((broadcast || message.getType() == Message.Type.normal || message.getType() == Message.Type.headline)
            && message.getBody() != null) {
        nickname = Res.getString("broadcast") + " - " + nickname;
    }
    return nickname;
}
 
Example 6
Source File: GroupChatInvitationTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
public void testInvitation() {
    try {
        GroupChatInvitation invitation = new GroupChatInvitation("test@" + getChatDomain());
        Message message = new Message(getBareJID(1));
        message.setBody("Group chat invitation!");
        message.addExtension(invitation);
        getConnection(0).sendStanza(message);

        Thread.sleep(250);

        Message result = (Message)collector.pollResult();
        assertNotNull("Message not delivered correctly.", result);

        GroupChatInvitation resultInvite = (GroupChatInvitation)result.getExtension("x",
                "jabber:x:conference");

        assertEquals("Invitation not to correct room", "test@" + getChatDomain(),
                resultInvite.getRoomAddress());
    }
    catch (Exception e) {
        fail(e.getMessage());
    }
}
 
Example 7
Source File: OperationSetTypingNotificationsJabberImpl.java    From jitsi with Apache License 2.0 5 votes vote down vote up
@Override
public void processStanza(Stanza packet)
{
    Message msg = (Message) packet;
    ChatStateExtension ext = (ChatStateExtension) msg.getExtension(
        "http://jabber.org/protocol/chatstates");
    if(ext == null)
        return;
    stateChanged(ChatState.valueOf(ext.getElementName()), msg);
}
 
Example 8
Source File: ClientUtils.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
public static MessageContent parseMessageContent(Message m, boolean decrypted) {
    MessageContent.Builder builder = new MessageContent.Builder();

    // parsing only default body
    String plainText = StringUtils.defaultString(m.getBody());
    String encrypted = "";

    if (!decrypted) {
        ExtensionElement e2eExt = m.getExtension(E2EEncryption.ELEMENT_NAME, E2EEncryption.NAMESPACE);
        if (e2eExt instanceof E2EEncryption) {
            // encryption extension (RFC 3923), decrypted later
            encrypted = EncodingUtils.bytesToBase64(((E2EEncryption) e2eExt).getData());
            // remove extension before parsing all others
            m.removeExtension(E2EEncryption.ELEMENT_NAME, E2EEncryption.NAMESPACE);
        }
        ExtensionElement openPGPExt = m.getExtension(OpenPGPExtension.ELEMENT_NAME, OpenPGPExtension.NAMESPACE);
        if (openPGPExt instanceof OpenPGPExtension) {
            if (!encrypted.isEmpty()) {
                LOGGER.info("message contains e2e and OpenPGP element, ignoring e2e");
            }
            encrypted = ((OpenPGPExtension) openPGPExt).getData();
            // remove extension before parsing all others
            m.removeExtension(OpenPGPExtension.ELEMENT_NAME, OpenPGPExtension.NAMESPACE);
        }
    }

    if (!encrypted.isEmpty()) {
        if (!plainText.isEmpty()) {
            LOGGER.config("message contains encryption and body (ignoring body): " + plainText);
            plainText = "";
        }
        builder.encrypted(encrypted);
    }
    addContent(builder, m.getExtensions(), plainText, decrypted);
    return builder.build();
}
 
Example 9
Source File: SmackGcmUpstreamMessageListener.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void processPacket(Packet packet) throws NotConnectedException {
    Message incomingMessage = (Message) packet;
    SmackGcmPacketExtension gcmPacket = (SmackGcmPacketExtension) incomingMessage.getExtension(GcmServiceConstants.GCM_NAMESPACE);
    String json = gcmPacket.getJson();
    try {

        Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json);
        Object messageType = jsonObject.get("message_type");

        if ("ack".equals(messageType.toString())) {
            handleAckReceipt(jsonObject);
        } else if ("nack".equals(messageType.toString())) {
            handleNackReceipt(jsonObject);
        } else if ("control".equals(messageType.toString())) {
            handleControlMessage(jsonObject);
        } else if ("receipt".equals(messageType.toString())) {
            handleDeliveryReceipt(jsonObject);
        } else {
            logger.warn("Unrecognized message type " + messageType.toString());
        }

    } catch (ParseException e1) {
        logger.error("Error parsing JSON " + json, e1);
    } catch (Exception e2) {
        logger.error("Failed to process packet", e2);
    }
}
 
Example 10
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 11
Source File: MessageCorrectExtension.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static MessageCorrectExtension from(Message message) {
    return message.getExtension(MessageCorrectExtension.class);
}
 
Example 12
Source File: Unfriend.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static Unfriend from(Message message) {
    return message.getExtension(Unfriend.class);
}
 
Example 13
Source File: Friend.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static Friend from(Message message) {
    return message.getExtension(Friend.class);
}
 
Example 14
Source File: GeoLocationTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void toXMLMethodTest() throws Exception {

    // @formatter:off
    final String geoLocationMessageString = "<message from='[email protected]'"
    + " to='[email protected]'>"
    + "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
    + "<accuracy>23</accuracy>"
    + "<alt>1000</alt>"
    + "<altaccuracy>10</altaccuracy>"
    + "<area>Delhi</area>"
    + "<bearing>10</bearing>"
    + "<building>Small Building</building>"
    + "<country>India</country>"
    + "<countrycode>IN</countrycode>"
    + "<description>My Description</description>"
    + "<error>90</error>"
    + "<floor>top</floor>"
    + "<lat>25.098345</lat>"
    + "<locality>awesome</locality>"
    + "<lon>77.992034</lon>"
    + "<postalcode>110085</postalcode>"
    + "<region>North</region>"
    + "<room>small</room>"
    + "<speed>250.0</speed>"
    + "<street>Wall Street</street>"
    + "<text>Unit Testing GeoLocation</text>"
    + "<timestamp>2004-02-19</timestamp>"
    + "<tzo>+5:30</tzo>"
    + "<uri>http://xmpp.org</uri>"
    + "</geoloc>"
    + "</message>";
    // @formatter:on

    Message messageWithGeoLocation = PacketParserUtils.parseStanza(geoLocationMessageString);
    assertNotNull(messageWithGeoLocation);

    GeoLocation geoLocation = messageWithGeoLocation.getExtension(GeoLocation.class);
    assertNotNull(geoLocation);
    assertNotNull(geoLocation.toXML());

    @SuppressWarnings("deprecation")
    GeoLocation constructedGeoLocation = GeoLocation.builder().setAccuracy(23d).setAlt(1000d).setAltAccuracy(10d).setArea("Delhi").setBearing(
                    10d).setBuilding("Small Building").setCountry("India").setCountryCode("IN").setDescription(
                    "My Description").setError(90d).setFloor("top").setLat(25.098345d).setLocality("awesome").setLon(
                    77.992034).setPostalcode("110085").setRegion("North").setRoom("small").setSpeed(250.0d).setStreet(
                    "Wall Street").setText("Unit Testing GeoLocation").setTimestamp(
                    XmppDateTime.parseDate("2004-02-19")).setTzo("+5:30").setUri(new URI("http://xmpp.org")).build();

    assertEquals(constructedGeoLocation.toXML().toString(), geoLocation.toXML().toString());

}
 
Example 15
Source File: ChatMarkersElements.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static ReceivedExtension from(Message message) {
    return message.getExtension(ReceivedExtension.class);
}
 
Example 16
Source File: GeoLocationProviderTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void testGeoLocationProviderWithNoDatumSet() throws Exception {
    // @formatter:off
    final String geoLocationString = "<message from='[email protected]'"
    + " to='[email protected]'>"
    + "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
    + "<accuracy>23</accuracy>"
    + "<alt>1000</alt>"
    + "<altaccuracy>10</altaccuracy>"
    + "<area>Delhi</area>"
    + "<bearing>10</bearing>"
    + "<building>Small Building</building>"
    + "<country>India</country>"
    + "<countrycode>IN</countrycode>"
    + "<description>My Description</description>"
    + "<error>90</error>"
    + "<floor>top</floor>"
    + "<lat>25.098345</lat>"
    + "<locality>awesome</locality>"
    + "<lon>77.992034</lon>"
    + "<postalcode>110085</postalcode>"
    + "<region>North</region>"
    + "<room>small</room>"
    + "<speed>250.0</speed>"
    + "<street>Wall Street</street>"
    + "<text>Unit Testing GeoLocation</text>"
    + "<timestamp>2004-02-19</timestamp>"
    + "<tzo>+5:30</tzo>"
    + "<uri>http://xmpp.org</uri>"
    + "</geoloc>"
    + "</message>";
    // @formatter:on

    Message messageWithGeoLocation = PacketParserUtils.parseStanza(geoLocationString);
    assertNotNull(messageWithGeoLocation);

    GeoLocation geoLocation = messageWithGeoLocation.getExtension(GeoLocation.class);
    assertNotNull(geoLocation);

    assertEquals((Double) 23d, geoLocation.getAccuracy());
    assertEquals((Double) 1000d, geoLocation.getAlt());
    assertEquals((Double) 10d, geoLocation.getAltAccuracy());
    assertEquals("Delhi", geoLocation.getArea());
    assertEquals((Double) 10d, geoLocation.getBearing());
    assertEquals("Small Building", geoLocation.getBuilding());
    assertEquals("India", geoLocation.getCountry());
    assertEquals("IN", geoLocation.getCountryCode());
    assertEquals("WGS84", geoLocation.getDatum());
    assertEquals("My Description", geoLocation.getDescription());
    @SuppressWarnings("deprecation")
    Double error = geoLocation.getError();
    assertEquals(90, error);
    assertEquals("top", geoLocation.getFloor());
    assertEquals((Double) 25.098345d, geoLocation.getLat());
    assertEquals("awesome", geoLocation.getLocality());
    assertEquals((Double) 77.992034d, geoLocation.getLon());
    assertEquals("110085", geoLocation.getPostalcode());
    assertEquals("North", geoLocation.getRegion());
    assertEquals("small", geoLocation.getRoom());
    assertEquals((Double) 250d, geoLocation.getSpeed());
    assertEquals("Wall Street", geoLocation.getStreet());
    assertEquals("Unit Testing GeoLocation", geoLocation.getText());
    assertEquals(XmppDateTime.parseDate("2004-02-19"), geoLocation.getTimestamp());
    assertEquals("+5:30", geoLocation.getTzo());
    assertEquals(new URI("http://xmpp.org"), geoLocation.getUri());

}
 
Example 17
Source File: ExplicitMessageEncryptionElement.java    From Smack with Apache License 2.0 4 votes vote down vote up
public static ExplicitMessageEncryptionElement from(Message message) {
    return message.getExtension(ExplicitMessageEncryptionElement.class);
}
 
Example 18
Source File: GeoLocationProviderTest.java    From Smack with Apache License 2.0 4 votes vote down vote up
@Test
public void testGeoLocationWithDatumSet() throws Exception {

    // @formatter:off
    final String geoLocationString = "<message from='[email protected]'"
    + " to='[email protected]'>"
    + "<geoloc xmlns='http://jabber.org/protocol/geoloc'>"
    + "<accuracy>23</accuracy>"
    + "<alt>1000</alt>"
    + "<altaccuracy>10</altaccuracy>"
    + "<area>Delhi</area>"
    + "<bearing>10</bearing>"
    + "<building>Small Building</building>"
    + "<country>India</country>"
    + "<countrycode>IN</countrycode>"
    + "<datum>Test Datum</datum>"
    + "<description>My Description</description>"
    + "<error>90</error>"
    + "<floor>top</floor>"
    + "<lat>25.098345</lat>"
    + "<locality>awesome</locality>"
    + "<lon>77.992034</lon>"
    + "<postalcode>110085</postalcode>"
    + "<region>North</region>"
    + "<room>small</room>"
    + "<speed>250.0</speed>"
    + "<street>Wall Street</street>"
    + "<text>Unit Testing GeoLocation</text>"
    + "<timestamp>2004-02-19</timestamp>"
    + "<tzo>+5:30</tzo>"
    + "<uri>http://xmpp.org</uri>"
    + "</geoloc>"
    + "</message>";
    // @formatter:on

    Message messageWithGeoLocation = PacketParserUtils.parseStanza(geoLocationString);
    assertNotNull(messageWithGeoLocation);

    GeoLocation geoLocation = messageWithGeoLocation.getExtension(GeoLocation.class);
    assertNotNull(geoLocation);

    assertEquals((Double) 23d, geoLocation.getAccuracy());
    assertEquals((Double) 1000d, geoLocation.getAlt());
    assertEquals((Double) 10d, geoLocation.getAltAccuracy());
    assertEquals("Delhi", geoLocation.getArea());
    assertEquals((Double) 10d, geoLocation.getBearing());
    assertEquals("Small Building", geoLocation.getBuilding());
    assertEquals("India", geoLocation.getCountry());
    assertEquals("IN", geoLocation.getCountryCode());
    assertEquals("Test Datum", geoLocation.getDatum());
    assertEquals("My Description", geoLocation.getDescription());
    @SuppressWarnings("deprecation")
    Double error = geoLocation.getError();
    assertEquals(90, error);
    assertEquals("top", geoLocation.getFloor());
    assertEquals((Double) 25.098345d, geoLocation.getLat());
    assertEquals("awesome", geoLocation.getLocality());
    assertEquals((Double) 77.992034d, geoLocation.getLon());
    assertEquals("110085", geoLocation.getPostalcode());
    assertEquals("North", geoLocation.getRegion());
    assertEquals("small", geoLocation.getRoom());
    assertEquals((Double) 250d, geoLocation.getSpeed());
    assertEquals("Wall Street", geoLocation.getStreet());
    assertEquals("Unit Testing GeoLocation", geoLocation.getText());
    assertEquals(XmppDateTime.parseDate("2004-02-19"), geoLocation.getTimestamp());
    assertEquals("+5:30", geoLocation.getTzo());
    assertEquals(new URI("http://xmpp.org"), geoLocation.getUri());

}
 
Example 19
Source File: StanzaIdElement.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Return the stanza-id element of a message.
 *
 * @param message message
 * @return stanza-id element of a jid, or null if absent.
 */
public static StanzaIdElement getStanzaId(Message message) {
    return message.getExtension(StanzaIdElement.class);
}
 
Example 20
Source File: GeoLocation.java    From Smack with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the first GeoLocation, or <code>null</code> if it doesn't exist in {@link Message}.
 * <br>
 * @param message The Message stanza containing GeoLocation
 * @return GeoLocation
 */
public static GeoLocation from(Message message) {
    return message.getExtension(GeoLocation.class);
}