/* (non-Javadoc)
   * @see org.osgi.framework.ServiceFactory#getService(org.osgi.framework.Bundle, org.osgi.framework.ServiceRegistration)
   */
  @Override
  public Object getService(Bundle bundle, ServiceRegistration registration) {
    if (serviceInstance == null) {
      IRepositoryService repositoryService = null;
      IMarketService marketService = null;

      try {
        BundleContext context = CoreActivator.getDefault().getBundle().getBundleContext();

        ServiceReference serviceReference =
            context.getServiceReference(IRepositoryService.class.getName());
        if (serviceReference != null) {
          repositoryService = (IRepositoryService) context.getService(serviceReference);
          context.ungetService(serviceReference);
        }

        serviceReference = context.getServiceReference(IMarketService.class.getName());
        if (serviceReference != null) {
          marketService = (IMarketService) context.getService(serviceReference);
          context.ungetService(serviceReference);
        }

        serviceInstance = new CurrencyService(repositoryService, marketService);
        serviceInstance.startUp(null);
      } catch (Exception e) {
        CoreActivator.log("Error starting currency service", e);
      }
    }
    return serviceInstance;
  }
  @Override
  public com.liferay.portal.model.Portlet addingService(
      ServiceReference<Portlet> serviceReference) {

    BundleContext bundleContext = _componentContext.getBundleContext();

    Portlet portlet = bundleContext.getService(serviceReference);

    String portletName = (String) serviceReference.getProperty("javax.portlet.name");

    if (Validator.isNull(portletName)) {
      Class<?> clazz = portlet.getClass();

      portletName =
          StringUtil.replace(clazz.getName(), new String[] {".", "$"}, new String[] {"_", "_"});
    }

    String portletId =
        StringUtil.replace(portletName, new String[] {".", "$"}, new String[] {"_", "_"});

    if (portletId.length() > PortletInstance.PORTLET_INSTANCE_KEY_MAX_LENGTH) {

      _log.error(
          "Portlet ID "
              + portletId
              + " has more than "
              + PortletInstance.PORTLET_INSTANCE_KEY_MAX_LENGTH
              + " characters");

      bundleContext.ungetService(serviceReference);

      return null;
    }

    com.liferay.portal.model.Portlet portletModel = _portletLocalService.getPortletById(portletId);

    if (portletModel != null) {
      _log.error("Portlet id " + portletId + " is already in use");

      bundleContext.ungetService(serviceReference);

      return null;
    }

    if (_log.isInfoEnabled()) {
      _log.info("Adding " + serviceReference);
    }

    portletModel = addingPortlet(serviceReference, portlet, portletName, portletId);

    if (portletModel == null) {
      bundleContext.ungetService(serviceReference);
    }

    return portletModel;
  }
  @Override
  public void start(BundleContext context) throws Exception {
    LOG.info("Starting Bundle");

    // Get our name.
    String myName = context.getBundle().getSymbolicName();

    // Find reference.
    ServiceReference<HelloService> ref = context.getServiceReference(HelloService.class);
    if (ref != null) {
      try {
        // Print service properties.
        String props = getServiceProperties(ref);
        LOG.info(
            "Calling HelloService#sayHello('{}') Published by {}. Props:\n{}",
            myName,
            ref.getBundle().getSymbolicName(),
            props);
        // Get the service
        HelloService service = context.getService(ref);
        if (service != null) {
          service.sayHello(myName);
        }
      } finally {
        // Release reference
        context.ungetService(ref);
      }
    }
  }
Beispiel #4
0
 static Object getService(String name) {
   ServiceReference reference = context.getServiceReference(name);
   if (reference == null) return null;
   Object result = context.getService(reference);
   context.ungetService(reference);
   return result;
 }
