/** * WhiteboardObjectTextJabberImpl constructor. * * @param xml the XML string object to parse. */ public WhiteboardObjectTextJabberImpl(String xml) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); InputStream in = new ByteArrayInputStream(xml.getBytes()); Document doc = builder.parse(in); Element e = doc.getDocumentElement(); String elementName = e.getNodeName(); if (elementName.equals("text")) { // we have a text String id = e.getAttribute("id"); double x = Double.parseDouble(e.getAttribute("x")); double y = Double.parseDouble(e.getAttribute("y")); String fill = e.getAttribute("fill"); String fontFamily = e.getAttribute("font-family"); int fontSize = Integer.parseInt(e.getAttribute("font-size")); String text = e.getTextContent(); this.setID(id); this.setWhiteboardPoint(new WhiteboardPoint(x, y)); this.setFontName(fontFamily); this.setFontSize(fontSize); this.setText(text); this.setColor(Color.decode(fill).getRGB()); } } catch (ParserConfigurationException ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } catch (IOException ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } catch (Exception ex) { if (logger.isDebugEnabled()) logger.debug("Problem WhiteboardObject : " + xml); } }
/** * Tries to obtain a mapped/public address for the specified port (possibly by executing a STUN * query). * * @param dst the destination that we'd like to use this address with. * @param port the port whose mapping we are interested in. * @return a public address corresponding to the specified port or null if all attempts to * retrieve such an address have failed. * @throws IOException if an error occurs while stun4j is using sockets. * @throws BindException if the port is already in use. */ public InetSocketAddress getPublicAddressFor(InetAddress dst, int port) throws IOException, BindException { if (!useStun || (dst instanceof Inet6Address)) { logger.debug( "Stun is disabled for destination " + dst + ", skipping mapped address recovery (useStun=" + useStun + ", IPv6@=" + (dst instanceof Inet6Address) + ")."); // we'll still try to bind though so that we could notify the caller // if the port has been taken already. DatagramSocket bindTestSocket = new DatagramSocket(port); bindTestSocket.close(); // if we're here then the port was free. return new InetSocketAddress(getLocalHost(dst), port); } StunAddress mappedAddress = queryStunServer(port); InetSocketAddress result = null; if (mappedAddress != null) result = mappedAddress.getSocketAddress(); else { // Apparently STUN failed. Let's try to temporarily disble it // and use algorithms in getLocalHost(). ... We should probably // eveng think about completely disabling stun, and not only // temporarily. // Bug report - John J. Barton - IBM InetAddress localHost = getLocalHost(dst); result = new InetSocketAddress(localHost, port); } if (logger.isDebugEnabled()) logger.debug("Returning mapping for port:" + port + " as follows: " + result); return result; }
/** * Initializes this network address manager service implementation and starts all * processes/threads associated with this address manager, such as a stun firewall/nat detector, * keep alive threads, binding lifetime discovery threads and etc. The method may also be used * after a call to stop() as a reinitialization technique. */ public void start() { // init stun String stunAddressStr = null; int port = -1; stunAddressStr = NetaddrActivator.getConfigurationService().getString(PROP_STUN_SERVER_ADDRESS); String portStr = NetaddrActivator.getConfigurationService().getString(PROP_STUN_SERVER_PORT); this.localHostFinderSocket = initRandomPortSocket(); if (stunAddressStr == null || portStr == null) { useStun = false; // we use the default stun server address only for chosing a public // route and not for stun queries. stunServerAddress = new StunAddress(DEFAULT_STUN_SERVER_ADDRESS, DEFAULT_STUN_SERVER_PORT); logger.info( "Stun server address(" + stunAddressStr + ")/port(" + portStr + ") not set (or invalid). Disabling STUN."); } else { try { port = Integer.valueOf(portStr).intValue(); } catch (NumberFormatException ex) { logger.error(portStr + " is not a valid port number. " + "Defaulting to 3478", ex); port = 3478; } stunServerAddress = new StunAddress(stunAddressStr, port); detector = new SimpleAddressDetector(stunServerAddress); if (logger.isDebugEnabled()) { logger.debug( "Created a STUN Address detector for the following " + "STUN server: " + stunAddressStr + ":" + port); } detector.start(); logger.debug("STUN server detector started;"); // make sure that someone doesn't set invalid stun address and port NetaddrActivator.getConfigurationService() .addVetoableChangeListener(PROP_STUN_SERVER_ADDRESS, this); NetaddrActivator.getConfigurationService() .addVetoableChangeListener(PROP_STUN_SERVER_PORT, this); // now start a thread query to the stun server and only set the // useStun flag to true if it succeeds. launchStunServerTest(); } }
/** * The dependent service is available and the bundle will start. * * @param dependentService the UIService this activator is waiting. */ @Override public void start(Object dependentService) { if (logger.isDebugEnabled()) logger.debug("Update checker [STARTED]"); ConfigurationService cfg = getConfiguration(); if (OSUtils.IS_WINDOWS) { updateService = new Update(); bundleContext.registerService(UpdateService.class.getName(), updateService, null); // Register the "Check for Updates" menu item if // the "Check for Updates" property isn't disabled. if (!cfg.getBoolean(CHECK_FOR_UPDATES_MENU_DISABLED_PROP, false)) { // Register the "Check for Updates" menu item. CheckForUpdatesMenuItemComponent checkForUpdatesMenuItemComponent = new CheckForUpdatesMenuItemComponent(Container.CONTAINER_HELP_MENU); Hashtable<String, String> toolsMenuFilter = new Hashtable<String, String>(); toolsMenuFilter.put(Container.CONTAINER_ID, Container.CONTAINER_HELP_MENU.getID()); bundleContext.registerService( PluginComponent.class.getName(), checkForUpdatesMenuItemComponent, toolsMenuFilter); } // Check for software update upon startup if enabled. if (cfg.getBoolean(UPDATE_ENABLED, true)) updateService.checkForUpdates(false); } if (cfg.getBoolean(CHECK_FOR_UPDATES_DAILY_ENABLED_PROP, false)) { logger.info("Scheduled update checking enabled"); // Schedule a "check for updates" task that will run once a day int hoursToWait = calcHoursToWait(); Runnable updateRunnable = new Runnable() { public void run() { logger.debug("Performing scheduled update check"); getUpdateService().checkForUpdates(false); } }; mUpdateExecutor = Executors.newSingleThreadScheduledExecutor(); mUpdateExecutor.scheduleAtFixedRate( updateRunnable, hoursToWait, 24 * 60 * 60, TimeUnit.SECONDS); } if (logger.isDebugEnabled()) logger.debug("Update checker [REGISTERED]"); }
/** * Subscribes this provider as interested in receiving notifications for new mail messages from * Google mail services such as Gmail or Google Apps. */ private void subscribeForGmailNotifications() { // first check support for the notification service String accountIDService = jabberProvider.getAccountID().getService(); boolean notificationsAreSupported = jabberProvider.isFeatureSupported(accountIDService, NewMailNotificationIQ.NAMESPACE); if (!notificationsAreSupported) { if (logger.isDebugEnabled()) logger.debug( accountIDService + " does not seem to provide a Gmail notification " + " service so we won't be trying to subscribe for it"); return; } if (logger.isDebugEnabled()) logger.debug( accountIDService + " seems to provide a Gmail notification " + " service so we will try to subscribe for it"); ProviderManager providerManager = ProviderManager.getInstance(); providerManager.addIQProvider( MailboxIQ.ELEMENT_NAME, MailboxIQ.NAMESPACE, new MailboxIQProvider()); providerManager.addIQProvider( NewMailNotificationIQ.ELEMENT_NAME, NewMailNotificationIQ.NAMESPACE, new NewMailNotificationProvider()); Connection connection = jabberProvider.getConnection(); connection.addPacketListener(new MailboxIQListener(), new PacketTypeFilter(MailboxIQ.class)); connection.addPacketListener( new NewMailNotificationListener(), new PacketTypeFilter(NewMailNotificationIQ.class)); if (opSetPersPresence.getCurrentStatusMessage().equals(JabberStatusEnum.OFFLINE)) return; // create a query with -1 values for newer-than-tid and // newer-than-time attributes MailboxQueryIQ mailboxQuery = new MailboxQueryIQ(); if (logger.isTraceEnabled()) logger.trace( "sending mailNotification for acc: " + jabberProvider.getAccountID().getAccountUniqueID()); jabberProvider.getConnection().sendPacket(mailboxQuery); }
/** * Send an instant message from the tested operation set and assert reception by the tester agent. */ public void firstTestReceiveMessage() { String body = "This is an IM coming from the tester agent" + " on " + new Date().toString(); ImEventCollector evtCollector = new ImEventCollector(); // add a msg listener and register to the op set and send an instant // msg from the tester agent. opSetBasicIM1.addMessageListener(evtCollector); Contact testerAgentContact = opSetPresence2.findContactByID(fixture.userID1); logger.debug("Will send message " + body + " to: " + testerAgentContact); opSetBasicIM2.sendInstantMessage(testerAgentContact, opSetBasicIM2.createMessage(body)); evtCollector.waitForEvent(10000); opSetBasicIM1.removeMessageListener(evtCollector); // assert reception of a message event assertTrue( "No events delivered upon a received message", evtCollector.collectedEvents.size() > 0); // assert event instance of Message Received Evt assertTrue( "Received evt was not an instance of " + MessageReceivedEvent.class.getName(), evtCollector.collectedEvents.get(0) instanceof MessageReceivedEvent); // assert source contact == testAgent.uin MessageReceivedEvent evt = (MessageReceivedEvent) evtCollector.collectedEvents.get(0); assertEquals("message sender ", evt.getSourceContact().getAddress(), fixture.userID2); // assert messageBody == body assertEquals("message body", body, evt.getSourceMessage().getContent()); }
/** Updates Jitsi icon notification to reflect current global status. */ public void updateJitsiIconNotification() { String status; if (getGlobalStatus().isOnline()) { // At least one provider is online status = JitsiApplication.getResString(R.string.service_gui_ONLINE); } else { // There are no active providers so we consider to be in // the offline state status = JitsiApplication.getResString(R.string.service_gui_OFFLINE); } int notificationID = OSGiService.getGeneralNotificationId(); if (notificationID == -1) { logger.debug( "Not displaying status notification because" + " there's no global notification icon available."); return; } AndroidUtils.updateGeneralNotification( JitsiApplication.getGlobalContext(), notificationID, JitsiApplication.getResString(R.string.app_name), status, System.currentTimeMillis()); }
private void handleMuteIq(MuteIq muteIq) { Boolean doMute = muteIq.getMute(); String jid = muteIq.getJid(); if (doMute == null || StringUtils.isNullOrEmpty(jid)) return; String from = muteIq.getFrom(); JitsiMeetConference conference = getConferenceForMucJid(from); if (conference == null) { logger.debug("Mute error: room not found for JID: " + from); return; } IQ result; if (conference.handleMuteRequest(muteIq.getFrom(), jid, doMute)) { result = IQ.createResultIQ(muteIq); if (!muteIq.getFrom().equals(jid)) { MuteIq muteStatusUpdate = new MuteIq(); muteStatusUpdate.setType(IQ.Type.SET); muteStatusUpdate.setTo(jid); muteStatusUpdate.setMute(doMute); smackXmpp.getXmppConnection().sendPacket(muteStatusUpdate); } } else { result = IQ.createErrorResponse(muteIq, new XMPPError(XMPPError.Condition.interna_server_error)); } smackXmpp.getXmppConnection().sendPacket(result); }
/** * Called to indicate that delivery of a WhiteboardObject sent earlier has failed. Reason code and * phrase are contained by the <tt>WhiteboardObjectDeliveryFailedEvent</tt> * * @param evt the <tt>WhiteboardObjectDeliveryFailedEvent</tt> containing the ID of the * WhiteboardObject whose delivery has failed. */ public void whiteboardObjectDeliveryFailed(WhiteboardObjectDeliveryFailedEvent evt) { String errorMessage = null; if (evt.getErrorCode() == WhiteboardObjectDeliveryFailedEvent.NETWORK_FAILURE) { errorMessage = "Network failure."; } else if (evt.getErrorCode() == WhiteboardObjectDeliveryFailedEvent.OFFLINE_MESSAGES_NOT_SUPPORTED) { errorMessage = "Offline messages aren't supported."; } else if (evt.getErrorCode() == WhiteboardObjectDeliveryFailedEvent.PROVIDER_NOT_REGISTERED) { errorMessage = "Protocol provider is not registered."; } else if (evt.getErrorCode() == WhiteboardObjectDeliveryFailedEvent.INTERNAL_ERROR) { errorMessage = "An internal error occured."; } else if (evt.getErrorCode() == WhiteboardObjectDeliveryFailedEvent.UNKNOWN_ERROR) { errorMessage = "An unknown error occured."; } String debugErrorMessage = "WBObjectDeliveryFailedEvent: The following object: " + evt.getSourceWhiteboardObject() + " has NOT been delivered to " + evt.getDestinationContact().getDisplayName() + " because of the following error: " + errorMessage; logger.debug(debugErrorMessage); WhiteboardActivator.getUiService() .getPopupDialog() .showMessagePopupDialog(errorMessage, "Error", PopupDialog.ERROR_MESSAGE); }
@Override /** * Returns the size of the image in bytes. * * @param sourceString the image link. * @return the file size in bytes of the image link provided; -1 if the size isn't available or * exceeds the max allowed image size. */ public int getImageSize(String sourceString) { int length = -1; try { URL url = new URL(sourceString); String protocol = url.getProtocol(); if (protocol.equals("http") || protocol.equals("https")) { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); length = connection.getContentLength(); connection.disconnect(); } else if (protocol.equals("ftp")) { FTPUtils ftp = new FTPUtils(sourceString); length = ftp.getSize(); ftp.disconnect(); } if (length > imgMaxSize) { length = -1; } } catch (Exception e) { logger.debug("Failed to get the length of the image in bytes", e); } return length; }
/** * Presents the login welcome message to user * * @param sshContact ID of SSH Contact */ public void showWelcomeMessage(ContactSSH sshContact) throws IOException { /* //sending the command sshContact.sendLine(testCommand); String reply = "", line = ""; // message is extracted until the test Command ie echoed back while(line.indexOf(testCommand) == -1) { reply += line + "\n"; line = sshContact.getLine(); } uiService.getPopupDialog().showMessagePopupDialog (reply,"Message from " + sshContact.getDisplayName(), uiService.getPopupDialog().INFORMATION_MESSAGE); if(line.startsWith(testCommand)) while(!sshContact.getLine().contains(testCommand)); //one line output of testCommand sshContact.getLine(); */ logger.debug("SSH: Welcome message shown"); }
/** * A method that would simply send messages to a group of people so that they would get notified * that tests are being run. */ public void testSendFunMessages() { String hostname = ""; try { hostname = java.net.InetAddress.getLocalHost().getHostName() + ": "; } catch (UnknownHostException ex) { } String message = hostname + "Hello this is the SIP Communicator (version " + System.getProperty("sip-communicator.version") + ") build on: " + new Date().toString() + ". Have a very nice day!"; String list = System.getProperty("accounts.reporting.ICQ_REPORT_LIST"); logger.debug("Will send message " + message + " to: " + list); // if no property is specified - return if (list == null || list.trim().length() == 0) return; StringTokenizer tokenizer = new StringTokenizer(list, " "); while (tokenizer.hasMoreTokens()) { fixture.testerAgent.sendMessage(tokenizer.nextToken(), message); } }
public void setCurrentContact(Contact contact, String resourceName) { if (contact == null) { this.otrContact = null; this.setPolicy(null); this.setStatus(ScSessionStatus.PLAINTEXT); return; } if (resourceName == null) { OtrContact otrContact = OtrContactManager.getOtrContact(contact, null); if (this.otrContact == otrContact) return; this.otrContact = otrContact; this.setStatus(OtrActivator.scOtrEngine.getSessionStatus(otrContact)); this.setPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact)); return; } for (ContactResource resource : contact.getResources()) { if (resource.getResourceName().equals(resourceName)) { OtrContact otrContact = OtrContactManager.getOtrContact(contact, resource); if (this.otrContact == otrContact) return; this.otrContact = otrContact; this.setStatus(OtrActivator.scOtrEngine.getSessionStatus(otrContact)); this.setPolicy(OtrActivator.scOtrEngine.getContactPolicy(contact)); return; } } logger.debug("Could not find resource for contact " + contact); }
/** * Called when the underlying implementation has received an indication that a WhiteboardObject, * sent earlier has been successfully received by the destination. * * @param evt the WhiteboardObjectDeliveredEvent containing the id of the WhiteboardObject that * has caused the event. */ public void whiteboardObjectDelivered(WhiteboardObjectDeliveredEvent evt) { logger.debug( "WBObjectDeliveredEvent: The following object: " + evt.getSourceWhiteboardObject() + " has been delivered to " + evt.getDestinationContact().getDisplayName()); }
/** * The AIM server doesn't like it if we change states too often and we use this method to slow * things down. */ private void pauseBetweenStateChanges() { try { Thread.sleep(5000); } catch (InterruptedException ex) { logger.debug("Pausing between state changes was interrupted", ex); } }
private void handleRayoIQ(RayoIqProvider.DialIq dialIq) { String from = dialIq.getFrom(); JitsiMeetConference conference = getConferenceForMucJid(from); if (conference == null) { logger.debug("Mute error: room not found for JID: " + from); return; } ChatRoomMemberRole role = conference.getRoleForMucJid(from); if (role == null) { // Only room members are allowed to send requests IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.forbidden)); smackXmpp.getXmppConnection().sendPacket(error); return; } if (ChatRoomMemberRole.MODERATOR.compareTo(role) < 0) { // Moderator permission is required IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.not_allowed)); smackXmpp.getXmppConnection().sendPacket(error); return; } // Check if Jigasi is available String jigasiJid = conference.getServices().getSipGateway(); if (StringUtils.isNullOrEmpty(jigasiJid)) { // Not available IQ error = createErrorResponse(dialIq, new XMPPError(XMPPError.Condition.service_unavailable)); smackXmpp.getXmppConnection().sendPacket(error); return; } // Redirect original request to Jigasi component String originalPacketId = dialIq.getPacketID(); dialIq.setFrom(null); dialIq.setTo(jigasiJid); dialIq.setPacketID(IQ.nextID()); IQ reply = (IQ) smackXmpp.getXmppConnection().sendPacketAndGetReply(dialIq); // Send Jigasi response back to the client reply.setFrom(null); reply.setTo(from); reply.setPacketID(originalPacketId); smackXmpp.getXmppConnection().sendPacket(reply); }
/** * Initializes and binds a socket that on a random port number. The method would try to bind on a * random port and retry 5 times until a free port is found. * * @return the socket that we have initialized on a randomport number. */ private DatagramSocket initRandomPortSocket() { DatagramSocket resultSocket = null; String bindRetriesStr = NetaddrActivator.getConfigurationService().getString(BIND_RETRIES_PROPERTY_NAME); int bindRetries = 5; if (bindRetriesStr != null) { try { bindRetries = Integer.parseInt(bindRetriesStr); } catch (NumberFormatException ex) { logger.error( bindRetriesStr + " does not appear to be an integer. " + "Defaulting port bind retries to " + bindRetries, ex); } } int currentlyTriedPort = NetworkUtils.getRandomPortNumber(); // we'll first try to bind to a random port. if this fails we'll try // again (bindRetries times in all) until we find a free local port. for (int i = 0; i < bindRetries; i++) { try { resultSocket = new DatagramSocket(currentlyTriedPort); // we succeeded - break so that we don't try to bind again break; } catch (SocketException exc) { if (exc.getMessage().indexOf("Address already in use") == -1) { logger.fatal( "An exception occurred while trying to create" + "a local host discovery socket.", exc); resultSocket = null; return null; } // port seems to be taken. try another one. logger.debug("Port " + currentlyTriedPort + " seems in use."); currentlyTriedPort = NetworkUtils.getRandomPortNumber(); logger.debug("Retrying bind on port " + currentlyTriedPort); } } return resultSocket; }
/** * Stop the bundle. Nothing to stop for now. * * @param bundleContext <tt>BundleContext</tt> provided by OSGi framework * @throws Exception if something goes wrong during stop */ public void stop(BundleContext bundleContext) throws Exception { if (logger.isDebugEnabled()) logger.debug("Update checker [STOPPED]"); if (mUpdateExecutor != null) { mUpdateExecutor.shutdown(); mUpdateExecutor = null; } }
/** * Handles {@link EventFactory#FOCUS_JOINED_ROOM_TOPIC} and {@link * EventFactory#CONFERENCE_ROOM_TOPIC}. * * <p>{@inheritDoc} */ @Override public void handleEvent(Event event) { String topic = event.getTopic(); if (!topic.equals(EventFactory.FOCUS_JOINED_ROOM_TOPIC) && !topic.equals(EventFactory.CONFERENCE_ROOM_TOPIC)) { logger.error("Unexpected event topic: " + topic); return; } String roomJid = (String) event.getProperty(EventFactory.ROOM_JID_KEY); JitsiMeetConference conference = focusManager.getConference(roomJid); if (conference == null) { logger.error("Conference is null"); return; } ChatRoom chatRoom = conference.getChatRoom(); if (chatRoom == null) { logger.error("Chat room is null"); return; } JitsiMeetServices meetServices = focusManager.getJitsiMeetServices(); ComponentVersionsExtension versionsExtension = new ComponentVersionsExtension(); // XMPP Version xmppServerVersion = meetServices.getXMPPServerVersion(); if (xmppServerVersion != null) { versionsExtension.addComponentVersion( ComponentVersionsExtension.COMPONENT_XMPP_SERVER, xmppServerVersion.getNameVersionOsString()); } // Conference focus org.jitsi.service.version.Version jicofoVersion = versionService.getCurrentVersion(); versionsExtension.addComponentVersion( ComponentVersionsExtension.COMPONENT_FOCUS, jicofoVersion.getApplicationName() + "(" + jicofoVersion.toString() + "," + System.getProperty("os.name") + ")"); // Videobridge // It is not be reported for FOCUS_JOINED_ROOM_TOPIC String bridgeJid = (String) event.getProperty(EventFactory.BRIDGE_JID_KEY); Version jvbVersion = bridgeJid == null ? null : meetServices.getBridgeVersion(bridgeJid); if (jvbVersion != null) { versionsExtension.addComponentVersion( ComponentVersionsExtension.COMPONENT_VIDEOBRIDGE, jvbVersion.getNameVersionOsString()); } meetTools.sendPresenceExtension(chatRoom, versionsExtension); if (logger.isDebugEnabled()) logger.debug("Sending versions: " + versionsExtension.toXML()); }
public void waitForUnsubscribre(long waitFor) { synchronized (this) { try { wait(waitFor); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a subscription evt", ex); } } }
/** Creates instances of CameraTextureRender and SurfaceTexture. */ public SurfaceTextureManager() { textureRender = new CameraTextureRender(); textureRender.surfaceCreated(); logger.debug("textureID=" + textureRender.getTextureId()); surfaceTexture = new SurfaceTexture(textureRender.getTextureId()); surfaceTexture.setOnFrameAvailableListener(this); }
public void waitForAuthRequest(long waitFor) { synchronized (this) { if (isAuthorizationRequestReceived) return; try { wait(waitFor); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a subscription evt", ex); } } }
/** * Ends the call with for this <tt>CallPeer</tt>. Depending on the state of the peer the method * would send a CANCEL, BYE, or BUSY_HERE message and set the new state to DISCONNECTED. * * @param failed indicates if the hangup is following to a call failure or simply a disconnect * @param reasonText the text, if any, to be set on the <tt>ReasonPacketExtension</tt> as the * value of its * @param reasonOtherExtension the <tt>PacketExtension</tt>, if any, to be set on the * <tt>ReasonPacketExtension</tt> as the value of its <tt>otherExtension</tt> property */ public void hangup(boolean failed, String reasonText, PacketExtension reasonOtherExtension) { // do nothing if the call is already ended if (CallPeerState.DISCONNECTED.equals(getState()) || CallPeerState.FAILED.equals(getState())) { if (logger.isDebugEnabled()) logger.debug("Ignoring a request to hangup a call peer " + "that is already DISCONNECTED"); return; } CallPeerState prevPeerState = getState(); getMediaHandler().getTransportManager().close(); if (failed) setState(CallPeerState.FAILED, reasonText); else setState(CallPeerState.DISCONNECTED, reasonText); SessionIQ responseIQ = null; if (prevPeerState.equals(CallPeerState.CONNECTED) || CallPeerState.isOnHold(prevPeerState)) { responseIQ = GTalkPacketFactory.createBye(getProtocolProvider().getOurJID(), peerJID, getSID()); responseIQ.setInitiator(isInitiator() ? getAddress() : getProtocolProvider().getOurJID()); } else if (CallPeerState.CONNECTING.equals(prevPeerState) || CallPeerState.CONNECTING_WITH_EARLY_MEDIA.equals(prevPeerState) || CallPeerState.ALERTING_REMOTE_SIDE.equals(prevPeerState)) { responseIQ = GTalkPacketFactory.createCancel(getProtocolProvider().getOurJID(), peerJID, getSID()); responseIQ.setInitiator(isInitiator() ? getAddress() : getProtocolProvider().getOurJID()); } else if (prevPeerState.equals(CallPeerState.INCOMING_CALL)) { responseIQ = GTalkPacketFactory.createBusy(getProtocolProvider().getOurJID(), peerJID, getSID()); responseIQ.setInitiator(isInitiator() ? getAddress() : getProtocolProvider().getOurJID()); } else if (prevPeerState.equals(CallPeerState.BUSY) || prevPeerState.equals(CallPeerState.FAILED)) { // For FAILED and BUSY we only need to update CALL_STATUS // as everything else has been done already. } else { logger.info("Could not determine call peer state!"); } if (responseIQ != null) { if (reasonOtherExtension != null) { ReasonPacketExtension reason = (ReasonPacketExtension) responseIQ.getExtension( ReasonPacketExtension.ELEMENT_NAME, ReasonPacketExtension.NAMESPACE); if (reason == null) { if (reasonOtherExtension instanceof ReasonPacketExtension) { responseIQ.setReason((ReasonPacketExtension) reasonOtherExtension); } } else reason.setOtherExtension(reasonOtherExtension); } getProtocolProvider().getConnection().sendPacket(responseIQ); } }
/** * Dispatches the event received from a JAIN-SIP <tt>SipProvider</tt> to one of our "candidate * recipient" listeners. * * @param event the event received for a <tt>SipProvider</tt>. */ public void processIOException(IOExceptionEvent event) { try { if (logger.isTraceEnabled()) logger.trace(event); // impossible to dispatch, log here if (logger.isDebugEnabled()) logger.debug("@todo implement processIOException()"); } catch (Throwable exc) { // any exception thrown within our code should be caught here // so that we could log it rather than interrupt stack activity with // it. this.logApplicationException(DialogTerminatedEvent.class, exc); } }
/** * The method queries a Stun server for a binding for the specified port. * * @param port the port to resolve (the stun message gets sent trhough that port) * @return StunAddress the address returned by the stun server or null if an error occurred or no * address was returned * @throws IOException if an error occurs while stun4j is using sockets. * @throws BindException if the port is already in use. */ private StunAddress queryStunServer(int port) throws IOException, BindException { StunAddress mappedAddress = null; if (detector != null && useStun) { mappedAddress = detector.getMappingFor(port); if (logger.isDebugEnabled()) logger.debug( "For port:" + port + "a Stun server returned the " + "following mapping [" + mappedAddress); } return mappedAddress; }
/** * Creates a new <tt>JingleNodesRelayedCandidate</tt> instance which is to represent a specific * <tt>TransportAddress</tt>. * * @param transportAddress the <tt>TransportAddress</tt> allocated by the relay * @param component the <tt>Component</tt> for which the candidate will be added * @param localEndPoint <tt>TransportAddress</tt> of the Jingle Nodes relay where we will send our * packet. * @return a new <tt>JingleNodesRelayedCandidate</tt> instance which represents the specified * <tt>TransportAddress</tt> */ protected JingleNodesCandidate createJingleNodesCandidate( TransportAddress transportAddress, Component component, TransportAddress localEndPoint) { JingleNodesCandidate cand = null; try { cand = new JingleNodesCandidate(transportAddress, component, localEndPoint); IceSocketWrapper stunSocket = cand.getStunSocket(null); cand.getStunStack().addSocket(stunSocket); } catch (Throwable e) { logger.debug("Exception occurred when creating JingleNodesCandidate: " + e); } return cand; }
/** * Creates and sends a SUBSCRIBE request to a specific subscription <tt>Address</tt>/Request URI * if it matches a <tt>Subscription</tt> with an id tag of its Event header of a specific value in * the list of subscriptions managed by this instance with an Expires header value of zero in * order to terminate receiving event notifications and removes the specified * <tt>Subscription</tt> from the list of subscriptions managed by this instance. The removed * <tt>Subscription</tt> may receive notifications to process the <tt>Request</tt>s and/or * <tt>Response</tt>s which constitute the signaling session associated with it. If the attempt to * create the SUBSCRIBE request fails, the associated <tt>Subscription</tt> is not removed from * the list of subscriptions managed by this instance. If the specified <tt>Address</tt> does not * identify an existing <tt>Subscription</tt> in the list of subscriptions managed by this * instance, an assertion may optionally be performed or no reaction can be taken. * * @param toAddress a subscription <tt>Address</tt>/Request URI which identifies a * <tt>Subscription</tt> to be removed from the list of subscriptions managed by this instance * @param eventId the id tag placed in the Event header of the <tt>Subscription</tt> to be matched * if there is one or <tt>null</tt> if the <tt>Subscription</tt> should have no id tag in its * Event header * @param assertSubscribed <tt>true</tt> to assert if the specified subscription * <tt>Address</tt>/Request URI does not identify an existing <tt>Subscription</tt> in the * list of subscriptions managed by this instance; <tt>false</tt> to not assert if the * mentioned condition is met * @throws IllegalArgumentException if <tt>assertSubscribed</tt> is <tt>true</tt> and * <tt>toAddress</tt> and <tt>eventId</tt> do not identify an existing <tt>Subscription</tt> * in the list of subscriptions managed by this instance * @throws OperationFailedException if we fail constructing or sending the unSUBSCRIBE request. */ public void unsubscribe(Address toAddress, String eventId, boolean assertSubscribed) throws IllegalArgumentException, OperationFailedException { Subscription subscription = getSubscription(toAddress, eventId); if (subscription == null) if (assertSubscribed) throw new IllegalArgumentException("trying to unregister a not registered contact"); else return; Dialog dialog = subscription.getDialog(); // we stop the subscription if we're subscribed to this contact if (dialog != null) { String callId = dialog.getCallId().getCallId(); ClientTransaction subscribeTransaction; try { subscribeTransaction = createSubscription(subscription, dialog, 0); } catch (OperationFailedException e) { if (logger.isDebugEnabled()) logger.debug("failed to create the unsubscription", e); throw e; } // we are not anymore subscribed to this contact // this ensure that the response of this request will be // handled as an unsubscription response removeSubscription(callId, subscription); try { dialog.sendRequest(subscribeTransaction); } catch (SipException e) { if (logger.isDebugEnabled()) logger.debug("Can't send the request", e); throw new OperationFailedException( "Failed to send the subscription message", OperationFailedException.NETWORK_FAILURE, e); } } }
/** {@inheritDoc} */ @Override public VerifyCertificateDialog createDialog(Certificate[] certs, String title, String message) { if (title == null) title = JitsiApplication.getResString(R.string.service_gui_CERT_DIALOG_TITLE); Long requestId = System.currentTimeMillis(); VerifyCertDialog verifyCertDialog = new VerifyCertDialog(requestId, certs[0], title, message); requestMap.put(requestId, verifyCertDialog); logger.debug(hashCode() + " creating dialog: " + requestId); return verifyCertDialog; }
/** * Sets the icon for the given file. * * @param file the file to set an icon for * @return the byte array containing the thumbnail */ private byte[] getFileThumbnail(File file) { byte[] bytes = null; if (FileUtils.isImage(file.getName())) { try { ImageIcon image = new ImageIcon(file.toURI().toURL()); int width = image.getIconWidth(); int height = image.getIconHeight(); if (width > THUMBNAIL_WIDTH) width = THUMBNAIL_WIDTH; if (height > THUMBNAIL_HEIGHT) height = THUMBNAIL_HEIGHT; bytes = ImageUtils.getScaledInstanceInBytes(image.getImage(), width, height); } catch (MalformedURLException e) { if (logger.isDebugEnabled()) logger.debug("Could not locate image.", e); } } return bytes; }
/** * Gets the max allowed size value in bytes from Configuration service and sets the value to * <tt>imgMaxSize</tt> if succeed. If the configuration property isn't available or the value * can't be parsed correctly the value of <tt>imgMaxSize</tt> isn't changed. */ private void setMaxImgSizeFromConf() { ConfigurationService configService = DirectImageActivator.getConfigService(); if (configService != null) { String confImgSizeStr = (String) configService.getProperty(MAX_IMG_SIZE); try { if (confImgSizeStr != null) { imgMaxSize = Long.parseLong(confImgSizeStr); } else { configService.setProperty(MAX_IMG_SIZE, imgMaxSize); } } catch (NumberFormatException e) { if (logger.isDebugEnabled()) logger.debug( "Failed to parse max image size: " + confImgSizeStr + ". Going for default."); } } }