Esempio n. 1
0
  /** @param serviceReference */
  private void removeBatchProcessor(ServiceReference serviceReference) {
    Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);
    SolrSearchResultProcessor processor = processorsById.remove(serviceId);
    if (processor != null) {
      List<String> toRemove = new ArrayList<String>();
      for (Entry<String, SolrSearchResultProcessor> e : processors.entrySet()) {
        if (processor.equals(e.getValue())) {
          toRemove.add(e.getKey());
        }
      }
      for (String r : toRemove) {
        processors.remove(r);
      }

      // bit of a kludge until I can figure out why felix doesn't wire up the default
      // processor even though it finds a matching service.
      boolean defaultBatchProcessor =
          getSetting(
              serviceReference.getProperty(
                  SolrSearchBatchResultProcessor.DEFAULT_BATCH_PROCESSOR_PROP),
              false);
      if (defaultBatchProcessor) {
        defaultSearchBatchProcessor = null;
      }
    }
  }
Esempio n. 2
0
  private Collection<CommandName> listCommands() {
    Set<CommandName> commands = new HashSet<>();

    ServiceReference<?>[] refs;
    try {
      refs = context.getAllServiceReferences(null, "(osgi.command.scope=*)");
    } catch (InvalidSyntaxException e) {
      // should never happen
      throw new RuntimeException(e);
    }
    for (ServiceReference<?> ref : refs) {
      String scope = (String) ref.getProperty("osgi.command.scope");
      Object funcsObj = ref.getProperty("osgi.command.function");
      String[] funcs;
      if (funcsObj instanceof String[]) funcs = (String[]) funcsObj;
      else if (funcsObj instanceof String) funcs = new String[] {(String) funcsObj};
      else funcs = new String[0];

      for (String func : funcs) {
        CommandName command = new CommandName(scope, func);
        commands.add(command);
      }
    }
    return commands;
  }
    public int compareTo(Object reference) {
      ServiceReference other = (ServiceReference) reference;

      Long id = (Long) getProperty(Constants.SERVICE_ID);
      Long otherId = (Long) other.getProperty(Constants.SERVICE_ID);

      if (id.equals(otherId)) {
        return 0; // same service
      }

      Object rankObj = getProperty(Constants.SERVICE_RANKING);
      Object otherRankObj = other.getProperty(Constants.SERVICE_RANKING);

      // If no rank, then spec says it defaults to zero.
      rankObj = (rankObj == null) ? new Integer(0) : rankObj;
      otherRankObj = (otherRankObj == null) ? new Integer(0) : otherRankObj;

      // If rank is not Integer, then spec says it defaults to zero.
      Integer rank = (rankObj instanceof Integer) ? (Integer) rankObj : new Integer(0);
      Integer otherRank =
          (otherRankObj instanceof Integer) ? (Integer) otherRankObj : new Integer(0);

      // Sort by rank in ascending order.
      if (rank.compareTo(otherRank) < 0) {
        return -1; // lower rank
      } else if (rank.compareTo(otherRank) > 0) {
        return 1; // higher rank
      }

      // If ranks are equal, then sort by service id in descending order.
      return (id.compareTo(otherId) < 0) ? 1 : -1;
    }
  @Override
  public int compare(ServiceReference<T> serviceReference1, ServiceReference<T> serviceReference2) {

    if (serviceReference1 == null) {
      if (serviceReference2 == null) {
        return 0;
      } else {
        return 1;
      }
    } else if (serviceReference2 == null) {
      return -1;
    }

    Object propertyValue1 = serviceReference1.getProperty(_propertyKey);
    Object propertyValue2 = serviceReference2.getProperty(_propertyKey);

    if (propertyValue1 == null) {
      if (propertyValue2 == null) {
        return 0;
      } else {
        return 1;
      }
    } else if (propertyValue2 == null) {
      return -1;
    }

    if (!(propertyValue2 instanceof Comparable)) {
      return serviceReference2.compareTo(serviceReference1);
    }

    Comparable<Object> propertyValueComparable2 = (Comparable<Object>) propertyValue2;

    return propertyValueComparable2.compareTo(propertyValue1);
  }