Beispiel #5
0
 @Override
 public void undeployBundle(String bundleName) throws BundleException {
   if (bundleName == null) {
     // ignore
     return;
   }
   log.info(
       String.format(
           "Before undeploy bundle with name '%s'.\n" + "%s", bundleName, getRuntimeStatus()));
   BundleContext ctx = getBundleContext();
   ServiceReference ref = ctx.getServiceReference(PackageAdmin.class.getName());
   PackageAdmin srv = (PackageAdmin) ctx.getService(ref);
   try {
     for (Bundle b : srv.getBundles(bundleName, null)) {
       if (b != null && b.getState() == Bundle.ACTIVE) {
         Transaction tx = TransactionHelper.suspendTransaction();
         try {
           b.stop();
           b.uninstall();
         } finally {
           TransactionHelper.resumeTransaction(tx);
         }
       }
     }
   } finally {
     ctx.ungetService(ref);
   }
   log.info(String.format("Undeploy done.\n" + "%s", getRuntimeStatus()));
 }
  /**
   * This will try and find a resource of the given name using the bundle from which was originally
   * loaded the given class so as to try and detect if it is jarred. If <code>clazz</code> hasn't
   * been loaded from a bundle class loader, we'll resort to the default class loader mechanism.
   * This will only return <code>null</code> in the case where the resource at <code>resourcePath
   * </code> cannot be located at all.
   *
   * @param clazz Class which class loader will be used to try and locate the resource.
   * @param resourcePath Path of the resource we seek, relative to the class.
   * @return The URL of the resource as we could locate it.
   * @throws IOException This will be thrown if we fail to convert bundle-scheme URIs into
   *     file-scheme URIs.
   */
  public static URL getResourceURL(Class<?> clazz, String resourcePath) throws IOException {
    BundleContext context = AcceleoCommonPlugin.getDefault().getContext();
    ServiceReference packageAdminReference =
        context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = null;
    if (packageAdminReference != null) {
      packageAdmin = (PackageAdmin) context.getService(packageAdminReference);
    }

    URL resourceURL = null;
    if (packageAdmin != null) {
      Bundle bundle = packageAdmin.getBundle(clazz);
      if (bundle != null) {
        final String pathSeparator = "/"; // $NON-NLS-1$
        // We found the appropriate bundle. We'll now try and determine whether the emtl is jarred
        resourceURL = getBundleResourceURL(bundle, pathSeparator, resourcePath);
      }
    }
    /*
     * We couldn't locate either the bundle which loaded the class or the resource. Resort to the class
     * loader and return null if it cannot locate the resource either.
     */
    if (resourceURL == null) {
      resourceURL = clazz.getResource(resourcePath);
    }

    if (packageAdminReference != null) {
      context.ungetService(packageAdminReference);
    }
    return resourceURL;
  }
  public void stop() throws IOException {
    if (context != null && httpServiceReference != null) context.ungetService(httpServiceReference);

    httpService = null;
    httpServiceReference = null;
    registrations.clear();
  }
 /**
  * This method tells the proxy to dispose of its service object; this is called when the
  * underlying service goes away.
  */
 public void dispose() {
   if (m_shape != null) {
     m_context.ungetService(m_ref);
     m_context = null;
     m_ref = null;
     m_shape = null;
   }
 }
Beispiel #9
0
 public static void ungetService(Object service) {
   if (service != null) {
     ServiceReference<?> serviceRef = services.remove(service);
     if (serviceRef != null) {
       bundleContext.ungetService(serviceRef);
     }
   }
 }
Beispiel #10
0
 private void removeRef(ServiceReference<T> ref) {
   synchronized (refs) {
     if (refs.remove(ref) == null) {
       return;
     }
   }
   ctx.ungetService(ref);
 }
  public void stop(BundleContext bundleContext) throws Exception {
    runnablePrinterClient.stop();
    if (serviceReference != null) {
      bundleContext.ungetService(serviceReference);
    }

    bundleContext.removeServiceListener(this);
  }
