Logo Studenta

UC3M _Universidad Carlos III de Madrid_ _ Máster en Ingeniería de Telecomunicaciones _ Programación C y Java Telecomunicaciones _ especifica

Esta es una vista previa del archivo. Inicie sesión para ver el archivo original

CodigoFuente.zip
mensajesSIP/ACKMessage.java
mensajesSIP/ACKMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class ACKMessage extends SIPMessage {
    private String destination;
    private String route;
    private int maxForwards;
    private int contentLength;
/**
 * Devuelve el contenido de las Vias como ArrayList de Strings.
 * Las Vias contienen la lista de puntos por los que va pasando el mensaje y se añade el último punto al inicio de las Vias.
 * El mensaje en la red tendra vias con formato: Via: SIP/2.0/UDP identificador donde el identificador podrá contener dirección IP o nombre de máquina con o sin y puerto 
 * Este API guardará solo la parte de identificador en la lista de vias y concatenará la parte de Via: SIP/2.0/UDP al generar el mensaje en formato cadena
 *
 * @return      las Vias del mensaje
 */
    public ArrayList<String> getVias() {
        return vias;
    }
/**
 * Establece el contenido de las Vias como ArrayList de Strings 
 * Cada String contiene el contenido del punto del camino de que se ha quitado la parte de Via: SIP/2.0/UDP  
 *
 * @param  vias  las Vias a establecer como ArrayList 
  */
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
/**
 * Añade una Via como String. El API añade las vias en formato pila de forma que la última via añadida es la primera en quitarse 
 *
 * @param  via  la Via a añadir
 */
    public void addVia(String via) {
        this.vias.add(0, via);
    }
/**
 * Borra la última Via añadida
 *
 */
    public void deleteVia() {
        this.vias.remove(0);
    }
/**
 * Recupera el nombre del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @return      el nombre del destinatario
 */
    public String getToName() {
        return toName;
    }
/**
 * Establece el nombre del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @param  toName   el nombre a añadir
 */
    public void setToName(String toName) {
        this.toName = toName;
    }
/**
 * Recupera la Uri del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @return      la Uri del destinatario
 */
    public String getToUri() {
        return toUri;
    }
/**
 * Establece la Uri del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @param  toUri        la Uri del destinatario a añadir
 */
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
/**
 * Recupera el nombre del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @return      el nombre del origen
 */
    public String getFromName() {
        return fromName;
    }
/**
 * Establece el nombre del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @param  fromName el nombre del origen a añadir
 */
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
/**
 * Recupera la Uri del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @return      la Uri del origen
 */
    public String getFromUri() {
        return fromUri;
    }
/**
 * Establece la Uri del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @param  fromUri      la Uri del origen a añadir
 */
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
/**
 * Recupera el CallId de la llamada.
 * El Call Id de la llamada se forma como se especifica en la RFC 3261 "by the combination of a random string and the softphone's host name or IP address". Este API no hace comprabaciones del formato en esta linea.
 * 
 * @return      el CallId de la llamada
 */
    public String getCallId() {
        return callId;
    }
/**
 * Establece el CallId de la llamada. 
 *
 * @param   callId   el CallId de la llamada
 */
    public void setCallId(String callId) {
        this.callId = callId;
    }
/**
 * Recupera el cSeqNumber de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 * 
 * @return      el cSeqNumber de la llamada
 */
    public String getcSeqNumber() {
        return cSeqNumber;
    }
/**
 * Establece el cSeqNumber de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 *
 * @param   cSeqNumber   el cSeqNumber de la llamada
 */
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
/**
 * Recupera el cSeqStr de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr.
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 * 
 * @return      el cSeqStr de la llamada
 */
    public String getcSeqStr() {
        return cSeqStr;
    }
/**
 * Establece el cSeqStr de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr.
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 *
 * @param   cSeqStr  el cSeqNumber de la llamada
 */
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
/**
 * Recupera el destino de la llamada. El destino será la dirección SIP que va en la linea de petición
 * 
 * @return      el destino de la llamada
 */
    public String getDestination() {
        return destination;
    }
/**
 * Establece el destino de la llamada. El destino será la dirección SIP que va en la linea de petición
 * 
 * @param   el destino de la llamada
 */
    public void setDestination(String destination) {
        this.destination = destination;
    }
/**
 * Recupera el maxForwards.
 * 
 * @return      el maxForwards 
 */
    public int getMaxForwards() {
        return maxForwards;
    }
/**
 * Establece el maxForwards.
 * 
 * @param   maxForwards
 */
    public void setMaxForwards(int maxForwards) {
        this.maxForwards = maxForwards;
    }
/**
 * Recupera el route.
 * 
 * @return      el route
 */
    public String getRoute() {
        return route;
    }
/**
 * Establece el route.
 * 
 * @param   route
 */
    public void setRoute(String route) {
        this.route = route;
    }
/**
 * Recupera el contentLength.
 * 
 * @return      el contentLength
 */
    public int getContentLength() {
        return contentLength;
    }
/**
 * Establece el contentLength.
 * 
 * @param   contentLength
 */
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
/**
 * Convierte el mensaje en un String. Para ello concatena la información de las cabeceras del mensaje.
 * El toName y el fromName son opcionales a la hora de componer las
cabeceras to y from pero las URIs si han de estar presentes en las variables toUri y fromUri
 * Estas cabeceras se componen como "To: " + toName + " <" + toUri + ">\n"
 * El CSeq se compone como "CSeq: " + cSeqNumber + " " + cSeqStr + "\n"
 * No hay contact
 * No hay carga en SDP debe tener contenido
 * la cabecera route es opcional (en función de si se ha especificado loose routing en el INVITE)
 * 
 * @return      el mensaje como String.
 */
    @Override
    public String toStringMessage() {
        String ack;
        ack = "ACK " + destination + " SIP/2.0\n";
        for (int i=0; i<vias.size(); i++) {
            ack += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if (route != null) {
            ack += "Route: " + route + "\n";
        }
        ack += "Max-Forwards: " + maxForwards + "\n";
        if(toName!=null)
            ack += "To: " + toName + " <" + toUri + ">\n";
        else
            ack += "To: <" + toUri + ">\n";
        if(fromName!=null)
            ack += "From: " + fromName + " <" + fromUri + ">\n";
        else
            ack += "From: <" + fromUri + ">\n";
        ack += "Call-ID: " + callId + "\n";
        ack += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        ack += "\n";
        return ack;
    }
}
mensajesSIP/BusyHereMessage.java
mensajesSIP/BusyHereMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 * For documentation details
 * @see ACKMessage InviteMessage SDPMessage SIPMessage
 */
public class BusyHereMessage extends SIPMessage {
    private int contentLength;
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    
    public void deleteVia() 
    {
        this.vias.remove(0);
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    @Override
    public String toStringMessage() {
        String bh;
        bh = "SIP/2.0 486 Busy Here\n";
        for (int i=0; i<vias.size(); i++) {
            bh += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if(toName!=null)
            bh += "To: " + toName + " <" + toUri + ">\n";
        else
            bh += "To: <" + toUri + ">\n";
        if(fromName!=null)
            bh += "From: " + fromName + " <" + fromUri + ">\n";
        else
            bh += "From: <" + fromUri + ">\n";
        bh += "Call-ID: " + callId + "\n";
        bh += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        bh += "Content-Length: " + contentLength + "\n";
        bh += "\n";
        return bh;
    }
}
mensajesSIP/ByeMessage.java
mensajesSIP/ByeMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class ByeMessage extends SIPMessage {
    private String destination;
    private String route;
    private int maxForwards;
    private int contentLength;
    public void addVia(String via) {
        this.vias.add(0, via);
    }
    public void deleteVia() {
        this.vias.remove(0);
    }
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public String getDestination() {
        return destination;
    }
    public void setDestination(String destination) {
        this.destination = destination;
    }
    public String getRoute() {
        return route;
    }
    public void setRoute(String route) {
        this.route = route;
    }
    public int getMaxForwards() {
        return maxForwards;
    }
    public void setMaxForwards(int maxForwards) {
        this.maxForwards = maxForwards;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    @Override
    public String toStringMessage() {
        String bye;
        bye = "BYE " + destination + " SIP/2.0\n";
        for (int i=0; i<vias.size(); i++) {
            bye += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if (route != null) {
            bye += "Route: " + route + "\n";
        }
        bye += "Max-Forwards: " + maxForwards + "\n";
        if(toName!=null)
            bye += "To: " + toName + " <" + toUri + ">\n";
        else
            bye += "To: <" + toUri + ">\n";
        if(fromName!=null)
            bye += "From: " + fromName + " <" + fromUri + ">\n";
        else
            bye += "From: <" + fromUri + ">\n";
        bye += "Call-ID: " + callId + "\n";
        bye += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        bye += "Content-Length: " + contentLength + "\n";
        bye += "\n";
        return bye;
    }
}
mensajesSIP/InviteMessage.java
mensajesSIP/InviteMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para
la práctica
 */
package mensajesSIP;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author SMA
 */
public class InviteMessage extends SIPMessage {
    private String destination;
    private String recordRoute;
    private int maxForwards;
    private String contact;
    private String proxyAuthentication;
    private String contentType;
    private int contentLength;
    private SDPMessage sdp;
/**
 * Añade una Via como String. El API añade las vias en formato pila de forma que la última via añadida es la primera en quitarse 
 *
 * @param  via  la Via a añadir
 */
    public void addVia(String via) {
        this.vias.add(0, via);
    }
/**
 * Borra la última Via añadida
 *
 */
    public void deleteVia() {
        this.vias.remove(0);
    }
/**
 * Devuelve el contenido de las Vias como ArrayList de Strings.
 * Las Vias contienen la lista de puntos por los que va pasando el mensaje y se añade el último punto al inicio de las Vias.
 * El mensaje en la red tendra vias con formato: Via: SIP/2.0/UDP identificador donde el identificador podrá contener dirección IP o nombre de máquina con o sin y puerto 
 * Este API guardará solo la parte de identificador en la lista de vias y concatenará la parte de Via: SIP/2.0/UDP al generar el mensaje en formato cadena
 *
 * @return      las Vias del mensaje
 */
    public ArrayList<String> getVias() {
        return vias;
    }
/**
 * Establece el contenido de las Vias como ArrayList de Strings 
 * Cada String contiene el contenido del punto del camino de que se ha quitado la parte de Via: SIP/2.0/UDP  
 *
 * @param  vias  las Vias a establecer como ArrayList 
  */
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
/**
 * Recupera el nombre del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @return      el nombre del destinatario
 */
    public String getToName() {
        return toName;
    }
/**
 * Establece el nombre del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @param  toName   el nombre a añadir
 */
    public void setToName(String toName) {
        this.toName = toName;
    }
/**
 * Recupera la Uri del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @return      la Uri del destinatario
 */
    public String getToUri() {
        return toUri;
    }
/**
 * Establece la Uri del destinatario. 
 * La direccion del destinatario tendrá formato <strong>toName &lt;toUri&gt; </strong>
 *
 * @param  toUri        la Uri del destinatario a añadir
 */
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
/**
 * Recupera el nombre del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @return      el nombre del origen
 */
    public String getFromName() {
        return fromName;
    }
/**
 * Establece el nombre del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @param  fromName el nombre del origen a añadir
 */
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
/**
 * Recupera la Uri del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @return      la Uri del origen
 */
    public String getFromUri() {
        return fromUri;
    }
/**
 * Establece la Uri del origen. 
 * La direccion del destinatario tendrá formato <strong>fromName &lt;fromUri&gt; </strong>
 *
 * @param  fromUri      la Uri del origen a añadir
 */
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
/**
 * Recupera el CallId de la llamada.
 * El Call Id de la llamada se forma como se especifica en la RFC 3261 "by the combination of a random string and the softphone's host name or IP address". Este API no hace comprabaciones del formato en esta linea.
 * 
 * @return      el CallId de la llamada
 */
    public String getCallId() {
        return callId;
    }
/**
 * Establece el CallId de la llamada. 
 *
 * @param   callId   el CallId de la llamada
 */
    public void setCallId(String callId) {
        this.callId = callId;
    }
/**
 * Recupera el cSeqNumber de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 * 
 * @return      el cSeqNumber de la llamada
 */
    public String getcSeqNumber() {
        return cSeqNumber;
    }
/**
 * Establece el cSeqNumber de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 *
 * @param   cSeqNumber   el cSeqNumber de la llamada
 */
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
/**
 * Recupera el cSeqStr de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr.
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 * 
 * @return      el cSeqStr de la llamada
 */
    public String getcSeqStr() {
        return cSeqStr;
    }
/**
 * Establece el cSeqStr de la llamada. En SIP el número de secuencia será la concatenación de cSeqNumber y cSeqStr.
 * Para un primer mensaje INVITE por ejemplo, el número de secuencia se formaría como 1 INVITE, donde cSeqNumber=1 y cSeqStr= INVITE 
 *
 * @param   cSeqStr  el cSeqNumber de la llamada
 */
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
/**
 * Recupera el destino de la llamada. El destino será la dirección SIP que va en la linea de petición
 * 
 * @return      el destino de la llamada
 */
    public String getDestination() {
        return destination;
    }
/**
 * Establece el destino de la llamada. El destino será la dirección SIP que va en la linea de petición
 * 
 * @param   el destino de la llamada
 */
    public void setDestination(String destination) {
        this.destination = destination;
    }
/**
 * Recupera el recordRoute. El recordRoute será un String que contiene la concatenación de los puntos intermedios de la llamada por los que tienen que pasar los futuros mensajes. Será una lista separada por comas. El API lo gestiona como un String sin separar cada uno de los puntos intermedios que se incluyen.
 * 
 * @return      el recordRoute
 */
    public String getRecordRoute() {
        return recordRoute;
    }
/**
 * Establece el recordRoute. El recordRoute será un String que contiene la concatenación de los puntos intermedios de la llamada por los que tienen que pasar los futuros mensajes. Será una lista separada por comas. El API lo gestiona como un String sin separar cada uno de los puntos intermedios que se incluyen.
 * 
 * @param   recordRoute
 */
    public void setRecordRoute(String recordRoute) {
        this.recordRoute = recordRoute;
    }
/**
 * Recupera el maxForwards.
 * 
 * @return      el maxForwards 
 */
    public int getMaxForwards() {
        return maxForwards;
    }
/**
 * Establece el maxForwards.
* 
 * @param   maxForwards
 */
    public void setMaxForwards(int maxForwards) {
        this.maxForwards = maxForwards;
    }
/**
 * Recupera el contact. El contact contiene la URI sip del origen a la que se le ha quitado la parte de sip:
 * 
 * @return      el contact
 */
    public String getContact() {
        return contact;
    }
/**
 * Establece el contact. El contact contiene la URI sip del origen a la que se le ha quitado la parte de sip:
 * 
 * @param   contact 
 */
    public void setContact(String contact) {
        this.contact = contact;
    }
    
    
/**
* Recupera el proxyAuthentication. El proxyAuthentication contiene una cadena con el hash MD5 de lo recibido en proxyAuthenticate del mensaje 407 ProxyAuthentication al que se le concatena la contraseña de usuario para calcular el hash * 
 * @return      el proxyAuthentication
 */
    public String getProxyAuthentication() {
        return proxyAuthentication;
    }
/**
 * Establece el proxyAuthentication. El proxyAuthentication contiene una cadena con el hash MD5 de lo recibido en proxyAuthenticate del mensaje 407 ProxyAuthentication al que se le concatena la contraseña de usuario para calcular el hash
 * 
 * @param   proxyAuthentication 
 */
    public void setProxyAuthentication(String proxyAuthentication) {
        this.proxyAuthentication = proxyAuthentication;
    }
    
/**
 * Recupera el Content-Type. El Content-Type será el tipo MIME asociado al contenido que se transporta en el mensaje INVITE. Nosotros usaremos Application/SDP 
 * 
 * @return      contentType
 */
 
    public String getContentType() {
        return contentType;
    }
    /**
 * Establece el Content-Type. El Content-Type será el tipo MIME asociado al contenido que se transporta en el mensaje INVITE. Nosotros usaremos Application/SDP 
 * 
 * @param   contentType 
 */
 
    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    
/**
 * Recupera el Content-Length. El Content-Length será el tamaño del contenido que se transporta en el mensaje INVITE en numero de caracteres. 
 * 
 * @return      contentLength
 */
    public int getContentLength() {
        return contentLength;
    }
        /**
 * Establece el Content-Length. El Content-Length será el tamaño del contenido que se transporta en el mensaje INVITE en numero de caracteres.  
 * 
 * @param   contentLength 
 */
 
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
/**
 * Recupera el contenido de la carga útil en SDP mediante la clase de soporte SDPMessage que permite establecer la IP y pueto de la sesión de medios así como los atributos de la misma.
 * 
 * @return      el SDPMessage 
 */
    public SDPMessage getSdp() {
        return sdp;
    }
/**
 * Establece el contenido de la carga útil en SDP mediante la clase de soporte SDPMessage que permite establecer la IP y pueto de la sesión de medios así como los atributos de la misma.
 * 
 * @param   sdp - el SDPMessage 
 */
    public void setSdp(SDPMessage sdp) {
        this.sdp = sdp;
    }
/**
 * Convierte el mensaje en un String. Para ello concatena la información de las cabeceras del mensaje.
 * El toName y el fromName son opcionales a la hora de componer las cabeceras to y from pero las URIs si han de estar presentes en las variables toUri y fromUri
 * Estas cabeceras se componen como "To: " + toName + " <" + toUri + ">\n"
 * El CSeq se compone como "CSeq: " + cSeqNumber + " " + cSeqStr + "\n"
 * El Contact como "Contact: <sip:" + contact + ">\n" donde la variable contact tiene la información de contacto pero sin la parte sip: de la URI final
 * La carga en SDP debe tener contenido
 * 
 * @return      el mensaje como String.
 */
    
    @Override
    public String toStringMessage() {
        String invite;
        invite = "INVITE " + destination + " SIP/2.0\n";
        for (int i=0; i<vias.size(); i++) {
            invite += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if (recordRoute != null) {
            invite += "Record-Route: " + recordRoute + "\n";
        }
        invite += "Max-Forwards: " + maxForwards + "\n";
        if(toName!=null)
            invite += "To: " + toName + " <" + toUri + ">\n";
        else
            invite += "To: <" + toUri + ">\n";
        if(fromName!=null)
            invite += "From: " + fromName + " <" + fromUri + ">\n";
        else
            invite += "From: <" + fromUri + ">\n";
        invite += "Call-ID: " + callId + "\n";
        invite += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        invite += "Contact: <sip:" + contact + ">\n";
        if (proxyAuthentication!=null) invite += "ProxyAuthentication: auth= " + proxyAuthentication + "\n";
        invite += "Content-Type: " + contentType + "\n";
        invite += "Content-Length: " + contentLength + "\n";
        invite += "\n";
        invite += sdp.toStringMessage();
        return invite;
    }
}
mensajesSIP/NotFoundMessage.java
mensajesSIP/NotFoundMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class NotFoundMessage extends SIPMessage {
    private String contact;
    private String expires;
    private int contentLength;
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public String getExpires() {
        return expires;
    }
    public void setExpires(String expires) {
        this.expires = expires;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    
    @Override
    public String toStringMessage() {
        String nf;
        nf = "SIP/2.0 404 Not Found\n";
        for (int i=0; i<vias.size(); i++) {
            nf += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if(toName!=null)
            nf += "To: " + toName + " <" + toUri + ">\n";
        else
            nf += "To: <" + toUri + ">\n";
        if(fromName!=null)
            nf += "From: " + fromName
+ " <" + fromUri + ">\n";
        else
            nf += "From: <" + fromUri + ">\n";
        nf += "Call-ID: " + callId + "\n";
        nf += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        nf += "Contact: <sip:" + contact + ">\n";
        nf += "Content-Length: " + contentLength + "\n";
        nf += "\n";
        return nf;
    }
}
mensajesSIP/OKMessage.java
mensajesSIP/OKMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class OKMessage extends SIPMessage {
    private String route;
    private String recordRoute; 
    private String contact;
    private String expires;
    private int contentLength;
    SDPMessage sdp;
    public void addVia(String via) {
        this.vias.add(0, via);
    }
    public void deleteVia() {
        this.vias.remove(0);
    }
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public void OKMessage() {
    }
    public String getRoute() {
        return route;
    }
    public void setRoute(String route) {
        this.route = route;
    }
/**
 * Recupera el recordRoute. El recordRoute será un String que contiene la concatenación de los puntos intermedios de la llamada por los que tienen que pasar los futuros mensajes. Será una lista separada por comas. El API lo gestiona como un String sin separar cada uno de los puntos intermedios que se incluyen.
 * 
 * @return      el recordRoute
 */
    public String getRecordRoute() {
        return recordRoute;
    }
/**
 * Establece el recordRoute. El recordRoute será un String que contiene la concatenación de los puntos intermedios de la llamada por los que tienen que pasar los futuros mensajes. Será una lista separada por comas. El API lo gestiona como un String sin separar cada uno de los puntos intermedios que se incluyen.
 * 
 * @param   recordRoute
 */
    public void setRecordRoute(String recordRoute) {
        this.recordRoute = recordRoute;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public String getExpires() {
        return expires;
    }
    public void setExpires(String expires) {
        this.expires = expires;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    
    public SDPMessage getSdp() {
        return sdp;
    }
    public void setSdp(SDPMessage sdp) {
        this.sdp = sdp;
    }
    @Override
    public String toStringMessage() {
        String ok;
        ok = "SIP/2.0 200 OK\n";
        for (int i=0; i<vias.size(); i++) {
            ok += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if (route != null) {
            ok += "Route: " + route + "\n";
        }
        if (recordRoute != null) {
            ok += "Record-Route: " + recordRoute + "\n";
        }
        if(toName!=null)
            ok += "To: " + toName + " <" + toUri + ">\n";
        else
            ok += "To: <" + toUri + ">\n";
        if(fromName!=null)
            ok += "From: " + fromName + " <" + fromUri + ">\n";
        else
            ok += "From: <" + fromUri + ">\n";
        ok += "Call-ID: " + callId + "\n";
        ok += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        ok += "Contact: <sip:" + contact + ">\n";
        if(expires != null)
            ok += "Expires: " + expires + "\n";
        ok += "Content-Length: " + contentLength + "\n";
        ok += "\n";
        if(sdp!=null){
            ok += sdp.toStringMessage();
        }
        return ok;
    }
}
mensajesSIP/ProxyAuthenticationMessage.java
mensajesSIP/ProxyAuthenticationMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class ProxyAuthenticationMessage extends SIPMessage {
    private String expires;
    private String proxyAuthenticate;
    private int contentLength;
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public String getproxyAuthenticate() {
        return proxyAuthenticate;
    }
    public void setproxyAuthenticate(String proxyAuthenticate) {
        this.proxyAuthenticate = proxyAuthenticate;
    }
    public String getExpires() {
        return expires;
    }
    public void setExpires(String expires) {
        this.expires = expires;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    
    @Override
    public String toStringMessage() {
        String nf;
        nf = "SIP/2.0 407 Proxy Authentication Required\n";
        for (int i=0; i<vias.size(); i++) {
            nf += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if(toName!=null)
nf += "To: " + toName + " <" + toUri + ">\n";
        else
            nf += "To: <" + toUri + ">\n";
        if(fromName!=null)
            nf += "From: " + fromName + " <" + fromUri + ">\n";
        else
            nf += "From: <" + fromUri + ">\n";
        nf += "Call-ID: " + callId + "\n";
        nf += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        nf += "ProxyAuthenticate: nonce= " + proxyAuthenticate + "\n";
        nf += "Content-Length: " + contentLength + "\n";
        nf += "\n";
        return nf;
    }
}
mensajesSIP/RegisterMessage.java
mensajesSIP/RegisterMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class RegisterMessage extends SIPMessage {
    public String destination;
    public int maxForwards;
    public String contact;
    public String expires;
    public int contentLength;
    public String getDestination() {
        return destination;
    }
    public void setDestination(String destination) {
        this.destination = destination;
    }
    public int getMaxForwards() {
        return maxForwards;
    }
    public void setMaxForwards(int maxForwards) {
        this.maxForwards = maxForwards;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    public String getExpires() {
        return expires;
    }
    public void setExpires(String expires) {
        this.expires = expires;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    @Override
    public String toStringMessage() {
        String register;
        register = "REGISTER " + destination + " SIP/2.0\n";
        for (int i=0; i<vias.size(); i++) {
            register += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        register += "Max-Forwards: " + maxForwards + "\n";
        if(toName!=null)
            register += "To: " + toName + " <" + toUri + ">\n";
        else
            register += "To: <" + toUri + ">\n";
        if(fromName!=null)
            register += "From: " + fromName + " <" + fromUri + ">\n";
        else
            register += "From: <" + fromUri + ">\n";
        register += "Call-ID: " + callId + "\n";
        register += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        register += "Contact: <sip:" + contact + ">\n";
        register += "Expires: " + expires + "\n";
        register += "Content-Length: " + contentLength + "\n";
        register += "\n";
        return register;
    }
}
mensajesSIP/RequestTimeoutMessage.java
mensajesSIP/RequestTimeoutMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class RequestTimeoutMessage extends SIPMessage {
    private int contentLength;
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public void addVia(String via) {
        this.vias.add(0, via);
    }
    public void deleteVia() {
        this.vias.remove(0);
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    
    @Override
    public String toStringMessage() {
        String rt;
        rt = "SIP/2.0 408 Request Timeout\n";
        for (int i=0; i<vias.size(); i++) {
            rt += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if(toName!=null)
            rt += "To: " + toName + " <" + toUri + ">\n";
        else
            rt += "To: <" + toUri + ">\n";
        if(fromName!=null)
            rt += "From: " + fromName + " <" + fromUri + ">\n";
        else
            rt += "From: <" + fromUri + ">\n";
        rt += "Call-ID: " + callId + "\n";
        rt += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        rt += "Content-Length: " + contentLength + "\n";
        rt += "\n";
        return rt;
    }
}
mensajesSIP/RingingMessage.java
mensajesSIP/RingingMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class RingingMessage extends SIPMessage {
    private String recordRoute;
    private String contact;
    private int contentLength;
    public void addVia(String via) {
        this.vias.add(0, via);
    }
    public void deleteVia() {
        this.vias.remove(0);
    }
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName()
{
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public String getRecordRoute() {
        return recordRoute;
    }
    public void setRecordRoute(String recordRoute) {
        this.recordRoute = recordRoute;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    public String getContact() {
        return contact;
    }
    public void setContact(String contact) {
        this.contact = contact;
    }
    @Override
    public String toStringMessage() {
        String ringing;
        ringing = "SIP/2.0 180 Ringing\n";
        for (int i=0; i<vias.size(); i++) {
            ringing += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if (recordRoute != null) {
            ringing += "Record-Route: " + recordRoute + "\n";
        }
        if(toName!=null)
            ringing += "To: " + toName + " <" + toUri + ">\n";
        else
            ringing += "To: <" + toUri + ">\n";
        if(fromName!=null)
            ringing += "From: " + fromName + " <" + fromUri + ">\n";
        else
            ringing += "From: <" + fromUri + ">\n";
        ringing += "Call-ID: " + callId + "\n";
        ringing += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        ringing += "Contact: <sip:" + contact + ">\n";
        ringing += "Content-Length: " + contentLength + "\n";
        ringing += "\n";
        return ringing;
    }
}
mensajesSIP/SDPMessage.java
mensajesSIP/SDPMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * @author SMA
 */
public class SDPMessage {
    private String ip;
    private int port;
    private ArrayList<Integer> options;
    public String getIp() {
        return ip;
    }
    public void setIp(String ip) {
        this.ip = ip;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
/**
 * Recupera el ArrayList que contiene las opciones ofrecidas en el mensaje SDP.
 * <p>Las opciones pueden ser 96|97|98.</p>
 * <p>96 genera la linea a=rtpmap:96 L8/8000 </p>
 * <p>97 genera la linea a=rtpmap:97 L16/8000 </p>
 * <p>98 genera la linea a=rtpmap:98 L8/11025/2 </p>
 * 
 * @return      el ArrayList con las opciones
 */
    public ArrayList<Integer> getOptions() {
        return options;
    }
/**
 * Establece el ArrayList que contiene las opciones ofrecidas en el mensaje SDP.
 * <p>Las opciones pueden ser 96|97|98.</p>
 * <p>96 genera la linea a=rtpmap:96 L8/8000 </p>
 * <p>97 genera la linea a=rtpmap:97 L16/8000 </p>
 * <p>98 genera la linea a=rtpmap:98 L8/11025/2 </p>
 * 
 * @param options     el ArrayList con las opciones
 */
    public void setOptions(ArrayList<Integer> options) {
        this.options = options;
    }
    public void parseMessage(String message) throws SIPException {
        String[] lines = message.split("\n");
        for (int i = 0; i < lines.length; i++) {
            if (lines[i].startsWith("c")) {
                parseC(lines[i]);
            } else if (lines[i].startsWith("m")) {
                parseM(lines[i]);
            }
        }
    }
/**
 * Convierte el mensaje en un String. Para ello concatena la información de las opciones c y m con la IP, puerto y opciones de los atributos de la clase.
 * 
 * @return      el mensaje como String.
 */
    public String toStringMessage() {
        String sdp = "";
        String a = "";
        
        sdp = "c=IN IP4 " + ip + "\n";
        sdp += "m=audio " + port + " RTP/AVP";
        for (int i = 0; i < options.size(); i++) {
            sdp += " " + options.get(i);
            if (options.get(i) == 96) {
                a += "a=rtpmap:96 L8/8000\n";
            } else if (options.get(i) == 97) {
                a += "a=rtpmap:97 L16/8000\n";
            } else if (options.get(i) == 98) {
                a += "a=rtpmap:98 L8/11025/2\n";
            }
        }
        sdp += "\n";
        sdp += a;
        return sdp;
    }
    private void parseC(String line) throws SIPException {
        Pattern pattern = Pattern.compile("c=IN IP4 ([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3})");
        Matcher matcher = pattern.matcher(line);
        if (matcher.matches()) {
            ip = matcher.group(1);
        } else {
            throw new SIPException("Malformed SDP payload");
        }
    }
    private void parseM(String line) throws SIPException {
        Pattern pattern = Pattern.compile("m=audio (\\d+) RTP/AVP (96|97|98) ?(96|97|98)? ?(96|97|98)?");
        
        //System.out.println(line);
        Matcher matcher = pattern.matcher(line);
        if (matcher.matches()) {
            port = Integer.parseInt(matcher.group(1));
            ArrayList<Integer> options = new ArrayList<Integer>();
            for (int i = 2; i <= matcher.groupCount(); i++) {
                if(matcher.group(i)!=null)
                    options.add(Integer.parseInt(matcher.group(i)));
            }
            this.options = options;
        } else {
            throw new SIPException("Malformed SDP payload");
        }
    }
}
mensajesSIP/ServiceUnavailableMessage.java
mensajesSIP/ServiceUnavailableMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class ServiceUnavailableMessage extends SIPMessage {
    private int contentLength;
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName)
{
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    @Override
    public String toStringMessage() {
        String su;
        su = "SIP/2.0 503 Service Unavailable\n";
        for (int i=0; i<vias.size(); i++) {
            su += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if(toName!=null)
            su += "To: " + toName + " <" + toUri + ">\n";
        else
            su += "To: <" + toUri + ">\n";
        if(fromName!=null)
            su += "From: " + fromName + " <" + fromUri + ">\n";
        else
            su += "From: <" + fromUri + ">\n";
        su += "Call-ID: " + callId + "\n";
        su += "CSeq: " + cSeqNumber + " " + cSeqStr + "\n";
        su += "Content-Length: " + contentLength + "\n";
        su += "\n";
        return su;
    }
}
mensajesSIP/SIPException.java
mensajesSIP/SIPException.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
/**
 *
 * @author SMA
 */
public class SIPException extends Exception{
    
    public SIPException(String message){
        super(message);
    }
    public SIPException() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    
}
mensajesSIP/SIPMessage.java
mensajesSIP/SIPMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 *
 * @author SMA
 */
public abstract class SIPMessage {
    
    protected ArrayList<String> vias;
    protected String toName;
    protected String toUri;
    protected String fromName;
    protected String fromUri;
    protected String callId;
    protected String cSeqNumber;
    protected String cSeqStr;
    
/**
 * Convierte el mensaje en un String. Para ello concatena la información de las cabeceras del mensaje.
 * 
 * @return      el mensaje como String.
 */
    public abstract String toStringMessage();
    
/**
 * Convierte el mensaje en un String. Para ello concatena la información de las cabeceras del mensaje.
 * <p> Nótese que es un método de clase o método estático de cara a poderse invocar sobre la propia clase SIPMessage. Este método se usa como factoría para generar los diferentes mensajes SIP a partir de lo recibido de la red.
 * <p> En realidad, como los mensajes generados heradarán de la clase SIPMessage, al invocar a parseMessage tendremos que hacer un casting a la clase apropiada.
 * 
 * @return      SIPMessage el mensaje parseado. 
 */
    public static SIPMessage parseMessage(String message) throws SIPException{
        
        String[] lines = message.split("\n");
        
        String recordRoute = null, route = null, maxForwards = null, callId = null, contact = null,
                contentLength = null, expires = null, proxyAuthenticate=null, proxyAuthentication=null;
        ArrayList<String> vias = new ArrayList<String>();
        String[] to = null, from = null, cSeq = null;
        for(int i=0; i<lines.length; i++){
            if(lines[i].startsWith("Via")){
                vias.add(parseVia(lines[i]));
            }
            else if(lines[i].startsWith("Record-Route")){
                recordRoute = parseRecordRoute(lines[i]);
            }
            else if(lines[i].startsWith("Route")){
                route = parseRoute(lines[i]);
            }
            else if(lines[i].startsWith("Max-Forwards")){
                maxForwards = parseMaxForwards(lines[i]);
            }
            else if(lines[i].startsWith("From")){
                from = parseFrom(lines[i]);
            }
            else if(lines[i].startsWith("To")){
                to = parseTo(lines[i]);
            }
            else if(lines[i].startsWith("Call-ID")){
                callId = parseCallId(lines[i]);
            }
            else if(lines[i].startsWith("CSeq")){
                cSeq = parseCSeq(lines[i]);
            }
            else if(lines[i].startsWith("Contact")){
                contact = parseContact(lines[i]);
            }
            else if(lines[i].startsWith("Content-Length")){
                contentLength = parseContentLength(lines[i]);
            }
            else if(lines[i].startsWith("Expires")){
                expires = parseExpires(lines[i]);
            }
            else if(lines[i].startsWith("ProxyAuthenticate")){
                proxyAuthenticate = parseProxyAuthenticate(lines[i]);
            }
            else if(lines[i].startsWith("ProxyAuthentication")){
                proxyAuthentication = parseProxyAuthentication(lines[i]);
            }
        }
        
        
        if(message.startsWith("INVITE")){
            InviteMessage invite = new InviteMessage();
            String[] parts = message.split("\n\n");
            
            //SDP message
            String sdpMessageStr = parts[1];
            
            invite.setDestination(parseRequestHeader(lines[0]));
            invite.setVias(vias);
         if (recordRoute!=null) invite.setRecordRoute(recordRoute);
            invite.setMaxForwards(Integer.parseInt(maxForwards));
            invite.setToName(to[0]);
            invite.setToUri(to[1]);
            invite.setFromName(from[0]);
            invite.setFromUri(from[1]);
            invite.setCallId(callId);
            invite.setcSeqNumber(cSeq[0]);
            invite.setcSeqStr(cSeq[1]);
            invite.setContact(contact);
            if (proxyAuthentication!=null) invite.setProxyAuthentication(proxyAuthentication);
            invite.setContentType("application/sdp");
            invite.setContentLength(Integer.parseInt(contentLength));
            
            SDPMessage sdp = new SDPMessage();
            sdp.parseMessage(sdpMessageStr);
            invite.setSdp(sdp);
            
            return invite;
        }
        else if(message.startsWith("REGISTER")){
            RegisterMessage register = new RegisterMessage();
            
            register.setDestination(parseRequestHeader(lines[0]));
            register.setVias(vias);
            register.setMaxForwards(Integer.parseInt(maxForwards));
            register.setToName(to[0]);
            register.setToUri(to[1]);
            register.setFromName(from[0]);
            register.setFromUri(from[1]);
            register.setCallId(callId);
            register.setcSeqNumber(cSeq[0]);
            register.setcSeqStr(cSeq[1]);
            register.setContact(contact);
            register.setExpires(expires);
            
            return register;
        }
        else if(message.startsWith("BYE")){
            ByeMessage bye = new ByeMessage();
            
            bye.setDestination(parseRequestHeader(lines[0]));
            bye.setVias(vias);
if(route!=null){
                bye.setRoute(route);
            }
            bye.setMaxForwards(Integer.parseInt(maxForwards));
            bye.setToName(to[0]);
            bye.setToUri(to[1]);
            bye.setFromName(from[0]);
            bye.setFromUri(from[1]);
            bye.setCallId(callId);
            bye.setcSeqNumber(cSeq[0]);
            bye.setcSeqStr(cSeq[1]);
            bye.setContentLength(0);
            
            return bye;
        }
        else if(message.startsWith("ACK")){
            ACKMessage ack = new ACKMessage();
            
            ack.setDestination(parseRequestHeader(lines[0]));
            ack.setVias(vias);
            if(route!=null){
                ack.setRoute(route);
            }
            ack.setMaxForwards(Integer.parseInt(maxForwards));
            ack.setToName(to[0]);
            ack.setToUri(to[1]);
            ack.setFromName(from[0]);
            ack.setFromUri(from[1]);
            ack.setCallId(callId);
            ack.setcSeqNumber(cSeq[0]);
            ack.setcSeqStr(cSeq[1]);
            ack.setContentLength(0);
            
            return ack;
        }
        else if(message.startsWith("SIP/2.0 100 Trying")){
            TryingMessage trying = new TryingMessage();
            
            trying.setVias(vias);
            trying.setToName(to[0]);
            trying.setToUri(to[1]);
            trying.setFromName(from[0]);
            trying.setFromUri(from[1]);
            trying.setCallId(callId);
            trying.setcSeqNumber(cSeq[0]);
            trying.setcSeqStr(cSeq[1]);
            trying.setContentLength(0);
            
            return trying;
        }
        else if(message.startsWith("SIP/2.0 180 Ringing")){
            RingingMessage ringing = new RingingMessage();
            
            ringing.setVias(vias);
            if(recordRoute!=null){
                ringing.setRecordRoute(recordRoute);
            }
            ringing.setToName(to[0]);
            ringing.setToUri(to[1]);
            ringing.setFromName(from[0]);
            ringing.setFromUri(from[1]);
            ringing.setCallId(callId);
            ringing.setcSeqNumber(cSeq[0]);
            ringing.setcSeqStr(cSeq[1]);
            ringing.setContact(contact);
            ringing.setContentLength(0);
            
            return ringing;
            
        }
        else if(message.startsWith("SIP/2.0 200 OK")){
            OKMessage ok = new OKMessage();
            
            String[] parts = message.split("\n\n");
            
            
            ok.setVias(vias);
            if(route!=null){
                ok.setRoute(route);
            }
            if(recordRoute!=null){
                ok.setRecordRoute(recordRoute);
            }
            ok.setToName(to[0]);
            ok.setToUri(to[1]);
            ok.setFromName(from[0]);
            ok.setFromUri(from[1]);
            ok.setCallId(callId);
            ok.setcSeqNumber(cSeq[0]);
            ok.setcSeqStr(cSeq[1]);
            if(contact!=null){
                ok.setContact(contact);
            }
            ok.setContentLength(0);
            
            if(parts.length==2){
                //SDP message
                String sdpMessageStr = parts[1];
                ok.setContentLength(sdpMessageStr.length());
                SDPMessage sdp = new SDPMessage();
                sdp.parseMessage(sdpMessageStr);
                ok.setSdp(sdp);
            }
            
            return ok;
        }
        else if(message.startsWith("SIP/2.0 404 Not Found")){
            NotFoundMessage nf = new NotFoundMessage();
            
            nf.setVias(vias);
            nf.setToName(to[0]);
            nf.setToUri(to[1]);
            nf.setFromName(from[0]);
            nf.setFromUri(from[1]);
            nf.setCallId(callId);
            nf.setcSeqNumber(cSeq[0]);
            nf.setcSeqStr(cSeq[1]);
            nf.setContact(contact);
            if(expires!=null){
                nf.setExpires(expires);
            }
            nf.setContentLength(0);
            
            return nf;
        }
        else if(message.startsWith("SIP/2.0 408 Request Timeout")){
            RequestTimeoutMessage rt = new RequestTimeoutMessage();
            
            rt.setVias(vias);
            rt.setToName(to[0]);
            rt.setToUri(to[1]);
            rt.setFromName(from[0]);
            rt.setFromUri(from[1]);
            rt.setCallId(callId);
            rt.setcSeqNumber(cSeq[0]);
            rt.setcSeqStr(cSeq[1]);
            rt.setContentLength(0);
            
            return rt; 
        }
        else if(message.startsWith("SIP/2.0 486 Busy Here")){
            BusyHereMessage bh = new BusyHereMessage();
            
            bh.setVias(vias);
            bh.setToName(to[0]);
            bh.setToUri(to[1]);
            bh.setFromName(from[0]);
            bh.setFromUri(from[1]);
            bh.setCallId(callId);
            bh.setcSeqNumber(cSeq[0]);
            bh.setcSeqStr(cSeq[1]);
            bh.setContentLength(0);
            
            return bh;
        }
        else if(message.startsWith("SIP/2.0 503 Service Unavailable")){
            ServiceUnavailableMessage su = new ServiceUnavailableMessage();
            
            su.setVias(vias);
            su.setToName(to[0]);
            su.setToUri(to[1]);
            su.setFromName(from[0]);
            su.setFromUri(from[1]);
            su.setCallId(callId);
            su.setcSeqNumber(cSeq[0]);
            su.setcSeqStr(cSeq[1]);
            su.setContentLength(0);
            
            return su;
        }
        else if(message.startsWith("SIP/2.0 407 Proxy Authentication Required")){
            ProxyAuthenticationMessage pa = new ProxyAuthenticationMessage();
            
            pa.setVias(vias);
            pa.setToName(to[0]);
            pa.setToUri(to[1]);
            pa.setFromName(from[0]);
            pa.setFromUri(from[1]);
            pa.setCallId(callId);
            pa.setcSeqNumber(cSeq[0]);
            pa.setcSeqStr(cSeq[1]);
            pa.setproxyAuthenticate(proxyAuthenticate);
            pa.setContentLength(0);
            
            return pa;
        }
        else{
            throw new SIPException();
        }
        
        
    }
    
    
    /**
     * Parsea cada una de las líneas de Via del mensaje recibido, les quita la parte de Via: SIP/2.0/UDP y el resultado lo devuelve como String para que pueda ser añadido al ArrayList de las Vias del mensaje
    * 
     * @param via en el formato red recibido del mensaje SIP
     * @return 
     */
    private static String parseVia(String via) throws SIPException{
        Pattern pattern = Pattern.compile("Via: SIP/2.0/UDP ([\\w\\.\\:]+)");
        Matcher matcher = pattern.matcher(via);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect VIA format");
        }
    }
    
    /**
     * 
     * @param from
     * @return 
     */
    private static String[] parseFrom(String toFrom) throws SIPException{
        Pattern pattern = Pattern.compile("From: ?(\\w+)? <(sip:\\w+@[\\w\\.]+)>");
        Matcher matcher = pattern.matcher(toFrom);
        if(matcher.matches()){
            return  new String[]{matcher.group(1),matcher.group(2)};
        }
        else{
            throw new SIPException("Incorrect FROM format");
        }
    }
    
    /**
     * 
     * @param to
     * @return 
     */
    private static String[] parseTo(String toFrom)
throws SIPException{
        Pattern pattern = Pattern.compile("To: ?(\\w+)? <(sip:\\w+@[\\w\\.]+)>");
        Matcher matcher = pattern.matcher(toFrom);
        if(matcher.matches()){
            return  new String[]{matcher.group(1),matcher.group(2)};
        }
        else{
            throw new SIPException("Incorrect TO format");
        } 
    }
    
    /**
     * 
     * @param contact
     * @return 
     */
    private static String parseContact(String contact) throws SIPException{
        Pattern pattern = Pattern.compile("Contact: <sip:([\\w\\.\\:@]+)>");
        Matcher matcher = pattern.matcher(contact);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect CONTACT format");
        }
    }
    
    /**
     * 
     * @param cSeq
     * @return 
     */
    private static String[] parseCSeq(String cSeq) throws SIPException{
        Pattern pattern = Pattern.compile("CSeq: (\\d+) (INVITE|REGISTER|BYE|ACK)");
        Matcher matcher = pattern.matcher(cSeq);
        if(matcher.matches()){
            return  new String[]{matcher.group(1),matcher.group(2)};
        }
        else{
            throw new SIPException("Incorrect CSEQ format");
        }
    }
    
    /**
     * 
     * @param callId
     * @return 
     */
    private static String parseCallId(String callId) throws SIPException{
        Pattern pattern = Pattern.compile("Call-ID: ([a-zA-Z0-9@\\.\\-]+)");
        Matcher matcher = pattern.matcher(callId);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect CALL ID format");
        }
    }
    
    /**
     * 
     * @param contentLength
     * @return 
     */
    private static String parseContentLength(String contentLength) throws SIPException{
        Pattern pattern = Pattern.compile("Content-Length: (\\d+)");
        Matcher matcher = pattern.matcher(contentLength);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect CONTENT LENGTH format");
        }
    }
    
    /**
     * 
     * @param maxForwards
     * @return 
     */
    private static String parseMaxForwards(String maxForwards) throws SIPException{
        Pattern pattern = Pattern.compile("Max-Forwards: (\\d+)");
        Matcher matcher = pattern.matcher(maxForwards);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect MAX FORWARDS format");
        }
    }
    
    /**
     * 
     * @param recordRoute
     * @return 
     */
    private static String parseRecordRoute(String recordRoute) throws SIPException{
        Pattern pattern = Pattern.compile("Record-Route: ([\\w\\.\\:\\,\\s@]+)");
        Matcher matcher = pattern.matcher(recordRoute);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect RECORD ROUTE format");
        }
    }
    
    /**
     * 
     * @param route
     * @return 
     */
    private static String parseRoute(String route) throws SIPException{
        Pattern pattern = Pattern.compile("Route: ([\\w\\.\\:\\s\\,@]+)");
        Matcher matcher = pattern.matcher(route);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect ROUTE format");
        }
    }
    
    /**
     * 
     * @param header
     * @return 
     */
    private static String parseRequestHeader(String header) throws SIPException{
        Pattern pattern = Pattern.compile("(INVITE|REGISTER|BYE|ACK) (sip:[\\w\\.@]+) SIP/2.0");
        Matcher matcher = pattern.matcher(header);
        if(matcher.matches()){
            return  matcher.group(2);
        }
        else{
            throw new SIPException("Incorrect HEADER format");
        }
    }
    
    /**
     * 
     * @param expires
     * @return 
     */
    private static String parseExpires(String expires) throws SIPException{
        Pattern pattern = Pattern.compile("Expires: (\\d+)");
        Matcher matcher = pattern.matcher(expires);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect EXPIRES format");
        }
    }
    
    /**
     * 
     * @param proxyAuthenticate
     * @return 
     */
    private static String parseProxyAuthenticate(String proxyAuthenticate) throws SIPException{
        Pattern pattern = Pattern.compile("ProxyAuthenticate: nonce= ([\\w\\.\\:\\s\\,@]+)");
        Matcher matcher = pattern.matcher(proxyAuthenticate);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect ProxyAuthenticate format");
        }
    }
    /**
     * 
     * @param proxyAuthentication
     * @return 
     */
    private static String parseProxyAuthentication(String proxyAuthentication) throws SIPException{
        Pattern pattern = Pattern.compile("ProxyAuthentication: auth= ([\\w\\.\\:\\s\\,@]+)");
        Matcher matcher = pattern.matcher(proxyAuthentication);
        if(matcher.matches()){
            return  matcher.group(1);
        }
        else{
            throw new SIPException("Incorrect ProxyAuthentication format");
        }
    }
    
}
mensajesSIP/TryingMessage.java
mensajesSIP/TryingMessage.java
/*
 * Código de base para parsear mensajes SIP
 * Puede ser adaptado, ampliado, modificado por el alumno
 * según sus necesidades para la práctica
 */
package mensajesSIP;
import java.util.ArrayList;
/**
 *
 * @author SMA
 */
public class TryingMessage extends SIPMessage {
    private int contentLength;
    public ArrayList<String> getVias() {
        return vias;
    }
    public void setVias(ArrayList<String> vias) {
        this.vias = vias;
    }
    public String getToName() {
        return toName;
    }
    public void setToName(String toName) {
        this.toName = toName;
    }
    public String getToUri() {
        return toUri;
    }
    public void setToUri(String toUri) {
        this.toUri = toUri;
    }
    public String getFromName() {
        return fromName;
    }
    public void setFromName(String fromName) {
        this.fromName = fromName;
    }
    public String getFromUri() {
        return fromUri;
    }
    public void setFromUri(String fromUri) {
        this.fromUri = fromUri;
    }
    public String getCallId() {
        return callId;
    }
    public void setCallId(String callId) {
        this.callId = callId;
    }
    public String getcSeqNumber() {
        return cSeqNumber;
    }
    public void setcSeqNumber(String cSeqNumber) {
        this.cSeqNumber = cSeqNumber;
    }
    public String getcSeqStr() {
        return cSeqStr;
    }
    public void setcSeqStr(String cSeqStr) {
        this.cSeqStr = cSeqStr;
    }
    public int getContentLength() {
        return contentLength;
    }
    public void setContentLength(int contentLength) {
        this.contentLength = contentLength;
    }
    
    @Override
    public String toStringMessage() {
        String trying;
        trying = "SIP/2.0 100 Trying\n";
        for (int i=0; i<vias.size(); i++) {
            trying += "Via: SIP/2.0/UDP " + vias.get(i) + "\n";
        }
        if(toName!=null)

Continuar navegando