Esempio n. 5
0
  /** @param serviceReference */
  private void addBatchProcessor(ServiceReference serviceReference) {
    SolrSearchBatchResultProcessor processor =
        (SolrSearchBatchResultProcessor)
            osgiComponentContext.locateService(SEARCH_BATCH_RESULT_PROCESSOR, serviceReference);
    Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);

    batchProcessorsById.put(serviceId, processor);
    String[] processorNames =
        getSetting(serviceReference.getProperty(REG_BATCH_PROCESSOR_NAMES), new String[0]);

    if (processorNames != null) {
      for (String processorName : processorNames) {
        batchProcessors.put(processorName, processor);
      }
    }

    // bit of a kludge until I can figure out why felix doesn't wire up the default
    // processor even though it finds a matching service.
    boolean defaultBatchProcessor =
        getSetting(
            serviceReference.getProperty(
                SolrSearchBatchResultProcessor.DEFAULT_BATCH_PROCESSOR_PROP),
            false);
    if (defaultBatchProcessor) {
      defaultSearchBatchProcessor = processor;
    }
  }
  /** @see UserAdminUtil#fireEvent(int, Role) */
  @Override
  public void fireEvent(int type, Role role) {
    if (null == role) {
      throw new IllegalArgumentException("parameter role must not be null");
    }
    ServiceReference<?> reference = userAdminRegistration.getReference();
    final UserAdminEvent uaEvent = new UserAdminEvent(reference, type, role);
    //
    // send event to all listeners, asynchronously - in a separate thread!!
    //
    UserAdminListener[] eventListeners = listenerService.getServices(new UserAdminListener[0]);
    if (null != eventListeners) {
      for (Object listenerObject : eventListeners) {
        final UserAdminListener listener = (UserAdminListener) listenerObject;
        eventExecutor.execute(
            new Runnable() {

              @Override
              public void run() {
                listener.roleChanged(uaEvent);
              }
            });
      }
    }
    //
    // send event to EventAdmin if present
    //
    EventAdmin eventAdmin = m_eventService.getService();
    String name = getEventTypeName(type);
    if (null != eventAdmin && name != null) {
      Dictionary<String, Object> properties = new Hashtable<String, Object>();
      properties.put("event", uaEvent);
      properties.put("role", role);
      properties.put("role.name", role.getName());
      properties.put("role.type", role.getType());
      properties.put("service", reference);
      properties.put("service.id", reference.getProperty(Constants.SERVICE_ID));
      properties.put("service.objectClass", reference.getProperty(Constants.OBJECTCLASS));
      properties.put("service.pid", reference.getProperty(Constants.SERVICE_PID));
      //
      Event event = new Event(PaxUserAdminConstants.EVENT_TOPIC_PREFIX + name, properties);
      eventAdmin.postEvent(event);
    } else {
      String message =
          "No event service available or incompatible type - cannot send event of type '"
              + name
              + "' for role '"
              + role.getName()
              + "'";
      logMessage(this, LogService.LOG_DEBUG, message);
    }
  }