Beispiel #12
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
   */
  @Override
  public void stop(BundleContext context) throws Exception {
    // Update everything in the ItemManager that requires it
    itemManager.persistItems();

    // Unregister with the HTTP Service
    if (httpServiceRef != null) {
      bundleContext.ungetService(httpServiceRef);
    }

    // Unregister with the Materials Database service
    if (matDBServiceRef != null) {
      bundleContext.ungetService(matDBServiceRef);
    }

    // Unregister this service from the framework
    registration.unregister();
  }
 public static void oneTimeTearDown() throws Exception {
   BundleContext context = TestActivator.getContext();
   certificateUIRegistration.unregister();
   PackageAdmin pkgAdmin = context.getService(packageAdminRef);
   stopTransient(pkgAdmin, BUNDLE_TESTSERVER);
   stopTransient(pkgAdmin, BUNDLE_EQUINOX_HTTP);
   context.ungetService(packageAdminRef);
   setUpCounter = 0;
 }
  /**
   * Return a map containing all managed {@code EventHandler}s and their status.
   *
   * @param command the manage handlers command to execute.
   * @return a result containing the map of event handlers (and their status).
   */
  @Override
  public ManageHandlersResult execute(ManageHandlersCommand command) {
    ManageHandlersResult result = new ManageHandlersResult(command.getId());

    BundleContext bundleContext =
        ((BundleReference) getClass().getClassLoader()).getBundle().getBundleContext();
    ServiceReference[] references = new ServiceReference[0];
    try {
      references =
          bundleContext.getServiceReferences(
              EventHandler.class.getName(), EventHandler.MANAGED_FILTER);
      if (references != null && references.length > 0) {
        for (ServiceReference ref : references) {
          EventHandler handler = (EventHandler) bundleContext.getService(ref);

          // unproxy if required (due to the Service Guard of Karaf 3.0.x)
          if (proxyManager.isProxy(handler)) {
            handler = (EventHandler) proxyManager.unwrap(handler).call();
          }

          if (command.getHandlerName() == null) {
            result
                .getHandlers()
                .put(handler.getClass().getName(), handler.getSwitch().getStatus().name());
          } else {
            if (command.getHandlerName().equals(handler.getClass().getName())) {
              if (command.getStatus() != null) {
                if (command.getStatus()) {
                  // persist the handler switch status to configuration admin
                  persist(handler.getClass().getName(), SwitchStatus.ON);
                  handler.getSwitch().turnOn();
                } else {
                  // persist the handler switch status to configuration admin
                  persist(handler.getClass().getName(), SwitchStatus.OFF);
                  handler.getSwitch().turnOff();
                }
              }
              result
                  .getHandlers()
                  .put(handler.getClass().getName(), handler.getSwitch().getStatus().name());
              break;
            }
          }
        }
      }
    } catch (Exception e) {
      LOGGER.error("Can't get the current handlers status", e);
    } finally {
      if (references != null) {
        for (ServiceReference ref : references) {
          bundleContext.ungetService(ref);
        }
      }
    }
    return result;
  }
Beispiel #15
0
 private void addRef(ServiceReference<T> ref) {
   T service = ctx.getService(ref);
   synchronized (refs) {
     if (!refs.containsKey(ref)) {
       refs.put(ref, service);
       return;
     }
   }
   ctx.ungetService(ref);
 }
Beispiel #16
0
  @Override
  protected void tearDown() throws Exception {
    BundleContext context = HistoryServiceLick.bc;

    context.ungetService(this.historyServiceRef);

    this.history = null;
    this.historyService = null;
    this.historyServiceRef = null;
  }
Beispiel #17
0
 public Object execute(CommandSession session, List<Object> arguments) throws Exception {
   Object target = context.getService(reference);
   try {
     if (target instanceof Function) {
       return ((Function) target).execute(session, arguments);
     } else {
       return method(session, target, function, arguments);
     }
   } finally {
     context.ungetService(reference);
   }
 }
Beispiel #18
0
 /**
  * Implements BundleActivator.start().
  *
  * @param context the framework context for the bundle.
  */
 public void start(BundleContext context) {
   ServiceReference ref = context.getServiceReference(Statistics.class.getName());
   if (ref != null) {
     Statistics stat = (Statistics) context.getService(ref);
     if (stat != null) {
       stat.addNumber(1.0);
       stat.addNumber(2.0);
       System.out.println("Average " + stat.getAverage());
     }
     context.ungetService(ref);
   }
 }
  /**
   * Returns a service with the specified name or {@code null} if none.
   *
   * @param serviceName name of service
   * @return service object or {@code null} if none
   */
  public Object getService(final String serviceName) {
    final ServiceReference reference = bundleContext.getServiceReference(serviceName);
    if (reference == null) {
      return null;
    }

    final Object service = bundleContext.getService(reference);
    if (service != null) {
      bundleContext.ungetService(reference);
    }

    return service;
  }
Beispiel #20
0
  /**
   * Internal log method.
   *
   * @param level the level of the message.
   * @param msg the message to log
   * @param exception the exception attached to the message
   */
  private void dispatch(int level, String msg, Throwable exception) {
    LogService log = null;
    ServiceReference ref = null;
    try {
      // Security Check
      if (SecurityHelper.hasPermissionToGetService(LogService.class.getName(), m_context)) {
        ref = m_context.getServiceReference(LogService.class.getName());
      } else {
        Extender.getIPOJOBundleContext().getServiceReference(LogService.class.getName());
      }

      if (ref != null) {
        log = (LogService) m_context.getService(ref);
      }
    } catch (IllegalStateException e) {
      // Handle the case where the iPOJO bundle is stopping, or the log service already ran away.
    }

    if (log == null) {
      log = m_defaultLogger;
    }

    String name = m_name;
    if (name == null) {
      name = "";
    }

    String message = String.format("%s %s : %s", getLogHeaderForLevel(level), name, msg);
    switch (level) {
      case DEBUG:
        log.log(LogService.LOG_DEBUG, message, exception);
        break;
      case INFO:
        log.log(LogService.LOG_INFO, message, exception);
        break;
      case WARNING:
        log.log(LogService.LOG_WARNING, message, exception);
        break;
      case ERROR:
        log.log(LogService.LOG_ERROR, message, exception);
        break;
      default:
        log.log(LogService.LOG_INFO, message, exception);
        break;
    }

    if (ref != null) {
      m_context.ungetService(ref);
    }
  }
