public DDMFormFieldValueRendererRegistryImpl() {
    Class<?> clazz = getClass();

    Bundle bundle = FrameworkUtil.getBundle(clazz);

    _bundleContext = bundle.getBundleContext();

    Filter filter = null;

    try {
      filter =
          FrameworkUtil.createFilter(
              "(&(objectClass="
                  + DDMFormFieldValueRenderer.class.getName()
                  + ")(!(objectClass="
                  + clazz.getName()
                  + ")))");
    } catch (InvalidSyntaxException ise) {
      ReflectionUtil.throwException(ise);
    }

    _serviceTracker =
        new ServiceTracker<>(
            _bundleContext, filter, new DDMFormFieldValueRendererServiceTrackerCustomizer());

    _serviceTracker.open();
  }
  public void execute(@Observes(precedence = Integer.MAX_VALUE) EventContext<BeforeSuite> event)
      throws Exception {

    Bundle bundle = FrameworkUtil.getBundle(getClass());

    BundleContext bundleContext = bundle.getBundleContext();

    Filter filter =
        FrameworkUtil.createFilter(
            "(&(objectClass=org.springframework.context.ApplicationContext)"
                + "(org.springframework.context.service.name="
                + bundleContext.getBundle().getSymbolicName()
                + "))");

    ServiceTracker<ApplicationContext, ApplicationContext> serviceTracker =
        new ServiceTracker<>(bundleContext, filter, null);

    serviceTracker.open();

    try {
      serviceTracker.waitForService(30 * 1000L);
    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    }

    serviceTracker.close();

    event.proceed();
  }
 private String getLocalizedString(String string, String type, String defaultValue) {
   if (Property.DEFAULT_LOCAL_STRING.equals(string)) {
     Method getter = getGetter();
     String propertyName = BeanUtils.getPropertyNameFromGetter(getter.getName());
     Class<?> propOwner = getter.getDeclaringClass();
     Bundle bundle = FrameworkUtil.getBundle(propOwner);
     ResourceBundle resourceBundle = Platform.getResourceBundle(bundle);
     String messageID = "meta." + propOwner.getName() + "." + propertyName + "." + type;
     String result = null;
     try {
       result = resourceBundle.getString(messageID);
     } catch (Exception e) {
       // Try to find the same property in parent classes
       for (Class parent = getter.getDeclaringClass().getSuperclass();
           parent != null && parent != Object.class;
           parent = parent.getSuperclass()) {
         try {
           Method parentGetter = parent.getMethod(getter.getName(), getter.getParameterTypes());
           Class<?> parentOwner = parentGetter.getDeclaringClass();
           Bundle parentBundle = FrameworkUtil.getBundle(parentOwner);
           if (parentBundle == null || parentBundle == bundle) {
             continue;
           }
           ResourceBundle parentResourceBundle = Platform.getResourceBundle(parentBundle);
           messageID = "meta." + parentOwner.getName() + "." + propertyName + "." + type;
           try {
             result = parentResourceBundle.getString(messageID);
             break;
           } catch (Exception e1) {
             // Just skip it
           }
         } catch (NoSuchMethodException e1) {
           // Just skip it
         }
       }
       if (result == null) {
         if (type.equals(Property.RESOURCE_TYPE_NAME)) {
           log.debug(
               "Resource '" + messageID + "' not found in bundle " + bundle.getSymbolicName());
         }
         return defaultValue;
       }
     }
     if (!result.equals(messageID)) {
       return result;
     }
     return defaultValue;
   }
   return string;
 }
 public SecurityServiceImpl() {
   this.userServiceTracker =
       new ServiceTracker<>(
           FrameworkUtil.getBundle(SecurityServiceImpl.class).getBundleContext(),
           UserService.class,
           null);
 }
