/**
   * Handles registration of a new configuration form.
   *
   * @param event the <tt>ServiceEvent</tt> that notified us
   */
  public void serviceChanged(ServiceEvent event) {
    Object sService = AdvancedConfigActivator.bundleContext.getService(event.getServiceReference());

    // we don't care if the source service is not a configuration form
    if (!(sService instanceof ConfigurationForm)) return;

    ConfigurationForm configForm = (ConfigurationForm) sService;

    /*
     * This AdvancedConfigurationPanel is an advanced ConfigurationForm so
     * don't try to add it to itself.
     */
    if ((configForm == this) || !configForm.isAdvanced()) return;

    switch (event.getType()) {
      case ServiceEvent.REGISTERED:
        if (logger.isInfoEnabled())
          logger.info("Handling registration of a new Configuration Form.");

        this.addConfigForm(configForm);
        break;

      case ServiceEvent.UNREGISTERING:
        this.removeConfigForm(configForm);
        break;
    }
  }
示例#2
0
  /**
   * 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 evt the event containing details on the received message
   */
  public void messageReceived(MessageReceivedEvent evt) {
    if (logger.isTraceEnabled())
      logger.trace("MESSAGE RECEIVED from contact: " + evt.getSourceContact().getAddress());

    Contact protocolContact = evt.getSourceContact();
    ContactResource contactResource = evt.getContactResource();
    Message message = evt.getSourceMessage();
    int eventType = evt.getEventType();
    MetaContact metaContact =
        GuiActivator.getContactListService().findMetaContactByContact(protocolContact);

    if (metaContact != null) {
      messageReceived(
          protocolContact,
          contactResource,
          metaContact,
          message,
          eventType,
          evt.getTimestamp(),
          evt.getCorrectedMessageUID(),
          evt.isPrivateMessaging(),
          evt.getPrivateMessagingContactRoom());
    } else {
      if (logger.isTraceEnabled())
        logger.trace("MetaContact not found for protocol contact: " + protocolContact + ".");
    }
  }
示例#3
0
  /**
   * 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());
  }
  /**
   * Returns the <tt>URL</tt> of the image corresponding to the given key.
   *
   * @param urlKey The identifier of the image in the resource properties file.
   * @return the <tt>URL</tt> of the image corresponding to the given key
   */
  public URL getImageURL(String urlKey) {
    String path = getImagePath(urlKey);

    if (path == null || path.length() == 0) {
      if (logger.isInfoEnabled()) logger.info("Missing resource for key: " + urlKey);
      return null;
    }
    return getImageURLForPath(path);
  }
示例#5
0
  /**
   * Returns the current stream connection that is opened.
   *
   * @return a stream connection, can be a cached one, never <code>null</code>.
   * @throws IOException in case of I/O problems creating the stream connection.
   */
  private StreamConnection getStreamConnection() throws IOException {
    if (this.connection == null) {
      final String uri = this.config.getConnectionURI();

      if (LOG.isLoggable(Level.INFO)) {
        LOG.info("Connecting to " + uri);
      }

      this.connection = createStreamConnection(uri);
    }
    return this.connection;
  }
  /**
   * Start the swing notification service
   *
   * @param bc
   * @throws java.lang.Exception
   */
  public void start(BundleContext bc) throws Exception {
    if (logger.isInfoEnabled()) logger.info("Swing Notification ...[  STARTING ]");

    bundleContext = bc;

    PopupMessageHandler handler = null;
    handler = new PopupMessageHandlerSwingImpl();

    getConfigurationService();

    bc.registerService(PopupMessageHandler.class.getName(), handler, null);

    if (logger.isInfoEnabled()) logger.info("Swing Notification ...[REGISTERED]");
  }
