Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

osgi blueprint how to read resource file in bundle

I use osgi and blueprint, i search how to read file in my bundle? Such as : mybundle

  • file.json
  • OSGI-INF/blueprint/blueprint.xml
  • WEB-INF
  • *

I want read file.json in myservice.

like image 455
timactive Avatar asked May 06 '13 15:05

timactive


1 Answers

To do this, the easy method is to inject bundlecontext in your bean

blueprint.xml

<bean id="plugin" class="com.timactive.MyBean" init-method="start">
    <property name="bcontext" ref="blueprintBundleContext"></property>
 </bean>

The possible reference :

blueprintBundle Provides bundle's Bundle object.

blueprintBundleContext Provides bundle's BundleContext object.

blueprintContainer Provides the BlueprintContainer object for the bundle.

blueprintConverter Provides the Converter object for the bundle that provides access to the Blueprint Container type conversion facility. Type conversion has more information. source:http://www.ibm.com/developerworks/opensource/library/os-osgiblueprint/

And in your class :

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext
public class MyBean  {

    public BundleContext bcontext;
    public boolean start(){
    try {
    Bundle bundle = bcontext.getBundle();
    InputStream is = bundle.getEntry("/file.json").openStream();
    String jsondb =  readFile(is);

    } catch (IOException e) {
                LOG.error("The file treefield.json not found", e);
                return(false);
            }

        }

        return(true);
    }

    private String readFile(InputStream is ) throws IOException {
        java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
        return s.hasNext() ? s.next() : "";
   }
   public void setBcontext(BundleContext bcontext) {
    this.bcontext = bcontext;
}
like image 162
timactive Avatar answered Oct 22 '22 12:10

timactive