Message.java

  1. /**
  2.  *
  3.  * Copyright 2003-2007 Jive Software.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.jivesoftware.smack.packet;

  18. import java.util.ArrayList;
  19. import java.util.Collections;
  20. import java.util.HashSet;
  21. import java.util.List;
  22. import java.util.Locale;
  23. import java.util.Set;

  24. import org.jivesoftware.smack.util.TypedCloneable;
  25. import org.jivesoftware.smack.util.XmlStringBuilder;
  26. import org.jxmpp.jid.Jid;

  27. /**
  28.  * Represents XMPP message packets. A message can be one of several types:
  29.  *
  30.  * <ul>
  31.  *      <li>Message.Type.NORMAL -- (Default) a normal text message used in email like interface.
  32.  *      <li>Message.Type.CHAT -- a typically short text message used in line-by-line chat interfaces.
  33.  *      <li>Message.Type.GROUP_CHAT -- a chat message sent to a groupchat server for group chats.
  34.  *      <li>Message.Type.HEADLINE -- a text message to be displayed in scrolling marquee displays.
  35.  *      <li>Message.Type.ERROR -- indicates a messaging error.
  36.  * </ul>
  37.  *
  38.  * For each message type, different message fields are typically used as follows:
  39.  * <p>
  40.  * <table border="1">
  41.  * <tr><td>&nbsp;</td><td colspan="5"><b>Message type</b></td></tr>
  42.  * <tr><td><i>Field</i></td><td><b>Normal</b></td><td><b>Chat</b></td><td><b>Group Chat</b></td><td><b>Headline</b></td><td><b>XMPPError</b></td></tr>
  43.  * <tr><td><i>subject</i></td> <td>SHOULD</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td><td>SHOULD NOT</td></tr>
  44.  * <tr><td><i>thread</i></td>  <td>OPTIONAL</td><td>SHOULD</td><td>OPTIONAL</td><td>OPTIONAL</td><td>SHOULD NOT</td></tr>
  45.  * <tr><td><i>body</i></td>    <td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD</td><td>SHOULD NOT</td></tr>
  46.  * <tr><td><i>error</i></td>   <td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST NOT</td><td>MUST</td></tr>
  47.  * </table>
  48.  *
  49.  * @author Matt Tucker
  50.  */
  51. public final class Message extends Stanza implements TypedCloneable<Message> {

  52.     public static final String ELEMENT = "message";
  53.     public static final String BODY = "body";

  54.     private Type type;
  55.     private String thread = null;

  56.     private final Set<Subject> subjects = new HashSet<Subject>();
  57.     private final Set<Body> bodies = new HashSet<Body>();

  58.     /**
  59.      * Creates a new, "normal" message.
  60.      */
  61.     public Message() {
  62.     }

  63.     /**
  64.      * Creates a new "normal" message to the specified recipient.
  65.      *
  66.      * @param to the recipient of the message.
  67.      */
  68.     public Message(Jid to) {
  69.         setTo(to);
  70.     }

  71.     /**
  72.      * Creates a new message of the specified type to a recipient.
  73.      *
  74.      * @param to the user to send the message to.
  75.      * @param type the message type.
  76.      */
  77.     public Message(Jid to, Type type) {
  78.         this(to);
  79.         setType(type);
  80.     }

  81.     /**
  82.      * Creates a new message to the specified recipient and with the specified body.
  83.      *
  84.      * @param to the user to send the message to.
  85.      * @param body the body of the message.
  86.      */
  87.     public Message(Jid to, String body) {
  88.         this(to);
  89.         setBody(body);
  90.     }

  91.     /**
  92.      * Copy constructor.
  93.      * <p>
  94.      * This does not perform a deep clone, as extension elements are shared between the new and old
  95.      * instance.
  96.      * </p>
  97.      *
  98.      * @param other
  99.      */
  100.     public Message(Message other) {
  101.         super(other);
  102.         this.type = other.type;
  103.         this.thread = other.thread;
  104.         this.subjects.addAll(other.subjects);
  105.         this.bodies.addAll(other.bodies);
  106.     }

  107.     /**
  108.      * Returns the type of the message. If no type has been set this method will return {@link
  109.      * org.jivesoftware.smack.packet.Message.Type#normal}.
  110.      *
  111.      * @return the type of the message.
  112.      */
  113.     public Type getType() {
  114.         if (type == null) {
  115.             return Type.normal;
  116.         }
  117.         return type;
  118.     }

  119.     /**
  120.      * Sets the type of the message.
  121.      *
  122.      * @param type the type of the message.
  123.      */
  124.     public void setType(Type type) {
  125.         this.type = type;
  126.     }

  127.     /**
  128.      * Returns the default subject of the message, or null if the subject has not been set.
  129.      * The subject is a short description of message contents.
  130.      * <p>
  131.      * The default subject of a message is the subject that corresponds to the message's language.
  132.      * (see {@link #getLanguage()}) or if no language is set to the applications default
  133.      * language (see {@link Stanza#getDefaultLanguage()}).
  134.      *
  135.      * @return the subject of the message.
  136.      */
  137.     public String getSubject() {
  138.         return getSubject(null);
  139.     }
  140.    
  141.     /**
  142.      * Returns the subject corresponding to the language. If the language is null, the method result
  143.      * will be the same as {@link #getSubject()}. Null will be returned if the language does not have
  144.      * a corresponding subject.
  145.      *
  146.      * @param language the language of the subject to return.
  147.      * @return the subject related to the passed in language.
  148.      */
  149.     public String getSubject(String language) {
  150.         Subject subject = getMessageSubject(language);
  151.         return subject == null ? null : subject.subject;
  152.     }
  153.    
  154.     private Subject getMessageSubject(String language) {
  155.         language = determineLanguage(language);
  156.         for (Subject subject : subjects) {
  157.             if (language.equals(subject.language)) {
  158.                 return subject;
  159.             }
  160.         }
  161.         return null;
  162.     }

  163.     /**
  164.      * Returns a set of all subjects in this Message, including the default message subject accessible
  165.      * from {@link #getSubject()}.
  166.      *
  167.      * @return a collection of all subjects in this message.
  168.      */
  169.     public Set<Subject> getSubjects() {
  170.         return Collections.unmodifiableSet(subjects);
  171.     }

  172.     /**
  173.      * Sets the subject of the message. The subject is a short description of
  174.      * message contents.
  175.      *
  176.      * @param subject the subject of the message.
  177.      */
  178.     public void setSubject(String subject) {
  179.         if (subject == null) {
  180.             removeSubject(""); // use empty string because #removeSubject(null) is ambiguous
  181.             return;
  182.         }
  183.         addSubject(null, subject);
  184.     }

  185.     /**
  186.      * Adds a subject with a corresponding language.
  187.      *
  188.      * @param language the language of the subject being added.
  189.      * @param subject the subject being added to the message.
  190.      * @return the new {@link org.jivesoftware.smack.packet.Message.Subject}
  191.      * @throws NullPointerException if the subject is null, a null pointer exception is thrown
  192.      */
  193.     public Subject addSubject(String language, String subject) {
  194.         language = determineLanguage(language);
  195.         Subject messageSubject = new Subject(language, subject);
  196.         subjects.add(messageSubject);
  197.         return messageSubject;
  198.     }

  199.     /**
  200.      * Removes the subject with the given language from the message.
  201.      *
  202.      * @param language the language of the subject which is to be removed
  203.      * @return true if a subject was removed and false if it was not.
  204.      */
  205.     public boolean removeSubject(String language) {
  206.         language = determineLanguage(language);
  207.         for (Subject subject : subjects) {
  208.             if (language.equals(subject.language)) {
  209.                 return subjects.remove(subject);
  210.             }
  211.         }
  212.         return false;
  213.     }

  214.     /**
  215.      * Removes the subject from the message and returns true if the subject was removed.
  216.      *
  217.      * @param subject the subject being removed from the message.
  218.      * @return true if the subject was successfully removed and false if it was not.
  219.      */
  220.     public boolean removeSubject(Subject subject) {
  221.         return subjects.remove(subject);
  222.     }

  223.     /**
  224.      * Returns all the languages being used for the subjects, not including the default subject.
  225.      *
  226.      * @return the languages being used for the subjects.
  227.      */
  228.     public List<String> getSubjectLanguages() {
  229.         Subject defaultSubject = getMessageSubject(null);
  230.         List<String> languages = new ArrayList<String>();
  231.         for (Subject subject : subjects) {
  232.             if (!subject.equals(defaultSubject)) {
  233.                 languages.add(subject.language);
  234.             }
  235.         }
  236.         return Collections.unmodifiableList(languages);
  237.     }

  238.     /**
  239.      * Returns the default body of the message, or null if the body has not been set. The body
  240.      * is the main message contents.
  241.      * <p>
  242.      * The default body of a message is the body that corresponds to the message's language.
  243.      * (see {@link #getLanguage()}) or if no language is set to the applications default
  244.      * language (see {@link Stanza#getDefaultLanguage()}).
  245.      *
  246.      * @return the body of the message.
  247.      */
  248.     public String getBody() {
  249.         return getBody(null);
  250.     }

  251.     /**
  252.      * Returns the body corresponding to the language. If the language is null, the method result
  253.      * will be the same as {@link #getBody()}. Null will be returned if the language does not have
  254.      * a corresponding body.
  255.      *
  256.      * @param language the language of the body to return.
  257.      * @return the body related to the passed in language.
  258.      * @since 3.0.2
  259.      */
  260.     public String getBody(String language) {
  261.         Body body = getMessageBody(language);
  262.         return body == null ? null : body.message;
  263.     }
  264.    
  265.     private Body getMessageBody(String language) {
  266.         language = determineLanguage(language);
  267.         for (Body body : bodies) {
  268.             if (language.equals(body.language)) {
  269.                 return body;
  270.             }
  271.         }
  272.         return null;
  273.     }

  274.     /**
  275.      * Returns a set of all bodies in this Message, including the default message body accessible
  276.      * from {@link #getBody()}.
  277.      *
  278.      * @return a collection of all bodies in this Message.
  279.      * @since 3.0.2
  280.      */
  281.     public Set<Body> getBodies() {
  282.         return Collections.unmodifiableSet(bodies);
  283.     }

  284.     /**
  285.      * Sets the body of the message. The body is the main message contents.
  286.      *
  287.      * @param body the body of the message.
  288.      */
  289.     public void setBody(String body) {
  290.         if (body == null) {
  291.             removeBody(""); // use empty string because #removeBody(null) is ambiguous
  292.             return;
  293.         }
  294.         addBody(null, body);
  295.     }

  296.     /**
  297.      * Adds a body with a corresponding language.
  298.      *
  299.      * @param language the language of the body being added.
  300.      * @param body the body being added to the message.
  301.      * @return the new {@link org.jivesoftware.smack.packet.Message.Body}
  302.      * @throws NullPointerException if the body is null, a null pointer exception is thrown
  303.      * @since 3.0.2
  304.      */
  305.     public Body addBody(String language, String body) {
  306.         language = determineLanguage(language);
  307.         Body messageBody = new Body(language, body);
  308.         bodies.add(messageBody);
  309.         return messageBody;
  310.     }

  311.     /**
  312.      * Removes the body with the given language from the message.
  313.      *
  314.      * @param language the language of the body which is to be removed
  315.      * @return true if a body was removed and false if it was not.
  316.      */
  317.     public boolean removeBody(String language) {
  318.         language = determineLanguage(language);
  319.         for (Body body : bodies) {
  320.             if (language.equals(body.language)) {
  321.                 return bodies.remove(body);
  322.             }
  323.         }
  324.         return false;
  325.     }

  326.     /**
  327.      * Removes the body from the message and returns true if the body was removed.
  328.      *
  329.      * @param body the body being removed from the message.
  330.      * @return true if the body was successfully removed and false if it was not.
  331.      * @since 3.0.2
  332.      */
  333.     public boolean removeBody(Body body) {
  334.         return bodies.remove(body);
  335.     }

  336.     /**
  337.      * Returns all the languages being used for the bodies, not including the default body.
  338.      *
  339.      * @return the languages being used for the bodies.
  340.      * @since 3.0.2
  341.      */
  342.     public List<String> getBodyLanguages() {
  343.         Body defaultBody = getMessageBody(null);
  344.         List<String> languages = new ArrayList<String>();
  345.         for (Body body : bodies) {
  346.             if (!body.equals(defaultBody)) {
  347.                 languages.add(body.language);
  348.             }
  349.         }
  350.         return Collections.unmodifiableList(languages);
  351.     }

  352.     /**
  353.      * Returns the thread id of the message, which is a unique identifier for a sequence
  354.      * of "chat" messages. If no thread id is set, <tt>null</tt> will be returned.
  355.      *
  356.      * @return the thread id of the message, or <tt>null</tt> if it doesn't exist.
  357.      */
  358.     public String getThread() {
  359.         return thread;
  360.     }

  361.     /**
  362.      * Sets the thread id of the message, which is a unique identifier for a sequence
  363.      * of "chat" messages.
  364.      *
  365.      * @param thread the thread id of the message.
  366.      */
  367.     public void setThread(String thread) {
  368.         this.thread = thread;
  369.     }

  370.     private String determineLanguage(String language) {
  371.        
  372.         // empty string is passed by #setSubject() and #setBody() and is the same as null
  373.         language = "".equals(language) ? null : language;

  374.         // if given language is null check if message language is set
  375.         if (language == null && this.language != null) {
  376.             return this.language;
  377.         }
  378.         else if (language == null) {
  379.             return getDefaultLanguage();
  380.         }
  381.         else {
  382.             return language;
  383.         }
  384.        
  385.     }

  386.     @Override
  387.     public XmlStringBuilder toXML() {
  388.         XmlStringBuilder buf = new XmlStringBuilder();
  389.         buf.halfOpenElement(ELEMENT);
  390.         addCommonAttributes(buf);
  391.         buf.optAttribute("type", type);
  392.         buf.rightAngleBracket();

  393.         // Add the subject in the default language
  394.         Subject defaultSubject = getMessageSubject(null);
  395.         if (defaultSubject != null) {
  396.             buf.element("subject", defaultSubject.subject);
  397.         }
  398.         // Add the subject in other languages
  399.         for (Subject subject : getSubjects()) {
  400.             // Skip the default language
  401.             if(subject.equals(defaultSubject))
  402.                 continue;
  403.             buf.halfOpenElement("subject").xmllangAttribute(subject.language).rightAngleBracket();
  404.             buf.escape(subject.subject);
  405.             buf.closeElement("subject");
  406.         }
  407.         // Add the body in the default language
  408.         Body defaultBody = getMessageBody(null);
  409.         if (defaultBody != null) {
  410.             buf.element("body", defaultBody.message);
  411.         }
  412.         // Add the bodies in other languages
  413.         for (Body body : getBodies()) {
  414.             // Skip the default language
  415.             if(body.equals(defaultBody))
  416.                 continue;
  417.             buf.halfOpenElement(BODY).xmllangAttribute(body.getLanguage()).rightAngleBracket();
  418.             buf.escape(body.getMessage());
  419.             buf.closeElement(BODY);
  420.         }
  421.         buf.optElement("thread", thread);
  422.         // Append the error subpacket if the message type is an error.
  423.         if (type == Type.error) {
  424.             appendErrorIfExists(buf);
  425.         }
  426.         // Add packet extensions, if any are defined.
  427.         buf.append(getExtensionsXML());
  428.         buf.closeElement(ELEMENT);
  429.         return buf;
  430.     }

  431.     /**
  432.      * Creates and returns a copy of this message stanza.
  433.      * <p>
  434.      * This does not perform a deep clone, as extension elements are shared between the new and old
  435.      * instance.
  436.      * </p>
  437.      * @return a clone of this message.
  438.      */
  439.     @Override
  440.     public Message clone() {
  441.         return new Message(this);
  442.     }

  443.     /**
  444.      * Represents a message subject, its language and the content of the subject.
  445.      */
  446.     public static class Subject {

  447.         private final String subject;
  448.         private final String language;

  449.         private Subject(String language, String subject) {
  450.             if (language == null) {
  451.                 throw new NullPointerException("Language cannot be null.");
  452.             }
  453.             if (subject == null) {
  454.                 throw new NullPointerException("Subject cannot be null.");
  455.             }
  456.             this.language = language;
  457.             this.subject = subject;
  458.         }

  459.         /**
  460.          * Returns the language of this message subject.
  461.          *
  462.          * @return the language of this message subject.
  463.          */
  464.         public String getLanguage() {
  465.             return language;
  466.         }

  467.         /**
  468.          * Returns the subject content.
  469.          *
  470.          * @return the content of the subject.
  471.          */
  472.         public String getSubject() {
  473.             return subject;
  474.         }


  475.         public int hashCode() {
  476.             final int prime = 31;
  477.             int result = 1;
  478.             result = prime * result + this.language.hashCode();
  479.             result = prime * result + this.subject.hashCode();
  480.             return result;
  481.         }

  482.         public boolean equals(Object obj) {
  483.             if (this == obj) {
  484.                 return true;
  485.             }
  486.             if (obj == null) {
  487.                 return false;
  488.             }
  489.             if (getClass() != obj.getClass()) {
  490.                 return false;
  491.             }
  492.             Subject other = (Subject) obj;
  493.             // simplified comparison because language and subject are always set
  494.             return this.language.equals(other.language) && this.subject.equals(other.subject);
  495.         }
  496.        
  497.     }

  498.     /**
  499.      * Represents a message body, its language and the content of the message.
  500.      */
  501.     public static class Body {

  502.         private final String message;
  503.         private final String language;

  504.         private Body(String language, String message) {
  505.             if (language == null) {
  506.                 throw new NullPointerException("Language cannot be null.");
  507.             }
  508.             if (message == null) {
  509.                 throw new NullPointerException("Message cannot be null.");
  510.             }
  511.             this.language = language;
  512.             this.message = message;
  513.         }

  514.         /**
  515.          * Returns the language of this message body.
  516.          *
  517.          * @return the language of this message body.
  518.          */
  519.         public String getLanguage() {
  520.             return language;
  521.         }

  522.         /**
  523.          * Returns the message content.
  524.          *
  525.          * @return the content of the message.
  526.          */
  527.         public String getMessage() {
  528.             return message;
  529.         }

  530.         public int hashCode() {
  531.             final int prime = 31;
  532.             int result = 1;
  533.             result = prime * result + this.language.hashCode();
  534.             result = prime * result + this.message.hashCode();
  535.             return result;
  536.         }

  537.         public boolean equals(Object obj) {
  538.             if (this == obj) {
  539.                 return true;
  540.             }
  541.             if (obj == null) {
  542.                 return false;
  543.             }
  544.             if (getClass() != obj.getClass()) {
  545.                 return false;
  546.             }
  547.             Body other = (Body) obj;
  548.             // simplified comparison because language and message are always set
  549.             return this.language.equals(other.language) && this.message.equals(other.message);
  550.         }
  551.        
  552.     }

  553.     /**
  554.      * Represents the type of a message.
  555.      */
  556.     public enum Type {

  557.         /**
  558.          * (Default) a normal text message used in email like interface.
  559.          */
  560.         normal,

  561.         /**
  562.          * Typically short text message used in line-by-line chat interfaces.
  563.          */
  564.         chat,

  565.         /**
  566.          * Chat message sent to a groupchat server for group chats.
  567.          */
  568.         groupchat,

  569.         /**
  570.          * Text message to be displayed in scrolling marquee displays.
  571.          */
  572.         headline,

  573.         /**
  574.          * indicates a messaging error.
  575.          */
  576.         error;

  577.         /**
  578.          * Converts a String into the corresponding types. Valid String values that can be converted
  579.          * to types are: "normal", "chat", "groupchat", "headline" and "error".
  580.          *
  581.          * @param string the String value to covert.
  582.          * @return the corresponding Type.
  583.          * @throws IllegalArgumentException when not able to parse the string parameter
  584.          * @throws NullPointerException if the string is null
  585.          */
  586.         public static Type fromString(String string) {
  587.             return Type.valueOf(string.toLowerCase(Locale.US));
  588.         }

  589.     }
  590. }