示例#7
0
  /**
   * Stops the <tt>msofficecomm</tt> bundle in a specific {@link BundleContext}.
   *
   * @param bundleContext the <tt>BundleContext</tt> in which the <tt>msofficecomm</tt> bundle is to
   *     be stopped
   * @throws Exception if anything goes wrong while stopping the <tt>msofficecomm</tt> bundle in the
   *     specified <tt>BundleContext</tt>
   */
  public void stop(BundleContext bundleContext) throws Exception {
    // The msofficecomm bundle is available on Windows only.
    if (!OSUtils.IS_WINDOWS) return;

    try {
      int hresult = OutOfProcessServer.stop();

      if (hresult < 0) throw new RuntimeException("HRESULT " + hresult);
    } finally {
      Messenger.stop(bundleContext);
    }

    if (logger.isInfoEnabled()) logger.info("MsOfficeComm plugin ... [UNREGISTERED]");
  }
示例#8
0
  /**
   * Sets the current device controller to the given value.
   *
   * @param aDeviceName the name of the device controller to set, cannot be <code>null</code>.
   */
  public synchronized void setDeviceController(final String aDeviceName) {
    if (LOG.isLoggable(Level.INFO)) {
      final String name = (aDeviceName == null) ? "no device" : aDeviceName;
      LOG.log(Level.INFO, "Setting current device controller to: \"{0}\" ...", name);
    }

    final Collection<DeviceController> devices = getDevices();
    for (DeviceController device : devices) {
      if (aDeviceName.equals(device.getName())) {
        this.currentDevCtrl = device;
      }
    }

    updateActions();
  }
示例#9
0
  /**
   * We fill the protocolProviderTable with all running protocol providers at the start of the
   * bundle.
   */
  private void init() {
    SystrayActivator.bundleContext.addServiceListener(new ProtocolProviderServiceListener());

    ServiceReference[] protocolProviderRefs = null;
    try {
      protocolProviderRefs =
          SystrayActivator.bundleContext.getServiceReferences(
              ProtocolProviderService.class.getName(), null);
    } catch (InvalidSyntaxException ex) {
      // this shouldn't happen since we're providing no parameter string
      // but let's log just in case.
      logger.error("Error while retrieving service refs", ex);
      return;
    }

    // in case we found any
    if (protocolProviderRefs != null) {

      for (int i = 0; i < protocolProviderRefs.length; i++) {
        ProtocolProviderService provider =
            (ProtocolProviderService)
                SystrayActivator.bundleContext.getService(protocolProviderRefs[i]);

        boolean isHidden =
            provider.getAccountID().getAccountProperties().get("HIDDEN_PROTOCOL") != null;

        if (!isHidden) this.addAccount(provider);
      }
    }
  }
示例#10
0
  /**
   * Runs the tool denoted by the given name.
   *
   * @param aToolName the name of the tool to run, cannot be <code>null</code>;
   * @param aParent the parent window to use, can be <code>null</code>.
   */
  public void runTool(final String aToolName, final Window aParent) {
    if (LOG.isLoggable(Level.INFO)) {
      LOG.log(Level.INFO, "Running tool: \"{0}\" ...", aToolName);
    }

    final Tool tool = findToolByName(aToolName);
    if (tool == null) {
      JOptionPane.showMessageDialog(
          aParent, "No such tool found: " + aToolName, "Error ...", JOptionPane.ERROR_MESSAGE);
    } else {
      final ToolContext context = createToolContext();
      tool.process(aParent, this.dataContainer, context, this);
    }

    updateActions();
  }
  /**
   * Removes the specified account from the list of accounts that this provider factory is handling.
   * If the specified accountID is unknown to the ProtocolProviderFactory, the call has no effect
   * and false is returned. This method is persistent in nature and once called the account
   * corresponding to the specified ID will not be loaded during future runs of the project.
   *
   * @param accountID the ID of the account to remove.
   * @return true if an account with the specified ID existed and was removed and false otherwise.
   */
  public boolean uninstallAccount(AccountID accountID) {
    // unregister the protocol provider
    ServiceReference serRef = getProviderForAccount(accountID);

    if (serRef == null) return false;

    ProtocolProviderService protocolProvider =
        (ProtocolProviderService) SipActivator.getBundleContext().getService(serRef);

    try {
      protocolProvider.unregister();
    } catch (OperationFailedException e) {
      logger.error(
          "Failed to unregister protocol provider for account : "
              + accountID
              + " caused by : "
              + e);
    }

    ServiceRegistration registration = (ServiceRegistration) registeredAccounts.remove(accountID);

    if (registration == null) return false;

    // kill the service
    registration.unregister();

    return removeStoredAccount(SipActivator.getBundleContext(), accountID);
  }
