Search in sources :

Example 11 with ServiceReference

use of org.osgi.framework.ServiceReference in project tdi-studio-se by Talend.

the class ComponentsFactory method loadComponentsFromFolder.

private void loadComponentsFromFolder(String pathSource, AbstractComponentsProvider provider) {
    boolean isCustom = false;
    if ("org.talend.designer.components.model.UserComponentsProvider".equals(provider.getId()) || "org.talend.designer.components.exchange.ExchangeComponentsProvider".equals(provider.getId())) {
        isCustom = true;
    }
    File source;
    try {
        source = provider.getInstallationFolder();
    } catch (IOException e1) {
        ExceptionHandler.process(e1);
        return;
    }
    File[] childDirectories;
    FileFilter fileFilter = new FileFilter() {

        @Override
        public boolean accept(final File file) {
            return file.isDirectory() && file.getName().charAt(0) != '.' && !file.getName().equals(IComponentsFactory.EXTERNAL_COMPONENTS_INNER_FOLDER);
        }
    };
    if (source == null) {
        //$NON-NLS-1$
        ExceptionHandler.process(new Exception(Messages.getString("ComponentsFactory.componentNotFound") + pathSource));
        return;
    }
    childDirectories = source.listFiles(fileFilter);
    IBrandingService service = (IBrandingService) GlobalServiceRegister.getDefault().getService(IBrandingService.class);
    // String[] availableComponents = service.getBrandingConfiguration().getAvailableComponents();
    FileFilter skeletonFilter = new FileFilter() {

        @Override
        public boolean accept(final File file) {
            String fileName = file.getName();
            return file.isFile() && fileName.charAt(0) != '.' && (fileName.endsWith(SKELETON_SUFFIX) || fileName.endsWith(INCLUDEFILEINJET_SUFFIX));
        }
    };
    // Changed by Marvin Wang on Feb.22 for bug TDI-19166, caz the test ConnectionManagerTest maybe get the null
    // context.
    BundleContext context = null;
    if (Platform.getProduct() != null) {
        final Bundle definingBundle = Platform.getProduct().getDefiningBundle();
        if (definingBundle != null) {
            context = definingBundle.getBundleContext();
        }
    }
    if (context == null) {
        context = CodeGeneratorActivator.getDefault().getBundle().getBundleContext();
    }
    ServiceReference sref = context.getServiceReference(PackageAdmin.class.getName());
    PackageAdmin admin = (PackageAdmin) context.getService(sref);
    String bundleName;
    if (!isCustom) {
        bundleName = admin.getBundle(provider.getClass()).getSymbolicName();
    } else {
        bundleName = IComponentsFactory.COMPONENTS_LOCATION;
    }
    if (childDirectories != null) {
        if (monitor != null) {
            this.subMonitor = SubMonitor.convert(monitor, Messages.getString("ComponentsFactory.load.components"), //$NON-NLS-1$
            childDirectories.length);
        }
        if (skeletonList != null) {
            // to optimize the size of the array
            skeletonList.ensureCapacity(childDirectories.length);
            for (File currentFolder : childDirectories) {
                // get the skeleton files first, then XML config files later.
                File[] skeletonFiles = currentFolder.listFiles(skeletonFilter);
                if (skeletonFiles != null) {
                    for (File file : skeletonFiles) {
                        // path
                        skeletonList.add(file.getAbsolutePath());
                    }
                }
                try {
                    File xmlMainFile = new File(currentFolder, ComponentFilesNaming.getInstance().getMainXMLFileName(currentFolder.getName(), getCodeLanguageSuffix()));
                    if (!xmlMainFile.exists()) {
                        // if not a component folder, ignore it.
                        continue;
                    }
                    String currentXmlSha1 = null;
                    try {
                        currentXmlSha1 = SHA1Util.calculateFromTextStream(new FileInputStream(xmlMainFile));
                    } catch (FileNotFoundException e) {
                    // nothing since exceptions are directly in the check bellow
                    }
                    // Need to check if this component is already in the cache or not.
                    // if yes, then we compare the sha1... and if different we reload the component
                    // if component is not in the cache, of course just load it!
                    ComponentsCache cache = ComponentManager.getComponentCache();
                    boolean foundComponentIsSame = false;
                    ComponentInfo existingComponentInfoInCache = null;
                    if (cache.getComponentEntryMap().containsKey(currentFolder.getName())) {
                        EList<ComponentInfo> infos = cache.getComponentEntryMap().get(currentFolder.getName());
                        for (ComponentInfo info : infos) {
                            if (StringUtils.equals(bundleName, info.getSourceBundleName())) {
                                existingComponentInfoInCache = info;
                                if (StringUtils.equals(info.getSha1(), currentXmlSha1)) {
                                    foundComponentIsSame = true;
                                }
                                // found component, no matter changed or not
                                break;
                            }
                        }
                    }
                    if (foundComponentIsSame) {
                        // it should go here mainly for commandline or if use like ctrl+shift+f3
                        if (componentsCache.containsKey(xmlMainFile.getAbsolutePath())) {
                            IComponent componentFromThisProvider = null;
                            for (IComponent component : componentsCache.get(xmlMainFile.getAbsolutePath()).values()) {
                                if (component instanceof EmfComponent) {
                                    if (bundleName.equals(((EmfComponent) component).getSourceBundleName())) {
                                        componentFromThisProvider = component;
                                        break;
                                    }
                                }
                            }
                            if (componentFromThisProvider != null) {
                                // In headless mode, we assume the components won't change and we will use a cache
                                componentList.add(componentFromThisProvider);
                                if (isCustom) {
                                    customComponentList.add(componentFromThisProvider);
                                }
                                continue;
                            }
                        }
                    }
                    if (!foundComponentIsSame) {
                        ComponentFileChecker.checkComponentFolder(currentFolder, getCodeLanguageSuffix());
                    }
                    String pathName = xmlMainFile.getAbsolutePath();
                    String applicationPath = ComponentBundleToPath.getPathFromBundle(bundleName);
                    // pathName = C:\myapp\plugins\myplugin\components\mycomponent\mycomponent.xml
                    pathName = (new Path(pathName)).toPortableString();
                    // pathName = C:/myapp/plugins/myplugin/components/mycomponent/mycomponent.xml
                    //$NON-NLS-1$
                    pathName = pathName.replace(applicationPath, "");
                    // pathName = /components/mycomponent/mycomponent.xml
                    // if not already in memory, just load the component from cache.
                    // if the component is already existing in cache and if it's the same, it won't reload all (cf
                    // flag: foundComponentIsSame)
                    EmfComponent currentComp = new EmfComponent(pathName, bundleName, xmlMainFile.getParentFile().getName(), pathSource, cache, foundComponentIsSame, provider);
                    if (!foundComponentIsSame) {
                        // force to call some functions to update the cache. (to improve)
                        currentComp.isVisibleInComponentDefinition();
                        currentComp.isTechnical();
                        currentComp.getOriginalFamilyName();
                        currentComp.getTranslatedFamilyName();
                        currentComp.getPluginExtension();
                        currentComp.getVersion();
                        currentComp.getModulesNeeded(null);
                        currentComp.getPluginDependencies();
                        // end of force cache update.
                        EList<ComponentInfo> componentsInfo = cache.getComponentEntryMap().get(currentFolder.getName());
                        for (ComponentInfo cInfo : componentsInfo) {
                            if (cInfo.getSourceBundleName().equals(bundleName)) {
                                cInfo.setSha1(currentXmlSha1);
                                break;
                            }
                        }
                        // this will force to save the cache later.
                        ComponentManager.setModified(true);
                    }
                    boolean hiddenComponent = false;
                    Collection<IComponentFactoryFilter> filters = ComponentsFactoryProviderManager.getInstance().getProviders();
                    for (IComponentFactoryFilter filter : filters) {
                        if (!filter.isAvailable(currentComp.getName())) {
                            hiddenComponent = true;
                            break;
                        }
                    }
                    // just don't load it
                    if (hiddenComponent && !(currentComp.getOriginalFamilyName().contains("Technical") || currentComp.isTechnical())) {
                        continue;
                    }
                    componentToProviderMap.put(currentComp, provider);
                    // hide it
                    if (hiddenComponent && (currentComp.getOriginalFamilyName().contains("Technical") || currentComp.isTechnical())) {
                        currentComp.setVisible(false);
                        currentComp.setTechnical(true);
                    }
                    if (provider.getId().contains("Camel")) {
                        currentComp.setPaletteType(ComponentCategory.CATEGORY_4_CAMEL.getName());
                    } else {
                        currentComp.setPaletteType(currentComp.getType());
                    }
                    if (componentList.contains(currentComp)) {
                        //$NON-NLS-1$ //$NON-NLS-2$
                        log.warn("Component " + currentComp.getName() + " already exists. Cannot load user version.");
                    } else {
                        // currentComp.setResourceBundle(getComponentResourceBundle(currentComp, source.toString(),
                        // null,
                        // provider));
                        currentComp.setProvider(provider);
                        componentList.add(currentComp);
                        if (isCustom) {
                            customComponentList.add(currentComp);
                        }
                        if (pathSource != null) {
                            Path userComponent = new Path(pathSource);
                            Path templatePath = new Path(IComponentsFactory.COMPONENTS_INNER_FOLDER + File.separatorChar + IComponentsFactory.EXTERNAL_COMPONENTS_INNER_FOLDER + File.separatorChar + ComponentUtilities.getExtFolder(OLD_COMPONENTS_USER_INNER_FOLDER));
                            if (userComponent.equals(templatePath)) {
                                userComponentList.add(currentComp);
                            }
                        }
                    }
                    // componentsCache only used bellow in case of headless (commandline) or if use like
                    // ctrl+shift+f3
                    String componentName = xmlMainFile.getAbsolutePath();
                    if (!componentsCache.containsKey(componentName)) {
                        componentsCache.put(componentName, new HashMap<String, IComponent>());
                    }
                    componentsCache.get(xmlMainFile.getAbsolutePath()).put(currentComp.getPaletteType(), currentComp);
                } catch (MissingMainXMLComponentFileException e) {
                    //$NON-NLS-1$ //$NON-NLS-2$
                    log.trace(currentFolder.getName() + " is not a " + getCodeLanguageSuffix() + " component", e);
                } catch (BusinessException e) {
                    BusinessException ex = new BusinessException(//$NON-NLS-1$ //$NON-NLS-2$
                    "Cannot load component \"" + currentFolder.getName() + "\": " + e.getMessage(), e);
                    ExceptionHandler.process(ex, Level.ERROR);
                }
                if (this.subMonitor != null) {
                    this.subMonitor.worked(1);
                }
                if (this.monitor != null && this.monitor.isCanceled()) {
                    return;
                }
            }
            // to optimize the size of the array
            skeletonList.trimToSize();
        }
    }
}
Also used : IComponent(org.talend.core.model.components.IComponent) IComponentFactoryFilter(org.talend.core.model.components.filters.IComponentFactoryFilter) FileNotFoundException(java.io.FileNotFoundException) BusinessException(org.talend.commons.exception.BusinessException) FileFilter(java.io.FileFilter) Path(org.eclipse.core.runtime.Path) ComponentBundleToPath(org.talend.designer.core.model.components.ComponentBundleToPath) Bundle(org.osgi.framework.Bundle) ResourceBundle(java.util.ResourceBundle) IOException(java.io.IOException) IBrandingService(org.talend.core.ui.branding.IBrandingService) ComponentsCache(org.talend.core.model.component_cache.ComponentsCache) FileNotFoundException(java.io.FileNotFoundException) BusinessException(org.talend.commons.exception.BusinessException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) ServiceReference(org.osgi.framework.ServiceReference) PackageAdmin(org.osgi.service.packageadmin.PackageAdmin) EmfComponent(org.talend.designer.core.model.components.EmfComponent) ComponentInfo(org.talend.core.model.component_cache.ComponentInfo) File(java.io.File) BundleContext(org.osgi.framework.BundleContext)

