⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sipmanager.java.svn-base

📁 开源项目openfire的完整源程序
💻 SVN-BASE
📖 第 1 页 / 共 5 页
字号:
                Log.error("start", ex);

                throw new CommunicationsException(
                        "Could not create factories!\n", ex);
            }
            try {
                sipProvider.addSipListener(this);
            }
            catch (TooManyListenersException exc) {
                throw new CommunicationsException(
                        "Could not register SipManager as a sip listener!", exc);
            }

            // we should have a security authority to be able to handle
            // authentication
            if (sipSecurityManager.getSecurityAuthority() == null) {
                throw new CommunicationsException(
                        "No SecurityAuthority was provided to SipManager!");
            }

            // we should have also have a SubsciptionAuthority to be able to
            // handle
            // incoming Subscription requests.
            if (sipSecurityManager.getSecurityAuthority() == null) {
                throw new CommunicationsException(
                        "No SubscriptionAuthority was provided to SipManager!");
            }

            sipSecurityManager.setHeaderFactory(headerFactory);
            sipSecurityManager.setTransactionCreator(sipProvider);
            sipSecurityManager.setSipManCallback(this);

            // Make sure prebuilt headers are nulled so that they get reinited
            // if this is a restart
            contactHeader = null;
            fromHeader = null;
            viaHeaders = null;
            maxForwardsHeader = null;
            isStarted = true;
        }
        finally {

        }
    }

    /**
     * Unregisters listening points, deletes sip providers, and generally
     * prepares the stack for a re-start(). This method is meant to be used when
     * properties are changed and should be reread by the stack.
     *
     * @throws CommunicationsException
     */
    synchronized public void stop() throws CommunicationsException {
        try {
            if (registerProcessing != null)
                registerProcessing.cancelSchedules();

            if (sipStack == null)
                return;

            sipProvider.removeSipListener(this);

            // Delete SipProvider
            int tries = 0;
            for (tries = 0; tries < RETRY_OBJECT_DELETES; tries++) {
                try {
                    sipStack.deleteSipProvider(sipProvider);
                }
                catch (ObjectInUseException ex) {

                    sleep(RETRY_OBJECT_DELETES_AFTER);
                    continue;
                }
                break;
            }

            if (sipStack == null)
                return;

            if (tries >= RETRY_OBJECT_DELETES)
                throw new CommunicationsException(
                        "Failed to delete the sipProvider!");

            if (sipStack == null)
                return;

            // Delete RI ListeningPoint
            for (tries = 0; tries < RETRY_OBJECT_DELETES; tries++) {
                try {
                    sipStack.deleteListeningPoint(listeningPoint);
                }
                catch (ObjectInUseException ex) {
                    // Log.debug("Retrying delete of riListeningPoint!");
                    sleep(RETRY_OBJECT_DELETES_AFTER);
                    continue;
                }
                break;
            }

            if (sipStack != null) {

                for (Iterator it = sipStack.getSipProviders(); it.hasNext();) {
                    SipProvider element = (SipProvider) it.next();
                    try {
                        sipStack.deleteSipProvider(element);
                    }
                    catch (Exception e) {

                    }
                }
            }
            if (tries >= RETRY_OBJECT_DELETES)
                throw new CommunicationsException(
                        "Failed to delete a listeningPoint!");

            listeningPoint = null;
            addressFactory = null;
            messageFactory = null;
            headerFactory = null;
            sipStack = null;

            registrarAddress = null;
            securityAuthority = null;
            viaHeaders = null;
            contactHeader = null;
            fromHeader = null;

            NetworkAddressManager.shutDown();

        }
        finally {
            isStarted = false;
        }
    }

    /**
     * Waits during _no_less_ than sleepFor milliseconds. Had to implement it on
     * top of Thread.sleep() to guarantee minimum sleep time.
     *
     * @param sleepFor the number of miliseconds to wait
     */
    protected static void sleep(long sleepFor) {
        long startTime = System.currentTimeMillis();
        long haveBeenSleeping = 0;
        while (haveBeenSleeping < sleepFor) {
            try {
                Thread.sleep(sleepFor - haveBeenSleeping);
            }
            catch (InterruptedException ex) {
                // we-ll have to wait again!
            }
            haveBeenSleeping = (System.currentTimeMillis() - startTime);
        }
    }

    /**
     * @param uri the currentlyUsedURI to set.
     */
    public void setCurrentlyUsedURI(String uri) {
        this.currentlyUsedURI = uri;
    }

    /**
     * Get the currently used SIP username
     */
    public String getCurrentUsername() {
        return this.username;
    }

    /**
     * Causes the RegisterProcessing object to send a registration request to
     * the registrar defined in net.java.mais.sip.REGISTRAR_ADDRESS and to
     * register with the address defined in the net.java.mais.sip.PUBLIC_ADDRESS
     * property
     *
     * @throws CommunicationsException if an exception is thrown by the underlying stack. The
     *                                 exception that caused this CommunicationsException may be
     *                                 extracted with CommunicationsException.getCause()
     */
    public void register() throws CommunicationsException {
        register(currentlyUsedURI);
    }

    /**
     * Registers using the specified public address.
     *
     * @param sipServerAddress the address of the server.
     * @throw CommunicationsException
     */
    public void register(String sipServerAddress) throws CommunicationsException {
        try {

            if (sipServerAddress == null || sipServerAddress.trim().length() == 0) {
                Log.debug("PUBLIC NOT FOUND!");
                throw new CommunicationsException("Public address NOT FOUND");
            }

            // Handle default domain name (i.e. transform 1234 -> 1234@sip.com
            String defaultDomainName = SIPConfig.getDefaultDomain();

            if (sipServerAddress.toLowerCase().indexOf("sipphone.com") != -1
                    || (defaultDomainName != null && defaultDomainName
                    .indexOf("sipphone.com") != -1)) {
                StringBuffer buff = new StringBuffer(sipServerAddress);
                int nameEnd = sipServerAddress.indexOf('@');
                nameEnd = nameEnd == -1 ? Integer.MAX_VALUE : nameEnd;
                nameEnd = Math.min(nameEnd, buff.length()) - 1;

                int nameStart = sipServerAddress.indexOf("sip:");
                nameStart = nameStart == -1 ? 0 : nameStart + "sip:".length();

                for (int i = nameEnd; i >= nameStart; i--)
                    if (!Character.isLetter(buff.charAt(i))
                            && !Character.isDigit(buff.charAt(i)))
                        buff.deleteCharAt(i);
                sipServerAddress = buff.toString();
            }

            // if user didn't provide a domain name in the URL and someone
            // has defined the DEFAULT_DOMAIN_NAME property - let's fill in the
            // blank.
            if (defaultDomainName != null && sipServerAddress.indexOf('@') == -1) {
                sipServerAddress = sipServerAddress + "@" + defaultDomainName;

            }

            if (!sipServerAddress.trim().toLowerCase().startsWith("sip:")) {
                sipServerAddress = "sip:" + sipServerAddress;
            }

            this.currentlyUsedURI = sipServerAddress;

            registerProcessing.register(registrarAddress, registrarPort, registrarTransport, registrationsExpiration);
        }
        catch (Exception e) {
            fireRegistrationFailed(registrarAddress, RegistrationEvent.Type.TimeOut);
            Log.error("register", e);
        }
    }

    public void startRegisterProcess(String userName, String authUserName,
                                     String password) throws CommunicationsException {

        try {

            SIPTransaction.setRegisterTimeout(10);

            //registerRetries = 0;

            checkIfStarted();

            // Obtain initial credentials
            Credentials defaultCredentials = new Credentials();

            this.username = userName;

            defaultCredentials.setUserName(userName);
            defaultCredentials.setPassword(password.toCharArray());

            defaultCredentials
                    .setAuthUserName(authUserName != null ? authUserName
                            : userName);

            String realm = SIPConfig.getAuthenticationRealm();
            realm = realm == null ? "" : realm;

            Credentials initialCredentials = securityAuthority
                    .obtainCredentials(realm, defaultCredentials);

            SIPConfig.setUserName(initialCredentials.getUserName());
            SIPConfig.setAuthUserName(initialCredentials.getAuthUserName());

            register(initialCredentials.getUserName());

            // at this point a simple register request has been sent and the
            // global
            // from header in SipManager has been set to a valid value by the
            // RegisterProcesing
            // class. Use it to extract the valid user name that needs to be
            // cached by
            // the security manager together with the user provided password.

            //initialCredentials.setUserName(((SipURI) getFromHeader().getAddress().getURI()).getUser());

            cacheCredentials(realm, initialCredentials);

        }
        catch (Exception ee) {
            Log.error("startRegisterProcess", ee);
        }
    }

    /**
     * Causes the PresenceAgent object to notify all subscribers of our brand
     * new offline status and the RegisterProcessing object to send a
     * registration request with a 0 "expires" interval to the registrar defined
     * in net.java.mais.sip.REGISTRAR_ADDRESS.
     *
     * @throws CommunicationsException if an exception is thrown by the underlying stack. The
     *                                 exception that caused this CommunicationsException may be
     *                                 extracted with CommunicationsException.getCause()
     */
    public void unregister() throws CommunicationsException {
        try {
            checkIfStarted();
            if (!isRegistered()) {
                return;
            }
            registerProcessing.unregister();
            fireUnregistered(registrarAddress == null ? "" : registrarAddress);
        }
        catch (Exception e) {
            Log.error("unregister", e);
        }
    }

    private boolean registrationFailed(RegistrationEvent.Type type) {
        try {
            //if (RegistrationEvent.Type.TimeOut.equals(type))
            if (registerRetries++ < 2) {
                stop();
                while (isStarted()) ;
                start();
                while (!isStarted()) ;
                register();
                return false;
            } else {
                if (NetworkAddressManager.nextIndex()) {
                    stop();
                    start();
                    registerRetries = 0;
                    register();
                    return false;
                }
            }
        }
        catch (Exception e) {
            Log.error("unregister", e);
        }
        return true;
    }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -