/**
  * At present the logging for bundles positioned below org.eclipse.core.runtime in the bundle
  * dependency stack is really sub-optimal.
  *
  * <p>In particular, logging with RuntimeLog on shutdown doesn't work as Platform shuts down
  * (removing listeners from RuntimeLog) before this bundle shuts down.
  *
  * <p>As such, until there is improved logging, the errors that occur on shutdown should use this
  * method. However, errors occuring during normal operations should use RuntimeLog as otherwise
  * the Error View is not getting updated.
  */
 public void frameworkLogError(String msg, int severity, Throwable e) {
   if ((logTracker == null) && (bundleContext != null)) {
     logTracker = new ServiceTracker(bundleContext, FrameworkLog.class.getName(), null);
     logTracker.open();
   }
   FrameworkLog log = (logTracker == null) ? null : (FrameworkLog) logTracker.getService();
   if (log != null) log.log(new FrameworkLogEntry(PI_AUTH, severity, 0, msg, 0, e, null));
   else {
     if (msg != null) System.err.println(msg);
     if (e != null) e.printStackTrace(System.err);
   }
 }
 @SuppressWarnings("PMD.SystemPrintln")
 private void logError(String message, Throwable throwable) {
   ServiceReference lRef = bundleContext.getServiceReference(LogService.class.getName());
   if (lRef != null) {
     try {
       LogService logService = (LogService) bundleContext.getService(lRef);
       if (logService != null) {
         logService.log(LogService.LOG_ERROR, message, throwable);
         return;
       }
     } finally {
       bundleContext.ungetService(lRef);
     }
   }
   System.err.println("Jolokia-Error: " + message + " : " + throwable.getMessage());
 }
  /**
   * Creates an account for the given user and password.
   *
   * @param providerFactory the ProtocolProviderFactory which will create the account
   * @param userName the user identifier
   * @param passwd the password
   * @return the <tt>ProtocolProviderService</tt> for the new account.
   * @throws OperationFailedException if the operation didn't succeed
   */
  protected ProtocolProviderService installAccount(
      ProtocolProviderFactory providerFactory, String userName, String passwd)
      throws OperationFailedException {
    if (logger.isTraceEnabled()) {
      logger.trace("Preparing to install account for user " + userName);
    }
    Hashtable<String, String> accountProperties = new Hashtable<String, String>();

    String protocolIconPath = getProtocolIconPath();

    String accountIconPath = getAccountIconPath();

    registration.storeProperties(
        userName, passwd, protocolIconPath, accountIconPath, accountProperties);

    accountProperties.put(
        ProtocolProviderFactory.IS_PREFERRED_PROTOCOL, Boolean.toString(isPreferredProtocol()));
    accountProperties.put(ProtocolProviderFactory.PROTOCOL, getProtocol());

    if (isModification()) {
      providerFactory.modifyAccount(protocolProvider, accountProperties);

      setModification(false);

      return protocolProvider;
    }

    try {
      if (logger.isTraceEnabled()) {
        logger.trace(
            "Will install account for user "
                + userName
                + " with the following properties."
                + accountProperties);
      }

      AccountID accountID = providerFactory.installAccount(userName, accountProperties);

      ServiceReference serRef = providerFactory.getProviderForAccount(accountID);

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

      throw new OperationFailedException(
          "Username, password or server is null.", OperationFailedException.ILLEGAL_ARGUMENT);
    } catch (IllegalStateException exc) {
      logger.warn(exc.getMessage());

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

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

    return protocolProvider;
  }
  /**
   * Bottom level event dispatcher for the BundleContext.
   *
   * @param originalListener listener object registered under.
   * @param l listener to call (may be filtered).
   * @param action Event class type
   * @param object Event object
   */
  public void dispatchEvent(Object originalListener, Object l, int action, Object object) {
    // save the bundle ref to a local variable
    // to avoid interference from another thread closing this context
    AbstractBundle tmpBundle = bundle;
    Object previousTCCL = setContextFinder();
    try {
      if (isValid()) /* if context still valid */ {
        switch (action) {
          case Framework.BUNDLEEVENT:
          case Framework.BUNDLEEVENTSYNC:
            {
              BundleListener listener = (BundleListener) l;

              if (Debug.DEBUG_EVENTS) {
                String listenerName =
                    listener.getClass().getName()
                        + "@"
                        + Integer.toHexString(System.identityHashCode(listener)); // $NON-NLS-1$
                Debug.println(
                    "dispatchBundleEvent["
                        + tmpBundle
                        + "]("
                        + listenerName
                        + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              }

              BundleEvent event = (BundleEvent) object;
              switch (event.getType()) {
                case Framework.BATCHEVENT_BEGIN:
                  {
                    if (listener instanceof BatchBundleListener)
                      ((BatchBundleListener) listener).batchBegin();
                    break;
                  }
                case Framework.BATCHEVENT_END:
                  {
                    if (listener instanceof BatchBundleListener)
                      ((BatchBundleListener) listener).batchEnd();
                    break;
                  }
                default:
                  {
                    listener.bundleChanged((BundleEvent) object);
                  }
              }
              break;
            }

          case ServiceRegistry.SERVICEEVENT:
            {
              ServiceEvent event = (ServiceEvent) object;

              ServiceListener listener = (ServiceListener) l;
              if (Debug.DEBUG_EVENTS) {
                String listenerName =
                    listener.getClass().getName()
                        + "@"
                        + Integer.toHexString(System.identityHashCode(listener)); // $NON-NLS-1$
                Debug.println(
                    "dispatchServiceEvent["
                        + tmpBundle
                        + "]("
                        + listenerName
                        + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              }
              listener.serviceChanged(event);

              break;
            }

          case Framework.FRAMEWORKEVENT:
            {
              FrameworkListener listener = (FrameworkListener) l;

              if (Debug.DEBUG_EVENTS) {
                String listenerName =
                    listener.getClass().getName()
                        + "@"
                        + Integer.toHexString(System.identityHashCode(listener)); // $NON-NLS-1$
                Debug.println(
                    "dispatchFrameworkEvent["
                        + tmpBundle
                        + "]("
                        + listenerName
                        + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              }

              listener.frameworkEvent((FrameworkEvent) object);
              break;
            }
          default:
            {
              throw new InternalError();
            }
        }
      }
    } catch (Throwable t) {
      if (Debug.DEBUG_GENERAL) {
        Debug.println(
            "Exception in bottom level event dispatcher: " + t.getMessage()); // $NON-NLS-1$
        Debug.printStackTrace(t);
      }
      // allow the adaptor to handle this unexpected error
      framework.adaptor.handleRuntimeError(t);
      publisherror:
      {
        if (action == Framework.FRAMEWORKEVENT) {
          FrameworkEvent event = (FrameworkEvent) object;
          if (event.getType() == FrameworkEvent.ERROR) {
            break publisherror; // avoid infinite loop
          }
        }

        framework.publishFrameworkEvent(FrameworkEvent.ERROR, tmpBundle, t);
      }
    } finally {
      if (previousTCCL != Boolean.FALSE)
        Thread.currentThread().setContextClassLoader((ClassLoader) previousTCCL);
    }
  }