Beispiel #21
0
  public void close() {
    if (open.compareAndSet(true, false)) {
      ctx.removeServiceListener(listener);

      List<ServiceReference> oldRefs;
      synchronized (refs) {
        oldRefs = new ArrayList<ServiceReference>(refs.keySet());
        refs.clear();
      }
      for (ServiceReference ref : oldRefs) {
        ctx.ungetService(ref);
      }
    }
  }
  /**
   * locateProxyTarget.
   *
   * @return a {@link org.ops4j.pax.wicket.spi.ProxyTarget} object.
   */
  public ProxyTarget locateProxyTarget() {
    if (bundleContext == null) {
      throw new IllegalStateException("Bundle context is not allowed to be null");
    }
    ClassLoader oldClassloader = Thread.currentThread().getContextClassLoader();
    String filter = getApplicationContextFilter(bundleContext.getBundle().getSymbolicName());
    ServiceReference<?>[] references = null;
    try {
      references = bundleContext.getServiceReferences(getContainerClass().getName(), filter);
    } catch (InvalidSyntaxException e) {
      throw new IllegalStateException("not possible", e);
    }
    if (references == null || references.length == 0) {
      throw new IllegalStateException(
          String.format(
              "Found zero service references for %s; this is not OK...",
              bundleContext.getBundle().getSymbolicName()));
    }
    try {
      Thread.currentThread().setContextClassLoader(parent.getClassLoader());
      final BeanReactor<Container> strategy = createStrategy();
      for (ServiceReference<?> serviceReference : references) {
        @SuppressWarnings("unchecked")
        final Container service = (Container) bundleContext.getService(serviceReference);
        try {
          if (!strategy.containsBean(service)) {
            continue;
          }
          return new ProxyTarget() {

            public Object getTarget() {
              return strategy.createBean(service);
            }
          };
        } finally {
          bundleContext.ungetService(serviceReference);
        }
      }
    } finally {
      Thread.currentThread().setContextClassLoader(oldClassloader);
    }
    throw new IllegalStateException(
        String.format(
            "Bundle %s can no longer attach bean %s, class %s to page %s",
            bundleContext.getBundle().getSymbolicName(),
            beanType.getName(),
            beanType.getName(),
            parent.getName()));
  }
Beispiel #23
0
 /*
  * (non-Javadoc)
  *
  * @see
  * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
  * )
  */
 @SuppressWarnings({"rawtypes", "unchecked"})
 public void start(BundleContext context) throws Exception {
   super.start(context);
   plugin = this;
   DebugOptions service = null;
   final ServiceReference reference = context.getServiceReference(DebugOptions.class.getName());
   if (reference != null) service = (DebugOptions) context.getService(reference);
   if (service == null) return;
   try {
     LOGGING = service.getBooleanOption("org.eclipse.rcptt.tesla.core.am/logging", false);
   } finally {
     // we have what we want - release the service
     context.ungetService(reference);
   }
 }
 @Override
 public void run() {
   while (!stop) {
     ServiceObjects<String> serviceObjects = ctx.getServiceObjects(ref);
     try {
       String svc = serviceObjects.getService();
       if (!"bar".equals(svc)) System.out.println("Bad Service!");
       else counter++;
       //                serviceObjects.ungetService(svc);
     } finally {
       ctx.ungetService(ref);
     }
   }
   System.out.println("Thread done (" + getClass().getSimpleName() + ")");
 }
 private void setDebugEnabled(final BundleContext bundleContext) {
   final ServiceReference<?> debugOptionsReference =
       bundleContext.getServiceReference(DebugOptions.class.getName());
   if (debugOptionsReference != null) {
     final DebugOptions debugOptions =
         (DebugOptions) bundleContext.getService(debugOptionsReference);
     if (debugOptions != null) {
       Log.debugEnabled =
           debugOptions.getBooleanOption(
               "org.eclipse.equinox.weaving.caching/debug", false); // $NON-NLS-1$
     }
   }
   if (debugOptionsReference != null) {
     bundleContext.ungetService(debugOptionsReference);
   }
 }
