Example #1
0
  /**
   * Sends a typing notification state.
   *
   * @param typingState the typing notification state to send
   * @return the result of this operation. One of the TYPING_NOTIFICATION_XXX constants defined in
   *     this class
   */
  public int sendTypingNotification(int typingState) {
    // If this chat transport does not support sms messaging we do
    // nothing here.
    if (!allowsTypingNotifications()) return -1;

    ProtocolProviderService protocolProvider = contact.getProtocolProvider();
    OperationSetTypingNotifications tnOperationSet =
        protocolProvider.getOperationSet(OperationSetTypingNotifications.class);

    // if protocol is not registered or contact is offline don't
    // try to send typing notifications
    if (protocolProvider.isRegistered()
        && contact.getPresenceStatus().getStatus() >= PresenceStatus.ONLINE_THRESHOLD) {
      try {
        tnOperationSet.sendTypingNotification(contact, typingState);

        return ChatPanel.TYPING_NOTIFICATION_SUCCESSFULLY_SENT;
      } catch (Exception ex) {
        logger.error("Failed to send typing notifications.", ex);

        return ChatPanel.TYPING_NOTIFICATION_SEND_FAILED;
      }
    }

    return ChatPanel.TYPING_NOTIFICATION_SEND_FAILED;
  }
Example #2
0
  /**
   * Sends the given file through this chat transport file transfer operation set.
   *
   * @param file the file to send
   * @return the <tt>FileTransfer</tt> object charged to transfer the file
   * @throws Exception if anything goes wrong
   */
  public FileTransfer sendFile(File file) throws Exception {
    // If this chat transport does not support instant messaging we do
    // nothing here.
    if (!allowsFileTransfer()) return null;

    OperationSetFileTransfer ftOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetFileTransfer.class);

    if (FileUtils.isImage(file.getName())) {
      // Create a thumbnailed file if possible.
      OperationSetThumbnailedFileFactory tfOpSet =
          contact.getProtocolProvider().getOperationSet(OperationSetThumbnailedFileFactory.class);

      if (tfOpSet != null) {
        byte[] thumbnail = getFileThumbnail(file);

        if (thumbnail != null && thumbnail.length > 0) {
          file =
              tfOpSet.createFileWithThumbnail(
                  file, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT, "image/png", thumbnail);
        }
      }
    }
    return ftOpSet.sendFile(contact, file);
  }
  /**
   * Permanently removes locally stored message history for the metacontact, remove any recent
   * contacts if any.
   */
  public void eraseLocallyStoredHistory(MetaContact contact) throws IOException {
    List<ComparableEvtObj> toRemove = null;
    synchronized (recentMessages) {
      toRemove = new ArrayList<ComparableEvtObj>();
      Iterator<Contact> iter = contact.getContacts();
      while (iter.hasNext()) {
        Contact item = iter.next();
        String id = item.getAddress();
        ProtocolProviderService provider = item.getProtocolProvider();

        for (ComparableEvtObj msc : recentMessages) {
          if (msc.getProtocolProviderService().equals(provider)
              && msc.getContactAddress().equals(id)) {
            toRemove.add(msc);
          }
        }
      }

      recentMessages.removeAll(toRemove);
    }
    if (recentQuery != null) {
      for (ComparableEvtObj msc : toRemove) {
        recentQuery.fireContactRemoved(msc);
      }
    }
  }
Example #4
0
  public static void main(String[] args) {
    FileHandler fh = new FileHandler();
    Contact c = new Contact();
    List<Contact> contactList = new ArrayList<Contact>();

    String[] fields = fh.readFile(new File("/names.txt"));
    for (int i = 0; i < fields.length; i++) {
      if (!(fields[i].equals("-----"))) {
        c.setFirstName(fields[i++]);
        c.setLastName(fields[i++]);
        c.setAddress(fields[i++]);
        c.setCity(fields[i++]);
        c.setState(fields[i++]);
        c.setZip(fields[i++]);
        c.setEmail(fields[i++]);
        c.setPhone(fields[i++]);
      }
      contactList.add(c);
    }
    for (int i = 0; i < contactList.size(); i++) {
      System.out.println(
          contactList.get(i).getFirstName() + " " + contactList.get(i).getLastName());
      System.out.println(contactList.get(i).getAddress());
      System.out.println(
          contactList.get(i).getCity()
              + ", "
              + contactList.get(i).getState()
              + "  "
              + contactList.get(i).getZip());
      System.out.println(contactList.get(i).getPhone());
      System.out.println(contactList.get(i).getEmail());
      System.out.println();
    }
  }
  @Override
  public void supportedOperationSetsChanged(ContactCapabilitiesEvent event) {
    Contact contact = event.getSourceContact();

    if (contact == null) return;

    for (ComparableEvtObj msc : recentMessages) {
      if (contact.equals(msc.getContact())) {
        if (recentQuery != null) recentQuery.updateCapabilities(msc, contact);

        return;
      }
    }
  }
Example #6
0
 public void contactPolicyChanged(Contact contact) {
   // OtrMetaContactButton.this.contact can be null.
   if (OtrMetaContactButton.this.otrContact != null
       && contact.equals(OtrMetaContactButton.this.otrContact.contact)) {
     setPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact));
   }
 }
Example #7
0
  /**
   * Sends the given sms message trough this chat transport.
   *
   * @param phoneNumber phone number of the destination
   * @param messageText The message to send.
   * @throws Exception if the send operation is interrupted
   */
  public void sendSmsMessage(String phoneNumber, String messageText) throws Exception {
    // If this chat transport does not support sms messaging we do
    // nothing here.
    if (!allowsSmsMessage()) return;

    SMSManager.sendSMS(contact.getProtocolProvider(), phoneNumber, messageText);
  }