Example 12 with ServiceReference

use of org.osgi.framework.ServiceReference in project Activiti by Activiti.

the class Extender method resolveScriptEngine.

// script engine part
public static ScriptEngine resolveScriptEngine(String scriptEngineName) throws InvalidSyntaxException {
    ServiceReference[] refs = context.getServiceReferences(ScriptEngineResolver.class.getName(), null);
    if (refs == null) {
        LOGGER.info("No OSGi script engine resolvers available!");
        return null;
    }
    LOGGER.debug("Found {} OSGi ScriptEngineResolver services", refs.length);
    for (ServiceReference ref : refs) {
        ScriptEngineResolver resolver = (ScriptEngineResolver) context.getService(ref);
        ScriptEngine engine = resolver.resolveScriptEngine(scriptEngineName);
        context.ungetService(ref);
        LOGGER.debug("OSGi resolver {} produced {} engine {}", resolver, scriptEngineName, engine);
        if (engine != null) {
            return engine;
        }
    }
    return null;
}
Also used : ScriptEngine(javax.script.ScriptEngine) ServiceReference(org.osgi.framework.ServiceReference)

Example 13 with ServiceReference

use of org.osgi.framework.ServiceReference in project aries by apache.

the class DirObjectFactoryHelper method getObjectInstanceUsingObjectFactoryBuilders.

