Package com.ericsson.ssa.sip

Source Code of com.ericsson.ssa.sip.AddressImpl

/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2009 Sun Microsystems, Inc. All rights reserved.
* Copyright (c) Ericsson AB, 2004-2008. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License").  You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code.  If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license."  If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above.  However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package com.ericsson.ssa.sip;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;

import java.util.Iterator;

import javax.servlet.sip.Address;
import javax.servlet.sip.ServletParseException;
import javax.servlet.sip.SipFactory;
import javax.servlet.sip.SipURI;
import javax.servlet.sip.URI;

import com.ericsson.ssa.container.SipBindingCtx;
import com.ericsson.ssa.container.SipBindingResolver;
import com.ericsson.ssa.sip.dns.TargetTuple;
import java.net.InetSocketAddress;


/**
* @author ekrigro
*/
public class AddressImpl extends ParameterableImpl implements Address,
    Serializable {
    private static final long serialVersionUID = 3761123855715873593L;
    static String DUPLICATE_PARAM = "The parsed Name Address has two parameter with the same name : ";
    public static final String Q_PARAM = "q";
    public static final String EXPIRES_PARAM = "expires";
    public static final String TAG_PARAM = "tag";
    transient private static SipFactory sf = SipFactoryImpl.getInstance();
    private String _displayName;
    private URI _uri;
    private boolean _wildcard = false;

    private static final String LOCALHOST = "localhost";
    private static final String LOCALIP = "127.0.0.1";


    private AddressImpl() {
    }

    public AddressImpl(String na) throws ServletParseException {
        if (na.trim().equals("*")) {
            _wildcard = true;
        } else {
           /* byte[] bytes = null;

            try {
                bytes = na.getBytes(SipFactoryImpl.SIP_CHARSET);
            } catch (UnsupportedEncodingException e) {
            }
            */

            parse(na, 0, na.length());
        }
    }

    public AddressImpl(URI uri) {
        _uri = uri;
    }

    private void writeObject(ObjectOutputStream stream)
        throws IOException {
        try {
            stream.defaultWriteObject();
        } catch (Exception ignore) {
        }
    }

    private void readObject(ObjectInputStream stream) throws IOException {
        try {
            // stream.registerValidation(this, 0);
            stream.defaultReadObject();
            sf = SipFactoryImpl.getInstance();
        } catch (Exception ignore) {
            ignore.printStackTrace();
        }
    }

    // From: "A. G. Bell" <sip:agb@bell-telephone.com> ;tag=a48s
    // From: sip:+12125551212@server.phone2net.com;tag=887s
    // f: Anonymous <sip:c8oqz84zk7z@privacy.org>;tag=hyh8
     private void parse(String na, int offset, int length)
        throws ServletParseException {
        int leftDquoteIndex = -1;
        int rightDquoteIndex = -1;
        int laquotIndex = -1;
        int raquotIndex = -1;
        int semiIndex = -1;
        int quoteCnt = 0;

        for (int i = offset; i < length; i++) {
            if (na.charAt(i) == '"') {
                quoteCnt++;

                if (laquotIndex == -1) {
                    if (leftDquoteIndex == -1) {
                        leftDquoteIndex = i;
                    } else if (rightDquoteIndex < 0) {
                        rightDquoteIndex = i;
                    }
                }
            } else if ((laquotIndex == -1) && (na.charAt(i) == '<') &&
                    ((quoteCnt % 2) == 0)) {
                laquotIndex = i;
            } else if ((raquotIndex == -1) && (na.charAt(i) == '>') &&
                    ((quoteCnt % 2) == 0)) {
                raquotIndex = i;
            } else if ((na.charAt(i) == ';') && (semiIndex < 0) &&
                    ((quoteCnt % 2) == 0)) {
                if (laquotIndex >= 0) {
                    if ((raquotIndex > 0) && (i > raquotIndex)) // Set only if there
                                                                // is
                                                                // a closing >
                    {
                        semiIndex = i;
                        break;
                    }
                } else {
                    semiIndex = i; // we don't have any <>
                    break;
                }
            }
        }

        if (((laquotIndex == -1) && (raquotIndex > 0)) ||
                ((laquotIndex > 0) && (raquotIndex == -1))) {
            throw new ServletParseException("invalid nr of > or <");
        }

        // TODO - Maybe a way to remove the trim()
        try {
            // Taking care of Display name
            if (rightDquoteIndex > -1) {
                // There is a displayname in quotes
                _displayName = na.substring(leftDquoteIndex + 1,
                        rightDquoteIndex);
                offset = rightDquoteIndex + 1;
            } else if (laquotIndex > -1) {
                // There could be a display name without quotes
                _displayName = na.substring(offset, laquotIndex).trim();
                offset = laquotIndex;
            }

            if (laquotIndex > -1) {
                // The URI is behind <>
                // TODO send the buffer without doing string
                String uri = na.substring(laquotIndex + 1,
                        raquotIndex);
                // _uri = new ()
                _uri = sf.createURI(uri);

                // After there are possible NA parameters
            } else {
                // There is only a URI
                // TODO send the buffer without doing string
                int endIndex = semiIndex;

                if (endIndex < 0) {
                    endIndex = length;
                }

                String uri = na.substring(offset, endIndex).trim();
                // _uri = new ()
                _uri = sf.createURI(uri);

                // After there are possible NA parameters
            }

            offset = semiIndex + 1;

            if (semiIndex > 0) {
                byte[] bytes = na.getBytes(SipFactoryImpl.SIP_CHARSET);
                // There might be more bytes than characters due to UTF-8 conversion from string to bytes.
                // As a consequence the semiIndex may have been pushed away. Search from the current position and forward.
                for (int i = semiIndex; i < bytes.length; i++) {
                    if (bytes[i] == ';') {
                        semiIndex = i;
                        break;
                    }
                }
                int numBytes = bytes.length - semiIndex;
                setParameterByteMap(na.getBytes(SipFactoryImpl.SIP_CHARSET), semiIndex, numBytes, ';');
            }
        } catch (UnsupportedEncodingException uee) {
        } // C.C.L.
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#getDisplayName()
     */
    public String getDisplayName() {
        return _displayName;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#setDisplayName(java.lang.String)
     */

    // If should be pretty print no "" should be there if it's only one word
    public void setDisplayName(String dn) {
        if (_wildcard) {
            throw new IllegalStateException(
                "Cannot set display name on wildcard address");
        }

        verify();

        _displayName = dn;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#getURI()
     */
    public URI getURI() {
        if (_wildcard) {
            (new Throwable()).printStackTrace();

            return null;
        } else {
            if (_uri != null) {
               ((URIImpl) _uri).setModifiable(isModifiable());
            }
            return _uri;
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#setURI(javax.servlet.sip.URI)
     */
    public void setURI(URI uri) {
        if (uri == null)
            throw new NullPointerException("URI argument is null");
        if (_wildcard) {
            throw new IllegalStateException(
                "Cannot set URI on wildcard address");
        }

        verify();

        _uri = uri;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#setParameter(java.lang.String,
     *      java.lang.String)
     */
    @Override
    public void setParameter(String param, String value) {
        if (_wildcard) {
            throw new IllegalStateException(
                "Cannot set parameter on wildcard address");
        }

        super.setParameter(param, value);
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#removeParameter(java.lang.String)
     */
    @Override
    public void removeParameter(String param) {
        if (_wildcard) {
            throw new IllegalStateException(
                "Cannot set parameter on wildcard address");
        }

        super.removeParameter(param);
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#isWildcard()
     */
    public boolean isWildcard() {
        return _wildcard;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#getQ()
     */
    public float getQ() {
        float q = (float) -1.0;
        String value = getParameter(Q_PARAM);

        if (value != null) {
            try {
                q = Float.parseFloat(value);
            } catch (Exception e) {
            } // Bad luck :-)
        }

        return q;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#setQ(float)
     */
    public void setQ(float value) {
        if ((value >= 0f) && (value <= 1f)) {
            setParameter(Q_PARAM, String.valueOf(value));
        } else {
            if (value == -1.0f) {
                removeParameter(Q_PARAM);
            } else {
                throw new IllegalArgumentException(
                    "Q Value should be in interval [0,1] or be -1 for removal");
            }
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#getExpires()
     */
    public int getExpires() {
        int expires = -1;
        String value = getParameter(EXPIRES_PARAM);

        if (value != null) {
            try {
                expires = Integer.parseInt(value);
            } catch (Exception e) {
            } // Bad luck :-)
        }

        return expires;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.servlet.sip.Address#setExpires(int)
     */
    public void setExpires(int value) {
        if (value < 0) {
            removeParameter(EXPIRES_PARAM);
        } else {
            setParameter(EXPIRES_PARAM, String.valueOf(value));
        }
    }

    /**
     * Returns a clone of this AddressImpl instance. The clone will be equal to
     * its original, except that it will have no tag parameter. This is the
     * implementation of the javax.servlet.sip.Address.clone() method. Also it
     * will not have the readOnly property, since an application may wish to
     * modify the clone even if it was created from a System Header address
     * object.
     */
    public Object clone() {
        return clone(false, false);
    }

    /**
     * Returns a clone of this AddressImpl instance. The clone will be equal to
     * its original, except that if copyTag is false it will have no tag
     * parameter. If copyReadyOnly is true the clone will have the same _readOnly
     * property as the original, otherwise the clone will be writable.
     */
    public Object clone(boolean copyTag, boolean copyReadOnly) {
        AddressImpl newAddress = (AddressImpl) super.clone(copyReadOnly);
        newAddress._displayName = _displayName;
        newAddress._uri = _uri;
        newAddress._wildcard = _wildcard;

        // Remove Tag parameter if it should be removed
        if ((!copyTag) && (!_wildcard)) {
            // Save readOnly status
            boolean saveReadOnly = newAddress.isReadOnly();
            newAddress.setReadOnly(false);
            // Remove the tag parameter
            newAddress.removeParameter(TAG_PARAM);
            newAddress.setReadOnly(saveReadOnly);
        }

        return newAddress;
    }

    /**
     * Compare Address according to rfc3261 specification for To and From
     * headers.
     *
     * Two From header fields are equivalent if their URIs match, and their
     * parameters match. Extension parameters in one header field, not present in
     * the other are ignored for the purposes of comparison. This means that the
     * display name and presence or absence of angle brackets do not affect
     * matching. Comparison of To header fields for equality is identical to
     * comparison of From header fields.
     *
     * Assume all Address objects can be compared in this way and only compare
     * URI and parameter parts. Skip to compare the display name.
     */
    public boolean equals(Object o) {
        if (o == null) {
            return false;
        }

        if (this == o) {
            return true;
        }

        if (!(o instanceof Address)) {
            return false;
        }

        Address a = (Address) o;

        if (!_uri.equals(a.getURI())) {
            return false;
        }

        if (_wildcard != a.isWildcard()) {
            return false;
        }

        // compare parameters
        if (a instanceof Address) {
            if (!super.equals(a)) {
                return false;
            }
        }

        return true;
    }

    /*
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    public String toString() {
        if (_wildcard) {
            return "*";
        }

        StringBuilder sb = new StringBuilder();

        if ((_displayName != null) && (_displayName.length() > 0)) {
            sb.append('"');
            sb.append(_displayName);
            sb.append('"');
        }

        sb.append('<');
        sb.append(_uri);
        sb.append('>');
        // Duplicated in SipURIImpl
        // if (_parameters != null && !_parameters.isEmpty())
        sb.append(super.toString());

        return sb.toString();
    }

    @Override
    public String  getValue() {
        if (_wildcard) {
            return new String("*");
        }

        StringBuilder sb = new StringBuilder();

        if ((_displayName != null) && (_displayName.length() > 0)) {
            sb.append('"');
            sb.append(_displayName);
            sb.append('"');
        }

        sb.append('<');
        sb.append(_uri);
        sb.append('>');
        return sb.toString();
      }

    void modifyContactParameters(Address other) {
        Iterator<String> otherParamNames = other.getParameterNames();

        while (otherParamNames.hasNext()) {
            String paramName = otherParamNames.next();
            setParameter(paramName, other.getParameter(paramName));
        }

        URIImpl otherUri = (URIImpl) other.getURI();
        Iterator<String> otherURIParamNames = otherUri.getParameterNames();
        URIImpl uri = (URIImpl) getURI();

        while (otherURIParamNames.hasNext()) {
            String paramName = otherURIParamNames.next();

            if (!paramName.equals("method") && !paramName.equals("ttl") &&
                    !paramName.equals("maddr") && !paramName.equals("lr")) {
                uri.setParameter(paramName, otherUri.getParameter(paramName));
            }
        }

        if (uri instanceof SipURI && otherUri instanceof SipURI) {
            ((SipURI) uri).setUser(((SipURI) otherUri).getUser());
        }
    }
   
    private boolean isAddressPresent(SipBindingCtx sipBindingCtx,
            String host, int port) {
        TargetTuple[] tts = sipBindingCtx.getTargetTuples();
        for (TargetTuple tt : tts) {
            InetSocketAddress isa =
                    new InetSocketAddress(host, port);
            if (isa.equals(tt.getSocketAddress())) {
                return true;
            }
        }
        return false;
    }
   
    public boolean isContainerAddress() {
        boolean found = false;
        if (!this.isWildcard()) {
            URI uri = this.getURI();

            // Check if the URI contains one of the listeners.
            if (uri.isSipURI()) {
                SipURI sipUri = (SipURI) uri;
                String host = sipUri.getHost();
                int port = sipUri.getPort();
                for (String publiccontext : SipBindingResolver.instance().
                        getPublicContexts()) {
                    SipBindingCtx sipBindingCtx = SipBindingResolver.instance().
                            getPublicContext(publiccontext);
                    found = isAddressPresent(sipBindingCtx, host, port);
                }
            }
        }
        return found;
    }

    public boolean isLocal() {
        boolean local = false;
        if (!this.isWildcard()) {
            URI uri = this.getURI();

            // Check if the URI contains localhost or 127.0.0.1
            if (uri.isSipURI()) {
                SipURI sipUri = (SipURI) uri;
                String host = sipUri.getHost();

                if (host.equalsIgnoreCase(LOCALHOST) ||
                        host.equals(LOCALIP)) {
                    // Fetch port from request (use 5060 if port is missing)
                    int port = sipUri.getPort();

                    if (port != -1) {
                        // Fetch valid ports
                        SipBindingCtx sipBindingCtx = SipBindingResolver.instance()
                        .getActiveExternalContext();

                        TargetTuple[] tt = sipBindingCtx.getTargetTuples();

                        // Check if port in request is one of the valid ones
                        for (int i = 0; i < tt.length; i++) {
                            if (port == tt[i].getPort()) {
                                local = true;

                                break;
                            }
                        }
                    } else {
                        local = true;
                    }
                }
            }
        }
        return local;
    }
}
TOP

Related Classes of com.ericsson.ssa.sip.AddressImpl

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.