org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension Java Examples

The following examples show how to use org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension. 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: JivePropertiesExtensionTest.java    From Smack with Apache License 2.0 6 votes vote down vote up
@Test
public void checkProvider() throws Exception {
    // @formatter:off
    String properties = "<message xmlns='jabber:client' from='[email protected]/orchard' to='[email protected]/balcony'>"
                    + "<body>Neither, fair saint, if either thee dislike.</body>"
                    + "<properties xmlns='http://www.jivesoftware.com/xmlns/xmpp/properties'>"
                    + "<property>"
                    + "<name>FooBar</name>"
                    + "<value type='integer'>42</value>"
                    + "</property>"
                    + "</properties>"
                    + "</message>";
    // @formatter:on

    Message message = PacketParserUtils.parseStanza(properties);
    JivePropertiesExtension jpe = JivePropertiesExtension.from(message);
    assertNotNull(jpe);

    Integer integer = (Integer) jpe.getProperty("FooBar");
    assertNotNull(integer);
    int fourtytwo = integer;
    assertEquals(42, fourtytwo);
}
 
Example #2
Source File: ChatRoom.java    From Spark with Apache License 2.0 6 votes vote down vote up
/**
 * Add a <code>ChatResponse</chat> to the current discussion chat area.
 *
 * @param message    the message to add to the transcript list
 * @param updateDate true if you wish the date label to be updated with the
 *                   date and time the message was received.
 */
public void addToTranscript(Message message, boolean updateDate) {
    // Create message to persist.
    final Message newMessage = new Message();
    newMessage.setTo(message.getTo());
    newMessage.setFrom(message.getFrom());
    newMessage.setBody(message.getBody());
    final Map<String, Object> properties = new HashMap<>();
    properties.put( "date", new Date() );
    newMessage.addExtension( new JivePropertiesExtension( properties ) );

    transcript.add(newMessage);

    // Add current date if this is the current agent
    if (updateDate && transcriptWindow.getLastUpdated() != null) {
        // Set new label date
        notificationLabel.setIcon(SparkRes.getImageIcon(SparkRes.SMALL_ABOUT_IMAGE));
        notificationLabel.setText(Res.getString("message.last.message.received", SparkManager.DATE_SECOND_FORMATTER.format(transcriptWindow.getLastUpdated())));
    }

    scrollToBottom();
}
 
Example #3
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 #4
Source File: CoBrowser.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void pushPage(String link) {
    updateLinkLabel(link);

    // If the disable box is not selected, update customer with
    // page push.
    final Message mes = new Message();
    final Map<String, Object> properties = new HashMap<>();
    properties.put( "PUSH_URL", link );
    mes.addExtension( new JivePropertiesExtension( properties ) );
    mes.setBody(FpRes.getString("message.start.cobrowsing", link));

    chatRoom.getTranscriptWindow().insertNotificationMessage(FpRes.getString("message.send.cobrowsing.message", link), ChatManager.NOTIFICATION_COLOR);

    send(mes);
    pushField.setText("");
    load(link);
}
 
Example #5
Source File: CoBrowser.java    From Spark with Apache License 2.0 6 votes vote down vote up
private void navigateUser(String href) {
    if (followMeButton.isSelected() && hasLoaded) {
        final Message mes = new Message();
        final Map<String, Object> properties = new HashMap<>();
        properties.put( "PUSH_URL", href );
        mes.addExtension( new JivePropertiesExtension( properties ) );
        mes.setBody("");
        send(mes);
        updateLinkLabel(href);
        hasLoaded = false;
    }
    else {
        updateLinkLabel(href);
    }
    hasLoaded = true;
}
 
Example #6
Source File: JivePropertiesManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Convenience method to get a property from a packet. Will return null if the stanza contains
 * not property with the given name.
 *
 * @param packet TODO javadoc me please
 * @param name TODO javadoc me please
 * @return the property or <code>null</code> if none found.
 */
public static Object getProperty(StanzaView packet, String name) {
    Object res = null;
    JivePropertiesExtension jpe = packet.getExtension(JivePropertiesExtension.class);
    if (jpe != null) {
        res = jpe.getProperty(name);
    }
    return res;
}
 
Example #7
Source File: JivePropertiesManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return a collection of the names of all properties of the given packet. If the packet
 * contains no properties extension, then an empty collection will be returned.
 *
 * @param packet TODO javadoc me please
 * @return a collection of the names of all properties.
 */
public static Collection<String> getPropertiesNames(Stanza packet) {
    JivePropertiesExtension jpe = (JivePropertiesExtension) packet.getExtension(JivePropertiesExtension.NAMESPACE);
    if (jpe == null) {
        return Collections.emptyList();
    }
    return jpe.getPropertyNames();
}
 
Example #8
Source File: JivePropertiesManager.java    From Smack with Apache License 2.0 5 votes vote down vote up
/**
 * Return a map of all properties of the given packet. If the stanza contains no properties
 * extension, an empty map will be returned.
 *
 * @param packet TODO javadoc me please
 * @return a map of all properties of the given packet.
 */