private Object getObjectInstanceUsingObjectFactoryBuilders(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment, Attributes attrs) throws Exception {
    ObjectFactory factory = null;
    ServiceReference[] refs = Utils.getReferencesPrivileged(callerContext, ObjectFactoryBuilder.class);
    if (refs != null) {
        Arrays.sort(refs, Utils.SERVICE_REFERENCE_COMPARATOR);
        for (ServiceReference ref : refs) {
            ObjectFactoryBuilder builder = (ObjectFactoryBuilder) Utils.getServicePrivileged(callerContext, ref);
            try {
                factory = builder.createObjectFactory(obj, environment);
            } catch (NamingException e) {
            // TODO: log it
            } finally {
                callerContext.ungetService(ref);
            }
            if (factory != null) {
                break;
            }
        }
    }
    Object result = null;
    if (factory != null) {
        if (factory instanceof DirObjectFactory) {
            result = ((DirObjectFactory) factory).getObjectInstance(obj, name, nameCtx, environment, attrs);
        } else {
            result = factory.getObjectInstance(obj, name, nameCtx, environment);
        }
    }
    return (result == null) ? obj : result;
}
Also used : DirObjectFactory(javax.naming.spi.DirObjectFactory) ObjectFactory(javax.naming.spi.ObjectFactory) ObjectFactoryBuilder(javax.naming.spi.ObjectFactoryBuilder) NamingException(javax.naming.NamingException) DirObjectFactory(javax.naming.spi.DirObjectFactory) ServiceReference(org.osgi.framework.ServiceReference)