/** @author Symphorien Wanko */
public class PopupMessageHandlerSLick extends TestSuite implements BundleActivator {
  /** Logger for this class */
  private static Logger logger = Logger.getLogger(PopupMessageHandlerSLick.class);

  /** our bundle context */
  protected static BundleContext bundleContext = null;

  /** implements BundleActivator.start() */
  public void start(BundleContext bc) throws Exception {
    logger.info("starting popup message test ");

    bundleContext = bc;

    setName("PopupMessageHandlerSLick");

    Hashtable<String, String> properties = new Hashtable<String, String>();

    properties.put("service.pid", getName());

    // we maybe are running on machine without WM and systray
    // (test server machine), skip tests
    if (ServiceUtils.getService(bc, SystrayService.class) != null) {
      addTest(TestPopupMessageHandler.suite());
    }

    bundleContext.registerService(getClass().getName(), this, properties);
  }

  /** implements BundleActivator.stop() */
  public void stop(BundleContext bc) throws Exception {}
}
示例#13
0
  /**
   * Starts the configuration service
   *
   * @param bundleContext the <tt>BundleContext</tt> as provided by the OSGi framework.
   * @throws Exception if anything goes wrong
   */
  public void start(BundleContext bundleContext) throws Exception {
    FileAccessService fas = ServiceUtils.getService(bundleContext, FileAccessService.class);

    if (fas != null) {
      File usePropFileConfig;
      try {
        usePropFileConfig =
            fas.getPrivatePersistentFile(".usepropfileconfig", FileCategory.PROFILE);
      } catch (Exception ise) {
        // There is somewhat of a chicken-and-egg dependency between
        // FileConfigurationServiceImpl and ConfigurationServiceImpl:
        // FileConfigurationServiceImpl throws IllegalStateException if
        // certain System properties are not set,
        // ConfigurationServiceImpl will make sure that these properties
        // are set but it will do that later.
        // A SecurityException is thrown when the destination
        // is not writable or we do not have access to that folder
        usePropFileConfig = null;
      }

      if (usePropFileConfig != null && usePropFileConfig.exists()) {
        logger.info("Using properties file configuration store.");
        this.cs = LibJitsi.getConfigurationService();
      }
    }

    if (this.cs == null) {
      this.cs = new JdbcConfigService(fas);
    }

    bundleContext.registerService(ConfigurationService.class.getName(), this.cs, null);

    fixPermissions(this.cs);
  }
  /** Prepares the factory for bundle shutdown. */
  public void stop() {
    if (logger.isTraceEnabled()) logger.trace("Preparing to stop all protocol providers of" + this);

    synchronized (registeredAccounts) {
      for (Enumeration<ServiceRegistration> registrations = registeredAccounts.elements();
          registrations.hasMoreElements(); ) {
        ServiceRegistration reg = registrations.nextElement();

        stop(reg);

        reg.unregister();
      }

      registeredAccounts.clear();
    }
  }
  /**
   * Returns the <tt>URL</tt> of the sound corresponding to the given property key.
   *
   * @return the <tt>URL</tt> of the sound corresponding to the given property key.
   */
  public URL getSoundURL(String urlKey) {
    String path = getSoundPath(urlKey);

    if (path == null || path.length() == 0) {
      logger.warn("Missing resource for key: " + urlKey);
      return null;
    }
    return getSoundURLForPath(path);
  }
  /**
   * Returns the int representation of the color corresponding to the given key.
   *
   * @param key The key of the color in the colors properties file.
   * @return the int representation of the color corresponding to the given key.
   */
  public int getColor(String key) {
    String res = getColorResources().get(key);

    if (res == null) {
      logger.error("Missing color resource for key: " + key);

      return 0xFFFFFF;
    } else return Integer.parseInt(res, 16);
  }
  /**
   * Returns the string representation of the color corresponding to the given key.
   *
   * @param key The key of the color in the colors properties file.
   * @return the string representation of the color corresponding to the given key.
   */
  public String getColorString(String key) {
    String res = getColorResources().get(key);

    if (res == null) {
      logger.error("Missing color resource for key: " + key);

      return "0xFFFFFF";
    } else return res;
  }
  /**
   * Returns the <tt>InputStream</tt> of the image corresponding to the given key.
   *
   * @param streamKey The identifier of the image in the resource properties file.
   * @return the <tt>InputStream</tt> of the image corresponding to the given key.
   */
  public InputStream getImageInputStream(String streamKey) {
    String path = getImagePath(streamKey);

    if (path == null || path.length() == 0) {
      logger.warn("Missing resource for key: " + streamKey);
      return null;
    }

    return getImageInputStreamForPath(path);
  }
 /**
  * stores the data to a HTML file
  *
  * @param aFile file object
  */
 private void storeToHtmlFile(final File aFile, final UARTDataSet aDataSet) {
   try {
     toHtmlPage(aFile, aDataSet);
   } catch (final IOException exception) {
     // Make sure to handle IO-interrupted exceptions properly!
     if (!HostUtils.handleInterruptedException(exception)) {
       LOG.log(Level.WARNING, "HTML export failed!", exception);
     }
   }
 }
