2011-08-11 73 views
7

我目前正在嘗試獲取包含Service Factory運行的簡單包。osgi:使用ServiceFactories?

這是我的工廠類:

public class SvcFactory implements ServiceFactory<ServiceB> { 

    @Override 
    public ServiceB getService(Bundle bundle, 
      ServiceRegistration<ServiceB> registration) { 

     return new ServiceBImpl(); 
    } 

    @Override 
    public void ungetService(Bundle bundle, ServiceRegistration<ServiceB> registration, 
      ServiceB service) { 

    } 

} 

這是我的服務,應該由工廠創建:

public class ServiceBImpl implements ServiceB { 

    private ServiceA svcA; 

    public void setA(ServiceA a) { 
     svcA = a; 
    } 

} 

最後的OSGI-INF/component.xml文件

<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="bundleb.internal.SvcFactory"> 

    <implementation class="bundleb.internal.SvcFactory"/> 

    <reference bind="setA" cardinality="1..1" interface="bundlea.ServiceA" name="ServiceA" policy="static"/> 

    <service servicefactory="true"> 
     <provide interface="bundleb.ServiceB"/> 
    </service> 
</scr:component> 

如果我運行我的測試捆綁包(A,B和C)在equinox我收到以下錯誤:

org.osgi.framework.ServiceException: org.eclipse.equinox.internal.ds.FactoryReg.getService() returned a service object that is not an instance of the service class bundleb.ServiceB 

我無法找到有關在Internet上使用組件定義中聲明的ServiceFeactors的更多信息。即使是「OSGi和Equinox」這本書也沒有給我太多關於使用它們的信息。 任何人都可以請解釋我做錯了什麼?

+0

包含你的服務的包不應該有ServiceB.class文件。如果是這樣,它會爲不同的捆綁使用不同的ServiceB--這是錯誤的。 –

+0

我想你誤會了。如果您指定了servicefactory屬性,那麼DS將爲每個包創建一個新實例。您可以從ComponentContext獲取您分配的包。 –

回答

12

下面是一個使用ComponentFactory的示例,它應該適合您的需求(並且包含一個簡單的集成測試以幫助您的other question)。免責聲明;代碼寫得不好,僅僅是爲了舉例。

一些服務接口:

package net.earcam.example.servicecomponent; 

public interface EchoService { 

    String REPEAT_PARAMETER = "repeat"; 
    String FACTORY_DS = "echo.factory"; 
    String NAME_DS = "echo"; 

    String echo(String message); 
} 

和:

package net.earcam.example.servicecomponent; 

public interface SequenceService { 
    long next(); 
} 

然後實現:

import static net.earcam.example.servicecomponent.EchoService.FACTORY_DS; 
import static net.earcam.example.servicecomponent.EchoService.NAME_DS; 
import static org.apache.felix.scr.annotations.ReferenceCardinality.MANDATORY_UNARY; 
import static org.apache.felix.scr.annotations.ReferencePolicy.DYNAMIC; 
import net.earcam.example.servicecomponent.EchoService; 
import net.earcam.example.servicecomponent.SequenceService; 

import org.apache.felix.scr.annotations.Activate; 
import org.apache.felix.scr.annotations.Component; 
import org.apache.felix.scr.annotations.Reference; 
import org.osgi.service.component.ComponentContext; 

@Component(factory = FACTORY_DS, name = NAME_DS) 
public class EchoServiceImp implements EchoService { 

    @Reference(cardinality = MANDATORY_UNARY, policy = DYNAMIC) 
    private SequenceService sequencer = null; 
    private transient int repeat = 1; 