Beispiel #26
0
 @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());
 }
  @Override
  public void start(BundleContext bundleContext) throws Exception {
    ServiceReference<ConfigurationAdmin> serviceReference =
        bundleContext.getServiceReference(ConfigurationAdmin.class);

    try {
      ConfigurationAdmin configurationAdmin = bundleContext.getService(serviceReference);

      _cxfConfiguration =
          configurationAdmin.createFactoryConfiguration(
              "com.liferay.portal.cxf.common.configuration." + "CXFEndpointPublisherConfiguration",
              null);

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

      properties.put("contextPath", "/soap-test");

      _cxfConfiguration.update(properties);

      _jaxWsApiConfiguration =
          configurationAdmin.getConfiguration(
              "com.liferay.portal.soap.extender.configuration." + "JaxWsApiConfiguration", null);

      properties = new Hashtable<>();

      properties.put("contextPath", "/soap-test");
      properties.put("timeout", 10000);

      _jaxWsApiConfiguration.update(properties);

      _soapConfiguration =
          configurationAdmin.createFactoryConfiguration(
              "com.liferay.portal.soap.extender.configuration." + "SoapExtenderConfiguration",
              null);

      properties = new Hashtable<>();

      properties.put("contextPaths", new String[] {"/soap-test"});
      properties.put("jaxWsHandlerFilterStrings", new String[] {"(soap.address=*)"});
      properties.put("jaxWsServiceFilterStrings", new String[] {"(jaxws=true)"});

      _soapConfiguration.update(properties);
    } finally {
      bundleContext.ungetService(serviceReference);
    }
  }
 /**
  * Helper method to create an {@link Action}.
  *
  * @param nsPrefix
  * @param name
  * @return
  * @deprecated Use {@link StorySchemaCatalog#createAction(Class)}.
  */
 @Deprecated
 public static <T extends Action> T createAction(@Nonnull final Class<T> targetClass) {
   final BundleContext bundleContext =
       FrameworkUtil.getBundle(StoryUtils.class).getBundleContext();
   final ServiceReference<StorySchemaCatalog> storySchemaCatalogRef =
       Preconditions.checkNotNull(
           bundleContext.getServiceReference(StorySchemaCatalog.class),
           "Cannot get %s service reference",
           StorySchemaCatalog.class.getName());
   final StorySchemaCatalog storySchemaCatalog =
       Preconditions.checkNotNull(
           bundleContext.getService(storySchemaCatalogRef),
           "Cannot get %s service",
           StorySchemaCatalog.class.getName());
   try {
     final ActionType actionType =
         Iterables.find(
             storySchemaCatalog.getActionTypes(),
             new Predicate<ActionType>() {
               @Override
               public boolean apply(@Nullable final ActionType input) {
                 return targetClass.equals(input.getJavaClass());
               }
             });
     return (T) actionType.create();
   } catch (final NoSuchElementException e) {
     final Function<ActionType, String> targetTypeQName =
         new Function<ActionType, String>() {
           @Override
           @Nullable
           public String apply(@Nullable ActionType input) {
             return input.getJavaClass().getName();
           }
         };
     final List<String> supportedActionTypeQNames =
         Lists.transform(storySchemaCatalog.getActionTypes(), targetTypeQName);
     throw new StoryException(
         String.format(
             "Cannot find action type %s, %s supported types are: %s",
             targetClass.getName(), supportedActionTypeQNames.size(), supportedActionTypeQNames),
         e);
   } finally {
     bundleContext.ungetService(storySchemaCatalogRef);
   }
 }
  /**
   * Returns the bundles with the given name.
   *
   * @param bundleName The bundle name.
   * @return The bundles with the given name.
   */
  public static Bundle[] getBundles(String bundleName) {
    Bundle[] bundle = null;
    BundleContext context = AcceleoCommonPlugin.getDefault().getContext();
    ServiceReference packageAdminReference =
        context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin packageAdmin = null;
    if (packageAdminReference != null) {
      packageAdmin = (PackageAdmin) context.getService(packageAdminReference);
    }

    if (packageAdmin != null) {
      bundle = packageAdmin.getBundles(bundleName, null);
    }
    if (packageAdminReference != null) {
      context.ungetService(packageAdminReference);
    }
    return bundle;
  }
  private <S> S getService(Class<S> clazz, String filter) {
    BundleContext context = Activator.getContext();
    if (context == null) return null;

    Collection<ServiceReference<S>> references;
    try {
      references = context.getServiceReferences(clazz, filter);
    } catch (InvalidSyntaxException e) {
      // TODO Auto-generated catch block
      return null;
    }
    if (references == null || references.size() == 0) return null;

    ServiceReference<S> ref = references.iterator().next();
    S result = context.getService(ref);
    context.ungetService(ref);
    return result;
  }