Esempio n. 7
0
  /** @param serviceReference */
  private void addProvider(ServiceReference serviceReference) {
    SolrSearchPropertyProvider provider =
        (SolrSearchPropertyProvider)
            osgiComponentContext.locateService(SEARCH_PROPERTY_PROVIDER, serviceReference);
    Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);

    propertyProviderById.put(serviceId, provider);
    String[] processorNames =
        getSetting(serviceReference.getProperty(REG_PROVIDER_NAMES), new String[0]);

    for (String processorName : processorNames) {
      propertyProvider.put(processorName, provider);
    }
  }
  protected void collectPortletModes(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    Map<String, Set<String>> portletModes = new HashMap<>();

    portletModes.put(
        ContentTypes.TEXT_HTML, SetUtil.fromArray(new String[] {toLowerCase(PortletMode.VIEW)}));

    List<String> portletModesStrings =
        StringPlus.asList(serviceReference.getProperty("javax.portlet.portlet-mode"));

    for (String portletModesString : portletModesStrings) {
      String[] portletModesStringParts = StringUtil.split(portletModesString, CharPool.SEMICOLON);

      if (portletModesStringParts.length != 2) {
        continue;
      }

      String mimeType = portletModesStringParts[0];

      Set<String> mimeTypePortletModes = new HashSet<>();

      mimeTypePortletModes.add(toLowerCase(PortletMode.VIEW));
      mimeTypePortletModes.addAll(toLowerCaseSet(portletModesStringParts[1]));

      portletModes.put(mimeType, mimeTypePortletModes);
    }

    portletModel.setPortletModes(portletModes);
  }
  @SuppressWarnings({"rawtypes", "unchecked", "unused"})
  private void logServiceProperties(final Class<?> klaz, final Object instance) throws Exception {

    final BundleContext context = bundleContext();

    final ServiceReference[] referenceArray = context.getAllServiceReferences(klaz.getName(), null);

    for (final ServiceReference reference : referenceArray) {

      final Object service = context.getService(reference);

      if (service == instance) {

        log.info("instance=" + instance);

        final String[] propKeyArray = reference.getPropertyKeys();

        for (final String propKey : propKeyArray) {

          final Object propValue = reference.getProperty(propKey);

          log.info(propKey + "=" + propValue);
        }

        // final String[] nameArray = (String[]) reference
        // .getProperty("objectClass");
        // for (final String name : nameArray) {
        // log.info("name=" + name);
        // }

      }
    }
  }
Esempio n. 10
0
  protected void collectSupportedPublishingEvents(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    Set<QName> publishingEvents = new HashSet<>();

    PortletApp portletApp = portletModel.getPortletApp();

    List<String> supportedPublishingEvents =
        StringPlus.asList(serviceReference.getProperty("javax.portlet.supported-publishing-event"));

    for (String supportedPublishingEvent : supportedPublishingEvents) {
      String name = supportedPublishingEvent;
      String qname = null;

      String[] parts = StringUtil.split(supportedPublishingEvent, StringPool.SEMICOLON);

      if (parts.length == 2) {
        name = parts[0];
        qname = parts[1];
      }

      QName qName = getQName(name, qname, portletApp.getDefaultNamespace());

      publishingEvents.add(qName);
    }

    portletModel.setPublishingEvents(publishingEvents);
  }
Esempio n. 11
0
  protected void collectSupportedPublicRenderParameters(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    Set<PublicRenderParameter> publicRenderParameters = new HashSet<>();

    PortletApp portletApp = portletModel.getPortletApp();

    List<String> supportedPublicRenderParameters =
        StringPlus.asList(
            serviceReference.getProperty("javax.portlet.supported-public-render-parameter"));

    for (String supportedPublicRenderParameter : supportedPublicRenderParameters) {

      String name = supportedPublicRenderParameter;
      String qname = null;

      String[] parts = StringUtil.split(supportedPublicRenderParameter, StringPool.SEMICOLON);

      if (parts.length == 2) {
        name = parts[0];
        qname = parts[1];
      }

      QName qName = getQName(name, qname, portletApp.getDefaultNamespace());

      PublicRenderParameter publicRenderParameter =
          new PublicRenderParameterImpl(name, qName, portletApp);

      publicRenderParameters.add(publicRenderParameter);
    }

    portletModel.setPublicRenderParameters(publicRenderParameters);
  }