    @Activate 
protected void activate(final ComponentContext componentContext) 
{ 
    repeat = Integer.parseInt(componentContext.getProperties().get(REPEAT_PARAMETER).toString()); 
} 


@Override 
public String echo(final String message) 
{ 
    StringBuilder stringBuilder = new StringBuilder(); 
    for(int i = 0; i < repeat; i++) { 
     addEchoElement(stringBuilder, message); 
    } 
    return stringBuilder.toString(); 
} 


private void addEchoElement(final StringBuilder stringBuilder, final String message) { 
    stringBuilder.append(sequencer.next()).append(' ').append(message).append("\n");   
} 


protected void unbindSequencer() 
{ 
    sequencer = null; 
} 


protected void bindSequencer(final SequenceService sequencer) 
{ 
    this.sequencer = sequencer; 
} 

}

和:

package net.earcam.example.servicecomponent.internal; 

import java.util.concurrent.atomic.AtomicLong; 

import net.earcam.example.servicecomponent.SequenceService; 

import org.apache.felix.scr.annotations.Activate; 
import org.apache.felix.scr.annotations.Component; 
import org.apache.felix.scr.annotations.Deactivate; 
import org.apache.felix.scr.annotations.Service; 

/** 
* @author caspar 
*/ 
@Component 
@Service 
public class SequenceServiceImp implements SequenceService { 

    private AtomicLong sequence; 


    @Override 
    public long next() 
    { 
     return sequence.incrementAndGet(); 
    } 


    @Activate 
    protected void activate() 
    { 
     sequence = new AtomicLong(); 
    } 


    @Deactivate 
    protected void deactivate() 
    { 
     sequence = null; 
    } 
} 

驅動整個事情的集成測試(注意;有一個主要的方法,所以你開始/停止捆綁等運行它)。

package net.earcam.example.servicecomponent.test; 

import static org.ops4j.pax.exam.CoreOptions.*; 
import static org.ops4j.pax.exam.OptionUtils.combine; 
import static org.ops4j.pax.exam.spi.container.PaxExamRuntime.createContainer; 
import static org.ops4j.pax.exam.spi.container.PaxExamRuntime.createTestSystem; 

import java.io.File; 
import java.io.FileFilter; 
import java.io.FileNotFoundException; 
import java.util.Dictionary; 
import java.util.Hashtable; 
import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

import net.earcam.example.servicecomponent.EchoService; 
import net.earcam.example.servicecomponent.SequenceService; 

import org.junit.Assert; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.ops4j.pax.exam.Option; 
import org.ops4j.pax.exam.junit.Configuration; 
import org.ops4j.pax.exam.junit.ExamReactorStrategy; 
import org.ops4j.pax.exam.junit.JUnit4TestRunner; 
import org.ops4j.pax.exam.spi.reactors.EagerSingleStagedReactorFactory; 
import org.osgi.framework.BundleContext; 
import org.osgi.framework.ServiceReference; 
import org.osgi.service.component.ComponentFactory; 
import org.osgi.service.component.ComponentInstance; 


@ExamReactorStrategy(EagerSingleStagedReactorFactory.class) 
@RunWith(JUnit4TestRunner.class) 
public class EchoServiceIntegrationTest { 


    public static void main(String[] args) { 
     try { 
      createContainer(
        createTestSystem(
          combine(
            new EchoServiceIntegrationTest().config(), 
            profile("gogo")) 
        )).start(); 
     } catch(Throwable t) { 
      t.printStackTrace(); 
     } 
    } 



    @Configuration 
    public Option[] config() 
    { 
     return options(
       felix(), 
       equinox(), 
       junitBundles(), 
       systemProperty("org.ops4j.pax.logging.DefaultServiceLog.level").value("TRACE"), 
       mavenBundle().groupId("org.apache.felix").artifactId("org.apache.felix.scr").versionAsInProject(), 
       bundle("file:" + findFileInCurrentDirectoryAndBelow(
         Pattern.compile("net\\.earcam\\.example\\.servicecomponent\\-[\\.\\d]+(\\-SNAPSHOT)?\\.[wj]ar"))) 
     ); 
    } 


    @Test 
    public void bundleContextIsAvailable(BundleContext context) 
    { 
     Assert.assertNotNull("PAX Exam BundleContext available", context); 
    } 