Example #8
0
  /**
   * Determines whether this chat transport supports the supplied content type
   *
   * @param contentType the type we want to check
   * @return <tt>true</tt> if the chat transport supports it and <tt>false</tt> otherwise.
   */
  public boolean isContentTypeSupported(String contentType) {
    OperationSetBasicInstantMessaging imOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class);

    if (imOpSet != null) return imOpSet.isContentTypeSupported(contentType);
    else return false;
  }
Example #9
0
  /**
   * Remove records telling what entity caps node a contact has.
   *
   * @param contact the contact
   */
  public void removeContactCapsNode(Contact contact) {
    Caps caps = null;
    String lastRemovedJid = null;

    Iterator<String> iter = userCaps.keySet().iterator();
    while (iter.hasNext()) {
      String jid = iter.next();

      if (StringUtils.parseBareAddress(jid).equals(contact.getAddress())) {
        caps = userCaps.get(jid);
        lastRemovedJid = jid;
        iter.remove();
      }
    }

    // fire only for the last one, at the end the event out
    // of the protocol will be one and for the contact
    if (caps != null) {
      UserCapsNodeListener[] listeners;
      synchronized (userCapsNodeListeners) {
        listeners = userCapsNodeListeners.toArray(NO_USER_CAPS_NODE_LISTENERS);
      }
      if (listeners.length != 0) {
        String nodeVer = caps.getNodeVer();

        for (UserCapsNodeListener listener : listeners)
          listener.userCapsNodeRemoved(lastRemovedJid, nodeVer, false);
      }
    }
  }
Example #10
0
  /**
   * Returns <code>true</code> if this chat transport supports typing notifications, otherwise
   * returns <code>false</code>.
   *
   * @return <code>true</code> if this chat transport supports typing notifications, otherwise
   *     returns <code>false</code>.
   */
  public boolean allowsTypingNotifications() {
    Object tnOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetTypingNotifications.class);

    if (tnOpSet != null) return true;
    else return false;
  }
Example #11
0
  public void setCurrentContact(Contact contact, String resourceName) {
    if (contact == null) {
      this.otrContact = null;
      this.setPolicy(null);
      this.setStatus(ScSessionStatus.PLAINTEXT);
      return;
    }

    if (resourceName == null) {
      OtrContact otrContact = OtrContactManager.getOtrContact(contact, null);
      if (this.otrContact == otrContact) return;
      this.otrContact = otrContact;
      this.setStatus(OtrActivator.scOtrEngine.getSessionStatus(otrContact));
      this.setPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact));
      return;
    }
    for (ContactResource resource : contact.getResources()) {
      if (resource.getResourceName().equals(resourceName)) {
        OtrContact otrContact = OtrContactManager.getOtrContact(contact, resource);
        if (this.otrContact == otrContact) return;
        this.otrContact = otrContact;
        this.setStatus(OtrActivator.scOtrEngine.getSessionStatus(otrContact));
        this.setPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact));
        return;
      }
    }
    logger.debug("Could not find resource for contact " + contact);
  }
  /**
   * If a contact is renamed update the locally stored message if any.
   *
   * @param evt the <tt>ContactPropertyChangeEvent</tt> containing the source
   */
  @Override
  public void contactModified(ContactPropertyChangeEvent evt) {
    if (!evt.getPropertyName().equals(ContactPropertyChangeEvent.PROPERTY_DISPLAY_NAME)) return;

    Contact contact = evt.getSourceContact();

    if (contact == null) return;

    for (ComparableEvtObj msc : recentMessages) {
      if (contact.equals(msc.getContact())) {
        if (recentQuery != null)
          recentQuery.updateContactDisplayName(msc, contact.getDisplayName());

        return;
      }
    }
  }
Example #13
0
  /**
   * Whether a dialog need to be opened so the user can enter the destination number.
   *
   * @return <tt>true</tt> if dialog needs to be open.
   */
  public boolean askForSMSNumber() {
    // If this chat transport does not support sms messaging we do
    // nothing here.
    if (!allowsSmsMessage()) return false;

    OperationSetSmsMessaging smsOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetSmsMessaging.class);

    return smsOpSet.askForNumber(contact);
  }
Example #14
0
  /**
   * Removes the given sms message listener from this chat transport.
   *
   * @param l The message listener to remove.
   */
  public void removeSmsMessageListener(MessageListener l) {
    // If this chat transport does not support sms messaging we do
    // nothing here.
    if (!allowsSmsMessage()) return;

    OperationSetSmsMessaging smsOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetSmsMessaging.class);

    smsOpSet.removeMessageListener(l);
  }
Example #15
0
  /**
   * Removes the instant message listener from this chat transport.
   *
   * @param l The message listener to remove.
   */
  public void removeInstantMessageListener(MessageListener l) {
    // If this chat transport does not support instant messaging we do
    // nothing here.
    if (!allowsInstantMessage()) return;

    OperationSetBasicInstantMessaging imOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class);

    imOpSet.removeMessageListener(l);
  }
Example #16
0
  /**
   * If sending im is supported check it for supporting html messages if a font is set. As it can be
   * slow make sure its not on our way
   */
  private void checkImCaps() {
    if (ConfigurationUtils.getChatDefaultFontFamily() != null
        && ConfigurationUtils.getChatDefaultFontSize() > 0) {
      OperationSetBasicInstantMessaging imOpSet =
          contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class);

      if (imOpSet != null)
        imOpSet.isContentTypeSupported(OperationSetBasicInstantMessaging.HTML_MIME_TYPE, contact);
    }
  }