Esempio n. 12
0
  protected void collectSecurityRoleRefs(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    Set<String> unlinkedRoles = new HashSet<>();

    List<String> roleRefs =
        StringPlus.asList(serviceReference.getProperty("javax.portlet.security-role-ref"));

    if (roleRefs.isEmpty()) {
      roleRefs.add("administrator");
      roleRefs.add("guest");
      roleRefs.add("power-user");
      roleRefs.add("user");
    }

    for (String roleRef : roleRefs) {
      for (String curRoleRef : StringUtil.split(roleRef)) {
        unlinkedRoles.add(curRoleRef);
      }
    }

    portletModel.setUnlinkedRoles(unlinkedRoles);

    portletModel.linkRoles();
  }
 public void serviceChanged(ServiceEvent serviceEvent) {
   int serviceEventType = serviceEvent.getType();
   switch (serviceEventType) {
     case ServiceEvent.REGISTERED:
       {
         ServiceReference serviceReference = serviceEvent.getServiceReference();
         Filter filter = (Filter) serviceReference.getProperty(UPnPEventListener.UPNP_FILTER);
         if (filter == null) {
           addNewListener(serviceReference);
         } else if (filter.match(properties)) {
           addNewListener(serviceReference);
         }
       }
       ;
       break;
     case ServiceEvent.MODIFIED:
       {
       }
       ;
       break;
     case ServiceEvent.UNREGISTERING:
       {
         removeListener(serviceEvent.getServiceReference());
       }
       ;
       break;
   }
 }
 private ServiceReference createReference(List<ServiceReference> references, String symbolicName) {
   ServiceReference ref = Mockito.mock(ServiceReference.class);
   Mockito.when(ref.getProperty("org.springframework.context.service.name"))
       .thenReturn(symbolicName);
   references.add(ref);
   return ref;
 }
  @Override
  @SuppressWarnings("unchecked")
  public <T> T createProxy(
      BundleContext bundleContext, ServiceReference reference, ClassLoader classLoader) {
    Bundle exportingBundle = reference.getBundle();
    if (exportingBundle == null) {
      throw new IllegalArgumentException(
          String.format("Service [%s] has been unregistered", reference));
    }

    InvocationHandler handler = new OsgiInvocationHandler(bundleContext, reference);

    String[] classNames = (String[]) reference.getProperty(Constants.OBJECTCLASS);
    List<Class<?>> classes = new ArrayList<Class<?>>(classNames.length);

    for (String className : classNames) {
      try {
        Class<?> clazz = classLoader.loadClass(className);
        if (clazz.isInterface()) {
          classes.add(clazz);
        }
      } catch (ClassNotFoundException e) {
        throw new IllegalArgumentException(
            String.format(
                "Unable to find class [%s] with classloader [%s]", className, classLoader));
      }
    }
    classes.add(OsgiProxy.class);
    classes.add(ServiceReference.class);

    return (T)
        Proxy.newProxyInstance(classLoader, classes.toArray(new Class<?>[classes.size()]), handler);
  }
 private void extractPort(final ServiceReference reference) {
   // ignore if the help is starting
   if ("org.eclipse.help".equals(reference.getProperty("other.info"))) {
     return;
   } //$NON-NLS-1$ //$NON-NLS-2$
   try {
     // The http.port property is not defined if the ServletBridge is
     // used to load Equinox.
     Object httpPortObject = reference.getProperty("http.port"); // $NON-NLS-1$
     httpPort = Integer.parseInt(httpPortObject.toString());
   } catch (Exception ex) {
     // Do not throw exception - it will prevent the application from
     // starting when deployed with the ServletBridge.
     httpPort = null;
   }
 }
  /**
   * * Call all plugins contained in a list and * optionally allow modifications. * *
   *
   * @param targetServiceReference Reference to the target ManagedService(Factory). *
   * @param servicePid The service PID corresponding to the current configuration
   * @param dictionary The configuration dictionary to process. *
   * @param plugins list of references to ConfigurationPlugins. *
   * @param allowModification Should modifications to the configuration dictionary be allowed. * *
   * @return The modified configuration dictionary.
   */
  private ConfigurationDictionary callPlugins(
      ServiceReference targetServiceReference,
      String servicePid,
      ConfigurationDictionary dictionary,
      List plugins,
      boolean allowModification) {
    ConfigurationDictionary currentDictionary = dictionary;
    Iterator it = plugins.iterator();
    while (it.hasNext()) {
      ServiceReference pluginReference = (ServiceReference) it.next();

      // Only call the plugin if no cm.target is specified or if it
      // matches the pid of the target service
      String cmTarget = (String) pluginReference.getProperty(ConfigurationPlugin.CM_TARGET);
      if (cmTarget == null || cmTarget.equals(servicePid)) {
        ConfigurationPlugin plugin = (ConfigurationPlugin) context.getService(pluginReference);
        if (plugin == null) {
          continue;
        }
        ConfigurationDictionary dictionaryCopy = new ConfigurationDictionary(dictionary);
        try {
          plugin.modifyConfiguration(targetServiceReference, dictionaryCopy);
          if (allowModification) {
            currentDictionary = dictionaryCopy;
          }
        } catch (Exception exception) {
          LOG.error("[CM] Exception thrown by plugin: " + exception.getMessage());
        }
      }
    }
    return currentDictionary;
  }