    @Test 
    public void sequenceServiceIsAvailable(BundleContext context) 
    { 
     Assert.assertNotNull("SequenceService available", fetchService(context, SequenceService.class)); 
    } 


    @Test 
    public void serviceResponseContainsThreeEchos(BundleContext context) throws Exception 
    { 
     final String message = "message"; 
     final String expected = "1 " + message + "\n2 " + message + "\n3 " + message + "\n"; 

     ComponentFactory factory = fetchComponentFactory(context, EchoService.FACTORY_DS); 

     Dictionary<String, String> properties = new Hashtable<String, String>(); 
     properties.put(EchoService.REPEAT_PARAMETER, "3"); 
     ComponentInstance instance = factory.newInstance(properties); 
     EchoService service = (EchoService) instance.getInstance(); 
     String actual = service.echo(message); 
     Assert.assertEquals("Expected response", expected, actual); 
    } 


    private ComponentFactory fetchComponentFactory(BundleContext context, String componentFactoryId) throws Exception 
    { 
     String filter = "(component.factory=" + componentFactoryId + ")"; 
     ServiceReference[] references = context.getServiceReferences(ComponentFactory.class.getCanonicalName(), filter); 
     return (references.length) == 0 ? null : (ComponentFactory) context.getService(references[0]); 
    } 


    private <T> T fetchService(BundleContext context, Class<T> clazz) 
    { 
     ServiceReference reference = context.getServiceReference(clazz.getCanonicalName()); 
     @SuppressWarnings("unchecked") 
     T service = (T) context.getService(reference); 
     return service; 
    } 


    private String findFileInCurrentDirectoryAndBelow(final Pattern filePattern) { 
     FileFilter filter = new FileFilter() { 
      @Override 
      public boolean accept(File pathname) { 
       Matcher matcher = filePattern.matcher(pathname.getName()); 
       return (matcher.matches()); 
      } 
     }; 
     return findFile(new File("."), filter, filePattern); 
    } 


    private String findFile(File directory, FileFilter filter, Pattern filePattern) { 
     File[] matches = directory.listFiles(filter); 
     if(matches != null && matches.length > 0) { 
      return matches[0].getAbsolutePath(); 
     } 
     File[] subdirs = directory.listFiles(new FileFilter() { 
      @Override 
      public boolean accept(File pathname) { 
       return pathname.isDirectory(); 
      } 
     }); 
     for(final File subdir : subdirs) { 
      String found = findFile(subdir, filter, filePattern); 
      if(!"".equals(found)) { 
       return found; 
      } 
     } 
     throw new RuntimeException(new FileNotFoundException("No match for pattern: " + filePattern.pattern())); 
    } 
} 