示例#20
0
  /**
   * Computes and returns the hash of the specified <tt>capsString</tt> using the specified
   * <tt>hashAlgorithm</tt>.
   *
   * @param hashAlgorithm the name of the algorithm to be used to generate the hash
   * @param capsString the capabilities string that we'd like to compute a hash for.
   * @return the hash of <tt>capsString</tt> computed by the specified <tt>hashAlgorithm</tt> or
   *     <tt>null</tt> if generating the hash has failed
   */
  private static String capsToHash(String hashAlgorithm, String capsString) {
    try {
      MessageDigest md = MessageDigest.getInstance(hashAlgorithm);
      byte[] digest = md.digest(capsString.getBytes());

      return Base64.encodeBytes(digest);
    } catch (NoSuchAlgorithmException nsae) {
      logger.error("Unsupported XEP-0115: Entity Capabilities hash algorithm: " + hashAlgorithm);
      return null;
    }
  }
  /**
   * Starts the Metacafe replacement source bundle
   *
   * @param context the <tt>BundleContext</tt> as provided from the OSGi framework
   * @throws Exception if anything goes wrong
   */
  public void start(BundleContext context) throws Exception {
    Hashtable<String, String> hashtable = new Hashtable<String, String>();
    hashtable.put(
        ReplacementService.SOURCE_NAME, ReplacementServiceMetacafeImpl.METACAFE_CONFIG_LABEL);
    metacafeSource = new ReplacementServiceMetacafeImpl();

    metacafeServReg =
        context.registerService(ReplacementService.class.getName(), metacafeSource, hashtable);

    logger.info("Metacafe source implementation [STARTED].");
  }
示例#22
0
  /**
   * 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");
      }
    }
  }
示例#23
0
  /**
   * 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);
  }
示例#24
0
  /** {@inheritDoc} */
  public void start(BundleContext bc) throws Exception {
    bundleContext = bc;
    try {
      logger.logEntry();
      logger.info("Android notification handler Service...[  STARTED ]");

      // Get the notification service implementation
      ServiceReference notifReference =
          bundleContext.getServiceReference(NotificationService.class.getName());

      notificationService = (NotificationService) bundleContext.getService(notifReference);

      vibrateHandler = new VibrateHandlerImpl();

      notificationService.addActionHandler(vibrateHandler);

      logger.info("Android notification handler Service...[REGISTERED]");
    } finally {
      logger.logExit();
    }
  }