Esempio n. 18
0
 public static String getString(final ServiceReference<?> ref, final String key) {
   final Object value = ref.getProperty(key);
   if (value instanceof String) {
     return (String) value;
   }
   return null;
 }
Esempio n. 19
0
  @Override
  public TrackingStruct addingService(ServiceReference<ResourceAnalyzer> reference) {
    TrackingStruct struct = new TrackingStruct();
    try {
      String filterStr = (String) reference.getProperty(ResourceAnalyzer.FILTER);
      Filter filter = (filterStr != null) ? FrameworkUtil.createFilter(filterStr) : null;

      ResourceAnalyzer analyzer = context.getService(reference);
      if (analyzer == null) return null;

      struct = new TrackingStruct();
      struct.analyzer = analyzer;
      struct.filter = filter;
      struct.valid = true;

      indexer.addAnalyzer(analyzer, filter);
    } catch (InvalidSyntaxException e) {
      struct.valid = false;
      log.log(
          reference,
          LogService.LOG_ERROR,
          "Ignoring ResourceAnalyzer due to invalid filter expression",
          e);
    }
    return struct;
  }
 private static ServiceReferenceDTO getServiceReferenceDTO(ServiceReference<?> ref) {
   if (ref == null) {
     return null;
   }
   Bundle b = ref.getBundle();
   if (b == null) {
     // service has been unregistered
     return null;
   }
   ServiceReferenceDTO dto = new ServiceReferenceDTO();
   dto.bundle = b.getBundleId();
   String[] keys = ref.getPropertyKeys();
   Map<String, Object> properties = newMap(keys.length);
   for (String k : keys) {
     Object v = ref.getProperty(k);
     if (Constants.SERVICE_ID.equals(k)) {
       dto.id = ((Long) v).longValue();
     }
     properties.put(k, mapValue(v));
   }
   dto.properties = properties;
   Bundle[] using = ref.getUsingBundles();
   final int length = (using == null) ? 0 : using.length;
   long[] usingBundles = new long[length];
   for (int i = 0; i < length; i++) {
     usingBundles[i] = using[i].getBundleId();
   }
   dto.usingBundles = usingBundles;
   return dto;
 }
