osgi - 从 OSGi 包获取资源

标签 osgi bundle apache-felix getresource

我尝试使用 Felix/OSGi 从 bundle jar 中获取文件作为资源。 我已阅读No access to Bundle Resource/File (OSGi)How to reference an included file in OSGi bundle when performing java.io.File or FileInputStream但我不明白如何获取资源。

现在我有了加载器应用程序和一个 bundle ( bundle is here )。

在 bundle 中我有激活者,他注册了服务:

 public void start(BundleContext context) throws Exception {
    Hashtable<String, String> props = new Hashtable<String, String>();
    props.put("Funct", "MainForm");
    context.registerService(MainFormInterface.class.getName(), new MainForm(), props);

    ServiceReference[] refs = context.getServiceReferences(
            MainFormInterface.class.getName(), "(Funct=MainForm)");
    if (refs == null) {
        System.out.println("Not Found MainForm on start");
    } else {
        MainFormInterface MainForm = (MainFormInterface) context.getService(refs[0]);
        MainForm.sendContext(context);
        MainForm.showWindow();
    }
}

服务等级为

    package ihtika2.mainform;

import ihtika2.mainform.service.MainFormInterface;
import javax.swing.SwingUtilities;
import org.osgi.framework.BundleContext;

/**
 *
 * @author Arthur
 */
public class MainForm implements MainFormInterface {

    BundleContext context;

    @Override
    public void sendContext(BundleContext context) {
        this.context = context;
    }

    IC_MainForm MainForm;

    @Override
    public void showWindow() {
        SwingUtilities.invokeLater(new Runnable() {
            // This creates of the application window.
            @Override
            public void run() {
                MainForm = new IC_MainForm();
//                MainForm.main();
                MainForm.main(context);


            }
        });
    }

表单的代码是

package ihtika2.mainform;

import com.google.code.ihtika.Vars.Ini;
import ihtika2.i_aboutform.service.AboutFormInterface;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
import javax.swing.JFrame;
import org.apache.log4j.*;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;

/**
 *
 * @author Arthur Khusnutdinov
 */
public class IC_MainForm extends JFrame {

    private static IC_MainForm localFrame;
    BundleContext context;

    /**
     * Creates new form IC_MainForm
     */
    public IC_MainForm(BundleContext context) {
        initComponents();
        PropertyConfigurator.configure(props());
        Ini.logger = Logger.getRootLogger();
        this.context = context;




    }