Example #17
0
  /**
   * Returns <code>true</code> if this chat transport supports message corrections and false
   * otherwise.
   *
   * @return <code>true</code> if this chat transport supports message corrections and false
   *     otherwise.
   */
  public boolean allowsMessageCorrections() {
    OperationSetContactCapabilities capOpSet =
        getProtocolProvider().getOperationSet(OperationSetContactCapabilities.class);

    if (capOpSet != null) {
      return capOpSet.getOperationSet(contact, OperationSetMessageCorrection.class) != null;
    } else {
      return contact.getProtocolProvider().getOperationSet(OperationSetMessageCorrection.class)
          != null;
    }
  }
  /**
   * Tries to match the event object to already existing ComparableEvtObj in the supplied list.
   *
   * @param obj the object that we will try to match.
   * @param list the list we will search in.
   * @return the found ComparableEvtObj
   */
  private static ComparableEvtObj findRecentMessage(EventObject obj, List<ComparableEvtObj> list) {
    Contact contact = null;
    ChatRoom chatRoom = null;

    if (obj instanceof MessageDeliveredEvent) {
      contact = ((MessageDeliveredEvent) obj).getDestinationContact();
    } else if (obj instanceof MessageReceivedEvent) {
      contact = ((MessageReceivedEvent) obj).getSourceContact();
    } else if (obj instanceof ChatRoomMessageDeliveredEvent) {
      chatRoom = ((ChatRoomMessageDeliveredEvent) obj).getSourceChatRoom();
    } else if (obj instanceof ChatRoomMessageReceivedEvent) {
      chatRoom = ((ChatRoomMessageReceivedEvent) obj).getSourceChatRoom();
    }

    for (ComparableEvtObj evt : list) {
      if ((contact != null && contact.equals(evt.getContact()))
          || (chatRoom != null && chatRoom.equals(evt.getRoom()))) return evt;
    }

    return null;
  }
    /**
     * Extract values from <tt>EventObject</tt>.
     *
     * @param source
     */
    public void update(EventObject source) {
      this.eventObject = source;

      if (source instanceof MessageDeliveredEvent) {
        MessageDeliveredEvent e = (MessageDeliveredEvent) source;

        this.contact = e.getDestinationContact();

        this.address = contact.getAddress();
        this.ppService = contact.getProtocolProvider();
        this.timestamp = e.getTimestamp();
      } else if (source instanceof MessageReceivedEvent) {
        MessageReceivedEvent e = (MessageReceivedEvent) source;

        this.contact = e.getSourceContact();

        this.address = contact.getAddress();
        this.ppService = contact.getProtocolProvider();
        this.timestamp = e.getTimestamp();
      } else if (source instanceof ChatRoomMessageDeliveredEvent) {
        ChatRoomMessageDeliveredEvent e = (ChatRoomMessageDeliveredEvent) source;

        this.room = e.getSourceChatRoom();

        this.address = room.getIdentifier();
        this.ppService = room.getParentProvider();
        this.timestamp = e.getTimestamp();
      } else if (source instanceof ChatRoomMessageReceivedEvent) {
        ChatRoomMessageReceivedEvent e = (ChatRoomMessageReceivedEvent) source;

        this.room = e.getSourceChatRoom();

        this.address = room.getIdentifier();
        this.ppService = room.getParentProvider();
        this.timestamp = e.getTimestamp();
      }
    }
Example #20
0
  /**
   * Returns <code>true</code> if this chat transport supports sms messaging, otherwise returns
   * <code>false</code>.
   *
   * @return <code>true</code> if this chat transport supports sms messaging, otherwise returns
   *     <code>false</code>.
   */
  public boolean allowsSmsMessage() {
    // First try to ask the capabilities operation set if such is
    // available.
    OperationSetContactCapabilities capOpSet =
        getProtocolProvider().getOperationSet(OperationSetContactCapabilities.class);

    if (capOpSet != null) {
      if (capOpSet.getOperationSet(contact, OperationSetSmsMessaging.class) != null) {
        return true;
      }
    } else if (contact.getProtocolProvider().getOperationSet(OperationSetSmsMessaging.class)
        != null) return true;

    return false;
  }
  /**
   * Sends a file transfer request to the given <tt>toContact</tt> by specifying the local and
   * remote file path and the <tt>fromContact</tt>, sending the file.
   *
   * @param toContact the contact that should receive the file
   * @param file the file to send
   * @return the transfer object
   * @throws IllegalStateException if the protocol provider is not registered or connected
   * @throws IllegalArgumentException if some of the arguments doesn't fit the protocol requirements
   */
  public FileTransfer sendFile(Contact toContact, File file)
      throws IllegalStateException, IllegalArgumentException {
    assertConnected();

    if (file.length() > getMaximumFileLength())
      throw new IllegalArgumentException("File length exceeds the allowed one for this protocol");

    // Get the aim connection
    AimConnection aimConnection = icqProvider.getAimConnection();

    // Create an outgoing file transfer instance
    OutgoingFileTransfer outgoingFileTransfer =
        aimConnection
            .getIcbmService()
            .getRvConnectionManager()
            .createOutgoingFileTransfer(new Screenname(toContact.getAddress()));

    String id =
        String.valueOf(outgoingFileTransfer.getRvSessionInfo().getRvSession().getRvSessionId());

    FileTransferImpl outFileTransfer =
        new FileTransferImpl(outgoingFileTransfer, id, toContact, file, FileTransfer.OUT);

    // Adding the file to the outgoing file transfer
    try {
      outgoingFileTransfer.setSingleFile(new File(file.getPath()));
    } catch (IOException e) {
      if (logger.isDebugEnabled()) logger.debug("Error sending file", e);
      return null;
    }

    // Notify all interested listeners that a file transfer has been
    // created.
    FileTransferCreatedEvent event = new FileTransferCreatedEvent(outFileTransfer, new Date());

    fireFileTransferCreated(event);

    // Sending the file
    outgoingFileTransfer.sendRequest(new InvitationMessage(""));

    outFileTransfer.fireStatusChangeEvent(FileTransferStatusChangeEvent.PREPARING);

    return outFileTransfer;
  }
  /**
   * Sends the <tt>message</tt> to the destination indicated by the <tt>to</tt> contact.
   *
   * @param to the <tt>Contact</tt> to send <tt>message</tt> to
   * @param message the <tt>Message</tt> to send.
   * @throws java.lang.IllegalStateException if the underlying stack is not registered and
   *     initialized.
   * @throws java.lang.IllegalArgumentException if <tt>to</tt> is not an instance of ContactImpl.
   */
  public void sendInstantMessage(Contact to, Message message)
      throws IllegalStateException, IllegalArgumentException {
    if (!(to instanceof ContactSipImpl))
      throw new IllegalArgumentException("The specified contact is not a Sip contact." + to);

    assertConnected();

    // offline message
    if (to.getPresenceStatus().equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE))
        && !offlineMessageSupported) {
      if (logger.isDebugEnabled()) logger.debug("trying to send a message to an offline contact");
      fireMessageDeliveryFailed(
          message, to, MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED);
      return;
    }

    // create the message
    Request mes;
    try {
      mes = createMessageRequest(to, message);
    } catch (OperationFailedException ex) {
      logger.error("Failed to create the message.", ex);

      fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.INTERNAL_ERROR);
      return;
    }

    try {
      sendMessageRequest(mes, to, message);
    } catch (TransactionUnavailableException ex) {
      logger.error(
          "Failed to create messageTransaction.\n"
              + "This is most probably a network connection error.",
          ex);

      fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.NETWORK_FAILURE);
      return;
    } catch (SipException ex) {
      logger.error("Failed to send the message.", ex);

      fireMessageDeliveryFailed(message, to, MessageDeliveryFailedEvent.INTERNAL_ERROR);
      return;
    }
  }
