2015-05-12 2 views
0

У меня вопрос об аутентификации с jain sip library. Я использую jain sip для регистрации учетных записей sip на сервере Asterisk. Как только я пытаюсь добавить AuthorizationHeader следующее сообщение об ошибке появляется:sip заголовок авторизации не может быть добавлен

The method makeAuthHeader(HeaderFactory, Response, Request, String, String) is undefined for the type Utils

Вот фрагмент кода:

AuthorizationHeader authHeader = Utils.makeAuthHeader(
       headerFactory, response, request, userId, password); 
     request.addHeader(authHeader); 

Кажется, что может не метод makeAuthHeader() не может быть найден.

Код SipClientServiceImpl.java:

@Service("clientService") 
public class SipClientServiceImpl implements SipClientService, SipListener { 

    SipFactory sipFactory; // Used to access the SIP API. 
    SipStack sipStack; // The SIP stack. 
    SipProvider sipProvider; // Used to send SIP messages. 
    MessageFactory messageFactory; // Used to create SIP message factory. 
    HeaderFactory headerFactory; // Used to create SIP headers. 
    AddressFactory addressFactory; // Used to create SIP URIs. 
    ListeningPoint listeningPoint; // SIP listening IP address/port. 
    Properties properties; // Other properties. 

    // Objects keeping local configuration. 
    String ip; // The local IP address. 
    int port = 6060; // The local port. 
    String protocol = "udp"; // The local protocol (UDP). 
    int tag = (new Random()).nextInt(); // The local tag. 
    Address contactAddress; // The contact address. 
    ContactHeader contactHeader; 
    String asteriskServer = "10.0.0.0.0"; 
    int asteriksPort = 5060; 
    String sipPasswordForAllAccounts = "1234"; 
    Request request = null; 
    Response response = null; 

    private ClientTransaction inviteTid; 
    long invco = 1; 

    public void registerToAsterisk(String userId) throws ParseException, 
      InvalidArgumentException, PeerUnavailableException, 
      TransportNotSupportedException, ObjectInUseException, 
      TooManyListenersException { 
     init(); 
     try { 
      // Get the destination address from the text field. 
      Address addressTo = addressFactory.createAddress("sip:" + userId 
        + '@' + asteriskServer + ":" + asteriksPort); 

      // Create the request URI for the SIP message. 
      javax.sip.address.URI requestURI = addressTo.getURI(); 

      // Create the SIP message headers. 

      // The "Via" headers. 
      ArrayList viaHeaders = new ArrayList(); 
      ViaHeader viaHeader = this.headerFactory.createViaHeader(this.ip, 
        this.port, "udp", null); 
      viaHeaders.add(viaHeader); 
      // The "Max-Forwards" header. 
      MaxForwardsHeader maxForwardsHeader = this.headerFactory 
        .createMaxForwardsHeader(70); 
      // The "Call-Id" header. 
      CallIdHeader callIdHeader = this.sipProvider.getNewCallId(); 
      // The "CSeq" header. 
      CSeqHeader cSeqHeader = this.headerFactory.createCSeqHeader(1L, 
        "REGISTER"); 
      // The "From" header. 
      FromHeader fromHeader = this.headerFactory.createFromHeader(
        this.contactAddress, String.valueOf(this.tag)); 
      // The "To" header. 
      ToHeader toHeader = this.headerFactory.createToHeader(addressTo, 
        null); 

      // AuthorizationHeader authHeader = Utils.makeAuthHeader(
      // headerFactory, response, request, userId, 
      // sipPasswordForAllAccounts); 

      // Create the REGISTER request. 
      Request request = this.messageFactory.createRequest(requestURI, 
        "REGISTER", callIdHeader, cSeqHeader, fromHeader, toHeader, 
        viaHeaders, maxForwardsHeader); 
      // Add the "Contact" header to the request. 
      request.addHeader(contactHeader); 
      // request.addHeader(authHeader); 

      // Send the request statelessly through the SIP provider. 
      this.sipProvider.sendRequest(request); 

     } catch (Exception e) { 
      // TODO: handle exception 
     } 
     // TODO Auto-generated method stub 

    } 

    public void processRequest(RequestEvent requestEvent) { 

    } 

    public void processResponse(ResponseEvent responseEvent) { 
     Response response = responseEvent.getResponse(); 
     System.out.println(response); 
     ClientTransaction tid = responseEvent.getClientTransaction(); 
     CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME); 

