/** * Put the JAIN-SIP stack in a state where it cannot receive any data and frees the network ports * used. That is to say remove JAIN-SIP <tt>ListeningPoint</tt>s and <tt>SipProvider</tt>s. */ @SuppressWarnings("unchecked") // jain-sip legacy code private void stopListening() { try { this.secureJainSipProvider.removeSipListener(this); this.stack.deleteSipProvider(this.secureJainSipProvider); this.secureJainSipProvider = null; this.clearJainSipProvider.removeSipListener(this); this.stack.deleteSipProvider(this.clearJainSipProvider); this.clearJainSipProvider = null; Iterator<ListeningPoint> it = this.stack.getListeningPoints(); Vector<ListeningPoint> lpointsToRemove = new Vector<ListeningPoint>(); while (it.hasNext()) { lpointsToRemove.add(it.next()); } it = lpointsToRemove.iterator(); while (it.hasNext()) { this.stack.deleteListeningPoint(it.next()); } this.stack.stop(); if (logger.isTraceEnabled()) logger.trace("stopped listening"); } catch (ObjectInUseException ex) { logger.fatal("Failed to stop listening", ex); } }
/** * 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 {@link CallJabberImpl} containing a {@link CallPeerJabberImpl} whose corresponding * jingle session has the specified jingle <tt>sid</tt>. * * @param sid the jingle <tt>sid</tt> we're looking for. * @return the {@link CallJabberImpl} containing the peer with the specified <tt>sid</tt> or * <tt>null</tt> if we couldn't find one matching it. */ public T findSID(String sid) { Iterator<T> calls = getActiveCalls(); while (calls.hasNext()) { T call = calls.next(); if (call.containsSID(sid)) return call; } return null; }
/** * Delivers the file transfer to all registered listeners. * * @param event the <tt>FileTransferEvent</tt> that we'd like delivered to all registered file * transfer listeners. */ void fireFileTransferCreated(FileTransferCreatedEvent event) { Iterator<FileTransferListener> listeners = null; synchronized (fileTransferListeners) { listeners = new ArrayList<FileTransferListener>(fileTransferListeners).iterator(); } while (listeners.hasNext()) { FileTransferListener listener = listeners.next(); listener.fileTransferCreated(event); } }
@Override protected void run() { Iterator<ChatRoomProviderWrapper> chatRoomProviders = mucService.getChatRoomProviders(); while (chatRoomProviders.hasNext()) { ChatRoomProviderWrapper provider = chatRoomProviders.next(); providerAdded(provider, true); } if (getStatus() != QUERY_CANCELED) setStatus(QUERY_COMPLETED); }
/** * Returns the {@link CallPeerJabberImpl} whose jingle session has the specified jingle * <tt>sid</tt>. * * @param sid the jingle <tt>sid</tt> we're looking for. * @return the {@link CallPeerJabberImpl} with the specified <tt>sid</tt> or <tt>null</tt> if we * couldn't find one matching it. */ public U findCallPeer(String sid) { Iterator<T> calls = getActiveCalls(); while (calls.hasNext()) { T call = calls.next(); U peer = call.getPeer(sid); if (peer != null) return peer; } return null; }
/** * Returns the {@link CallPeerJabberImpl} whose session-init's ID has the specified IQ * <tt>id</tt>. * * @param id the IQ <tt>id</tt> we're looking for. * @return the {@link CallPeerJabberImpl} with the specified <tt>id</tt> or <tt>null</tt> if we * couldn't find one matching it. */ public U findCallPeerBySessInitPacketID(String id) { Iterator<T> calls = getActiveCalls(); while (calls.hasNext()) { T call = calls.next(); U peer = call.getPeerBySessInitPacketID(id); if (peer != null) return peer; } return null; }
/** * Returns the index of the contact in the contact results list. * * @param contact the contact. * @return the index of the contact in the contact results list. */ public synchronized int indexOf(ChatRoomSourceContact contact) { Iterator<ChatRoomSourceContact> it = contactResults.iterator(); int i = 0; while (it.hasNext()) { if (contact.equals(it.next())) { return i; } i++; } return -1; }
public WhiteboardSessionManager() { if (WhiteboardActivator.getWhiteboardOperationSets() == null) return; Iterator opSets = WhiteboardActivator.getWhiteboardOperationSets().iterator(); while (opSets.hasNext()) { OperationSetWhiteboarding whiteboardOpSet = (OperationSetWhiteboarding) opSets.next(); whiteboardOpSet.addInvitationListener(new InvitationListener()); whiteboardOpSet.addPresenceListener(new PresenceListener()); } }
/** * Returns the JAIN-SIP <tt>ListeningPoint</tt> associated to the given transport string. * * @param transport a string like "UDP", "TCP" or "TLS". * @return the LP associated to the given transport. */ @SuppressWarnings("unchecked") // jain-sip legacy code public ListeningPoint getLP(String transport) { ListeningPoint lp; Iterator<ListeningPoint> it = this.stack.getListeningPoints(); while (it.hasNext()) { lp = it.next(); // FIXME: JAIN-SIP stack is not consistent with case // (reported upstream) if (lp.getTransport().toLowerCase().equals(transport.toLowerCase())) return lp; } throw new IllegalArgumentException("Invalid transport: " + transport); }
/** * Implements ChangeListener.stateChanged. Enables the hangup button if ones selects a tab in the * main tabbed pane that contains a call panel. */ public void stateChanged(ChangeEvent e) { this.updateButtonsStateAccordingToSelectedPanel(); Component selectedPanel = mainFrame.getSelectedTab(); if (selectedPanel == null || !(selectedPanel instanceof CallPanel)) { Iterator callPanels = activeCalls.values().iterator(); while (callPanels.hasNext()) { CallPanel callPanel = (CallPanel) callPanels.next(); callPanel.removeDialogs(); } } }
/** * Removes from the specified list of candidates providers connected to a registrar that does not * match the IP address that we are receiving a request from. * * @param candidates the list of providers we've like to filter. * @param request the request that we are currently dispatching */ private void filterByAddress(List<ProtocolProviderServiceSipImpl> candidates, Request request) { Iterator<ProtocolProviderServiceSipImpl> iterPP = candidates.iterator(); while (iterPP.hasNext()) { ProtocolProviderServiceSipImpl candidate = iterPP.next(); if (candidate.getRegistrarConnection() == null) { // RegistrarLess connections are ok continue; } if (!candidate.getRegistrarConnection().isRegistrarless() && !candidate.getRegistrarConnection().isRequestFromSameConnection(request)) { iterPP.remove(); } } }
public void run() { ProtocolProviderService pps = call.getProtocolProvider(); Iterator participants = call.getCallParticipants(); while (participants.hasNext()) { CallParticipant participant = (CallParticipant) participants.next(); OperationSetBasicTelephony telephony = mainFrame.getTelephonyOpSet(pps); try { telephony.answerCallParticipant(participant); } catch (OperationFailedException e) { logger.error( "Could not answer to : " + participant + " caused by the following exception: " + e); } } }
/** * Searches for contact ids in history of recent messages. * * @param provider * @param after * @return */ List<String> getRecentContactIDs(String provider, Date after) { List<String> res = new ArrayList<String>(); try { History history = getHistory(); if (history != null) { Iterator<HistoryRecord> recs = history.getReader().findLast(NUMBER_OF_MSGS_IN_HISTORY); SimpleDateFormat sdf = new SimpleDateFormat(HistoryService.DATE_FORMAT); while (recs.hasNext()) { HistoryRecord hr = recs.next(); String contact = null; String recordProvider = null; Date timestamp = null; for (int i = 0; i < hr.getPropertyNames().length; i++) { String propName = hr.getPropertyNames()[i]; if (propName.equals(STRUCTURE_NAMES[0])) recordProvider = hr.getPropertyValues()[i]; else if (propName.equals(STRUCTURE_NAMES[1])) contact = hr.getPropertyValues()[i]; else if (propName.equals(STRUCTURE_NAMES[2])) { try { timestamp = sdf.parse(hr.getPropertyValues()[i]); } catch (ParseException e) { timestamp = new Date(Long.parseLong(hr.getPropertyValues()[i])); } } } if (recordProvider == null || contact == null) continue; if (after != null && timestamp != null && timestamp.before(after)) continue; if (recordProvider.equals(provider)) res.add(contact); } } } catch (IOException ex) { logger.error("cannot create recent_messages history", ex); } return res; }
/** * Notifies this instance that a specific <tt>ColibriConferenceIQ</tt> has been received. * * @param conferenceIQ the <tt>ColibriConferenceIQ</tt> which has been received */ private void processColibriConferenceIQ(ColibriConferenceIQ conferenceIQ) { /* * The application is not a Jitsi Videobridge server, it is a client. * Consequently, the specified ColibriConferenceIQ is sent to it in * relation to the part of the application's functionality which makes * requests to a Jitsi Videobridge server i.e. CallJabberImpl. * * Additionally, the method processColibriConferenceIQ is presently tasked * with processing ColibriConferenceIQ requests only. They are SET IQs * sent by the Jitsi Videobridge server to notify the application about * updates in the states of (colibri) conferences organized by the * application. */ if (IQ.Type.SET.equals(conferenceIQ.getType()) && conferenceIQ.getID() != null) { OperationSetBasicTelephony<?> basicTelephony = protocolProvider.getOperationSet(OperationSetBasicTelephony.class); if (basicTelephony != null) { Iterator<? extends Call> i = basicTelephony.getActiveCalls(); while (i.hasNext()) { Call call = i.next(); if (call instanceof CallJabberImpl) { CallJabberImpl callJabberImpl = (CallJabberImpl) call; MediaAwareCallConference conference = callJabberImpl.getConference(); if ((conference != null) && conference.isJitsiVideobridge()) { /* * TODO We may want to disallow rogue CallJabberImpl * instances which may throw an exception to prevent * the conferenceIQ from reaching the CallJabberImpl * instance which it was meant for. */ if (callJabberImpl.processColibriConferenceIQ(conferenceIQ)) break; } } } } } }
/** * Creates a <tt>RegistrationStateChangeEvent</tt> corresponding to the specified old and new * states and notifies all currently registered listeners. * * @param oldState the state that the provider had before the change occurred * @param newState the state that the provider is currently in. * @param reasonCode a value corresponding to one of the REASON_XXX fields of the * RegistrationStateChangeEvent class, indicating the reason for this state transition. * @param reason a String further explaining the reason code or null if no such explanation is * necessary. */ private void fireRegistrationStateChanged( RegistrationState oldState, RegistrationState newState, int reasonCode, String reason) { RegistrationStateChangeEvent event = new RegistrationStateChangeEvent(this, oldState, newState, reasonCode, reason); logger.debug( "Dispatching " + event + " to " + registrationStateListeners.size() + " listeners."); Iterator listeners = null; synchronized (registrationStateListeners) { listeners = new ArrayList(registrationStateListeners).iterator(); } while (listeners.hasNext()) { RegistrationStateChangeListener listener = (RegistrationStateChangeListener) listeners.next(); listener.registrationStateChanged(event); } logger.trace("Done."); }
/** Verifies that all necessary ICQ test states are supported by the implementation. */ public void testSupportedStatusSetForCompleteness() { // first create a local list containing the presence status instances // supported by the underlying implementation. Iterator<PresenceStatus> supportedStatusSetIter = operationSetPresence.getSupportedStatusSet(); List<PresenceStatus> supportedStatusSet = new LinkedList<PresenceStatus>(); while (supportedStatusSetIter.hasNext()) { supportedStatusSet.add(supportedStatusSetIter.next()); } // create a copy of the MUST status set and remove any matching status // that is also present in the supported set. List<?> requiredStatusSetCopy = (List<?>) IcqStatusEnum.icqStatusSet.clone(); requiredStatusSetCopy.removeAll(supportedStatusSet); // if we have anything left then the implementation is wrong. int unsupported = requiredStatusSetCopy.size(); assertTrue( "There are " + unsupported + " statuses as follows:" + requiredStatusSetCopy, unsupported == 0); }
@Override public void run() { try { logger.logEntry(); // From FromHeader fromHeader = null; try { // this keep alive task only makes sense in case we have // a registrar so we deliberately use our AOR and do not // use the getOurSipAddress() method. fromHeader = provider .getHeaderFactory() .createFromHeader( provider.getRegistrarConnection().getAddressOfRecord(), SipMessageFactory.generateLocalTag()); } catch (ParseException ex) { // this should never happen so let's just log and bail. logger.error("Failed to generate a from header for " + "our register request.", ex); return; } // Call ID Header CallIdHeader callIdHeader = provider.getDefaultJainSipProvider().getNewCallId(); // CSeq Header CSeqHeader cSeqHeader = null; try { cSeqHeader = provider.getHeaderFactory().createCSeqHeader(getNextCSeqValue(), Request.OPTIONS); } catch (ParseException ex) { // Should never happen logger.error("Corrupt Sip Stack", ex); return; } catch (InvalidArgumentException ex) { // Should never happen logger.error("The application is corrupt", ex); return; } // To Header ToHeader toHeader = null; try { // this request isn't really going anywhere so we put our // own address in the To Header. toHeader = provider.getHeaderFactory().createToHeader(fromHeader.getAddress(), null); } catch (ParseException ex) { logger.error("Could not create a To header for address:" + fromHeader.getAddress(), ex); return; } // MaxForwardsHeader MaxForwardsHeader maxForwardsHeader = provider.getMaxForwardsHeader(); // Request Request request = null; try { // create a host-only uri for the request uri header. String domain = ((SipURI) toHeader.getAddress().getURI()).getHost(); // request URI SipURI requestURI = provider.getAddressFactory().createSipURI(null, domain); // Via Headers ArrayList<ViaHeader> viaHeaders = provider.getLocalViaHeaders(requestURI); request = provider .getMessageFactory() .createRequest( requestURI, Request.OPTIONS, callIdHeader, cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwardsHeader); if (logger.isDebugEnabled()) logger.debug("Created OPTIONS request " + request); } catch (ParseException ex) { logger.error("Could not create an OPTIONS request!", ex); return; } Iterator<String> supportedMethods = provider.getSupportedMethods().iterator(); // add to the allows header all methods that we support while (supportedMethods.hasNext()) { String method = supportedMethods.next(); // don't support REGISTERs if (method.equals(Request.REGISTER)) continue; request.addHeader(provider.getHeaderFactory().createAllowHeader(method)); } Iterator<String> events = provider.getKnownEventsList().iterator(); synchronized (provider.getKnownEventsList()) { while (events.hasNext()) { String event = events.next(); request.addHeader(provider.getHeaderFactory().createAllowEventsHeader(event)); } } // Transaction ClientTransaction optionsTrans = null; try { optionsTrans = provider.getDefaultJainSipProvider().getNewClientTransaction(request); } catch (TransactionUnavailableException ex) { logger.error("Could not create options transaction!\n", ex); return; } try { optionsTrans.sendRequest(); if (logger.isDebugEnabled()) logger.debug("sent request= " + request); } catch (SipException ex) { logger.error("Could not send out the options request!", ex); if (ex.getCause() instanceof IOException) { // IOException problem with network disconnect(); } return; } } catch (Exception ex) { logger.error("Cannot send OPTIONS keep alive", ex); } }
/** * 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); } }
/** * parses received phones list and creates/resolves groups and contacts * * @param objReceived the obj with data. */ private void phonesRecieved(JSONObject objReceived) { try { if (!objReceived.get("function").equals("sendlist") || !objReceived.containsKey("payload")) return; JSONObject payload = (JSONObject) objReceived.get("payload"); /* * FIXME The following contains two very inefficient Map-iterating * loops. */ Iterator iter = payload.keySet().iterator(); List<JSONObject> phoneList = new ArrayList<JSONObject>(); while (iter.hasNext()) { JSONObject obj = (JSONObject) payload.get(iter.next()); Iterator phonesIter = obj.keySet().iterator(); while (phonesIter.hasNext()) phoneList.add((JSONObject) obj.get(phonesIter.next())); } for (JSONObject phone : phoneList) { try { // don't handle non sip phones if (!((String) phone.get("tech")).equalsIgnoreCase("sip")) continue; String groupName = (String) phone.get("context"); ContactGroupSipImpl parentGroup = findGroupByName(groupName); if (parentGroup == null) { parentGroup = new ContactGroupSipImpl(groupName, sipProvider); parentGroup.setPersistent(true); getRootGroup().addSubgroup(parentGroup); fireGroupEvent(parentGroup, ServerStoredGroupEvent.GROUP_CREATED_EVENT); } String number = (String) phone.get("number"); Address address = sipProvider.parseAddressString(number); // if the contact is already in the contact list ContactSipImpl contact = parentOperationSet.resolveContactID(address.toString()); if (contact == null) { contact = new ContactSipImpl(address, sipProvider); contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname")); contact.setResolved(true); parentGroup.addContact(contact); fireContactAdded(parentGroup, contact); } else { contact.setDisplayName(phone.get("firstname") + " " + phone.get("lastname")); contact.setResolved(true); fireContactResolved(parentGroup, contact); } } catch (Throwable t) { logger.error("Error parsing " + phone); } } } catch (Throwable t) { logger.error("Error init list from server", t); } }
/** * Retrieves a server stored contact list and checks whether it contains all contacts that have * been added there during the initialization phase by the testerAgent. */ public void testRetrievingServerStoredContactList() { ContactGroup rootGroup = opSetPersPresence1.getServerStoredContactListRoot(); logger.debug("=========== Server Stored Contact List ================="); logger.debug( "rootGroup=" + rootGroup.getGroupName() + " rootGroup.childContacts=" + rootGroup.countContacts() + "rootGroup.childGroups=" + rootGroup.countSubgroups() + "Printing rootGroupContents=\n" + rootGroup.toString()); Hashtable<String, List<String>> expectedContactList = GibberishSlickFixture.preInstalledBuddyList; logger.debug("============== Expected Contact List ==================="); logger.debug(expectedContactList); // Go through the contact list retrieved by the persistence presence set // and remove the name of every contact and group that we find there from // the expected contct list hashtable. Iterator<ContactGroup> groups = rootGroup.subgroups(); while (groups.hasNext()) { ContactGroup group = groups.next(); List<String> expectedContactsInGroup = expectedContactList.get(group.getGroupName()); // When sending the offline message // the sever creates a group NotInContactList, // because the buddy we are sending message to is not in // the contactlist. So this group must be ignored if (!group.getGroupName().equals("NotInContactList")) { assertNotNull( "Group " + group.getGroupName() + " was returned by " + "the server but was not in the expected contact list.", expectedContactsInGroup); Iterator<Contact> contactsIter = group.contacts(); while (contactsIter.hasNext()) { String contactID = contactsIter.next().getAddress(); expectedContactsInGroup.remove(contactID); } // If we've removed all the sub contacts, remove the group too. if (expectedContactsInGroup.size() == 0) expectedContactList.remove(group.getGroupName()); } } // whatever we now have in the expected contact list snapshot are groups, // that have been added by the testerAgent but that were not retrieved // by the persistent presence operation set. assertTrue( "The following contacts were on the server sidec contact " + "list, but were not returned by the pers. pres. op. set" + expectedContactList.toString(), expectedContactList.isEmpty()); }
/** * 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; }
/** * Handles the <tt>ActionEvent</tt> generated when user presses one of the buttons in this panel. */ public void actionPerformed(ActionEvent evt) { JButton button = (JButton) evt.getSource(); String buttonName = button.getName(); if (buttonName.equals("call")) { Component selectedPanel = mainFrame.getSelectedTab(); // call button is pressed over an already open call panel if (selectedPanel != null && selectedPanel instanceof CallPanel && ((CallPanel) selectedPanel).getCall().getCallState() == CallState.CALL_INITIALIZATION) { NotificationManager.stopSound(NotificationManager.BUSY_CALL); NotificationManager.stopSound(NotificationManager.INCOMING_CALL); CallPanel callPanel = (CallPanel) selectedPanel; Iterator participantPanels = callPanel.getParticipantsPanels(); while (participantPanels.hasNext()) { CallParticipantPanel panel = (CallParticipantPanel) participantPanels.next(); panel.setState("Connecting"); } Call call = callPanel.getCall(); answerCall(call); } // call button is pressed over the call list else if (selectedPanel != null && selectedPanel instanceof CallListPanel && ((CallListPanel) selectedPanel).getCallList().getSelectedIndex() != -1) { CallListPanel callListPanel = (CallListPanel) selectedPanel; GuiCallParticipantRecord callRecord = (GuiCallParticipantRecord) callListPanel.getCallList().getSelectedValue(); String stringContact = callRecord.getParticipantName(); createCall(stringContact); } // call button is pressed over the contact list else if (selectedPanel != null && selectedPanel instanceof ContactListPanel) { // call button is pressed when a meta contact is selected if (isCallMetaContact) { Object[] selectedContacts = mainFrame.getContactListPanel().getContactList().getSelectedValues(); Vector telephonyContacts = new Vector(); for (int i = 0; i < selectedContacts.length; i++) { Object o = selectedContacts[i]; if (o instanceof MetaContact) { Contact contact = ((MetaContact) o).getDefaultContact(OperationSetBasicTelephony.class); if (contact != null) telephonyContacts.add(contact); else { new ErrorDialog( this.mainFrame, Messages.getI18NString("warning").getText(), Messages.getI18NString( "contactNotSupportingTelephony", new String[] {((MetaContact) o).getDisplayName()}) .getText()) .showDialog(); } } } if (telephonyContacts.size() > 0) createCall(telephonyContacts); } else if (!phoneNumberCombo.isComboFieldEmpty()) { // if no contact is selected checks if the user has chosen // or has // writen something in the phone combo box String stringContact = phoneNumberCombo.getEditor().getItem().toString(); createCall(stringContact); } } else if (selectedPanel != null && selectedPanel instanceof DialPanel) { String stringContact = phoneNumberCombo.getEditor().getItem().toString(); createCall(stringContact); } } else if (buttonName.equalsIgnoreCase("hangup")) { Component selectedPanel = this.mainFrame.getSelectedTab(); if (selectedPanel != null && selectedPanel instanceof CallPanel) { NotificationManager.stopSound(NotificationManager.BUSY_CALL); NotificationManager.stopSound(NotificationManager.INCOMING_CALL); NotificationManager.stopSound(NotificationManager.OUTGOING_CALL); CallPanel callPanel = (CallPanel) selectedPanel; Call call = callPanel.getCall(); if (removeCallTimers.containsKey(callPanel)) { ((Timer) removeCallTimers.get(callPanel)).stop(); removeCallTimers.remove(callPanel); } removeCallPanel(callPanel); if (call != null) { ProtocolProviderService pps = call.getProtocolProvider(); OperationSetBasicTelephony telephony = mainFrame.getTelephonyOpSet(pps); Iterator participants = call.getCallParticipants(); while (participants.hasNext()) { try { // now we hang up the first call participant in the // call telephony.hangupCallParticipant((CallParticipant) participants.next()); } catch (OperationFailedException e) { logger.error("Hang up was not successful: " + e); } } } } } else if (buttonName.equalsIgnoreCase("minimize")) { JCheckBoxMenuItem hideCallPanelItem = mainFrame.getMainMenu().getViewMenu().getHideCallPanelItem(); if (!hideCallPanelItem.isSelected()) hideCallPanelItem.setSelected(true); this.setCallPanelVisible(false); } else if (buttonName.equalsIgnoreCase("restore")) { JCheckBoxMenuItem hideCallPanelItem = mainFrame.getMainMenu().getViewMenu().getHideCallPanelItem(); if (hideCallPanelItem.isSelected()) hideCallPanelItem.setSelected(false); this.setCallPanelVisible(true); } }
/** * Handles incoming messages and dispatches whatever events are necessary. * * @param packet the packet that we need to handle (if it is a message). */ public void processPacket(Packet packet) { if (!(packet instanceof org.jivesoftware.smack.packet.Message)) return; org.jivesoftware.smack.packet.Message msg = (org.jivesoftware.smack.packet.Message) packet; boolean isForwardedSentMessage = false; if (msg.getBody() == null) { CarbonPacketExtension carbonExt = (CarbonPacketExtension) msg.getExtension(CarbonPacketExtension.NAMESPACE); if (carbonExt == null) return; isForwardedSentMessage = (carbonExt.getElementName() == CarbonPacketExtension.SENT_ELEMENT_NAME); List<ForwardedPacketExtension> extensions = carbonExt.getChildExtensionsOfType(ForwardedPacketExtension.class); if (extensions.isEmpty()) return; ForwardedPacketExtension forwardedExt = extensions.get(0); msg = forwardedExt.getMessage(); if (msg == null || msg.getBody() == null) return; } Object multiChatExtension = msg.getExtension("x", "http://jabber.org/protocol/muc#user"); // its not for us if (multiChatExtension != null) return; String userFullId = isForwardedSentMessage ? msg.getTo() : msg.getFrom(); String userBareID = StringUtils.parseBareAddress(userFullId); boolean isPrivateMessaging = false; ChatRoom privateContactRoom = null; OperationSetMultiUserChatJabberImpl mucOpSet = (OperationSetMultiUserChatJabberImpl) jabberProvider.getOperationSet(OperationSetMultiUserChat.class); if (mucOpSet != null) privateContactRoom = mucOpSet.getChatRoom(userBareID); if (privateContactRoom != null) { isPrivateMessaging = true; } if (logger.isDebugEnabled()) { if (logger.isDebugEnabled()) logger.debug("Received from " + userBareID + " the message " + msg.toXML()); } Message newMessage = createMessage(msg.getBody(), DEFAULT_MIME_TYPE, msg.getPacketID()); // check if the message is available in xhtml PacketExtension ext = msg.getExtension("http://jabber.org/protocol/xhtml-im"); if (ext != null) { XHTMLExtension xhtmlExt = (XHTMLExtension) ext; // parse all bodies Iterator<String> bodies = xhtmlExt.getBodies(); StringBuffer messageBuff = new StringBuffer(); while (bodies.hasNext()) { String body = bodies.next(); messageBuff.append(body); } if (messageBuff.length() > 0) { // we remove body tags around message cause their // end body tag is breaking // the visualization as html in the UI String receivedMessage = messageBuff .toString() // removes body start tag .replaceAll("\\<[bB][oO][dD][yY].*?>", "") // removes body end tag .replaceAll("\\</[bB][oO][dD][yY].*?>", ""); // for some reason ' is not rendered correctly // from our ui, lets use its equivalent. Other // similar chars(< > & ") seem ok. receivedMessage = receivedMessage.replaceAll("'", "'"); newMessage = createMessage(receivedMessage, HTML_MIME_TYPE, msg.getPacketID()); } } PacketExtension correctionExtension = msg.getExtension(MessageCorrectionExtension.NAMESPACE); String correctedMessageUID = null; if (correctionExtension != null) { correctedMessageUID = ((MessageCorrectionExtension) correctionExtension).getCorrectedMessageUID(); } Contact sourceContact = opSetPersPresence.findContactByID((isPrivateMessaging ? userFullId : userBareID)); if (msg.getType() == org.jivesoftware.smack.packet.Message.Type.error) { // error which is multichat and we don't know about the contact // is a muc message error which is missing muc extension // and is coming from the room, when we try to send message to // room which was deleted or offline on the server if (isPrivateMessaging && sourceContact == null) { if (privateContactRoom != null) { XMPPError error = packet.getError(); int errorResultCode = ChatRoomMessageDeliveryFailedEvent.UNKNOWN_ERROR; if (error != null && error.getCode() == 403) { errorResultCode = ChatRoomMessageDeliveryFailedEvent.FORBIDDEN; } String errorReason = error.getMessage(); ChatRoomMessageDeliveryFailedEvent evt = new ChatRoomMessageDeliveryFailedEvent( privateContactRoom, null, errorResultCode, errorReason, new Date(), newMessage); ((ChatRoomJabberImpl) privateContactRoom).fireMessageEvent(evt); } return; } if (logger.isInfoEnabled()) logger.info("Message error received from " + userBareID); int errorResultCode = MessageDeliveryFailedEvent.UNKNOWN_ERROR; if (packet.getError() != null) { int errorCode = packet.getError().getCode(); if (errorCode == 503) { org.jivesoftware.smackx.packet.MessageEvent msgEvent = (org.jivesoftware.smackx.packet.MessageEvent) packet.getExtension("x", "jabber:x:event"); if (msgEvent != null && msgEvent.isOffline()) { errorResultCode = MessageDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED; } } } if (sourceContact == null) { sourceContact = opSetPersPresence.createVolatileContact(userFullId, isPrivateMessaging); } MessageDeliveryFailedEvent ev = new MessageDeliveryFailedEvent( newMessage, sourceContact, correctedMessageUID, errorResultCode); // ev = messageDeliveryFailedTransform(ev); if (ev != null) fireMessageEvent(ev); return; } putJidForAddress(userFullId, msg.getThread()); // In the second condition we filter all group chat messages, // because they are managed by the multi user chat operation set. if (sourceContact == null) { if (logger.isDebugEnabled()) logger.debug("received a message from an unknown contact: " + userBareID); // create the volatile contact sourceContact = opSetPersPresence.createVolatileContact(userFullId, isPrivateMessaging); } Date timestamp = new Date(); // Check for XEP-0091 timestamp (deprecated) PacketExtension delay = msg.getExtension("x", "jabber:x:delay"); if (delay != null && delay instanceof DelayInformation) { timestamp = ((DelayInformation) delay).getStamp(); } // check for XEP-0203 timestamp delay = msg.getExtension("delay", "urn:xmpp:delay"); if (delay != null && delay instanceof DelayInfo) { timestamp = ((DelayInfo) delay).getStamp(); } ContactResource resource = ((ContactJabberImpl) sourceContact).getResourceFromJid(userFullId); EventObject msgEvt = null; if (!isForwardedSentMessage) msgEvt = new MessageReceivedEvent( newMessage, sourceContact, resource, timestamp, correctedMessageUID, isPrivateMessaging, privateContactRoom); else msgEvt = new MessageDeliveredEvent(newMessage, sourceContact, timestamp); // msgReceivedEvt = messageReceivedTransform(msgReceivedEvt); if (msgEvt != null) fireMessageEvent(msgEvt); }
/** * Creates an html description of the specified mailbox. * * @param mailboxIQ the mailboxIQ that we are to describe. * @return an html description of <tt>mailboxIQ</tt> */ private String createMailboxDescription(MailboxIQ mailboxIQ) { int threadCount = mailboxIQ.getThreadCount(); String resourceHeaderKey = threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_HEADER" : "service.gui.NEW_GMAIL_HEADER"; String resourceFooterKey = threadCount > 1 ? "service.gui.NEW_GMAIL_MANY_FOOTER" : "service.gui.NEW_GMAIL_FOOTER"; // FIXME Escape HTML! String newMailHeader = JabberActivator.getResources() .getI18NString( resourceHeaderKey, new String[] { jabberProvider.getAccountID().getService(), // {0} - service name mailboxIQ.getUrl(), // {1} - inbox URI Integer.toString(threadCount) // {2} - thread count }); StringBuilder message = new StringBuilder(newMailHeader); // we now start an html table for the threads. message.append("<table width=100% cellpadding=2 cellspacing=0 "); message.append("border=0 bgcolor=#e8eef7>"); Iterator<MailThreadInfo> threads = mailboxIQ.threads(); String maxThreadsStr = (String) JabberActivator.getConfigurationService() .getProperty(PNAME_MAX_GMAIL_THREADS_PER_NOTIFICATION); int maxThreads = 5; try { if (maxThreadsStr != null) maxThreads = Integer.parseInt(maxThreadsStr); } catch (NumberFormatException e) { if (logger.isDebugEnabled()) logger.debug("Failed to parse max threads count: " + maxThreads + ". Going for default."); } // print a maximum of MAX_THREADS for (int i = 0; i < maxThreads && threads.hasNext(); i++) { message.append(threads.next().createHtmlDescription()); } message.append("</table><br/>"); if (threadCount > maxThreads) { String messageFooter = JabberActivator.getResources() .getI18NString( resourceFooterKey, new String[] { mailboxIQ.getUrl(), // {0} - inbox URI Integer.toString(threadCount - maxThreads) // {1} - thread count }); message.append(messageFooter); } return message.toString(); }
/** * Create the contact list. Later will be test to be sure that creating is ok * * @throws Exception */ public void prepareContactList() throws Exception { fixture.clearProvidersLists(); Object o = new Object(); synchronized (o) { o.wait(3000); } String contactList = System.getProperty(GibberishProtocolProviderServiceLick.CONTACT_LIST_PROPERTY_NAME, null); logger.debug( "The " + GibberishProtocolProviderServiceLick.CONTACT_LIST_PROPERTY_NAME + " property is set to=" + contactList); if (contactList == null || contactList.trim().length() < 6) // at least 4 for a UIN, 1 for the // dot and 1 for the grp name throw new IllegalArgumentException( "The " + GibberishProtocolProviderServiceLick.CONTACT_LIST_PROPERTY_NAME + " property did not contain a contact list."); StringTokenizer tokenizer = new StringTokenizer(contactList, " \n\t"); logger.debug("tokens contained by the CL tokenized=" + tokenizer.countTokens()); Hashtable<String, List<String>> contactListToCreate = new Hashtable<String, List<String>>(); // go over all group.uin tokens while (tokenizer.hasMoreTokens()) { String groupUinToken = tokenizer.nextToken(); int dotIndex = groupUinToken.indexOf("."); if (dotIndex == -1) { throw new IllegalArgumentException(groupUinToken + " is not a valid Group.UIN token"); } String groupName = groupUinToken.substring(0, dotIndex); String uin = groupUinToken.substring(dotIndex + 1); if (groupName.trim().length() < 1 || uin.trim().length() < 4) { throw new IllegalArgumentException( groupName + " or " + uin + " are not a valid group name or Gibberish user id."); } // check if we've already seen this group and if not - add it List<String> uinInThisGroup = contactListToCreate.get(groupName); if (uinInThisGroup == null) { uinInThisGroup = new ArrayList<String>(); contactListToCreate.put(groupName, uinInThisGroup); } uinInThisGroup.add(uin); } // now init the list Enumeration<String> newGroupsEnum = contactListToCreate.keys(); // go over all groups in the contactsToAdd table while (newGroupsEnum.hasMoreElements()) { String groupName = newGroupsEnum.nextElement(); logger.debug("Will add group " + groupName); opSetPersPresence1.createServerStoredContactGroup( opSetPersPresence1.getServerStoredContactListRoot(), groupName); ContactGroup newlyCreatedGroup = opSetPersPresence1.getServerStoredContactListRoot().getGroup(groupName); Iterator<String> contactsToAddToThisGroup = contactListToCreate.get(groupName).iterator(); while (contactsToAddToThisGroup.hasNext()) { String id = contactsToAddToThisGroup.next(); logger.debug("Will add buddy " + id); opSetPersPresence1.subscribe(newlyCreatedGroup, id); } } // store the created contact list for later reference GibberishSlickFixture.preInstalledBuddyList = contactListToCreate; }
/** * Implements the ContactListListener.contactSelected method. * * @param evt the <tt>ContactListEvent</tt> that notified us */ public void contactClicked(ContactListEvent evt) { // We're interested only in two click events. if (evt.getClickCount() < 2) return; UIContact descriptor = evt.getSourceContact(); // We're currently only interested in MetaContacts. if (descriptor.getDescriptor() instanceof MetaContact) { MetaContact metaContact = (MetaContact) descriptor.getDescriptor(); // Searching for the right proto contact to use as default for the // chat conversation. Contact defaultContact = metaContact.getDefaultContact(OperationSetBasicInstantMessaging.class); // do nothing if (defaultContact == null) { defaultContact = metaContact.getDefaultContact(OperationSetSmsMessaging.class); if (defaultContact == null) return; } ProtocolProviderService defaultProvider = defaultContact.getProtocolProvider(); OperationSetBasicInstantMessaging defaultIM = defaultProvider.getOperationSet(OperationSetBasicInstantMessaging.class); ProtocolProviderService protoContactProvider; OperationSetBasicInstantMessaging protoContactIM; boolean isOfflineMessagingSupported = defaultIM != null && !defaultIM.isOfflineMessagingSupported(); if (defaultContact.getPresenceStatus().getStatus() < 1 && (!isOfflineMessagingSupported || !defaultProvider.isRegistered())) { Iterator<Contact> protoContacts = metaContact.getContacts(); while (protoContacts.hasNext()) { Contact contact = protoContacts.next(); protoContactProvider = contact.getProtocolProvider(); protoContactIM = protoContactProvider.getOperationSet(OperationSetBasicInstantMessaging.class); if (protoContactIM != null && protoContactIM.isOfflineMessagingSupported() && protoContactProvider.isRegistered()) { defaultContact = contact; } } } ContactEventHandler contactHandler = mainFrame.getContactHandler(defaultContact.getProtocolProvider()); contactHandler.contactClicked(defaultContact, evt.getClickCount()); } else if (descriptor.getDescriptor() instanceof SourceContact) { SourceContact contact = (SourceContact) descriptor.getDescriptor(); List<ContactDetail> imDetails = contact.getContactDetails(OperationSetBasicInstantMessaging.class); List<ContactDetail> mucDetails = contact.getContactDetails(OperationSetMultiUserChat.class); if (imDetails != null && imDetails.size() > 0) { ProtocolProviderService pps = imDetails.get(0).getPreferredProtocolProvider(OperationSetBasicInstantMessaging.class); GuiActivator.getUIService() .getChatWindowManager() .startChat(contact.getContactAddress(), pps); } else if (mucDetails != null && mucDetails.size() > 0) { ChatRoomWrapper room = GuiActivator.getMUCService().findChatRoomWrapperFromSourceContact(contact); if (room == null) { // lets check by id ProtocolProviderService pps = mucDetails.get(0).getPreferredProtocolProvider(OperationSetMultiUserChat.class); room = GuiActivator.getMUCService() .findChatRoomWrapperFromChatRoomID(contact.getContactAddress(), pps); if (room == null) { GuiActivator.getMUCService() .createChatRoom( contact.getContactAddress(), pps, new ArrayList<String>(), "", false, false, false); } } if (room != null) GuiActivator.getMUCService().openChatRoom(room); } else { List<ContactDetail> smsDetails = contact.getContactDetails(OperationSetSmsMessaging.class); if (smsDetails != null && smsDetails.size() > 0) { GuiActivator.getUIService() .getChatWindowManager() .startChat(contact.getContactAddress(), true); } } } }