Example #23
0
  /**
   * Sends <tt>message</tt> as a message correction through this transport, specifying the mime type
   * (html or plain text) and the id of the message to replace.
   *
   * @param message The message to send.
   * @param mimeType The mime type of the message to send: text/html or text/plain.
   * @param correctedMessageUID The ID of the message being corrected by this message.
   */
  public void correctInstantMessage(String message, String mimeType, String correctedMessageUID) {
    if (!allowsMessageCorrections()) {
      return;
    }

    OperationSetMessageCorrection mcOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetMessageCorrection.class);

    Message msg;
    if (mimeType.equals(OperationSetBasicInstantMessaging.HTML_MIME_TYPE)
        && mcOpSet.isContentTypeSupported(OperationSetBasicInstantMessaging.HTML_MIME_TYPE)) {
      msg =
          mcOpSet.createMessage(
              message, OperationSetBasicInstantMessaging.HTML_MIME_TYPE, "utf-8", "");
    } else {
      msg = mcOpSet.createMessage(message);
    }

    mcOpSet.correctMessage(contact, contactResource, msg, correctedMessageUID);
  }
Example #24
0
  /**
   * Sends the given instant message through this chat transport, by specifying the mime type (html
   * or plain text).
   *
   * @param message The message to send.
   * @param mimeType The mime type of the message to send: text/html or text/plain.
   * @throws Exception if the send operation is interrupted
   */
  public void sendInstantMessage(String message, String mimeType) throws Exception {
    // If this chat transport does not support instant messaging we do
    // nothing here.
    if (!allowsInstantMessage()) return;

    OperationSetBasicInstantMessaging imOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetBasicInstantMessaging.class);

    Message msg;
    if (mimeType.equals(OperationSetBasicInstantMessaging.HTML_MIME_TYPE)
        && imOpSet.isContentTypeSupported(OperationSetBasicInstantMessaging.HTML_MIME_TYPE)) {
      msg =
          imOpSet.createMessage(
              message, OperationSetBasicInstantMessaging.HTML_MIME_TYPE, "utf-8", "");
    } else {
      msg = imOpSet.createMessage(message);
    }

    if (contactResource != null) imOpSet.sendInstantMessage(contact, contactResource, msg);
    else imOpSet.sendInstantMessage(contact, ContactResource.BASE_RESOURCE, msg);
  }