    public IC_MainForm() {
//        if (Ini.goUpdate) {
//            JDialog updateDialog = null;
//            if (updateDialog == null) {
//                updateDialog = new UpdateIhtikaClient(null);
//            }
//            IhtikaClientApp.getApplication().show(updateDialog);
//
//        } else {
////            JOptionPane.showMessageDialog(null, "Ваша копия программы устарела"
////                    + "На http://ihtik.lib.ru/ ...", "LectorInstaller", 1);
////            System.exit(0);
//            show(new IhtikaClientView(this));
//        } 
        try {

            URL configURL = context.getBundle().getEntry("ihtika2/mainform/favicon_1.jpg");
            System.out.println("sdfsdfsdf");
            if (configURL != null) {
                InputStream input = configURL.openStream();
                try {
                    // process your input here or in separate method
                } finally {
                    input.close();
                }
            }

//            InputStream www = getClass().getResourceAsStream("/ihtika2/mainform/service/favicon_1.jpg");
//            InputStream www = getClass().getResourceAsStream("/com/google/code/ihtika/resources/favicon_1.jpg");

//            BufferedImage qqq;
//            qqq = javax.imageio.ImageIO.read(www);
//            this.setIconImage(qqq); // NOI18N

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        menuBar = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setIconImages(null);

        jMenu1.setText("Главное меню");

        jMenuItem2.setText("О программе");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem2);

        jMenuItem1.setText("Выход");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        menuBar.add(jMenu1);

        setJMenuBar(menuBar);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 800, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 598, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        System.exit(0);
    }                                          

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        try {

            ServiceReference[] refs = context.getServiceReferences(
                    AboutFormInterface.class.getName(), "(Funct=*)");
            if (refs == null) {
                System.out.println("Not Found AboutForm on show");
            } else {
                AboutFormInterface AboutForm = (AboutFormInterface) context.getService(refs[0]);
                AboutForm.showWindow();
            }
        } catch (Exception ex) {
            Ini.logger.fatal("Error on showing AboutForm", ex);
        }

    }                                          

//    public void main() {
    public void main(final BundleContext context) {

        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (Exception ex) {
            Ini.logger.fatal("Error in MainForm: ", ex);
        }
        //</editor-fold>

//        if (args.length>0 && (args[0].equals("update") || args[0].equals("updatesvn"))) {
//            Ini.updateType = args[0];
//            Ini.goUpdate = true;
//        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                localFrame = new IC_MainForm(context);
                localFrame.setVisible(true);
            }
        });
    }

    public static void stop() {
        localFrame.setVisible(false);
        localFrame.dispose();
        localFrame = null;
    }

    private static Properties props() {
        Properties props = new Properties();
        props.put("log4j.rootLogger", "INFO, R");
        props.put("log4j.appender.R",
                "org.apache.log4j.DailyRollingFileAppender");
        props.put("log4j.appender.R.File", "logs/IhtikaClient.log");
        props.put("log4j.appender.R.Append", "true");
        props.put("log4j.appender.R.Threshold", "INFO");
        props.put("log4j.appender.R.DatePattern", "'.'yyyy-MM-dd");
        props.put("log4j.appender.R.layout", "org.apache.log4j.PatternLayout");
        props.put("log4j.appender.R.layout.ConversionPattern",
                //"%d{HH:mm:ss,SSS} %c - %m%n");
                //"[%5p] %d{yyyy-MM-dd mm:ss} (%F:%M:%L)%n%m%n%n");
                "[%5p] %d{yyyy-MM-dd mm:ss} %c (%F:%M:%L)%n%m%n");
        return props;
    }
    // Variables declaration - do not modify                     
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuBar menuBar;
    // End of variables declaration                   
}

现在 jpg 图像位于路径 ihtika2\mainform\favicon_1.jpg 的 bundle 中

但现在启动时显示错误

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at ihtika2.mainform.IC_MainForm.<init>(IC_MainForm.java:54)
    at ihtika2.mainform.MainForm$1.run(MainForm.java:32)
    at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:701)
    at java.awt.EventQueue.access$000(EventQueue.java:102)
    at java.awt.EventQueue$3.run(EventQueue.java:662)
    at java.awt.EventQueue$3.run(EventQueue.java:660)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:671)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:244)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:163)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:147)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:139)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:97)

哪里出错了? 谢谢,抱歉我的英语不好。

最佳答案

我认为IC_MainForm中的context为空;您没有在 IC_MainForm() 中设置它。

关于osgi - 从 OSGi 包获取资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11757793/

相关文章:

java - 使用 maven-bundle-plugin 为不包含所有依赖项的 jar 的 OSGI 容器创建 Web 应用程序包 (WAB)

osgi - @Service用于在CQ中创建服务,那么BundleContext.registerService方法有什么用呢?

liferay - 在 osgi 文件夹中复制后,Liferay 7 tomcat 中的 war 在哪里爆炸

php - 当 bundle 产品位于购物车中时,从 Woocommerce 中的购物车中删除子组件

android - 如何检查 putExtra 是否存在?

未找到 Windows WinPlatformFactory 上的 JavaFx + Felix

java - 包含对实现代码的引用的 OSGi 导出 API 安全吗?

git - 如何解绑一个 git 包?

java - OSGI 未使用 导入包 make 作为可选

java - OSGi 包中访问标准 java 类时出现 NoClassDefFoundError