而這裏的Maven POM文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>net.earcam</groupId> 
    <artifactId>net.earcam.example.servicecomponent</artifactId> 
    <version>0.0.1-SNAPSHOT</version> 
    <packaging>jar</packaging> 

    <properties> 
     <version.java.source>1.6</version.java.source> 
     <version.java.target>1.6</version.java.target> 

     <version.osgi>4.2.0</version.osgi> 
     <version.paxexam>2.1.0</version.paxexam> 
     <version.paxrunner>1.7.4</version.paxrunner> 
     <version.cometd>2.3.1</version.cometd> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
    </properties> 

    <dependencies> 
     <dependency> 
      <groupId>org.osgi</groupId> 
      <artifactId>org.osgi.core</artifactId> 
      <version>${version.osgi}</version> 
      <scope>provided</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.osgi</groupId> 
      <artifactId>org.osgi.compendium</artifactId> 
      <version>${version.osgi}</version> 
      <scope>provided</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.apache.felix</groupId> 
      <artifactId>org.apache.felix.scr.annotations</artifactId> 
      <version>1.4.0</version> 
      <scope>provided</scope> 
     </dependency> 

     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.8.2</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.hamcrest</groupId> 
      <artifactId>hamcrest-core</artifactId> 
      <version>1.3.RC2</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.jmock</groupId> 
      <artifactId>jmock-junit4</artifactId> 
      <version>2.5.1</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.slf4j</groupId> 
      <artifactId>slf4j-simple</artifactId> 
      <version>1.6.1</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.ops4j.pax.exam</groupId> 
      <artifactId>pax-exam-junit4</artifactId> 
      <version>${version.paxexam}</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.ops4j.pax.exam</groupId> 
      <artifactId>pax-exam-container-paxrunner</artifactId> 
      <version>${version.paxexam}</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.ops4j.pax.exam</groupId> 
      <artifactId>pax-exam-link-assembly</artifactId> 
      <version>${version.paxexam}</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.ops4j.pax.exam</groupId> 
      <artifactId>pax-exam-testforge</artifactId> 
      <version>${version.paxexam}</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.ops4j.pax.runner</groupId> 
      <artifactId>pax-runner-no-jcl</artifactId> 
      <version>${version.paxrunner}</version> 
      <scope>test</scope> 
     </dependency> 

     <dependency> 
      <groupId>org.apache.felix</groupId> 
      <artifactId>org.apache.felix.scr</artifactId> 
      <version>1.6.0</version> 
      <scope>test</scope> 
     </dependency> 
    </dependencies> 

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-compiler-plugin</artifactId> 
       <version>2.3.2</version> 
       <configuration> 
        <source>${version.java.source}</source> 
        <target>${version.java.target}</target> 
        <encoding>${project.build.sourceEncoding}</encoding> 
       </configuration> 
      </plugin> 

      <plugin> 
       <!-- Unit Tests --> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-surefire-plugin</artifactId> 
       <version>2.8.1</version> 
       <executions> 
        <execution> 
         <goals> 
          <goal>test</goal> 
         </goals> 
        </execution> 
       </executions> 
       <configuration> 
        <excludes> 
         <exclude>**/*IntegrationTest.java</exclude> 
        </excludes> 
       </configuration> 
      </plugin> 

      <plugin> 
       <!-- Integration Tests --> 
       <groupId>org.codehaus.mojo</groupId> 
       <artifactId>failsafe-maven-plugin</artifactId> 
       <version>2.4.3-alpha-1</version> 
       <executions> 
        <execution> 
         <goals> 
          <goal>integration-test</goal> 
          <goal>verify</goal> 
         </goals> 
         <phase>integration-test</phase> 
        </execution> 
       </executions> 
       <configuration> 
        <includes> 
         <include>**/*IntegrationTest.java</include> 
        </includes> 
       </configuration> 
      </plugin> 

      <plugin> 
       <groupId>org.ops4j.pax.exam</groupId> 
       <artifactId>maven-paxexam-plugin</artifactId> 
       <version>1.2.3</version> 
       <executions> 
        <execution> 
         <id>generate-config</id> 
         <goals> 
          <goal>generate-depends-file</goal> 
         </goals> 
        </execution> 
       </executions> 
      </plugin> 

      <plugin> 
       <!-- Process the DS annotations --> 
       <groupId>org.apache.felix</groupId> 
       <artifactId>maven-scr-plugin</artifactId> 
       <version>1.6.0</version> 
       <executions> 
        <execution> 
         <id>generate-scr-descriptor</id> 
         <goals> 
          <goal>scr</goal> 
         </goals> 
         <phase>process-classes</phase> 
         <configuration> 
          <strictMode>true</strictMode> 
          <outputDirectory>${project.build.outputDirectory}/</outputDirectory> 
         </configuration> 
        </execution> 
       </executions> 
      </plugin> 


      <plugin> 
       <!-- Generate OSGi bundle MAINFEST.MF entries --> 
       <groupId>org.apache.felix</groupId> 
       <artifactId>maven-bundle-plugin</artifactId> 
       <version>2.3.4</version> 
       <extensions>true</extensions> 
       <configuration> 
        <supportedProjectTypes> 
         <supportedProjectType>jar</supportedProjectType> 
        </supportedProjectTypes> 
        <instructions> 
         <Bundle-Vendor>earcam</Bundle-Vendor> 
         <Service-Component>OSGI-INF/serviceComponents.xml</Service-Component> 
         <!-- PAX mangles this, it uses the name of the project for the symbolicname 
          of test bundle? <Bundle-SymbolicName>${project.name}</Bundle-SymbolicName> --> 
         <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName> 
         <Bundle-Version>${project.version}</Bundle-Version> 
         <Export-Package>!${project.artifactId}.internal,${project.artifactId}.*</Export-Package> 
         <Import-Package>*</Import-Package> 
        </instructions> 
       </configuration> 
       <executions> 
        <execution> 
         <id>bundle-manifest</id> 
         <phase>process-classes</phase> 
         <goals> 
          <goal>manifest</goal> 
         </goals> 
        </execution> 
       </executions> 
      </plugin> 

      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-jar-plugin</artifactId> 
       <version>2.3.1</version> 
       <configuration> 
        <archive> 
         <manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile> 
        </archive> 
       </configuration> 
      </plugin> 

     </plugins> 
    </build> 