Example #25
0
  /**
   * Creates an instance of <tt>MetaContactChatTransport</tt> by specifying the parent
   * <tt>chatSession</tt> and the <tt>contact</tt> associated with the transport.
   *
   * @param chatSession the parent <tt>ChatSession</tt>
   * @param contact the <tt>Contact</tt> associated with this transport
   * @param contactResource the <tt>ContactResource</tt> associated with the contact
   * @param isDisplayResourceOnly indicates if only the resource name should be displayed
   */
  public MetaContactChatTransport(
      MetaContactChatSession chatSession,
      Contact contact,
      ContactResource contactResource,
      boolean isDisplayResourceOnly) {
    this.parentChatSession = chatSession;
    this.contact = contact;
    this.contactResource = contactResource;
    this.isDisplayResourceOnly = isDisplayResourceOnly;

    presenceOpSet = contact.getProtocolProvider().getOperationSet(OperationSetPresence.class);

    if (presenceOpSet != null) presenceOpSet.addContactPresenceStatusListener(this);

    // checking this can be slow so make
    // sure its out of our way
    new Thread(
            new Runnable() {
              public void run() {
                checkImCaps();
              }
            })
        .start();
  }
  /**
   * Sends a file transfer request to the given <tt>toContact</tt>.
   *
   * @return the transfer object
   * @param toContact the contact that should receive the file
   * @param file file to send
   * @param gw special gateway to be used for receiver if its jid misses the domain part
   */
  FileTransfer sendFile(Contact toContact, File file, String gw)
      throws IllegalStateException, IllegalArgumentException, OperationNotSupportedException {
    OutgoingFileTransferJabberImpl outgoingTransfer = null;

    try {
      assertConnected();

      if (file.length() > getMaximumFileLength())
        throw new IllegalArgumentException("File length exceeds the allowed one for this protocol");

      String fullJid = null;
      // Find the jid of the contact which support file transfer
      // and is with highest priority if more than one found
      // if we have equals priorities
      // choose the one that is more available
      OperationSetMultiUserChat mucOpSet =
          jabberProvider.getOperationSet(OperationSetMultiUserChat.class);
      if (mucOpSet != null && mucOpSet.isPrivateMessagingContact(toContact.getAddress())) {
        fullJid = toContact.getAddress();
      } else {
        Iterator<Presence> iter =
            jabberProvider.getConnection().getRoster().getPresences(toContact.getAddress());
        int bestPriority = -1;

        PresenceStatus jabberStatus = null;

        while (iter.hasNext()) {
          Presence presence = iter.next();

          if (jabberProvider.isFeatureListSupported(
              presence.getFrom(),
              new String[] {
                "http://jabber.org/protocol/si",
                "http://jabber.org/protocol/si/profile/file-transfer"
              })) {

            int priority =
                (presence.getPriority() == Integer.MIN_VALUE) ? 0 : presence.getPriority();

            if (priority > bestPriority) {
              bestPriority = priority;
              fullJid = presence.getFrom();
              jabberStatus =
                  OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus(
                      presence, jabberProvider);
            } else if (priority == bestPriority && jabberStatus != null) {
              PresenceStatus tempStatus =
                  OperationSetPersistentPresenceJabberImpl.jabberStatusToPresenceStatus(
                      presence, jabberProvider);
              if (tempStatus.compareTo(jabberStatus) > 0) {
                fullJid = presence.getFrom();
                jabberStatus = tempStatus;
              }
            }
          }
        }
      }

      // First we check if file transfer is at all supported for this
      // contact.
      if (fullJid == null) {
        throw new OperationNotSupportedException(
            "Contact client or server does not support file transfers.");
      }

      if (gw != null && !fullJid.contains("@") && !fullJid.endsWith(gw)) {
        fullJid = fullJid + "@" + gw;
      }

      OutgoingFileTransfer transfer = manager.createOutgoingFileTransfer(fullJid);

      outgoingTransfer =
          new OutgoingFileTransferJabberImpl(toContact, file, transfer, jabberProvider);

      // Notify all interested listeners that a file transfer has been
      // created.
      FileTransferCreatedEvent event = new FileTransferCreatedEvent(outgoingTransfer, new Date());

      fireFileTransferCreated(event);

      // Send the file through the Jabber file transfer.
      transfer.sendFile(file, "Sending file");

      // Start the status and progress thread.
      new FileTransferProgressThread(transfer, outgoingTransfer).start();
    } catch (XMPPException e) {
      logger.error("Failed to send file.", e);
    }

    return outgoingTransfer;
  }
  /**
   * Construct a <tt>Request</tt> represent a new message.
   *
   * @param to the <tt>Contact</tt> to send <tt>message</tt> to
   * @param message the <tt>Message</tt> to send.
   * @return a Message Request destined to the contact
   * @throws OperationFailedException if an error occurred during the creation of the request
   */
  Request createMessageRequest(Contact to, Message message) throws OperationFailedException {
    Address toAddress = null;
    try {
      toAddress = sipProvider.parseAddressString(to.getAddress());
    } catch (ParseException exc) {
      // Shouldn't happen
      logger.error("An unexpected error occurred while" + "constructing the address", exc);
      throw new OperationFailedException(
          "An unexpected error occurred while" + "constructing the address",
          OperationFailedException.INTERNAL_ERROR,
          exc);
    }

    // Call ID
    CallIdHeader callIdHeader = this.sipProvider.getDefaultJainSipProvider().getNewCallId();

    // CSeq
    CSeqHeader cSeqHeader = null;

    try {
      // protect seqN
      synchronized (this) {
        cSeqHeader = this.sipProvider.getHeaderFactory().createCSeqHeader(seqN++, Request.MESSAGE);
      }
    } catch (InvalidArgumentException ex) {
      // Shouldn't happen
      logger.error("An unexpected error occurred while" + "constructing the CSeqHeadder", ex);
      throw new OperationFailedException(
          "An unexpected error occurred while" + "constructing the CSeqHeadder",
          OperationFailedException.INTERNAL_ERROR,
          ex);
    } catch (ParseException exc) {
      // shouldn't happen
      logger.error("An unexpected error occurred while" + "constructing the CSeqHeadder", exc);
      throw new OperationFailedException(
          "An unexpected error occurred while" + "constructing the CSeqHeadder",
          OperationFailedException.INTERNAL_ERROR,
          exc);
    }

    // FromHeader and ToHeader
    String localTag = SipMessageFactory.generateLocalTag();
    FromHeader fromHeader = null;
    ToHeader toHeader = null;
    try {
      // FromHeader
      fromHeader =
          this.sipProvider
              .getHeaderFactory()
              .createFromHeader(sipProvider.getOurSipAddress(toAddress), localTag);

      // ToHeader
      toHeader = this.sipProvider.getHeaderFactory().createToHeader(toAddress, null);
    } catch (ParseException ex) {
      // these two should never happen.
      logger.error(
          "An unexpected error occurred while" + "constructing the FromHeader or ToHeader", ex);
      throw new OperationFailedException(
          "An unexpected error occurred while" + "constructing the FromHeader or ToHeader",
          OperationFailedException.INTERNAL_ERROR,
          ex);
    }

    // ViaHeaders
    ArrayList<ViaHeader> viaHeaders = this.sipProvider.getLocalViaHeaders(toAddress);

    // MaxForwards
    MaxForwardsHeader maxForwards = this.sipProvider.getMaxForwardsHeader();

    // Content params
    ContentTypeHeader contTypeHeader;
    ContentLengthHeader contLengthHeader;
    try {
      contTypeHeader =
          this.sipProvider
              .getHeaderFactory()
              .createContentTypeHeader(getType(message), getSubType(message));

      if (!DEFAULT_MIME_ENCODING.equalsIgnoreCase(message.getEncoding()))
        contTypeHeader.setParameter("charset", message.getEncoding());

      contLengthHeader =
          this.sipProvider.getHeaderFactory().createContentLengthHeader(message.getSize());
    } catch (ParseException ex) {
      // these two should never happen.
      logger.error("An unexpected error occurred while" + "constructing the content headers", ex);
      throw new OperationFailedException(
          "An unexpected error occurred while" + "constructing the content headers",
          OperationFailedException.INTERNAL_ERROR,
          ex);
    } catch (InvalidArgumentException exc) {
      // these two should never happen.
      logger.error(
          "An unexpected error occurred while" + "constructing the content length header", exc);
      throw new OperationFailedException(
          "An unexpected error occurred while" + "constructing the content length header",
          OperationFailedException.INTERNAL_ERROR,
          exc);
    }

    Request req;
    try {
      req =
          this.sipProvider
              .getMessageFactory()
              .createRequest(
                  toHeader.getAddress().getURI(),
                  Request.MESSAGE,
                  callIdHeader,
                  cSeqHeader,
                  fromHeader,
                  toHeader,
                  viaHeaders,
                  maxForwards,
                  contTypeHeader,
                  message.getRawData());
    } catch (ParseException ex) {
      // shouldn't happen
      logger.error("Failed to create message Request!", ex);
      throw new OperationFailedException(
          "Failed to create message Request!", OperationFailedException.INTERNAL_ERROR, ex);
    }

    req.addHeader(contLengthHeader);

    return req;
  }
  @Override
  public List<File> generate() {
    Boolean generateApis = null;
    Boolean generateModels = null;
    Boolean generateSupportingFiles = null;

    Set<String> modelsToGenerate = null;
    Set<String> apisToGenerate = null;
    Set<String> supportingFilesToGenerate = null;

    // allows generating only models by specifying a CSV of models to generate, or empty for all
    if (System.getProperty("models") != null) {
      String modelNames = System.getProperty("models");
      generateModels = true;
      if (!modelNames.isEmpty()) {
        modelsToGenerate = new HashSet<String>(Arrays.asList(modelNames.split(",")));
      }
    }
    if (System.getProperty("apis") != null) {
      String apiNames = System.getProperty("apis");
      generateApis = true;
      if (!apiNames.isEmpty()) {
        apisToGenerate = new HashSet<String>(Arrays.asList(apiNames.split(",")));
      }
    }
    if (System.getProperty("supportingFiles") != null) {
      String supportingFiles = System.getProperty("supportingFiles");
      generateSupportingFiles = true;
      if (!supportingFiles.isEmpty()) {
        supportingFilesToGenerate = new HashSet<String>(Arrays.asList(supportingFiles.split(",")));
      }
    }

    if (generateApis == null && generateModels == null && generateSupportingFiles == null) {
      // no specifics are set, generate everything
      generateApis = true;
      generateModels = true;
      generateSupportingFiles = true;
    } else {
      if (generateApis == null) {
        generateApis = false;
      }
      if (generateModels == null) {
        generateModels = false;
      }
      if (generateSupportingFiles == null) {
        generateSupportingFiles = false;
      }
    }

    if (swagger == null || config == null) {
      throw new RuntimeException("missing swagger input or config!");
    }
    if (System.getProperty("debugSwagger") != null) {
      Json.prettyPrint(swagger);
    }
    List<File> files = new ArrayList<File>();
    config.processOpts();
    config.preprocessSwagger(swagger);

    config.additionalProperties().put("generatedDate", DateTime.now().toString());
    config.additionalProperties().put("generatorClass", config.getClass().toString());

    if (swagger.getInfo() != null) {
      Info info = swagger.getInfo();
      if (info.getTitle() != null) {
        config.additionalProperties().put("appName", info.getTitle());
      }
      if (info.getVersion() != null) {
        config.additionalProperties().put("appVersion", info.getVersion());
      }
      if (info.getDescription() != null) {
        config
            .additionalProperties()
            .put("appDescription", config.escapeText(info.getDescription()));
      }
      if (info.getContact() != null) {
        Contact contact = info.getContact();
        config.additionalProperties().put("infoUrl", contact.getUrl());
        if (contact.getEmail() != null) {
          config.additionalProperties().put("infoEmail", contact.getEmail());
        }
      }
      if (info.getLicense() != null) {
        License license = info.getLicense();
        if (license.getName() != null) {
          config.additionalProperties().put("licenseInfo", license.getName());
        }
        if (license.getUrl() != null) {
          config.additionalProperties().put("licenseUrl", license.getUrl());
        }
      }
      if (info.getVersion() != null) {
        config.additionalProperties().put("version", info.getVersion());
      }
    }

    StringBuilder hostBuilder = new StringBuilder();
    String scheme;
    if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) {
      scheme = swagger.getSchemes().get(0).toValue();
    } else {
      scheme = "https";
    }
    hostBuilder.append(scheme);
    hostBuilder.append("://");
    if (swagger.getHost() != null) {
      hostBuilder.append(swagger.getHost());
    } else {
      hostBuilder.append("localhost");
    }
    if (swagger.getBasePath() != null) {
      hostBuilder.append(swagger.getBasePath());
    }
    String contextPath = swagger.getBasePath() == null ? "" : swagger.getBasePath();
    String basePath = hostBuilder.toString();
    String basePathWithoutHost = swagger.getBasePath();

    // resolve inline models
    InlineModelResolver inlineModelResolver = new InlineModelResolver();
    inlineModelResolver.flatten(swagger);

    List<Object> allOperations = new ArrayList<Object>();
    List<Object> allModels = new ArrayList<Object>();

    // models
    Map<String, Model> definitions = swagger.getDefinitions();
    if (definitions != null) {
      List<String> sortedModelKeys = sortModelsByInheritance(definitions);

      if (generateModels) {
        if (modelsToGenerate != null && modelsToGenerate.size() > 0) {
          List<String> updatedKeys = new ArrayList<String>();
          for (String m : sortedModelKeys) {
            if (modelsToGenerate.contains(m)) {
              updatedKeys.add(m);
            }
          }
          sortedModelKeys = updatedKeys;
        }

        for (String name : sortedModelKeys) {
          try {
            // don't generate models that have an import mapping
            if (config.importMapping().containsKey(name)) {
              continue;
            }

            Model model = definitions.get(name);
            Map<String, Model> modelMap = new HashMap<String, Model>();
            modelMap.put(name, model);
            Map<String, Object> models = processModels(config, modelMap, definitions);
            models.putAll(config.additionalProperties());

            allModels.add(((List<Object>) models.get("models")).get(0));

            for (String templateName : config.modelTemplateFiles().keySet()) {
              String suffix = config.modelTemplateFiles().get(templateName);
              String filename =
                  config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix;
              if (!config.shouldOverwrite(filename)) {
                continue;
              }
              String templateFile = getFullTemplateFile(config, templateName);
              String template = readTemplate(templateFile);
              Template tmpl =
                  Mustache.compiler()
                      .withLoader(
                          new Mustache.TemplateLoader() {
                            @Override
                            public Reader getTemplate(String name) {
                              return getTemplateReader(
                                  getFullTemplateFile(config, name + ".mustache"));
                            }
                          })
                      .defaultValue("")
                      .compile(template);
              writeToFile(filename, tmpl.execute(models));
              files.add(new File(filename));
            }

            // to generate model test files
            for (String templateName : config.modelTestTemplateFiles().keySet()) {
              String suffix = config.modelTestTemplateFiles().get(templateName);
              String filename =
                  config.modelTestFileFolder()
                      + File.separator
                      + config.toModelTestFilename(name)
                      + suffix;
              if (!config.shouldOverwrite(filename)) {
                continue;
              }
              String templateFile = getFullTemplateFile(config, templateName);
              String template = readTemplate(templateFile);
              Template tmpl =
                  Mustache.compiler()
                      .withLoader(
                          new Mustache.TemplateLoader() {
                            @Override
                            public Reader getTemplate(String name) {
                              return getTemplateReader(
                                  getFullTemplateFile(config, name + ".mustache"));
                            }
                          })
                      .defaultValue("")
                      .compile(template);
              writeToFile(filename, tmpl.execute(models));
              files.add(new File(filename));
            }
          } catch (Exception e) {
            throw new RuntimeException("Could not generate model '" + name + "'", e);
          }
        }
      }
    }
    if (System.getProperty("debugModels") != null) {
      LOGGER.info("############ Model info ############");
      Json.prettyPrint(allModels);
    }

    // apis
    Map<String, List<CodegenOperation>> paths = processPaths(swagger.getPaths());
    if (generateApis) {
      if (apisToGenerate != null && apisToGenerate.size() > 0) {
        Map<String, List<CodegenOperation>> updatedPaths =
            new TreeMap<String, List<CodegenOperation>>();
        for (String m : paths.keySet()) {
          if (apisToGenerate.contains(m)) {
            updatedPaths.put(m, paths.get(m));
          }
        }
        paths = updatedPaths;
      }
      for (String tag : paths.keySet()) {
        try {
          List<CodegenOperation> ops = paths.get(tag);
          Map<String, Object> operation = processOperations(config, tag, ops);

          operation.put("basePath", basePath);
          operation.put("basePathWithoutHost", basePathWithoutHost);
          operation.put("contextPath", contextPath);
          operation.put("baseName", tag);
          operation.put("modelPackage", config.modelPackage());
          operation.putAll(config.additionalProperties());
          operation.put("classname", config.toApiName(tag));
          operation.put("classVarName", config.toApiVarName(tag));
          operation.put("importPath", config.toApiImport(tag));

          // Pass sortParamsByRequiredFlag through to the Mustache template...
          boolean sortParamsByRequiredFlag = true;
          if (this.config
              .additionalProperties()
              .containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) {
            sortParamsByRequiredFlag =
                Boolean.valueOf(
                    (String)
                        this.config
                            .additionalProperties()
                            .get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)
                            .toString());
          }
          operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag);

          processMimeTypes(swagger.getConsumes(), operation, "consumes");
          processMimeTypes(swagger.getProduces(), operation, "produces");

          allOperations.add(new HashMap<String, Object>(operation));
          for (int i = 0; i < allOperations.size(); i++) {
            Map<String, Object> oo = (Map<String, Object>) allOperations.get(i);
            if (i < (allOperations.size() - 1)) {
              oo.put("hasMore", "true");
            }
          }

          for (String templateName : config.apiTemplateFiles().keySet()) {
            String filename = config.apiFilename(templateName, tag);
            if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
              continue;
            }

            String templateFile = getFullTemplateFile(config, templateName);
            String template = readTemplate(templateFile);
            Template tmpl =
                Mustache.compiler()
                    .withLoader(
                        new Mustache.TemplateLoader() {
                          @Override
                          public Reader getTemplate(String name) {
                            return getTemplateReader(
                                getFullTemplateFile(config, name + ".mustache"));
                          }
                        })
                    .defaultValue("")
                    .compile(template);

            writeToFile(filename, tmpl.execute(operation));
            files.add(new File(filename));
          }

          // to generate api test files
          for (String templateName : config.apiTestTemplateFiles().keySet()) {
            String filename = config.apiTestFilename(templateName, tag);
            if (!config.shouldOverwrite(filename) && new File(filename).exists()) {
              continue;
            }

            String templateFile = getFullTemplateFile(config, templateName);
            String template = readTemplate(templateFile);
            Template tmpl =
                Mustache.compiler()
                    .withLoader(
                        new Mustache.TemplateLoader() {
                          @Override
                          public Reader getTemplate(String name) {
                            return getTemplateReader(
                                getFullTemplateFile(config, name + ".mustache"));
                          }
                        })
                    .defaultValue("")
                    .compile(template);

            writeToFile(filename, tmpl.execute(operation));
            files.add(new File(filename));
          }

        } catch (Exception e) {
          throw new RuntimeException("Could not generate api file for '" + tag + "'", e);
        }
      }
    }
    if (System.getProperty("debugOperations") != null) {
      LOGGER.info("############ Operation info ############");
      Json.prettyPrint(allOperations);
    }

    // supporting files
    Map<String, Object> bundle = new HashMap<String, Object>();
    bundle.putAll(config.additionalProperties());
    bundle.put("apiPackage", config.apiPackage());

    Map<String, Object> apis = new HashMap<String, Object>();
    apis.put("apis", allOperations);
    if (swagger.getHost() != null) {
      bundle.put("host", swagger.getHost());
    }
    bundle.put("swagger", this.swagger);
    bundle.put("basePath", basePath);
    bundle.put("scheme", scheme);
    bundle.put("contextPath", contextPath);
    bundle.put("apiInfo", apis);
    bundle.put("models", allModels);
    bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar));
    bundle.put("modelPackage", config.modelPackage());
    List<CodegenSecurity> authMethods = config.fromSecurity(swagger.getSecurityDefinitions());
    if (authMethods != null && !authMethods.isEmpty()) {
      bundle.put("authMethods", authMethods);
      bundle.put("hasAuthMethods", true);
    }
    if (swagger.getExternalDocs() != null) {
      bundle.put("externalDocs", swagger.getExternalDocs());
    }
    for (int i = 0; i < allModels.size() - 1; i++) {
      HashMap<String, CodegenModel> cm = (HashMap<String, CodegenModel>) allModels.get(i);
      CodegenModel m = cm.get("model");
      m.hasMoreModels = true;
    }

    config.postProcessSupportingFileData(bundle);

    if (System.getProperty("debugSupportingFiles") != null) {
      LOGGER.info("############ Supporting file info ############");
      Json.prettyPrint(bundle);
    }

    if (generateSupportingFiles) {
      for (SupportingFile support : config.supportingFiles()) {
        try {
          String outputFolder = config.outputFolder();
          if (isNotEmpty(support.folder)) {
            outputFolder += File.separator + support.folder;
          }
          File of = new File(outputFolder);
          if (!of.isDirectory()) {
            of.mkdirs();
          }
          String outputFilename = outputFolder + File.separator + support.destinationFilename;
          if (!config.shouldOverwrite(outputFilename)) {
            continue;
          }

          String templateFile = getFullTemplateFile(config, support.templateFile);

          boolean shouldGenerate = true;
          if (supportingFilesToGenerate != null && supportingFilesToGenerate.size() > 0) {
            if (supportingFilesToGenerate.contains(support.destinationFilename)) {
              shouldGenerate = true;
            } else {
              shouldGenerate = false;
            }
          }
          if (shouldGenerate) {
            if (templateFile.endsWith("mustache")) {
              String template = readTemplate(templateFile);
              Template tmpl =
                  Mustache.compiler()
                      .withLoader(
                          new Mustache.TemplateLoader() {
                            @Override
                            public Reader getTemplate(String name) {
                              return getTemplateReader(
                                  getFullTemplateFile(config, name + ".mustache"));
                            }
                          })
                      .defaultValue("")
                      .compile(template);

              writeToFile(outputFilename, tmpl.execute(bundle));
              files.add(new File(outputFilename));
            } else {
              InputStream in = null;

              try {
                in = new FileInputStream(templateFile);
              } catch (Exception e) {
                // continue
              }
              if (in == null) {
                in =
                    this.getClass()
                        .getClassLoader()
                        .getResourceAsStream(getCPResourcePath(templateFile));
              }
              File outputFile = new File(outputFilename);
              OutputStream out = new FileOutputStream(outputFile, false);
              if (in != null) {
                LOGGER.info("writing file " + outputFile);
                IOUtils.copy(in, out);
              } else {
                if (in == null) {
                  LOGGER.error("can't open " + templateFile + " for input");
                }
              }
              files.add(outputFile);
            }
          }
        } catch (Exception e) {
          throw new RuntimeException("Could not generate supporting file '" + support + "'", e);
        }
      }
    }
    config.processSwagger(swagger);
    return files;
  }
Example #29
0
  /**
   * Returns <code>true</code> if this chat transport supports file transfer, otherwise returns
   * <code>false</code>.
   *
   * @return <code>true</code> if this chat transport supports file transfer, otherwise returns
   *     <code>false</code>.
   */
  public boolean allowsFileTransfer() {
    Object ftOpSet = contact.getProtocolProvider().getOperationSet(OperationSetFileTransfer.class);

    if (ftOpSet != null) return true;
    else return false;
  }
Example #30
0
  /**
   * Returns the maximum file length supported by the protocol in bytes.
   *
   * @return the file length that is supported.
   */
  public long getMaximumFileLength() {
    OperationSetFileTransfer ftOpSet =
        contact.getProtocolProvider().getOperationSet(OperationSetFileTransfer.class);

    return ftOpSet.getMaximumFileLength();
  }