public static Map<String, Object> getProperties(Stanza packet) {
    JivePropertiesExtension jpe = (JivePropertiesExtension) packet.getExtension(JivePropertiesExtension.NAMESPACE);
    if (jpe == null) {
        return Collections.emptyMap();
    }
    return jpe.getProperties();
}
 
Example #9
Source File: ChatRoom.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
 * Adds a new message to the transcript history.
 *
 * @param to   who the message is to.
 * @param from who the message was from.
 * @param body the body of the message.
 * @param date when the message was received.
 */
public void addToTranscript(String to, String from, String body, Date date) {
    final Message newMessage = new Message();
    newMessage.setTo(to);
    newMessage.setFrom(from);
    newMessage.setBody(body);
    final Map<String, Object> properties = new HashMap<>();
    properties.put( "date", new Date() );
    newMessage.addExtension( new JivePropertiesExtension( properties ) );
    transcript.add(newMessage);
}
 
Example #10
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 #11
Source File: XMPPSession.java    From mangosta-android with Apache License 2.0 4 votes vote down vote up
private void manageMessageReceived(Message message, Date delayDate, String messageId, boolean fromMam) {
    String[] jidList = message.getFrom().toString().split("/");

    ChatMessage chatMessage = new ChatMessage();
    chatMessage.setMessageId(messageId);

    String chatRoomJID;
    if (!jidList[0].equals(Preferences.getInstance().getUserXMPPJid())) {
        chatRoomJID = jidList[0];
    } else {
        chatRoomJID = message.getTo().toString().split("/")[0];
    }
    chatMessage.setRoomJid(chatRoomJID);

    // not saving messages with my affiliation changes to "none", and delete the chat in that case
    if (checkIfMyIsAffiliationNone(message)) {
        deleteChat(chatRoomJID);
        return;
    }

    if (message.hasExtension(JivePropertiesExtension.ELEMENT, JivePropertiesExtension.NAMESPACE)) {
        return;
    }

    RoomsListManager.getInstance().createChatIfNotExists(chatRoomJID, true);

    manageSender(jidList, chatMessage, chatRoomJID);

    chatMessage.setStatus(ChatMessage.STATUS_SENT);
    chatMessage.setUnread(true);

    if (isBoBMessage(message)) {
        BoBExtension bobExtension = BoBExtension.from(message);
        chatMessage.setContent(Base64.decodeToString(bobExtension.getBoBHash().getHash()));
        chatMessage.setType(ChatMessage.TYPE_STICKER);
    } else {
        chatMessage.setContent(message.getBody());
        chatMessage.setType(ChatMessage.TYPE_CHAT);
    }

    Realm realm = RealmManager.getInstance().getRealm();
    Chat chatRoom = realm.where(Chat.class).equalTo("jid", chatRoomJID).findFirst();
    realm.beginTransaction();

    if (canBeTextMessageOrSticker(message) && !fromMam) {
        chatRoom.addUnreadMessage();
    }

    // room name or subject change
    manageConfigurationsChange(message, chatMessage, chatRoom);

    // not saving invalid messages
    if (chatMessage.getContent() == null || chatMessage.getContent().isEmpty() || chatMessage.getUserSender() == null) {
        realm.commitTransaction();
        realm.close();
        return;
    }

    // assign date
    manageDelayDate(delayDate, chatMessage);

    realm.copyToRealmOrUpdate(chatMessage);
    realm.commitTransaction();
    realm.close();
}
 
Example #12
Source File: JivePropertiesExtensionProvider.java    From Smack with Apache License 2.0 4 votes vote down vote up
/**
 * Parse a properties sub-packet. If any errors occur while de-serializing Java object
 * properties, an exception will be printed and not thrown since a thrown exception will shut
 * down the entire connection. ClassCastExceptions will occur when both the sender and receiver
 * of the stanza don't have identical versions of the same class.
 * <p>
 * Note that you have to explicitly enabled Java object deserialization with @{link
 * {@link JivePropertiesManager#setJavaObjectEnabled(boolean)}
 *
 * @param parser the XML parser, positioned at the start of a properties sub-packet.
 * @return a map of the properties.
 * @throws IOException if an I/O error occurred.
 * @throws XmlPullParserException if an error in the XML parser occurred.
 */