</project> 

幾件事情要注意;我喜歡在他們測試的模塊內部進行集成測試如果我的集成測試確實發生,mvn clean install deploy會失敗 - 但通常在所有集成測試中看到具有單個集成模塊的項目。這解釋了醜陋的方法findFileInCurrentDirectoryAndBelow(Pattern pattern),它用於在目標目錄中查找當前模塊的包,並解釋了maven-bundle-plugin和maven-scr-plugin插件的非標準設置。

另外Pax-Exam檢索依賴關係的方式需要您運行Maven構建以確定每個依賴和配置的更改(例如,bundle導入/導出,DS更改)。但一旦完成,您可以運行/調試Eclipse的測試。

我已經把這個項目的壓縮包here

HTH =)

+0

太棒了!非常感謝您的詳細回答和耐心。 –

+0

非常詳細的答案感謝@earcam,遠遠優於pax-exam文檔,它對我有很大的幫助。但有一些困惑,這是與JAVA 6但不是在JAVA 8,我試了很多與不同的PAX依賴版本,但無法找出與Java 8的衝突,你可以請提供版本依賴流如果可能? –

0

ServiceFactory允許您的代碼爲不同的包提供定製的服務對象。請注意,使用ServiceFactory時,您的服務的客戶端仍無法控制何時創建新實例,它們照常通過其接口(ServiceB)查找服務。因此,對於他們來說,如果您的服務註冊爲ServiceFactory,則沒有區別。

對於聲明性服務,您不應該自己實施ServiceFactory。只需將servicefactory="true"屬性添加到<service>元素(您已經完成),並且將爲不同的請求捆綁包自動創建(激活)您的組件類的不同實例。您需要指定ServiceBImpl作爲組件的實現類。

+0

OSGi平臺如何知道使用哪個工廠類? –

+0

我想提供自己的工廠實現來支持我的代碼的更好的可測試性。看到這個討論:http://stackoverflow.com/questions/7004165/unit-testing-osgi-components/7009717#7009717我發現在http://www.knopflerfish.org/osgi_service_tutorial.html一個例子如何做到這一點,但我必須在激活器中註冊服務工廠。在組件聲明中沒有辦法做到這一點,以便DS爲我做到這一點? –

+0

它會創建自己的工廠,基本上會做類似getService(){Object comp = clazz.newInstance(); activateComponent(COMP);返回comp; } –

1

它實際上是相當簡單的... DS會爲每個包一個實例,因此與DS不實現服務工廠,DS完成所有艱苦的工作。例如:

@Service(serviceFactory=true) 
public class MyServiceFactory implements XyzService { 

    ... 
    @Activate 
    void activate(ComponentContext ctx) { 
     System.out.println("Using bundle: " + ctx.getUsingBundle()); 
    } 
} 

每當另一個bundle獲取此XyzService時,DS將創建一個新實例。您可以使用ComponentContext(可選地在activate方法中傳遞)來獲取使用您的包。

+0

github鏈接現在已損壞 –