示例#25
0
  /**
   * Starts the <tt>msofficecomm</tt> bundle in a specific {@link BundleContext}.
   *
   * @param bundleContext the <tt>BundleContext</tt> in which the <tt>msofficecomm</tt> bundle is to
   *     be started
   * @throws Exception if anything goes wrong while starting the <tt>msofficecomm</tt> bundle in the
   *     specified <tt>BundleContext</tt>
   */
  public void start(BundleContext bundleContext) throws Exception {
    // The msofficecomm bundle is available on Windows only.
    if (!OSUtils.IS_WINDOWS) return;

    if (logger.isInfoEnabled()) logger.info("MsOfficeComm plugin ... [STARTED]");

    Messenger.start(bundleContext);

    boolean stopMessenger = true;

    try {
      int hresult = OutOfProcessServer.start();

      if (logger.isInfoEnabled())
        logger.info("MsOfficeComm started OutOfProcessServer HRESULT:" + hresult);

      if (hresult < 0) throw new RuntimeException("HRESULT " + hresult);
      else stopMessenger = false;
    } finally {
      if (stopMessenger) Messenger.stop(bundleContext);
    }
  }
  /**
   * Creates an account for the given user and password.
   *
   * @param providerFactory the ProtocolProviderFactory which will create the account
   * @param user the user identifier
   * @return the <tt>ProtocolProviderService</tt> for the new account.
   */
  public ProtocolProviderService installAccount(
      ProtocolProviderFactory providerFactory, String user) throws OperationFailedException {
    Hashtable<String, String> accountProperties = new Hashtable<String, String>();

    accountProperties.put(
        ProtocolProviderFactory.ACCOUNT_ICON_PATH,
        "resources/images/protocol/gibberish/gibberish32x32.png");

    if (registration.isRememberPassword()) {
      accountProperties.put(ProtocolProviderFactory.PASSWORD, registration.getPassword());
    }

    if (isModification()) {
      providerFactory.uninstallAccount(protocolProvider.getAccountID());
      this.protocolProvider = null;
      setModification(false);
    }

    try {
      AccountID accountID = providerFactory.installAccount(user, accountProperties);

      ServiceReference serRef = providerFactory.getProviderForAccount(accountID);

      protocolProvider =
          (ProtocolProviderService) GibberishAccRegWizzActivator.bundleContext.getService(serRef);
    } catch (IllegalStateException exc) {
      logger.warn(exc.getMessage());

      throw new OperationFailedException(
          "Account already exists.", OperationFailedException.IDENTIFICATION_CONFLICT);
    } catch (Exception exc) {
      logger.warn(exc.getMessage());

      throw new OperationFailedException(
          "Failed to add account", OperationFailedException.GENERAL_ERROR);
    }

    return protocolProvider;
  }
  /**
   * Creates an account for the given Account ID, Identity File and Known Hosts File
   *
   * @param providerFactory the ProtocolProviderFactory which will create the account
   * @param user the user identifier
   * @return the <tt>ProtocolProviderService</tt> for the new account.
   */
  public ProtocolProviderService installAccount(
      ProtocolProviderFactory providerFactory, String user) throws OperationFailedException {
    Hashtable<String, String> accountProperties = new Hashtable<String, String>();

    accountProperties.put(
        ProtocolProviderFactory.ACCOUNT_ICON_PATH, "resources/images/protocol/ssh/ssh32x32.png");

    accountProperties.put(
        ProtocolProviderFactory.NO_PASSWORD_REQUIRED, new Boolean(true).toString());

    accountProperties.put(
        ProtocolProviderFactorySSHImpl.IDENTITY_FILE, registration.getIdentityFile());

    accountProperties.put(
        ProtocolProviderFactorySSHImpl.KNOWN_HOSTS_FILE,
        String.valueOf(registration.getKnownHostsFile()));

    try {
      AccountID accountID = providerFactory.installAccount(user, accountProperties);

      ServiceReference serRef = providerFactory.getProviderForAccount(accountID);

      protocolProvider =
          (ProtocolProviderService) SSHAccRegWizzActivator.bundleContext.getService(serRef);
    } catch (IllegalStateException exc) {
      logger.warn(exc.getMessage());

      throw new OperationFailedException(
          "Account already exists.", OperationFailedException.IDENTIFICATION_CONFLICT);
    } catch (Exception exc) {
      logger.warn(exc.getMessage());

      throw new OperationFailedException(
          "Failed to add account", OperationFailedException.GENERAL_ERROR);
    }

    return protocolProvider;
  }
  /**
   * Returns the byte representation of the image corresponding to the given identifier.
   *
   * @param imageID the identifier of the image
   * @return the byte representation of the image corresponding to the given identifier.
   */
  private static byte[] getImageInBytes(String imageID) {
    InputStream in = getResources().getImageInputStream(imageID);

    if (in == null) return null;
    byte[] image = null;
    try {
      image = new byte[in.available()];

      in.read(image);
    } catch (IOException e) {
      logger.error("Failed to load image:" + imageID, e);
    }

    return image;
  }
