Example #1
0
  /**
   * Shares a geolocation with a contact. An exception if thrown if there is no ongoing CS call. The
   * parameter contact supports the following formats: MSISDN in national or international format,
   * SIP address, SIP-URI or Tel-URI. If the format of the contact is not supported an exception is
   * thrown.
   *
   * @param contact Contact
   * @param geoloc Geolocation info
   * @param listener Geoloc sharing event listener
   * @return Geoloc sharing
   * @throws ServerApiException
   */
  public IGeolocSharing shareGeoloc(String contact, Geoloc geoloc, IGeolocSharingListener listener)
      throws ServerApiException {
    if (logger.isActivated()) {
      logger.info("Initiate a geoloc sharing session with " + contact);
    }

    // Test IMS connection
    ServerApiUtils.testIms();

    try {
      // Create a geoloc content
      String msgId = ChatUtils.generateMessageId();
      GeolocPush geolocPush =
          new GeolocPush(
              geoloc.getLabel(),
              geoloc.getLatitude(),
              geoloc.getLongitude(),
              geoloc.getExpiration(),
              geoloc.getAccuracy());
      String geolocDoc =
          ChatUtils.buildGeolocDocument(
              geolocPush, ImsModule.IMS_USER_PROFILE.getPublicUri(), msgId);
      MmContent content =
          new GeolocContent("geoloc.xml", geolocDoc.getBytes().length, geolocDoc.getBytes());

      // Initiate a sharing session
      final GeolocTransferSession session =
          Core.getInstance()
              .getRichcallService()
              .initiateGeolocSharingSession(contact, content, geolocPush);

      // Add session listener
      GeolocSharingImpl sessionApi = new GeolocSharingImpl(session);
      sessionApi.addEventListener(listener);

      // Start the session
      Thread t =
          new Thread() {
            public void run() {
              session.startSession();
            }
          };
      t.start();

      // Add session in the list
      addGeolocSharingSession(sessionApi);
      return sessionApi;
    } catch (Exception e) {
      if (logger.isActivated()) {
        logger.error("Unexpected error", e);
      }
      throw new ServerApiException(e.getMessage());
    }
  }
  /**
   * Initiate a geoloc sharing session
   *
   * @param contact Contact
   * @param geoloc Geoloc info
   * @return Geoloc sharing session
   * @throws ServerApiException
   */
  public IGeolocSharingSession initiateGeolocSharing(String contact, GeolocPush geoloc)
      throws ServerApiException {
    if (logger.isActivated()) {
      logger.info("Initiate a geoloc sharing session with " + contact);
    }

    // Check permission
    ServerApiUtils.testPermission();

    // Test IMS connection
    ServerApiUtils.testIms();

    try {
      // Create a geoloc content
      String msgId = ChatUtils.generateMessageId();
      String geolocDoc =
          ChatUtils.buildGeolocDocument(geoloc, ImsModule.IMS_USER_PROFILE.getPublicUri(), msgId);
      MmContent content =
          new GeolocContent("geoloc.xml", geolocDoc.getBytes().length, geolocDoc.getBytes());

      // Initiate a sharing session
      GeolocTransferSession session =
          Core.getInstance()
              .getRichcallService()
              .initiateGeolocSharingSession(contact, content, geoloc);

      // Update rich call
      RichCall.getInstance()
          .addCall(
              contact,
              session.getSessionID(),
              RichCallData.EVENT_OUTGOING,
              session.getContent(),
              RichCallData.STATUS_STARTED);

      // Update rich messaging history
      GeolocMessage geolocMsg = new GeolocMessage(null, contact, geoloc, false);
      RichMessaging.getInstance().addOutgoingGeoloc(geolocMsg);

      // Add session in the list
      GeolocSharingSession sessionApi = new GeolocSharingSession(session);
      addGeolocSharingSession(sessionApi);
      return sessionApi;
    } catch (Exception e) {
      if (logger.isActivated()) {
        logger.error("Unexpected error", e);
      }
      throw new ServerApiException(e.getMessage());
    }
  }
  /** Send the file transfer information */
  private void sendFileTransferInfo() {
    // Send File transfer Info
    String mime = CpimMessage.MIME_TYPE;
    String from = ImsModule.IMS_USER_PROFILE.getPublicUri();
    String to = ChatUtils.ANOMYNOUS_URI;
    String msgId = IdGenerator.getIdentifier();

    // Send file info in CPIM message
    String content =
        ChatUtils.buildCpimMessageWithImdn(
            from, to, msgId, fileInfo, FileTransferHttpInfoDocument.MIME_TYPE);

    // Send content
    chatSession.sendDataChunks(ChatUtils.generateMessageId(), content, mime);
    RichMessaging.getInstance()
        .updateFileTransferChatId(getSessionID(), chatSession.getContributionID(), msgId);
  }
  /**
   * Prepare to send the info to terminating side
   *
   * @param result byte[] which contains the result of the 200 OK from the content server
   */
  private void sendResultToContact(byte[] result) {
    // Check if upload is cancelled
    if (uploadManager.isCancelled()) {
      return;
    }

    if (result != null && ChatUtils.parseFileTransferHttpDocument(result) != null) {
      fileInfo = new String(result);
      if (logger.isActivated()) {
        logger.debug("Upload done with success: " + fileInfo);
      }

      // Send the file transfer info via a chat message
      chatSession = (ChatSession) Core.getInstance().getImService().getSession(getChatSessionID());
      if (chatSession == null) {
        Vector<ChatSession> chatSessions =
            Core.getInstance().getImService().getImSessionsWith(participants.getList());
        try {
          chatSession = chatSessions.lastElement();
          setChatSessionID(chatSession.getSessionID());
          setContributionID(chatSession.getContributionID());
          if (logger.isActivated()) {
            logger.debug("Chat session found with participants");
          }
        } catch (NoSuchElementException nsee) {
          chatSession = null;
          if (logger.isActivated()) {
            logger.debug("No such Chat session found with participants");
          }
        }
      }
      if (chatSession != null) {
        // A chat session exists
        if (logger.isActivated()) {
          logger.debug("Send file transfer info via an existing chat session");
        }

        // Send file transfer info
        sendFileTransferInfo();

        // File transfered
        handleFileTransfered();
      } else {
        logger.debug("sendResultToContact error 1");
        // No chat error
        handleError(new FileSharingError(FileSharingError.NO_CHAT_SESSION));
      }
    } else {
      if (logger.isActivated()) {
        logger.debug("Upload has failed");
      }

      try {
        Thread.sleep(5 * 1000);
      } catch (InterruptedException e) {
        // Nothing to do
        logger.debug("sendResultToContact excepion in thread 1");
      }

      if (!uploadManager.isCancelled()) {
        logger.debug("Upload is cancelled123");
        try {
          Thread.sleep(10 * 1000);
        } catch (InterruptedException e) {
          // Nothing to do
          logger.debug("sendResultToContact excepion in thread 2");
        }
        if (!uploadManager.isCancelled()) {
          logger.debug("Upload is cancelled234");
          handleError(new FileSharingError(FileSharingError.MEDIA_UPLOAD_FAILED));
        }
      }

      // Upload error
    }
  }
  /**
   * Handle 200 0K response
   *
   * @param resp 200 OK response
   */
  public void handle200OK(SipResponse resp) {
    try {
      // 200 OK received
      if (logger.isActivated()) {
        logger.info("200 OK response received");
      }

      // The signalisation is established
      getDialogPath().sigEstablished();

      // Set the remote tag
      getDialogPath().setRemoteTag(resp.getToTag());

      // Set the target
      getDialogPath().setTarget(resp.getContactURI());

      // Set the route path with the Record-Route header
      Vector<String> newRoute = SipUtils.routeProcessing(resp, true);
      getDialogPath().setRoute(newRoute);

      // Set the remote SDP part
      getDialogPath().setRemoteContent(resp.getContent());

      // Parse the remote SDP part
      SdpParser parser = new SdpParser(getDialogPath().getRemoteContent().getBytes());
      Vector<MediaDescription> media = parser.getMediaDescriptions();
      MediaDescription mediaDesc = media.elementAt(0);
      MediaAttribute attr = mediaDesc.getMediaAttribute("path");
      String remoteMsrpPath = attr.getValue();
      String remoteHost = SdpUtils.extractRemoteHost(parser.sessionDescription.connectionInfo);
      int remotePort = mediaDesc.port;

      // Send ACK request
      if (logger.isActivated()) {
        logger.info("Send ACK");
      }
      getImsService().getImsModule().getSipManager().sendSipAck(getDialogPath());

      // The session is established
      getDialogPath().sessionEstablished();

      // Create the MSRP client session
      MsrpSession session =
          msrpMgr.createMsrpClientSession(remoteHost, remotePort, remoteMsrpPath, this);
      session.setFailureReportOption(false);
      session.setSuccessReportOption(true);

      // Open the MSRP session
      msrpMgr.openMsrpSession();

      // Start session timer
      if (getSessionTimerManager().isSessionTimerActivated(resp)) {
        getSessionTimerManager()
            .start(resp.getSessionTimerRefresher(), resp.getSessionTimerExpire());
      }

      // Notify listeners
      for (int i = 0; i < getListeners().size(); i++) {
        getListeners().get(i).handleSessionStarted();
      }

      // Start sending data chunks
      byte[] data = getContent().getData();
      InputStream stream;
      if (data == null) {
        // Load data from URL
        stream = FileFactory.getFactory().openFileInputStream(getContent().getUrl());
      } else {
        // Load data from memory
        stream = new ByteArrayInputStream(data);
      }
      msrpMgr.sendChunks(
          stream,
          ChatUtils.generateMessageId(),
          getContent().getEncoding(),
          getContent().getSize());
    } catch (Exception e) {
      if (logger.isActivated()) {
        logger.error("Session initiation has failed", e);
      }

      // Unexpected error
      handleError(new FileSharingError(FileSharingError.UNEXPECTED_EXCEPTION, e.getMessage()));
    }
  }