Esempio n. 21
0
  /**
   * Should only be called while holding a lock from {@link #lock}
   *
   * @return
   */
  private Snapshot getSnapshot(boolean openingPrices) {
    lock.readLock().lock();
    try {
      Availability availability = getCurrentAvailability();
      /* Nothing we can check */
      if (availability == Availability.NONE) {
        return new Snapshot(availability, null, Collections.<String, Double>emptyMap());
      }

      /* Pick a random Jedis to call */
      Map<ServiceReference<Endpoint>, JedisPool> toUse =
          new HashMap<ServiceReference<Endpoint>, JedisPool>(writableMap);
      toUse.putAll(readableMap);
      ServiceReference<Endpoint> ref = getARandomJedis(toUse);

      /* Get the prices */
      Map<String, Double> prices = getPrices(toUse.get(ref), openingPrices);
      while (prices == null && !toUse.isEmpty()) {
        // This Jedis didn't work!
        toUse.remove(ref);
        ref = getARandomJedis(toUse);
        prices = getPrices(toUse.get(ref), openingPrices);
      }
      /* Return the data */
      return (prices == null)
          ? new Snapshot(Availability.NONE, null, Collections.<String, Double>emptyMap())
          : new Snapshot(availability, (String) ref.getProperty(Endpoint.URI), prices);
    } finally {
      lock.readLock().unlock();
    }
  }
 private void createNotifier(String deviceId) {
   ServiceReference[] serviceListeners = null;
   ServiceReference serviceReference = null;
   Filter filter = null;
   String eventListenerFilter =
       "(" + Constants.OBJECTCLASS + "=" + UPnPEventListener.class.getName() + ")";
   properties = new Properties();
   properties.put(UPnPDevice.ID, deviceId);
   properties.put(UPnPService.ID, serviceId);
   try {
     serviceListeners = context.getServiceReferences(UPnPEventListener.class.getName(), null);
     if (serviceListeners != null && serviceListeners.length > 0) {
       for (int i = 0; i < serviceListeners.length; i++) {
         serviceReference = serviceListeners[i];
         filter = (Filter) serviceReference.getProperty(UPnPEventListener.UPNP_FILTER);
         if (filter == null) {
           eventListeners.add(serviceReference);
         } else if (filter.match(properties)) {
           addNewListener(serviceReference);
         }
       }
     }
   } catch (Exception e) {
   }
   try {
     String filterString = eventListenerFilter;
     context.addServiceListener(this, filterString);
   } catch (Exception e) {
   }
 }
  /**
   * An apform instance to represent a legacy component discovered in the OSGi registry
   *
   * @param ipojoInstance
   */
  public ApformOSGiInstance(Specification specification, ServiceReference<?> reference) {

    super(
        new InstanceDeclaration(
            VersionedReference.any(generateImplementationName(specification, reference)),
            generateInstanceName(specification, reference)));

    this.specification = specification;

    for (PropertyDefinition property : specification.getDeclaration().getPropertyDefinitions()) {
      Object value = reference.getProperty(property.getName());

      if (value != null) this.declaration.getProperties().put(property.getName(), value.toString());
    }

    this.reference = reference;
    this.bundle = reference.getBundle();
    this.bundleContext =
        AccessController.doPrivileged(
            new PrivilegedAction<BundleContext>() {
              public BundleContext run() {
                return bundle.getBundleContext();
              }
            });

    this.service = null;
  }
 private int getHandlerPortNumber(final ServiceReference<?> handlerServiceReference) {
   int portNumber = 0;
   final Object port = handlerServiceReference.getProperty("port");
   if (port instanceof String) {
     portNumber = Integer.parseInt((String) port);
   }
   return portNumber;
 }
  /**
   * Registers a new incoming ConfigurationPlugin
   *
   * @param serviceReference The reference to the configuration plugin
   */
  public synchronized void registeredConfigurationPlugin(ServiceReference serviceReference) {
    Object rankingProperty = serviceReference.getProperty(ConfigurationPlugin.CM_RANKING);
    if (rankingProperty == null) {
      rankingProperty = new Integer(0);
    } else if (rankingProperty.getClass() != Integer.class) {
      rankingProperty = new Integer(0);
    }

    Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID);
    if (serviceId == null) {
      LOG.error("Missing service id for a ConfigurationPlugin");
    } else {
      int ranking = ((Integer) rankingProperty).intValue();
      pluginRankings.put(serviceId, rankingProperty);
      insertPluginReference(serviceReference, ranking);
    }
  }
