首页 文章

从OSGi包中获取资源

提问于
浏览
2

我尝试使用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 is here) .

在捆绑我有激活,谁注册服务:

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的包中

但现在开始显示错误

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)

错误在哪里?谢谢,抱歉我的英语不好 .

1 回答

  • 2

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

相关问题