Change RepositoryFactory for Argeo v2
[lgpl/argeo-commons.git] / org.argeo.server.jcr / src / org / argeo / jackrabbit / OsgiJackrabbitRepositoryFactory.java
index b28699e60c029fdf35e2cc81e4d421627789e2dd..a617ec6e338402a91704d843f1c814ddd6914419 100644 (file)
  */
 package org.argeo.jackrabbit;
 
+import java.util.Collection;
 import java.util.Hashtable;
 import java.util.Properties;
 
 import javax.jcr.Repository;
 
+import org.argeo.jcr.ArgeoJcrException;
 import org.osgi.framework.BundleContext;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceReference;
 
 /**
  * OSGi-aware Jackrabbit repository factory which can retrieve/publish
  * {@link Repository} as OSGi services.
  */
-public class OsgiJackrabbitRepositoryFactory extends
-               JackrabbitRepositoryFactory {
+public class OsgiJackrabbitRepositoryFactory extends JackrabbitRepositoryFactory {
        private BundleContext bundleContext;
 
-       protected void publish(String alias, Repository repository,
-                       Properties properties) {
+       @Override
+       protected Repository getRepositoryByAlias(String alias) {
+               try {
+                       Collection<ServiceReference<Repository>> srs = bundleContext.getServiceReferences(Repository.class,
+                                       "(" + JCR_REPOSITORY_ALIAS + "=" + alias + ")");
+                       if (srs.size() == 0)
+                               throw new ArgeoJcrException("No repository with alias " + alias + " found in OSGi registry");
+                       else if (srs.size() > 1)
+                               throw new ArgeoJcrException(
+                                               srs.size() + " repositories with alias " + alias + " found in OSGi registry");
+                       return bundleContext.getService(srs.iterator().next());
+               } catch (InvalidSyntaxException e) {
+                       throw new ArgeoJcrException("Cannot find repository with alias " + alias, e);
+               }
+       }
+
+       protected void publish(String alias, Repository repository, Properties properties) {
                if (bundleContext != null) {
                        // do not modify reference
                        Hashtable<String, String> props = new Hashtable<String, String>();
                        props.putAll(props);
                        props.put(JCR_REPOSITORY_ALIAS, alias);
-                       bundleContext.registerService(Repository.class.getName(),
-                                       repository, props);
+                       bundleContext.registerService(Repository.class.getName(), repository, props);
                }
        }