Search in sources :

Example 1 with JivePropertiesExtension

use of org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension in project Smack by igniterealtime.

the class JivePropertiesExtensionProvider method parse.

/**
     * 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(/packet) 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 
     * @throws XmlPullParserException 
     */
@Override
public JivePropertiesExtension parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException {
    Map<String, Object> properties = new HashMap<String, Object>();
    while (true) {
        int eventType = parser.next();
        if (eventType == XmlPullParser.START_TAG && 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.START_TAG) {
                    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.END_TAG) {
                    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)) {
                            value = Boolean.valueOf(valueText);
                        } 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.END_TAG) {
            if (parser.getName().equals(JivePropertiesExtension.ELEMENT)) {
                break;
            }
        }
    }
    return new JivePropertiesExtension(properties);
}
Also used : HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) ObjectInputStream(java.io.ObjectInputStream)

Example 2 with JivePropertiesExtension

use of org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension in project Spark by igniterealtime.

the class ChatRoomImpl method processPacket.

/**
 * Process incoming packets.
 *
 * @param stanza - the packet to process
 */
public void processPacket(final Stanza stanza) {
    final Runnable runnable = () -> {
        try {
            if (stanza instanceof Presence) {
                Presence.Type oldType = presence.getType();
                presence = (Presence) stanza;
                final Presence presence1 = (Presence) stanza;
                ContactList list = SparkManager.getWorkspace().getContactList();
                ContactItem contactItem = list.getContactItemByJID(getParticipantJID());
                String time = DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());
                if (presence1.getType() == Presence.Type.unavailable && contactItem != null) {
                    getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.went.offline", participantNickname, time), ChatManager.NOTIFICATION_COLOR);
                } else if (oldType == Presence.Type.unavailable && presence1.getType() == Presence.Type.available) {
                    getTranscriptWindow().insertNotificationMessage("*** " + Res.getString("message.came.online", participantNickname, time), ChatManager.NOTIFICATION_COLOR);
                }
            } else if (stanza instanceof Message) {
                lastActivity = System.currentTimeMillis();
                // Do something with the incoming packet here.
                final Message message = (Message) stanza;
                fireReceivingIncomingMessage(message);
                if (message.getError() != null) {
                    if (message.getError().getCondition() == XMPPError.Condition.item_not_found) {
                        // Check to see if the user is online to recieve this message.
                        RosterEntry entry = roster.getEntry(participantJID);
                        if (!presence.isAvailable() && !offlineSent && entry != null) {
                            getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline.error"), ChatManager.ERROR_COLOR);
                            offlineSent = true;
                        }
                    }
                    return;
                }
                // Check to see if the user is online to recieve this message.
                RosterEntry entry = roster.getEntry(participantJID);
                if (!presence.isAvailable() && !offlineSent && entry != null) {
                    getTranscriptWindow().insertNotificationMessage(Res.getString("message.offline"), ChatManager.ERROR_COLOR);
                    offlineSent = true;
                }
                if (threadID == null) {
                    threadID = message.getThread();
                    if (threadID == null) {
                        threadID = StringUtils.randomString(6);
                    }
                }
                final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));
                final boolean broadcast = extension != null && extension.getProperty("broadcast") != null;
                // If this is a group chat message, discard
                if (message.getType() == Message.Type.groupchat || broadcast || message.getType() == Message.Type.normal || message.getType() == Message.Type.headline) {
                    return;
                }
                // Do not accept Administrative messages.
                final String host = SparkManager.getSessionManager().getServerAddress();
                if (host.equals(message.getFrom())) {
                    return;
                }
                final CarbonExtension carbon = (CarbonExtension) message.getExtension(CarbonExtension.NAMESPACE);
                if (carbon != null) {
                    // Is the a carbon copy?
                    final Message forwardedStanza = (Message) carbon.getForwarded().getForwardedPacket();
                    if (forwardedStanza.getBody() != null) {
                        if (carbon.getDirection() == CarbonExtension.Direction.received) {
                            // This is a stanza that we received from someone on one of our other clients.
                            participantJID = forwardedStanza.getFrom();
                            insertMessage(forwardedStanza);
                        } else {
                            // This is a stanza that one of our own clients sent.
                            participantJID = forwardedStanza.getTo();
                            displaySendMessage(forwardedStanza);
                        }
                        showTyping(false);
                    }
                } else if (message.getBody() != null) {
                    // If the message is not from the current agent. Append to chat.
                    participantJID = message.getFrom();
                    insertMessage(message);
                    showTyping(false);
                }
            }
        } catch (Exception e) {
            Log.error("An exception occurred while processing this incoming stanza: " + stanza, e);
        }
    };
    SwingUtilities.invokeLater(runnable);
}
Also used : HistoryMessage(org.jivesoftware.sparkimpl.plugin.transcripts.HistoryMessage) CarbonExtension(org.jivesoftware.smackx.carbons.packet.CarbonExtension) Date(java.util.Date) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) SmackException(org.jivesoftware.smack.SmackException) XMPPException(org.jivesoftware.smack.XMPPException) RosterEntry(org.jivesoftware.smack.roster.RosterEntry)