Example 14 with ServiceReference

use of org.osgi.framework.ServiceReference in project aries by apache.

the class ServiceHelper method findService.

private static ServicePair findService(BundleContext ctx, String interface1, String filter) throws NamingException {
    ServicePair p = null;
    try {
        ServiceReference[] refs = ctx.getServiceReferences(interface1, filter);
        if (refs != null) {
            // natural order is the exact opposite of the order we desire.
            Arrays.sort(refs, new Comparator<ServiceReference>() {

                public int compare(ServiceReference o1, ServiceReference o2) {
                    return o2.compareTo(o1);
                }
            });
            for (ServiceReference ref : refs) {
                Object service = ctx.getService(ref);
                if (service != null) {
                    p = new ServicePair();
                    p.ref = ref;
                    p.service = service;
                    break;
                }
            }
        }
    } catch (InvalidSyntaxException e) {
    // If we get an invalid syntax exception we just ignore it. Null
    // will be returned which
    // is valid and that may result in a NameNotFoundException if that
    // is the right thing to do
    }
    return p;
}
Also used : InvalidSyntaxException(org.osgi.framework.InvalidSyntaxException) ServiceReference(org.osgi.framework.ServiceReference)

Example 15 with ServiceReference

use of org.osgi.framework.ServiceReference in project aries by apache.