     System.out.println("Response received : Status Code = " 
       + response.getStatusCode() + " " + cseq); 
     // if (tid == null) { 
     // System.out.println("Stray response -- dropping "); 
     // return; 
     // } 
     try { 
      if (response.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED 
        || response.getStatusCode() == Response.UNAUTHORIZED) { 
       AuthenticationHelper authenticationHelper = ((SipStackExt) sipStack) 
         .getAuthenticationHelper(new AccountManagerImpl(), 
           headerFactory); 
       inviteTid = authenticationHelper.handleChallenge(response, tid, 
         sipProvider, 5, false); 
       inviteTid.sendRequest(); 
       invco++; 
      } 

     } catch (Exception ex) { 
      ex.printStackTrace(); 
      System.exit(0); 
     } 

    } 

    public void processTimeout(TimeoutEvent timeoutEvent) { 
     // TODO Auto-generated method stub 

    } 

    public void processIOException(IOExceptionEvent exceptionEvent) { 
     // TODO Auto-generated method stub 

    } 

    public void processTransactionTerminated(
      TransactionTerminatedEvent transactionTerminatedEvent) { 
     // TODO Auto-generated method stub 

    } 

    public void processDialogTerminated(
      DialogTerminatedEvent dialogTerminatedEvent) { 
     // TODO Auto-generated method stub 

    } 

    public void init() { 
     // Get the local IP address. 
     try { 
      this.ip = InetAddress.getLocalHost().getHostAddress(); 
      // Create the SIP factory and set the path name. 
      this.sipFactory = SipFactory.getInstance(); 
      this.sipFactory.setPathName("gov.nist"); 
      // Create and set the SIP stack properties. 
      this.properties = new Properties(); 
      this.properties.setProperty("javax.sip.STACK_NAME", "stack"); 
      // Create the SIP stack. 
      this.sipStack = this.sipFactory.createSipStack(this.properties); 
      // Create the SIP message factory. 
      this.messageFactory = this.sipFactory.createMessageFactory(); 
      // Create the SIP header factory. 
      this.headerFactory = this.sipFactory.createHeaderFactory(); 
      // Create the SIP address factory. 
      this.addressFactory = this.sipFactory.createAddressFactory(); 
      // Create the SIP listening point and bind it to the local IP 
      // address, port and protocol. 
      this.listeningPoint = this.sipStack.createListeningPoint(this.ip, 
        this.port, this.protocol); 
      // Create the SIP provider. 
      this.sipProvider = this.sipStack 
        .createSipProvider(this.listeningPoint); 
      // Add our application as a SIP listener. 
      this.sipProvider.addSipListener(this); 
      // Create the contact address used for all SIP messages. 
      this.contactAddress = this.addressFactory.createAddress("sip:" 
        + this.ip + ":" + this.port); 
      // Create the contact header used for all SIP messages. 
      this.contactHeader = this.headerFactory 
        .createContactHeader(contactAddress); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 

Стек след:

javax.sip.SipException: Unexpected exception 
at gov.nist.javax.sip.clientauthutils.AuthenticationHelperImpl.handleChallenge(AuthenticationHelperImpl.java:298) 
at com.musala.ving.voip.SipClientServiceImpl.processResponse(SipClientServiceImpl.java:152) 
at gov.nist.javax.sip.EventScanner.deliverEvent(EventScanner.java:296) 
at gov.nist.javax.sip.EventScanner.run(EventScanner.java:519) 
at java.lang.Thread.run(Unknown Source) 

Вызванный: java.lang.NullPointerException на gov.nist.javax.sip.clientauthutils.AuthenticationHelperImpl.handleChallenge (AuthenticationHelperImpl.java:149) ... 4 еще

Любое предложение оценено!

Спасибо!

+0

Трудно сказать, что происходит, как Utils это на самом деле не API. Этот пример должен помочь вам https://svn.java.net/svn/jsip~svn/trunk/src/examples/authorization/ShootistAuth.java. В противном случае отправьте полный код и журналы, –

+0

Спасибо за ваш ответ! Сообщение отредактировано – skywalker

ответ

1

Ну, Utils не является частью API, и у него просто нет метода, который вы пытаетесь использовать. Лучший способ сделать клиент авторизацию, чтобы использовать пример из https://svn.java.net/svn/jsip~svn/trunk/src/examples/authorization/ShootistAuth.java

Это соответствующая часть:

if (response.getStatusCode() == Response.PROXY_AUTHENTICATION_REQUIRED 
        || response.getStatusCode() == Response.UNAUTHORIZED) { 
       AuthenticationHelper authenticationHelper = 
        ((SipStackExt) sipStack).getAuthenticationHelper(new AccountManagerImpl(), headerFactory); 

       inviteTid = authenticationHelper.handleChallenge(response, tid, sipProvider, 5); 

       inviteTid.sendRequest(); 

       invco++; 
      } 
+0

Спасибо за ваш ответ – skywalker

+0

Нужно ли добавить следующий код в метод public void processResponse (ResponseEvent responseEvent'? По какой-то причине он не позволяет мне регистрироваться даже после выполнения шагов в фрагменте:/ – skywalker

+1

Скорее всего, да, но это зависит. Если вы делаете регистрацию, обязательно настройте код так, чтобы он выполнял транзакцию REGISTER, а не INVITE. –

0

Класс Utils не принадлежит этот метод, как вы можете увидеть здесь: http://grepcode.com/file/repo1.maven.org/maven2/javax.sip/jain-sip-ri/1.2.203/gov/nist/javax/sip/Utils.java Вы должны использовать что-то другое, но я не могу найти ничего о том, что класс/метод для использования.

+0

Ну, я это заметил. Вот почему задаю вопрос здесь :) Спасибо – skywalker