Example 3 with JivePropertiesExtension

use of org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension in project Spark by igniterealtime.

the class ChatTranscriptPlugin method persistChatRoom.

public void persistChatRoom(final ChatRoom room) {
    LocalPreferences pref = SettingsManager.getLocalPreferences();
    if (!pref.isChatHistoryEnabled()) {
        return;
    }
    final String jid = room.getRoomname();
    final List<Message> transcripts = room.getTranscripts();
    ChatTranscript transcript = new ChatTranscript();
    int count = 0;
    int i = 0;
    if (lastMessage.get(jid) != null) {
        count = transcripts.indexOf(lastMessage.get(jid)) + 1;
    }
    for (Message message : transcripts) {
        if (i < count) {
            i++;
            continue;
        }
        lastMessage.put(jid, message);
        HistoryMessage history = new HistoryMessage();
        history.setTo(message.getTo());
        history.setFrom(message.getFrom());
        history.setBody(message.getBody());
        final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));
        Date date = null;
        if (extension != null) {
            date = (Date) extension.getProperty("date");
        }
        history.setDate(date == null ? new Date() : date);
        transcript.addHistoryMessage(history);
    }
    ChatTranscripts.appendToTranscript(jid, transcript);
}
Also used : Message(org.jivesoftware.smack.packet.Message) LocalPreferences(org.jivesoftware.sparkimpl.settings.local.LocalPreferences) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) Date(java.util.Date)

Example 4 with JivePropertiesExtension

use of org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension in project Spark by igniterealtime.

the class TranscriptWindow method saveTranscript.

/**
 * Persist a current transcript.
 *
 * @param fileName   the name of the file to save the transcript as. Note: This can be modified by the user.
 * @param transcript the collection of transcript.
 * @param headerData the string to prepend to the transcript.
 * @see ChatRoom#getTranscripts()
 */
public void saveTranscript(String fileName, List<Message> transcript, String headerData) {
    final LocalPreferences pref = SettingsManager.getLocalPreferences();
    try {
        SimpleDateFormat formatter;
        File defaultSaveFile = new File(Spark.getSparkUserHome() + "/" + fileName);
        final JFileChooser fileChooser = new JFileChooser(defaultSaveFile);
        fileChooser.setSelectedFile(defaultSaveFile);
        // Show save dialog; this method does not return until the dialog is closed
        int result = fileChooser.showSaveDialog(this);
        final File selFile = fileChooser.getSelectedFile();
        if (selFile != null && result == JFileChooser.APPROVE_OPTION) {
            final StringBuilder buf = new StringBuilder();
            final Iterator<Message> transcripts = transcript.iterator();
            buf.append("<html><body>");
            if (headerData != null) {
                buf.append(headerData);
            }
            buf.append("<table width=600>");
            while (transcripts.hasNext()) {
                final Message message = transcripts.next();
                String from = message.getFrom();
                if (from == null) {
                    from = pref.getNickname();
                }
                if (Message.Type.groupchat == message.getType()) {
                    if (ModelUtil.hasLength(XmppStringUtils.parseResource(from))) {
                        from = XmppStringUtils.parseResource(from);
                    }
                }
                final String body = message.getBody();
                final JivePropertiesExtension extension = ((JivePropertiesExtension) message.getExtension(JivePropertiesExtension.NAMESPACE));
                Date insertionDate = null;
                if (extension != null) {
                    insertionDate = (Date) extension.getProperty("insertionDate");
                }
                formatter = new SimpleDateFormat("hh:mm:ss");
                String value = "";
                if (insertionDate != null) {
                    value = "(" + formatter.format(insertionDate) + ") ";
                }
                buf.append("<tr><td nowrap><font size=2>").append(value).append("<strong>").append(from).append(":</strong>&nbsp;").append(body).append("</font></td></tr>");
            }
            buf.append("</table></body></html>");
            final BufferedWriter writer = new BufferedWriter(new FileWriter(selFile));
            writer.write(buf.toString());
            writer.close();
            UIManager.put("OptionPane.okButtonText", Res.getString("ok"));
            JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "Chat transcript has been saved.", "Chat Transcript Saved", JOptionPane.INFORMATION_MESSAGE);
        }
    } catch (Exception ex) {
        Log.error("Unable to save chat transcript.", ex);
        UIManager.put("OptionPane.okButtonText", Res.getString("ok"));
        JOptionPane.showMessageDialog(SparkManager.getMainWindow(), "Could not save transcript.", "Error", JOptionPane.ERROR_MESSAGE);
    }
}
Also used : Message(org.jivesoftware.smack.packet.Message) FileWriter(java.io.FileWriter) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension) BufferedWriter(java.io.BufferedWriter) LocalPreferences(org.jivesoftware.sparkimpl.settings.local.LocalPreferences) SimpleDateFormat(java.text.SimpleDateFormat) File(java.io.File)

