/** * Determines whether the protocol supports the supplied content type for the given contact. * * @param contentType the type we want to check * @param contact contact which is checked for supported contentType * @return <tt>true</tt> if the contact supports it and <tt>false</tt> otherwise. */ @Override public boolean isContentTypeSupported(String contentType, Contact contact) { // by default we support default mime type, for other mimetypes // method must be overriden if (contentType.equals(DEFAULT_MIME_TYPE)) return true; else if (contentType.equals(HTML_MIME_TYPE)) { String toJID = recentJIDForAddress.get(contact.getAddress()); if (toJID == null) toJID = contact.getAddress(); return jabberProvider.isFeatureListSupported(toJID, HTML_NAMESPACE); } return false; }
/** * 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); } } }
/** * 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); } } }
/** * Returns the <tt>Contact</tt> with the specified address or identifier. * * @param id the addres or identifier of the <tt>Contact</tt> we are looking for. * @return the <tt>Contact</tt> with the specified id or address. */ public Contact getContact(String id) { Iterator<Contact> contactsIter = contacts(); while (contactsIter.hasNext()) { Contact contact = contactsIter.next(); if (contact.getAddress().equals(id)) return contact; } return null; }
/** * Load infos from contact in the corresponding views. * * @param c contact */ public void set(Contact c) { contact = c; setPerson(c); if (c != null) { setAddress(c.getAddress()); setTele(c.getTele()); setEmail(c.getEmail()); websiteView.setSites(c.getSites()); } }
/** Initializes all search strings for this <tt>MetaUIGroup</tt>. */ private void initSearchStrings() { searchStrings.add(metaContact.getDisplayName()); Iterator<Contact> contacts = metaContact.getContacts(); while (contacts.hasNext()) { Contact contact = contacts.next(); searchStrings.add(contact.getDisplayName()); searchStrings.add(contact.getAddress()); } }
/** * When a sent message is delivered shows it in the chat conversation panel. * * @param evt the event containing details on the message delivery */ public void messageDelivered(MessageDeliveredEvent evt) { Contact contact = evt.getDestinationContact(); MetaContact metaContact = GuiActivator.getContactListService().findMetaContactByContact(contact); if (logger.isTraceEnabled()) logger.trace("MESSAGE DELIVERED to contact: " + contact.getAddress()); ChatPanel chatPanel = chatWindowManager.getContactChat(metaContact, false); if (chatPanel != null) { Message msg = evt.getSourceMessage(); ProtocolProviderService protocolProvider = contact.getProtocolProvider(); if (logger.isTraceEnabled()) logger.trace( "MESSAGE DELIVERED: process message to chat for contact: " + contact.getAddress() + " MESSAGE: " + msg.getContent()); chatPanel.addMessage( this.mainFrame.getAccountAddress(protocolProvider), this.mainFrame.getAccountDisplayName(protocolProvider), evt.getTimestamp(), Chat.OUTGOING_MESSAGE, msg.getContent(), msg.getContentType(), msg.getMessageUID(), evt.getCorrectedMessageUID()); if (evt.isSmsMessage() && !ConfigurationUtils.isSmsNotifyTextDisabled()) { chatPanel.addMessage( contact.getDisplayName(), new Date(), Chat.ACTION_MESSAGE, GuiActivator.getResources().getI18NString("service.gui.SMS_SUCCESSFULLY_SENT"), "text"); } } }
/** * Shows a warning message to the user when message delivery has failed. * * @param evt the event containing details on the message delivery failure */ public void messageDeliveryFailed(MessageDeliveryFailedEvent evt) { logger.error(evt.getReason()); String errorMsg = null; Message sourceMessage = (Message) evt.getSource(); Contact sourceContact = evt.getDestinationContact(); MetaContact metaContact = GuiActivator.getContactListService().findMetaContactByContact(sourceContact); if (evt.getErrorCode() == MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED) { errorMsg = GuiActivator.getResources() .getI18NString( "service.gui.MSG_DELIVERY_NOT_SUPPORTED", new String[] {sourceContact.getDisplayName()}); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.NETWORK_FAILURE) { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_NOT_DELIVERED"); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.PROVIDER_NOT_REGISTERED) { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_SEND_CONNECTION_PROBLEM"); } else if (evt.getErrorCode() == MessageDeliveryFailedEvent.INTERNAL_ERROR) { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_DELIVERY_INTERNAL_ERROR"); } else { errorMsg = GuiActivator.getResources().getI18NString("service.gui.MSG_DELIVERY_ERROR"); } String reason = evt.getReason(); if (reason != null) errorMsg += " " + GuiActivator.getResources() .getI18NString("service.gui.ERROR_WAS", new String[] {reason}); ChatPanel chatPanel = chatWindowManager.getContactChat(metaContact, sourceContact); chatPanel.addMessage( sourceContact.getAddress(), metaContact.getDisplayName(), new Date(), Chat.OUTGOING_MESSAGE, sourceMessage.getContent(), sourceMessage.getContentType(), sourceMessage.getMessageUID(), evt.getCorrectedMessageUID()); chatPanel.addErrorMessage(metaContact.getDisplayName(), errorMsg); chatWindowManager.openChat(chatPanel, false); }
private void generateContacts() { Contact contact1 = new Contact(); contact1.setFirstName("Al"); contact1.setLastName("Bundy"); contact1.setAddress(new Address(9764, "Jeopardy Ln", "Chicago", "IL", 60290)); addressService.saveAddress(contact1.getAddress()); contactService.saveContact(contact1); Contact contact2 = new Contact(); contact2.setFirstName("Ned"); contact2.setLastName("Flanders"); contact2.setAddress(new Address(740, "Evergreen Terrace", "Springfield", "OR", 97477)); addressService.saveAddress(contact2.getAddress()); contactService.saveContact(contact2); Contact contact3 = new Contact(); contact3.setFirstName("Peter"); contact3.setLastName("Griffin"); contact3.setAddress(new Address(31, "Spooner St", "Quahog", "RI", 12908)); addressService.saveAddress(contact3.getAddress()); contactService.saveContact(contact3); }
/** * 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(); } }
/** * 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; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit_contact); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); final EditText name = (EditText) findViewById(R.id.edit_name); final EditText phone = (EditText) findViewById(R.id.edit_phone); final EditText email = (EditText) findViewById(R.id.edit_email); final EditText address = (EditText) findViewById(R.id.edit_address); final EditText digicode = (EditText) findViewById(R.id.edit_digicode); Bundle extra = getIntent().getExtras(); if (extra != null) { final int id = extra.getInt("id"); Contact contact = db.getContact(id); name.setText(contact.getName()); phone.setText(contact.getPhone()); email.setText(contact.getEmail()); address.setText(contact.getAddress()); digicode.setText(contact.getDigicode()); FloatingActionButton update = (FloatingActionButton) findViewById(R.id.update_btn); update.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { db.updateContact( id, name.getText().toString(), phone.getText().toString(), email.getText().toString(), address.getText().toString(), digicode.getText().toString()); Intent i = new Intent(EditContact.this, MainActivity.class); startActivity(i); } }); } }
/** * Creates an instance of <tt>MetaContactDetail</tt> by specifying the underlying protocol * <tt>Contact</tt>. * * @param contact the protocol contact, on which this implementation is based */ public MetaContactDetail(Contact contact) { super( contact.getAddress(), contact.getDisplayName(), new ImageIcon(contact.getPresenceStatus().getStatusIcon()), contact); this.contact = contact; ProtocolProviderService parentProvider = contact.getProtocolProvider(); Iterator<Class<? extends OperationSet>> opSetClasses = parentProvider.getSupportedOperationSetClasses().iterator(); while (opSetClasses.hasNext()) { Class<? extends OperationSet> opSetClass = opSetClasses.next(); addPreferredProtocolProvider(opSetClass, parentProvider); addPreferredProtocol(opSetClass, parentProvider.getProtocolName()); } }
/** * Returns the display name of this <tt>MetaUIContact</tt>. * * @return the display name of this <tt>MetaUIContact</tt> */ public String getDisplayName() { String displayName = metaContact.getDisplayName(); /* * If the MetaContact doesn't tell us a display name, make up a display * name so that we don't end up with "Unknown user". */ if ((displayName == null) || (displayName.trim().length() == 0)) { /* * Try to get a display name from one of the Contacts of the * MetaContact. If that doesn't cut it, use the address of a * Contact. Because it's not really clear which address to display * when there are multiple Contacts, use the address only when * there's a single Contact in the MetaContact. */ Iterator<Contact> contactIter = metaContact.getContacts(); int contactCount = 0; String address = null; while (contactIter.hasNext()) { Contact contact = contactIter.next(); contactCount++; displayName = contact.getDisplayName(); if ((displayName == null) || (displayName.trim().length() == 0)) { /* * As said earlier, only use an address if there's a single * Contact in the MetaContact. */ address = (contactCount == 1) ? contact.getAddress() : null; } else break; } if ((address != null) && (address.trim().length() != 0) && ((displayName == null) || (displayName.trim().length() == 0))) displayName = address; } return displayName; }
/** * When a message is received determines whether to open a new chat window or chat window tab, or * to indicate that a message is received from a contact which already has an open chat. When the * chat is found checks if in mode "Auto popup enabled" and if this is the case shows the message * in the appropriate chat panel. * * @param protocolContact the source contact of the event * @param contactResource the resource from which the contact is writing * @param metaContact the metacontact containing <tt>protocolContact</tt> * @param message the message to deliver * @param eventType the event type * @param timestamp the timestamp of the event * @param correctedMessageUID the identifier of the corrected message * @param isPrivateMessaging if <tt>true</tt> the message is received from private messaging * contact. * @param privateContactRoom the chat room associated with the private messaging contact. */ private void messageReceived( final Contact protocolContact, final ContactResource contactResource, final MetaContact metaContact, final Message message, final int eventType, final Date timestamp, final String correctedMessageUID, final boolean isPrivateMessaging, final ChatRoom privateContactRoom) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater( new Runnable() { public void run() { messageReceived( protocolContact, contactResource, metaContact, message, eventType, timestamp, correctedMessageUID, isPrivateMessaging, privateContactRoom); } }); return; } // Obtain the corresponding chat panel. final ChatPanel chatPanel = chatWindowManager.getContactChat( metaContact, protocolContact, contactResource, message.getMessageUID()); // Show an envelope on the sender contact in the contact list and // in the systray. if (!chatPanel.isChatFocused()) contactList.setActiveContact(metaContact, true); // Distinguish the message type, depending on the type of event that // we have received. String messageType = null; if (eventType == MessageReceivedEvent.CONVERSATION_MESSAGE_RECEIVED) { messageType = Chat.INCOMING_MESSAGE; } else if (eventType == MessageReceivedEvent.SYSTEM_MESSAGE_RECEIVED) { messageType = Chat.SYSTEM_MESSAGE; } else if (eventType == MessageReceivedEvent.SMS_MESSAGE_RECEIVED) { messageType = Chat.SMS_MESSAGE; } String contactAddress = (contactResource != null) ? protocolContact.getAddress() + " (" + contactResource.getResourceName() + ")" : protocolContact.getAddress(); chatPanel.addMessage( contactAddress, protocolContact.getDisplayName(), timestamp, messageType, message.getContent(), message.getContentType(), message.getMessageUID(), correctedMessageUID); String resourceName = (contactResource != null) ? contactResource.getResourceName() : null; if (isPrivateMessaging) { chatWindowManager.openPrivateChatForChatRoomMember(privateContactRoom, protocolContact); } else { chatWindowManager.openChat(chatPanel, false); } ChatTransport chatTransport = chatPanel.getChatSession().findChatTransportForDescriptor(protocolContact, resourceName); chatPanel.setSelectedChatTransport(chatTransport, true); }
/** * Create a new video call and invite the specified CallPeer to it. * * @param callee the address of the callee that we should invite to a new call. * @param mediaDevice the media device to use for the desktop streaming * @return CallPeer the CallPeer that will represented by the specified uri. All following state * change events will be delivered through that call peer. The Call that this peer is a member * of could be retrieved from the CallParticipatn instance with the use of the corresponding * method. * @throws OperationFailedException with the corresponding code if we fail to create the video * call. */ public Call createVideoCall(Contact callee, MediaDevice mediaDevice) throws OperationFailedException { return this.createOutgoingVideoCall(callee.getAddress(), mediaDevice); }
/** * Returns the contact address corresponding to this chat transport. * * @return The contact address corresponding to this chat transport. */ public String getName() { return contact.getAddress(); }
/** * Loads the tooltip with the data for current metacontact. * * @param tip the tooltip to fill. */ private void loadTooltip(final ExtendedTooltip tip) { Iterator<Contact> i = metaContact.getContacts(); ContactPhoneUtil contactPhoneUtil = ContactPhoneUtil.getPhoneUtil(metaContact); String statusMessage = null; Contact protocolContact; boolean isLoading = false; while (i.hasNext()) { protocolContact = i.next(); // Set the first found status message. if (statusMessage == null && protocolContact.getStatusMessage() != null && protocolContact.getStatusMessage().length() > 0) statusMessage = protocolContact.getStatusMessage(); if (ConfigurationUtils.isHideAccountStatusSelectorsEnabled()) break; ImageIcon protocolStatusIcon = ImageLoader.getIndexedProtocolIcon( ImageUtils.getBytesInImage(protocolContact.getPresenceStatus().getStatusIcon()), protocolContact.getProtocolProvider()); String contactAddress = protocolContact.getAddress(); // String statusMessage = protocolContact.getStatusMessage(); tip.addLine(protocolStatusIcon, contactAddress); addContactResourceTooltipLines(tip, protocolContact); if (!protocolContact.getProtocolProvider().isRegistered()) continue; contactPhoneUtil.addDetailsResponseListener( protocolContact, new OperationSetServerStoredContactInfo.DetailsResponseListener() { public void detailsRetrieved(final Iterator<GenericDetail> details) { if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater( new Runnable() { public void run() { detailsRetrieved(details); } }); return; } // remove previously shown information // as it contains "Loading..." text tip.removeAllLines(); // load it again loadTooltip(tip); } }); List<String> phones = contactPhoneUtil.getPhones(protocolContact); if (phones != null) { addPhoneTooltipLines(tip, phones.iterator()); } else isLoading = true; } if (isLoading) tip.addLine(null, GuiActivator.getResources().getI18NString("service.gui.LOADING")); if (statusMessage != null) tip.setBottomText(statusMessage); }
/** * 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; }
/** * Helper function used to send a message to a contact, with the given extensions attached. * * @param to The contact to send the message to. * @param toResource The resource to send the message to or null if no resource has been specified * @param message The message to send. * @param extensions The XMPP extensions that should be attached to the message before sending. * @return The MessageDeliveryEvent that resulted after attempting to send this message, so the * calling function can modify it if needed. */ private MessageDeliveredEvent sendMessage( Contact to, ContactResource toResource, Message message, PacketExtension[] extensions) { if (!(to instanceof ContactJabberImpl)) throw new IllegalArgumentException("The specified contact is not a Jabber contact." + to); assertConnected(); org.jivesoftware.smack.packet.Message msg = new org.jivesoftware.smack.packet.Message(); String toJID = null; if (toResource != null) { if (toResource.equals(ContactResource.BASE_RESOURCE)) { toJID = to.getAddress(); } else toJID = ((ContactResourceJabberImpl) toResource).getFullJid(); } if (toJID == null) { toJID = to.getAddress(); } msg.setPacketID(message.getMessageUID()); msg.setTo(toJID); for (PacketExtension ext : extensions) { msg.addExtension(ext); } if (logger.isTraceEnabled()) logger.trace("Will send a message to:" + toJID + " chat.jid=" + toJID); MessageDeliveredEvent msgDeliveryPendingEvt = new MessageDeliveredEvent(message, to, toResource); MessageDeliveredEvent[] transformedEvents = messageDeliveryPendingTransform(msgDeliveryPendingEvt); if (transformedEvents == null || transformedEvents.length == 0) return null; for (MessageDeliveredEvent event : transformedEvents) { String content = event.getSourceMessage().getContent(); if (message.getContentType().equals(HTML_MIME_TYPE)) { msg.setBody(Html2Text.extractText(content)); // Check if the other user supports XHTML messages // make sure we use our discovery manager as it caches calls if (jabberProvider.isFeatureListSupported(toJID, HTML_NAMESPACE)) { // Add the XHTML text to the message XHTMLManager.addBody(msg, OPEN_BODY_TAG + content + CLOSE_BODY_TAG); } } else { // this is plain text so keep it as it is. msg.setBody(content); } // msg.addExtension(new Version()); if (event.isMessageEncrypted() && isCarbonEnabled) { msg.addExtension(new CarbonPacketExtension.PrivateExtension()); } MessageEventManager.addNotificationsRequests(msg, true, false, false, true); String threadID = getThreadIDForAddress(toJID); if (threadID == null) threadID = nextThreadID(); msg.setThread(threadID); msg.setType(org.jivesoftware.smack.packet.Message.Type.chat); msg.setFrom(jabberProvider.getConnection().getUser()); jabberProvider.getConnection().sendPacket(msg); putJidForAddress(toJID, threadID); } return new MessageDeliveredEvent(message, to, toResource); }
/** * The method would add a subscription for a contact, wait for a subscription event confirming the * subscription, then change the status of the newly added contact (which is actually the * IcqTesterAgent) and make sure that the corresponding notification events have been generated. * * @throws java.lang.Exception if an exception occurs during testing. */ public void postTestSubscribe() throws Exception { logger.debug("Testing Subscription and Subscription Event Dispatch."); // First create a subscription and verify that it really gets created. SubscriptionEventCollector subEvtCollector = new SubscriptionEventCollector(); logger.trace("set Auth Handler"); operationSetPresence.setAuthorizationHandler(authEventCollector); synchronized (authEventCollector) { authEventCollector.authorizationRequestReason = "Please deny my request!"; fixture.testerAgent.getAuthCmdFactory().responseReasonStr = "First authorization I will Deny!!!"; fixture.testerAgent.getAuthCmdFactory().ACCEPT = false; operationSetPresence.subscribe(fixture.testerAgent.getIcqUIN()); // this one collects event that the buddy has been added // to the list as awaiting SubscriptionEventCollector moveEvtCollector = new SubscriptionEventCollector(); operationSetPresence.addSubscriptionListener(moveEvtCollector); logger.debug("Waiting for authorization error and authorization response..."); authEventCollector.waitForAuthResponse(15000); assertTrue( "Error adding buddy not recieved or the buddy(" + fixture.testerAgent.getIcqUIN() + ") doesn't require authorization", authEventCollector.isAuthorizationRequestSent); assertNotNull( "Agent haven't received any reason for authorization", fixture.testerAgent.getAuthCmdFactory().requestReasonStr); assertEquals( "Error sent request reason is not as the received one", authEventCollector.authorizationRequestReason, fixture.testerAgent.getAuthCmdFactory().requestReasonStr); logger.debug( "authEventCollector.isAuthorizationResponseReceived " + authEventCollector.isAuthorizationResponseReceived); assertTrue("Response not received!", authEventCollector.isAuthorizationResponseReceived); boolean isAcceptedAuthReuest = authEventCollector.response.getResponseCode().equals(AuthorizationResponse.ACCEPT); assertEquals( "Response is not as the sent one", fixture.testerAgent.getAuthCmdFactory().ACCEPT, isAcceptedAuthReuest); assertNotNull( "We didn't receive any reason! ", authEventCollector.authorizationResponseString); assertEquals( "The sent response reason is not as the received one", fixture.testerAgent.getAuthCmdFactory().responseReasonStr, authEventCollector.authorizationResponseString); // here we must wait for server to move the awaiting buddy // to the first specified group synchronized (moveEvtCollector) { moveEvtCollector.waitForEvent(20000); // don't want any more events operationSetPresence.removeSubscriptionListener(moveEvtCollector); } Contact c = operationSetPresence.findContactByID(fixture.testerAgent.getIcqUIN()); logger.debug("I will remove " + c + " from group : " + c.getParentContactGroup()); UnsubscribeWait unsubscribeEvtCollector = new UnsubscribeWait(); operationSetPresence.addSubscriptionListener(unsubscribeEvtCollector); synchronized (unsubscribeEvtCollector) { operationSetPresence.unsubscribe(c); logger.debug("Waiting to be removed..."); unsubscribeEvtCollector.waitForUnsubscribre(20000); logger.debug("Received unsubscribed ok or we lost patients!"); // don't want any more events operationSetPresence.removeSubscriptionListener(unsubscribeEvtCollector); } // so we haven't asserted so everithing is fine lets try to be authorized authEventCollector.authorizationRequestReason = "Please accept my request!"; fixture.testerAgent.getAuthCmdFactory().responseReasonStr = "Second authorization I will Accept!!!"; fixture.testerAgent.getAuthCmdFactory().ACCEPT = true; // clear some things authEventCollector.isAuthorizationRequestSent = false; authEventCollector.isAuthorizationResponseReceived = false; authEventCollector.authorizationResponseString = null; logger.debug( "I will add buddy does it exists ? " + (operationSetPresence.findContactByID(fixture.testerAgent.getIcqUIN()) != null)); // add the listener beacuse now our authorization will be accepted // and so the buddy will be finally added to the list operationSetPresence.addSubscriptionListener(subEvtCollector); // subscribe again so we can trigger again the authorization procedure operationSetPresence.subscribe(fixture.testerAgent.getIcqUIN()); logger.debug( "Waiting ... Subscribe must fail and the authorization process " + "to be trigered again so waiting for auth response ..."); authEventCollector.waitForAuthResponse(15000); assertTrue( "Error adding buddy not recieved or the buddy(" + fixture.testerAgent.getIcqUIN() + ") doesn't require authorization", authEventCollector.isAuthorizationRequestSent); assertNotNull( "Agent haven't received any reason for authorization", fixture.testerAgent.getAuthCmdFactory().requestReasonStr); // not working for now assertEquals( "Error sent request reason", authEventCollector.authorizationRequestReason, fixture.testerAgent.getAuthCmdFactory().requestReasonStr); // wait for authorization process to be finnished // the modification of buddy (server will inform us // that he removed - awaiting authorization flag) Object obj = new Object(); synchronized (obj) { logger.debug("wait for authorization process to be finnished"); obj.wait(10000); logger.debug("Stop waiting!"); } subEvtCollector.waitForEvent(10000); // don't want any more events operationSetPresence.removeSubscriptionListener(subEvtCollector); } // after adding awaitingAuthorization group here are catched 3 events // 1 - creating unresolved contact // 2 - move of the contact to awaitingAuthorization group // 3 - move of the contact from awaitingAuthorization group to original group assertTrue( "Subscription event dispatching failed.", subEvtCollector.collectedEvents.size() > 0); EventObject evt = null; Iterator<EventObject> events = subEvtCollector.collectedEvents.iterator(); while (events.hasNext()) { EventObject elem = events.next(); if (elem instanceof SubscriptionEvent) { if (((SubscriptionEvent) elem).getEventID() == SubscriptionEvent.SUBSCRIPTION_CREATED) evt = (SubscriptionEvent) elem; } } Object source = null; Contact srcContact = null; ProtocolProviderService srcProvider = null; // the event can be SubscriptionEvent and the new added one // SubscriptionMovedEvent if (evt instanceof SubscriptionEvent) { SubscriptionEvent subEvt = (SubscriptionEvent) evt; source = subEvt.getSource(); srcContact = subEvt.getSourceContact(); srcProvider = subEvt.getSourceProvider(); } assertEquals( "SubscriptionEvent Source:", fixture.testerAgent.getIcqUIN(), ((Contact) source).getAddress()); assertEquals( "SubscriptionEvent Source Contact:", fixture.testerAgent.getIcqUIN(), srcContact.getAddress()); assertSame("SubscriptionEvent Source Provider:", fixture.provider, srcProvider); subEvtCollector.collectedEvents.clear(); // make the user agent tester change its states and make sure we are // notified logger.debug("Testing presence notifications."); IcqStatusEnum testerAgentOldStatus = fixture.testerAgent.getPresneceStatus(); IcqStatusEnum testerAgentNewStatus = IcqStatusEnum.FREE_FOR_CHAT; long testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_FFC; // in case we are by any chance already in a FREE_FOR_CHAT status, we'll // be changing to something else if (testerAgentOldStatus.equals(testerAgentNewStatus)) { testerAgentNewStatus = IcqStatusEnum.DO_NOT_DISTURB; testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_DND; } // now do the actual status notification testing ContactPresenceEventCollector contactPresEvtCollector = new ContactPresenceEventCollector(fixture.testerAgent.getIcqUIN(), testerAgentNewStatus); operationSetPresence.addContactPresenceStatusListener(contactPresEvtCollector); synchronized (contactPresEvtCollector) { if (!fixture.testerAgent.enterStatus(testerAgentNewStatusLong)) { throw new RuntimeException( "Tester UserAgent Failed to switch to the " + testerAgentNewStatus.getStatusName() + " state."); } // we may already have the event, but it won't hurt to check. contactPresEvtCollector.waitForEvent(12000); operationSetPresence.removeContactPresenceStatusListener(contactPresEvtCollector); } if (contactPresEvtCollector.collectedEvents.size() == 0) { logger.info( "PROBLEM. Authorisation process doesn't have finnished " + "Server doesn't report us for changing authorization flag! Will try to authorize once again"); fixture.testerAgent.sendAuthorizationReplay( fixture.icqAccountID.getUserID(), fixture.testerAgent.getAuthCmdFactory().responseReasonStr, fixture.testerAgent.getAuthCmdFactory().ACCEPT); Object obj = new Object(); synchronized (obj) { logger.debug("wait for authorization process to be finnished for second time"); obj.wait(10000); logger.debug("Stop waiting!"); } testerAgentOldStatus = fixture.testerAgent.getPresneceStatus(); testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_FFC; // in case we are by any chance already in a FREE_FOR_CHAT status, we'll // be changing to something else if (testerAgentOldStatus.equals(testerAgentNewStatus)) { testerAgentNewStatus = IcqStatusEnum.OCCUPIED; testerAgentNewStatusLong = FullUserInfo.ICQSTATUS_OCCUPIED; } contactPresEvtCollector = new ContactPresenceEventCollector(fixture.testerAgent.getIcqUIN(), testerAgentNewStatus); operationSetPresence.addContactPresenceStatusListener(contactPresEvtCollector); synchronized (contactPresEvtCollector) { if (!fixture.testerAgent.enterStatus(testerAgentNewStatusLong)) { throw new RuntimeException( "Tester UserAgent Failed to switch to the " + testerAgentNewStatus.getStatusName() + " state."); } // we may already have the event, but it won't hurt to check. contactPresEvtCollector.waitForEvent(12000); operationSetPresence.removeContactPresenceStatusListener(contactPresEvtCollector); } } assertEquals( "Presence Notif. event dispatching failed.", 1, contactPresEvtCollector.collectedEvents.size()); ContactPresenceStatusChangeEvent presEvt = (ContactPresenceStatusChangeEvent) contactPresEvtCollector.collectedEvents.get(0); assertEquals( "Presence Notif. event Source:", fixture.testerAgent.getIcqUIN(), ((Contact) presEvt.getSource()).getAddress()); assertEquals( "Presence Notif. event Source Contact:", fixture.testerAgent.getIcqUIN(), presEvt.getSourceContact().getAddress()); assertSame( "Presence Notif. event Source Provider:", fixture.provider, presEvt.getSourceProvider()); PresenceStatus reportedNewStatus = presEvt.getNewStatus(); PresenceStatus reportedOldStatus = presEvt.getOldStatus(); assertEquals("Reported new PresenceStatus: ", testerAgentNewStatus, reportedNewStatus); // don't require equality between the reported old PresenceStatus and // the actual presence status of the tester agent because a first // notification is not supposed to have the old status as it really was. assertNotNull("Reported old PresenceStatus: ", reportedOldStatus); /** @todo tester agent changes status message we see the new message */ /** @todo we should see the alias of the tester agent. */ Object obj = new Object(); synchronized (obj) { logger.debug("wait a moment. give time to server"); obj.wait(4000); } }
/** * 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; }