Esempio n. 26
0
  protected void collectExpirationCache(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    int expirationCache =
        GetterUtil.getInteger(serviceReference.getProperty("javax.portlet.expiration-cache"));

    portletModel.setExpCache(expirationCache);
  }
  /**
   * Removes a servlet from being hosted on the server based on the provided service reference which
   * provides a ServletContainerService object. If the server is started, it is briefly stopped to
   * remove the servlet and is then restarted.
   *
   * @param ref service reference pointing to a ServletContainerService service
   */
  public synchronized void removeService(final ServiceReference<ServletContainerService> ref) {
    boolean wasRunning = false;
    try {
      if (!this.contexts.containsKey(ref.getProperty(Constants.SERVICE_ID))) {
        this.logger.warn(
            "The server servlet for bundle "
                + ref.getBundle().getSymbolicName()
                + " is not "
                + " currently registered, so nothing to remove.");
        return;
      }

      /* If running, stop the server. */
      wasRunning = this.server.isStarted() || this.server.isStarting();
      if (wasRunning) this.server.stop();

      Context con = this.contexts.remove(ref.getProperty(Constants.SERVICE_ID));

      this.contextCollection.stop();
      this.contextCollection.destroy();
      this.contextCollection.removeHandler(con);
      this.contextCollection.setHandlers(
          this.contexts.values().toArray(new Handler[this.contexts.size()]));
    } catch (Exception ex) {
      this.logger.error(
          "Failed removing server service from bundle "
              + ref.getBundle().getSymbolicName()
              + " because of exception with message: "
              + ex.getMessage()
              + '.');
    } finally {
      /* Restore the server state. */
      if (wasRunning && this.server.isStopped()) {
        try {
          this.logger.debug("Restarting Scheduling server servlet server.");
          this.server.start();
        } catch (Exception ex) {
          this.logger.error(
              "Failed starting Jetty server because of exception with message: "
                  + ex.getMessage()
                  + '.');
        }
      }
    }
  }
  protected T doAction(ServiceReference<S> serviceReference, T service, int action) {

    Map<String, String> initParameters = new HashMap<String, String>();

    if (action != ACTION_REMOVED) {
      for (String key : serviceReference.getPropertyKeys()) {
        if (key.startsWith("init.")) {
          String value = GetterUtil.getString(serviceReference.getProperty(key));

          initParameters.put(key.substring(5), value);
        }
      }

      int serviceRanking = GetterUtil.getInteger(serviceReference.getProperty("service.ranking"));

      initParameters.put("service.ranking", String.valueOf(serviceRanking));
    }

    Bundle bundle = serviceReference.getBundle();

    try {
      BundleServletContext bundleServletContext = httpSupport.getBundleServletContext(bundle);

      if (action != ACTION_ADDING) {
        unregisterService(bundleServletContext, serviceReference);
      }

      if (action != ACTION_REMOVED) {
        String contextId = GetterUtil.getString(serviceReference.getProperty("contextId"));

        HttpContext httpContext = httpSupport.getHttpContext(contextId);

        if (httpContext == null) {
          httpContext = bundleServletContext.getHttpContext();
        }

        registerService(
            bundleServletContext, serviceReference, service, initParameters, httpContext);
      }
    } catch (Exception e) {
      _log.error(e, e);
    }

    return service;
  }
Esempio n. 29
0
  private CharSequence print(ServiceReference ref) {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    String spid = "";
    Object pid = ref.getProperty("service.pid");
    if (pid != null) {
      spid = pid.toString();
    }

    f.format(
        "%06d %3s %-40s %s",
        ref.getProperty("service.id"),
        ref.getBundle().getBundleId(),
        getShortNames((String[]) ref.getProperty("objectclass")),
        spid);
    return sb;
  }
Esempio n. 30
0
  @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;
  }