2012-08-01 106 views
2

我嘗試從使用Felix/OSGi的軟件包jar中獲取文件作爲資源。 我已閱讀No access to Bundle Resource/File (OSGi)How to reference an included file in OSGi bundle when performing java.io.File or FileInputStream但我無法理解如何獲取資源。從OSGi軟件包獲取資源

現在我有裝載應用程序和一個包(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) 

哪裏是錯誤? 謝謝並對不起我的英文不好。

+0

除了你目前的例外,我發現你應該改進一件事。您正在Mainform中手動初始化日誌記錄。這在OSGi中不是一個好主意。你應該嘗試ops4j pax記錄。它爲您管理日誌設置。 http://team.ops4j.org/wiki/display/paxlogging/Pax+Logging – 2012-08-02 06:03:44

回答

2

我認爲contextIC_MainForm爲空;你沒有設置在IC_MainForm()

+0

是的,這是我的錯誤,我發現你的錯誤。但無論如何感謝您的迴應。 – 2012-08-01 12:30:25

+0

太棒了...通過代理進行調試! ;-) – 2012-08-01 17:50:33