@Override
public JivePropertiesExtension parse(XmlPullParser parser,
                int initialDepth, XmlEnvironment xmlEnvironment) throws XmlPullParserException,
                IOException {
    Map<String, Object> properties = new HashMap<>();
    while (true) {
        XmlPullParser.Event eventType = parser.next();
        if (eventType == XmlPullParser.Event.START_ELEMENT && parser.getName().equals("property")) {
            // Parse a property
            boolean done = false;
            String name = null;
            String type = null;
            String valueText = null;
            Object value = null;
            while (!done) {
                eventType = parser.next();
                if (eventType == XmlPullParser.Event.START_ELEMENT) {
                    String elementName = parser.getName();
                    if (elementName.equals("name")) {
                        name = parser.nextText();
                    }
                    else if (elementName.equals("value")) {
                        type = parser.getAttributeValue("", "type");
                        valueText = parser.nextText();
                    }
                }
                else if (eventType == XmlPullParser.Event.END_ELEMENT) {
                    if (parser.getName().equals("property")) {
                        if ("integer".equals(type)) {
                            value = Integer.valueOf(valueText);
                        }
                        else if ("long".equals(type))  {
                            value = Long.valueOf(valueText);
                        }
                        else if ("float".equals(type)) {
                            value = Float.valueOf(valueText);
                        }
                        else if ("double".equals(type)) {
                            value = Double.valueOf(valueText);
                        }
                        else if ("boolean".equals(type)) {
                            // CHECKSTYLE:OFF
                            value = Boolean.valueOf(valueText);
                            // CHECKSTYLE:ON
                        }
                        else if ("string".equals(type)) {
                            value = valueText;
                        }
                        else if ("java-object".equals(type)) {
                            if (JivePropertiesManager.isJavaObjectEnabled()) {
                                try {
                                    byte[] bytes = Base64.decode(valueText);
                                    ObjectInputStream in = new ObjectInputStream(
                                                    new ByteArrayInputStream(bytes));
                                    value = in.readObject();
                                }
                                catch (Exception e) {
                                    LOGGER.log(Level.SEVERE, "Error parsing java object", e);
                                }
                            }
                            else {
                                LOGGER.severe("JavaObject is not enabled. Enable with JivePropertiesManager.setJavaObjectEnabled(true)");
                            }
                        }
                        if (name != null && value != null) {
                            properties.put(name, value);
                        }
                        done = true;
                    }
                }
            }
        }
        else if (eventType == XmlPullParser.Event.END_ELEMENT) {
            if (parser.getName().equals(JivePropertiesExtension.ELEMENT)) {
                break;
            }
        }
    }
    return new JivePropertiesExtension(properties);
}
 
Example #13
Source File: Workspace.java    From Spark with Apache License 2.0 4 votes vote down vote up
/**
  * Starts the Loading of all Spark Plugins.
  */
 public void loadPlugins() {
 
     // Send Available status
     SparkManager.getSessionManager().changePresence(statusBox.getPresence());
     
     // Add presence and message listeners
     // we listen for these to force open a 1-1 peer chat window from other operators if
     // one isn't already open
     StanzaFilter workspaceMessageFilter = new StanzaTypeFilter(Message.class);

     // Add the packetListener to this instance
     SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(this, workspaceMessageFilter);

     // Make presence available to anonymous requests, if from anonymous user in the system.
     StanzaListener workspacePresenceListener = stanza -> {
         Presence presence = (Presence)stanza;
         JivePropertiesExtension extension = (JivePropertiesExtension) presence.getExtension( JivePropertiesExtension.NAMESPACE );
         if (extension != null && extension.getProperty("anonymous") != null) {
             boolean isAvailable = statusBox.getPresence().getMode() == Presence.Mode.available;
             Presence reply = new Presence(Presence.Type.available);
             if (!isAvailable) {
                 reply.setType(Presence.Type.unavailable);
             }
             reply.setTo(presence.getFrom());
             try
             {
                 SparkManager.getSessionManager().getConnection().sendStanza(reply);
             }
             catch ( SmackException.NotConnectedException e )
             {
                 Log.warning( "Unable to send presence reply to " + reply.getTo(), e );
             }
         }
     };

     SparkManager.getSessionManager().getConnection().addAsyncStanzaListener(workspacePresenceListener, new StanzaTypeFilter(Presence.class));

     // Until we have better plugin management, will init after presence updates.
     gatewayPlugin = new GatewayPlugin();
     gatewayPlugin.initialize();

     // Load all non-presence related items.
     conferences.loadConferenceBookmarks();
     SearchManager.getInstance();
     transcriptPlugin = new ChatTranscriptPlugin();

     // Load Broadcast Plugin
     broadcastPlugin = new BroadcastPlugin();
     broadcastPlugin.initialize();

     // Load BookmarkPlugin
     bookmarkPlugin = new BookmarkPlugin();
     bookmarkPlugin.initialize();

     // Schedule loading of the plugins after two seconds.
     TaskEngine.getInstance().schedule(new TimerTask() {
         @Override
public void run() {
             final PluginManager pluginManager = PluginManager.getInstance();

             SparkManager.getMainWindow().addMainWindowListener(pluginManager);
             pluginManager.initializePlugins();

             // Subscriptions are always manual
             Roster roster = Roster.getInstanceFor( SparkManager.getConnection() );
             roster.setSubscriptionMode(Roster.SubscriptionMode.manual);
         }
     }, 2000);

     // Check URI Mappings
     SparkManager.getChatManager().handleURIMapping(Spark.ARGUMENTS);
 }
 
Example #14
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);
            }
        }
    }
}