Exemplo n.º 5
0
 protected Class<?> getClass(String name) {
   BundleContext bundleContext = null;
   Bundle currentBundle = FrameworkUtil.getBundle(getClass());
   if (currentBundle != null) {
     bundleContext = currentBundle.getBundleContext();
   }
   if (bundleContext != null) {
     Bundle[] bundles = bundleContext.getBundles();
     for (Bundle bundle : bundles) {
       if (bundle.getState() >= Bundle.RESOLVED) {
         try {
           return bundle.loadClass(name);
         } catch (ClassNotFoundException e) {
           // Ignore
         }
       }
     }
   } else {
     try {
       return Class.forName(name);
     } catch (ClassNotFoundException e) {
       LOG.warn("Failed to find class for {}", name);
       throw new RuntimeException(e);
     }
   }
   LOG.warn("Failed to find class for {}", name);
   throw new RuntimeException(new ClassNotFoundException(name));
 }
 /**
  * Used to get Full form of URL from the Given Short Page URL
  *
  * @param pageFullPath
  * @return {@link String}
  * @throws Exception
  */
 public static String getFullURLPath(String shortUrlPath) throws Exception {
   ResourceResolver resourceResolver = null;
   try {
     Bundle bndl = FrameworkUtil.getBundle(ResourceResolverFactory.class);
     BundleContext bundleContext = bndl.getBundleContext();
     ServiceReference ref =
         bundleContext.getServiceReference(ResourceResolverFactory.class.getName());
     ResourceResolverFactory resolverFactory =
         (ResourceResolverFactory) bundleContext.getService(ref);
     resourceResolver = resolverFactory.getAdministrativeResourceResolver(null);
     Resource resource = resourceResolver.resolve(shortUrlPath);
     if (null != resource) {
       return java.net.URLDecoder.decode(resource.getPath(), "UTF-8");
     } else {
       if (LOGGER.isDebugEnabled()) {
         LOGGER.debug("Resource doesn't exists..." + shortUrlPath);
       }
     }
   } catch (Exception e) {
     LOGGER.error(
         " Error while getting Full URL for the path :"
             + shortUrlPath
             + " and the error message is :",
         e);
   } finally {
     resourceResolver.close();
   }
   return shortUrlPath;
 }
Exemplo n.º 7
0
 /**
  * Get a {@code Logger} for class {@code clazz}.
  *
  * <p>If this is called in an OSGi context this method will return the {@code Logger} of the Riena
  * framework. Otherwise if the boolean system property {@code LoggerMill.RIENA_DEFAULT_LOGGING} is
  * {@code true} a simple {@code Logger} that writes to the console will be returned. If the system
  * property is {@code false} a <i>null</i> logger that does nothing will be returned.
  *
  * @param clazz categorizes the logger
  * @return the {@code Logger}
  */
 public static Logger getLogger(final Class<?> clazz) {
   final Bundle bundle = FrameworkUtil.getBundle(clazz);
   if (bundle != null) {
     return LoggerProvider.instance().getLogger(clazz);
   }
   return getEmergencyLogger(clazz.getName());
 }
  /**
   * If no bundle exists for provided component reference, It create and returns a new OSGi bundle.
   * Or else it will return the existing bundle. Created bundle is reusable across multiple UUF
   * Apps.
   *
   * @return created OSGi bundle
   */
  private Bundle getBundle(
      String componentName, String componentVersion, ComponentReference componentReference) {
    BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
    Bundle bundle = bundleContext.getBundle(componentName);
    if (bundle != null) {
      return bundle;
    }

    try {
      return createBundle(
          componentName, getBundleVersion(componentVersion), getImports(componentReference));
    } catch (IOException e) {
      throw new FileOperationException(
          "Error while creating the OSGi bundle for component '"
              + componentName
              + "-"
              + componentVersion
              + "'.",
          e);
    } catch (BundleException e) {
      throw new UUFException(
          "Error while installing the OSGi bundle of component '"
              + componentName
              + "-"
              + componentVersion
              + "'.",
          e);
    }
  }
Exemplo n.º 9
0
 public void addStrategy(ServiceReference<FilterStrategy> filterStrategyRef) {
   Bundle bundle = FrameworkUtil.getBundle(FilterPlugin.class);
   if (bundle != null) {
     FilterStrategy filterStrategy = bundle.getBundleContext().getService(filterStrategyRef);
     filterStrategies.put(filterStrategyRef, filterStrategy);
   }
 }