示例#29
0
  public void start(int options) throws BundleException {
    if (getState() == UNINSTALLED) throw new IllegalStateException("Bundle.UNINSTALLED");

    BundleStartLevel bundleStartLevel = adapt(BundleStartLevel.class);
    FrameworkStartLevel frameworkStartLevel = getFramework().adapt(FrameworkStartLevel.class);

    if ((bundleStartLevel != null)
        && (bundleStartLevel.getStartLevel() > frameworkStartLevel.getStartLevel())) {
      if ((options & START_TRANSIENT) == START_TRANSIENT) throw new BundleException("startLevel");
      else return;
    }

    if (getState() == ACTIVE) return;

    if (getState() == INSTALLED) setState(RESOLVED);

    setState(STARTING);

    String location = getLocation();

    if (location != null) {
      BundleActivator bundleActivator = null;
      Throwable exception = null;

      try {
        bundleActivator = (BundleActivator) loadClass(location.replace('/', '.')).newInstance();

        bundleActivator.start(getBundleContext());
      } catch (Throwable t) {
        logger.log(Level.SEVERE, "Error starting bundle: " + bundleActivator, t);

        if (t instanceof ThreadDeath) throw (ThreadDeath) t;
        else exception = t;
      }

      if (exception == null) this.bundleActivator = bundleActivator;
      else {
        setState(STOPPING);
        setState(RESOLVED);
        getFramework().fireBundleEvent(BundleEvent.STOPPED, this);
        throw new BundleException("BundleActivator.start", exception);
      }
    }

    if (getState() == UNINSTALLED) throw new IllegalStateException("Bundle.UNINSTALLED");

    setState(ACTIVE);
  }
  /**
   * Initializes and creates an account corresponding to the specified accountProperties and
   * registers the resulting ProtocolProvider in the <tt>context</tt> BundleContext parameter.
   *
   * @param accountProperties a set of protocol (or implementation) specific properties defining the
   *     new account.
   * @return the AccountID of the newly created account
   */
  protected AccountID loadAccount(Map accountProperties) {
    BundleContext context = SipActivator.getBundleContext();
    if (context == null) throw new NullPointerException("The specified BundleContext was null");

    String userIDStr = (String) accountProperties.get(USER_ID);
    if (userIDStr == null)
      throw new NullPointerException("The account properties contained no user id.");

    if (accountProperties == null)
      throw new NullPointerException("The specified property map was null");

    String serverAddress = (String) accountProperties.get(SERVER_ADDRESS);

    if (serverAddress == null)
      throw new NullPointerException(serverAddress + " is not a valid ServerAddress");

    if (!accountProperties.containsKey(PROTOCOL))
      accountProperties.put(PROTOCOL, ProtocolNames.SIP);

    SipAccountID accountID = new SipAccountID(userIDStr, accountProperties, serverAddress);

    // get a reference to the configuration service and register whatever
    // properties we have in it.

    Hashtable properties = new Hashtable();
    properties.put(PROTOCOL, ProtocolNames.SIP);
    properties.put(USER_ID, userIDStr);

    ProtocolProviderServiceSipImpl sipProtocolProvider = new ProtocolProviderServiceSipImpl();

    try {
      sipProtocolProvider.initialize(userIDStr, accountID);

      // We store again the account in order to store all properties added
      // during the protocol provider initialization.
      this.storeAccount(SipActivator.getBundleContext(), accountID);
    } catch (OperationFailedException ex) {
      logger.error("Failed to initialize account", ex);
      throw new IllegalArgumentException("Failed to initialize account" + ex.getMessage());
    }

    ServiceRegistration registration =
        context.registerService(
            ProtocolProviderService.class.getName(), sipProtocolProvider, properties);

    registeredAccounts.put(accountID, registration);
    return accountID;
  }