Example 5 with JivePropertiesExtension

use of org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension in project Spark by igniterealtime.

the class ContactList method sendMessages.

private void sendMessages(Collection<ContactItem> items) {
    StringBuilder buf = new StringBuilder();
    InputDialog dialog = new InputDialog();
    final String messageText = dialog.getInput(Res.getString("title.broadcast.message"), Res.getString("message.enter.broadcast.message"), SparkRes.getImageIcon(SparkRes.BLANK_IMAGE), SparkManager.getMainWindow());
    if (ModelUtil.hasLength(messageText)) {
        final Map<String, Message> broadcastMessages = new HashMap<>();
        for (ContactItem item : items) {
            final Message message = new Message();
            message.setTo(item.getJID());
            final Map<String, Object> properties = new HashMap<>();
            properties.put("broadcast", true);
            message.addExtension(new JivePropertiesExtension(properties));
            message.setBody(messageText);
            if (!broadcastMessages.containsKey(item.getJID())) {
                buf.append(item.getDisplayName()).append("\n");
                broadcastMessages.put(item.getJID(), message);
            }
        }
        for (Message message : broadcastMessages.values()) {
            try {
                SparkManager.getConnection().sendStanza(message);
            } catch (SmackException.NotConnectedException e) {
                Log.warning("Unable to send broadcast to " + message.getTo(), e);
            }
        }
        UIManager.put("OptionPane.okButtonText", Res.getString("ok"));
        JOptionPane.showMessageDialog(SparkManager.getMainWindow(), Res.getString("message.broadcasted.to", buf.toString()), Res.getString("title.notification"), JOptionPane.INFORMATION_MESSAGE);
    }
}
Also used : InputDialog(org.jivesoftware.spark.component.InputDialog) Message(org.jivesoftware.smack.packet.Message) JivePropertiesExtension(org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension)

Aggregations

JivePropertiesExtension (org.jivesoftware.smackx.jiveproperties.packet.JivePropertiesExtension)22 Message (org.jivesoftware.smack.packet.Message)13 HashMap (java.util.HashMap)7 IOException (java.io.IOException)3 ByteArrayInputStream (java.io.ByteArrayInputStream)2 ObjectInputStream (java.io.ObjectInputStream)2 Date (java.util.Date)2 SmackException (org.jivesoftware.smack.SmackException)2 StanzaListener (org.jivesoftware.smack.StanzaListener)2 Stanza (org.jivesoftware.smack.packet.Stanza)2 DelayInformation (org.jivesoftware.smackx.delay.packet.DelayInformation)2 ChatRoomNotFoundException (org.jivesoftware.spark.ui.ChatRoomNotFoundException)2 LocalPreferences (org.jivesoftware.sparkimpl.settings.local.LocalPreferences)2 CardLayout (java.awt.CardLayout)1 Color (java.awt.Color)1 GridBagConstraints (java.awt.GridBagConstraints)1 GridBagLayout (java.awt.GridBagLayout)1 Insets (java.awt.Insets)1 ActionEvent (java.awt.event.ActionEvent)1 BufferedWriter (java.io.BufferedWriter)1