Exemplo n.º 10
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  private void getServices() {
    try {
      BundleContext bundleContext =
          FrameworkUtil.getBundle(VehicleViewForm.class).getBundleContext();

      ServiceReference vehicleServiceReference =
          bundleContext.getServiceReference(VehicleService.class.getName());
      vehicleService = VehicleService.class.cast(bundleContext.getService(vehicleServiceReference));

      ServiceReference supplierServiceReference =
          bundleContext.getServiceReference(SupplierService.class.getName());
      supplierService =
          SupplierService.class.cast(bundleContext.getService(supplierServiceReference));

      ServiceReference tireTypeServiceReference =
          bundleContext.getServiceReference(TireTypeService.class.getName());
      tireTypeService =
          TireTypeService.class.cast(bundleContext.getService(tireTypeServiceReference));

      ServiceReference tireStatusServiceReference =
          bundleContext.getServiceReference(TireStatusService.class.getName());
      tireStatusService =
          TireStatusService.class.cast(bundleContext.getService(tireStatusServiceReference));

    } catch (Exception e) {
      e.getMessage();
    }
  }
  protected void checkRequiredBundles() {
    IProject project = getDomainClass().getFragmentRoot().getJavaProject().getProject();
    BundleContext context = FrameworkUtil.getBundle(NewAddonClassWizard.class).getBundleContext();
    ServiceReference<IBundleProjectService> ref =
        context.getServiceReference(IBundleProjectService.class);
    IBundleProjectService service = context.getService(ref);
    try {
      IBundleProjectDescription description = service.getDescription(project);
      Set<String> requiredBundles = getRequiredBundles();
      IRequiredBundleDescription[] arTmp = description.getRequiredBundles();
      List<IRequiredBundleDescription> descs = new ArrayList<IRequiredBundleDescription>();
      if (arTmp != null) {
        descs.addAll(Arrays.asList(arTmp));
      }
      for (IRequiredBundleDescription bd : descs) {
        requiredBundles.remove(bd.getName());
      }

      if (requiredBundles.size() > 0) {
        for (String b : requiredBundles) {
          descs.add(service.newRequiredBundle(b, null, false, false));
        }
        description.setRequiredBundles(descs.toArray(new IRequiredBundleDescription[0]));
        description.apply(new NullProgressMonitor());
      }
    } catch (CoreException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 12
0
  public void activate() {
    try {
      // we need to call the activator ourselves as this bundle is included in the lib folder
      com.sun.jersey.core.osgi.Activator jerseyActivator = new com.sun.jersey.core.osgi.Activator();
      BundleContext bundleContext = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
      try {
        jerseyActivator.start(bundleContext);
      } catch (Exception e) {
        logger.error("Could not start Jersey framework", e);
      }

      httpPort = Integer.parseInt(bundleContext.getProperty("jetty.port"));
      httpSSLPort = Integer.parseInt(bundleContext.getProperty("jetty.port.ssl"));

      httpService.registerServlet(
          CV_SERVLET_ALIAS, new AtmosphereServlet(), getJerseyServletParams(), createHttpContext());

      logger.info("Started Cometvisu API at " + CV_SERVLET_ALIAS);

      if (discoveryService != null) {
        discoveryService.registerService(getDefaultServiceDescription());
        discoveryService.registerService(getSSLServiceDescription());
      }
    } catch (ServletException se) {
      throw new RuntimeException(se);
    } catch (NamespaceException se) {
      throw new RuntimeException(se);
    }
  }
public class DdmTemplateSelectorTagsTest {

  @Test
  public void findProblems() throws Exception {
    ServiceReference<Migration> sr = context.getServiceReference(Migration.class);

    Migration m = context.getService(sr);

    List<Problem> problems =
        m.findProblems(new File("jsptests/ddm-template-selector/"), new NullProgressMonitor());

    assertEquals(1, problems.size());

    boolean found = false;

    for (Problem problem : problems) {
      if (problem.file.getName().endsWith("DdmTemplateSelectorTagsTest.jsp")) {
        if (problem.lineNumber == 70 && problem.startOffset == 2538 && problem.endOffset == 2621) {
          found = true;
        }
      }
    }

    if (!found) {
      fail();
    }
  }

  private final BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
}
Exemplo n.º 14
0
  @Test
  public void testJRubyCreate() throws Exception {

    System.err.println();
    System.err.println();

    // System.setProperty( "jruby.debug.loadService", "true" );
    // System.setProperty( "jruby.native.enabled", "true" );

    OSGiIsolatedScriptingContainer jruby = new OSGiIsolatedScriptingContainer();
    jruby.addBundleToLoadPath("org.jruby.osgi.scripts-bundle");
    jruby.addBundleToGemPath(FrameworkUtil.getBundle(Gems.class));

    // run a script from LOAD_PATH
    String hello = (String) jruby.runScriptlet("require 'hello'; Hello.say");
    assertEquals("world", hello);

    System.err.println();
    System.err.println();

    String gemPath = (String) jruby.runScriptlet("Gem::Specification.dirs.inspect");
    gemPath = gemPath.replaceAll("bundle[^:]*://[^/]*", "bundle:/");
    assertEquals("[\"uri:bundle://specifications\"]", gemPath);

    // ensure we can load rake from the default gems
    boolean loaded = (Boolean) jruby.runScriptlet("require 'rake'");
    assertEquals(true, loaded);

    String list = (String) jruby.runScriptlet("Gem.loaded_specs.keys.inspect");
    assertEquals("[\"rake\"]", list);

    // ensure we have native working
    loaded = (Boolean) jruby.runScriptlet("JRuby.runtime.posix.is_native");
    assertEquals(true, loaded);

    // ensure we can load openssl (with its bouncy-castle jars)
    loaded = (Boolean) jruby.runScriptlet("require 'openssl'");
    assertEquals(true, loaded);

    jruby.runScriptlet("require 'jar-dependencies'");

    assertGemListEquals(jruby, "jar-dependencies", "jruby-openssl", "rake");

    // ensure we can load can load embedded gems
    loaded = (Boolean) jruby.runScriptlet("require 'virtus'");
    assertEquals(true, loaded);

    assertGemListEquals(
        jruby,
        "axiom-types",
        "coercible",
        "descendants_tracker",
        "equalizer",
        "ice_nine",
        "jar-dependencies",
        "jruby-openssl",
        "rake",
        "thread_safe",
        "virtus");
  }
 /**
  * creates a Filter, but wraps the {@link InvalidSyntaxException} into an {@link
  * IllegalArgumentException}
  */
 public static Filter createFilter(String filterString) {
   try {
     return FrameworkUtil.createFilter(filterString);
   } catch (InvalidSyntaxException e) {
     throw new IllegalArgumentException(e);
   }
 }
Exemplo n.º 16
0
 protected BundleContext getContext() {
   Bundle cxfBundle = FrameworkUtil.getBundle(ApplicationServiceBean.class);
   if (cxfBundle != null) {
     return cxfBundle.getBundleContext();
   }
   return null;
 }
Exemplo n.º 17
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;
  }
 @Override
 public Image loadImage(Class<?> clazz, String path) {
   final Bundle bundle = FrameworkUtil.getBundle(clazz);
   final URL url = FileLocator.find(bundle, new Path(path), null);
   final ImageDescriptor imageDescr = ImageDescriptor.createFromURL(url);
   return imageDescr.createImage();
 }
Exemplo n.º 19
0
public class AllProblemsTest {

  @Test
  public void allProblems() throws Exception {
    ServiceReference<Migration> sr = context.getServiceReference(Migration.class);
    Migration m = context.getService(sr);
    List<Problem> problems =
        m.findProblems(new File("../blade.migrate.liferay70/projects/"), new NullProgressMonitor());

    final int expectedSize = 290;
    final int size = problems.size();

    if (size != expectedSize) {
      System.err.println("All problems size is " + size + ", expected size is " + expectedSize);
    }

    assertEquals(expectedSize, size);

    //		List<String> lines = new ArrayList<>();
    //		String contents = new
    // String(IO.read(this.getClass().getResourceAsStream("BREAKING_CHANGES.tags")));
    //		BufferedReader reader = new BufferedReader(IO.reader(contents));
    //
    //		String read = reader.readLine();
    //		while(read != null) {
    //			lines.add(read);
    //			read = reader.readLine();
    //		}

    //		Collection<ServiceReference<FileMigrator>> refs =
    // context.getServiceReferences(FileMigrator.class, null);

    for (Problem problem : problems) {
      if (problem.html != null && problem.html.equals("#legacy")) continue;

      //			if (problem.html == null || problem.html.equals("")) {
      //				for (ServiceReference<FileMigrator> ref : refs) {
      //					String section = (String) ref.getProperty("problem.section");
      //					String title = (String) ref.getProperty("problem.title");
      //					if (title.equals(problem.title)) {
      //						for (String line : lines) {
      //							if (section.startsWith(line)) {
      //								fail("line=" + line + ", section=" + section);
      //							}
      //						}
      //					}
      //				}
      //			}

      assertNotNull(
          "problem.title=" + problem.title + ", problem.file=" + problem.file, problem.html);
      assertTrue(
          "problem.title=" + problem.title + ", problem.file=" + problem.file,
          problem.html.length() > 0);
    }
  }

  private final BundleContext context = FrameworkUtil.getBundle(this.getClass()).getBundleContext();
}
 /**
  * Gets the current value of the CONFIGURATION configuration attribute.
  *
  * @return the current value for the configuration attribute
  */
 private static String getConfigurationAttribute() {
   return Platform.getPreferencesService()
       .getString(
           FrameworkUtil.getBundle(WorkspaceConfigurationStatusUtil.class).getSymbolicName(),
           WorkspaceConfigurationConstants.CONFIG_CONFIGURED,
           "",
           null);
 }
Exemplo n.º 21
0
 Filter getAuthFilter() throws InvalidSyntaxException {
   StringBuilder sb = new StringBuilder("("); // $NON-NLS-1$
   sb.append(ServerConstants.CONFIG_AUTH_NAME);
   sb.append('=');
   sb.append(getAuthName());
   sb.append(')');
   return FrameworkUtil.createFilter(sb.toString());
 }
 @Override
 public Filter makeFilterForClass(String className) {
   try {
     return FrameworkUtil.createFilter(String.format("(%s=%s)", Constants.OBJECTCLASS, className));
   } catch (InvalidSyntaxException e) {
     throw new IllegalArgumentException(e);
   }
 }
 /**
  * Writes the value of the CONFIGURED attribute.
  *
  * @param value the value to set
  */
 private static void writeConfiguredAttribute(String value) {
   IEclipsePreferences rootNode =
       InstanceScope.INSTANCE.getNode(
           FrameworkUtil.getBundle(WorkspaceConfigurationStatusUtil.class).getSymbolicName());
   if (rootNode != null) {
     rootNode.put(WorkspaceConfigurationConstants.CONFIG_CONFIGURED, value);
   }
 }
Exemplo n.º 24
0
  public ChannelServiceImpl() {
    this.context = FrameworkUtil.getBundle(ChannelServiceImpl.class).getBundleContext();

    final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    this.readLock = lock.readLock();
    this.writeLock = lock.writeLock();
  }
 @SuppressWarnings({"rawtypes", "unchecked"})
 private void loadHazelcast() {
   BundleContext ctx = FrameworkUtil.getBundle(AnalyticsServiceHolder.class).getBundleContext();
   ServiceReference ref = ctx.getServiceReference(HazelcastInstance.class);
   if (ref != null) {
     AnalyticsServiceHolder.setHazelcastInstance((HazelcastInstance) ctx.getService(ref));
   }
 }
Exemplo n.º 26
0
 private BundleContext getBundleContext() {
   BundleContext bundleContext = null;
   Bundle currentBundle = FrameworkUtil.getBundle(getClass());
   if (currentBundle != null) {
     bundleContext = currentBundle.getBundleContext();
   }
   return bundleContext;
 }
  static {
    Bundle bundle = FrameworkUtil.getBundle(ShoppingOrderItemLocalServiceUtil.class);

    _serviceTracker =
        new ServiceTracker<ShoppingOrderItemLocalService, ShoppingOrderItemLocalService>(
            bundle.getBundleContext(), ShoppingOrderItemLocalService.class, null);

    _serviceTracker.open();
  }
  static {
    Bundle bundle = FrameworkUtil.getBundle(ShoppingCouponUtil.class);

    _serviceTracker =
        new ServiceTracker<ShoppingCouponPersistence, ShoppingCouponPersistence>(
            bundle.getBundleContext(), ShoppingCouponPersistence.class, null);

    _serviceTracker.open();
  }
  static {
    Bundle bundle = FrameworkUtil.getBundle(KaleoTaskInstanceTokenLocalServiceUtil.class);

    _serviceTracker =
        new ServiceTracker<KaleoTaskInstanceTokenLocalService, KaleoTaskInstanceTokenLocalService>(
            bundle.getBundleContext(), KaleoTaskInstanceTokenLocalService.class, null);

    _serviceTracker.open();
  }
  static {
    Bundle bundle = FrameworkUtil.getBundle(MDRRuleGroupServiceUtil.class);

    _serviceTracker =
        new ServiceTracker<MDRRuleGroupService, MDRRuleGroupService>(
            bundle.getBundleContext(), MDRRuleGroupService.class, null);

    _serviceTracker.open();
  }