the class ReferenceDependency method getServiceType.

private Class<?> getServiceType() {
    if (_reference.service() != Object.class) {
        return _reference.service();
    }
    Type type = _injectionPoint.getType();
    if (_bindType == BindType.SERVICE_PROPERTIES) {
        throw new IllegalArgumentException("A @Reference cannot bind service properties to a Map<String, Object> without " + "specifying the @Reference.service property: " + _injectionPoint);
    } else if ((_bindType == BindType.SERVICE_REFERENCE) && !(type instanceof ParameterizedType)) {
        throw new IllegalArgumentException("A @Reference cannot bind a ServiceReference without specifying either the " + "@Reference.service property or a generic type argument (e.g. ServiceReference<Foo>: " + _injectionPoint);
    }
    if (!(type instanceof ParameterizedType)) {
        return cast(type);
    }
    ParameterizedType parameterizedType = cast(type);
    Type rawType = parameterizedType.getRawType();
    if (Instance.class.isAssignableFrom(cast(rawType))) {
        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
        type = actualTypeArguments[0];
        if (type instanceof ParameterizedType) {
            parameterizedType = (ParameterizedType) type;
            rawType = parameterizedType.getRawType();
        } else {
            rawType = type;
        }
    }
    if (!ServiceReference.class.isAssignableFrom(cast(rawType))) {
        return cast(rawType);
    }
    Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
    Type first = actualTypeArguments[0];
    if (first instanceof ParameterizedType) {
        ParameterizedType parameterizedType1 = cast(first);
        return cast(parameterizedType1.getRawType());
    }
    return cast(first);
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) WildcardType(java.lang.reflect.WildcardType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) ServiceReference(org.osgi.framework.ServiceReference)

Aggregations

ServiceReference (org.osgi.framework.ServiceReference)1687 Test (org.junit.Test)926 Properties (java.util.Properties)396 Architecture (org.apache.felix.ipojo.architecture.Architecture)263 CheckService (org.apache.felix.ipojo.runtime.core.test.services.CheckService)233 BundleContext (org.osgi.framework.BundleContext)229 InstanceDescription (org.apache.felix.ipojo.architecture.InstanceDescription)227 ComponentInstance (org.apache.felix.ipojo.ComponentInstance)215 InvalidSyntaxException (org.osgi.framework.InvalidSyntaxException)182 ArrayList (java.util.ArrayList)167 Bundle (org.osgi.framework.Bundle)144 FooService (org.apache.felix.ipojo.runtime.core.services.FooService)141 Hashtable (java.util.Hashtable)124 IOException (java.io.IOException)107 CheckService (org.apache.felix.ipojo.runtime.core.services.CheckService)92 Dictionary (java.util.Dictionary)82 Configuration (org.osgi.service.cm.Configuration)74 CheckService (org.apache.felix.ipojo.handler.temporal.services.CheckService)70 FooService (org.apache.felix.ipojo.handler.temporal.services.FooService)70 CheckService (org.apache.felix.ipojo.handler.transaction.services.CheckService)65