我使用JSch和连接和会话对象不在子类中继承

时间:2013-09-30 09:56:01

标签: java jsch

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSchException;

public class ImageTypeDeployer extends MainImageDeployer {

public ImageTypeDeployer(String VolID,String oS,String imageName){

    String command="some command"

    try {        
        channel=session.openChannel("exec");
        channel.setInputStream(null);
        ((ChannelExec)channel).setCommand(command);
        channel.connect();
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}   

}

我在NullPointerException上收到了line channel = session.openChannel("exec") 当我把代码放在superclass中时,同样的事情也有效。 这是因为会话和通道变量不是继承的,还是其他的?

这是我正在建立连接的超类代码。

public void makeAConnection(){

    inputFile = RESTEngine.getFilePath();
    Properties defaultProps = new Properties();
    try {
        fin = new FileInputStream(inputFile);
        defaultProps.load(fin);
        fin.close();
    }
    catch(FileNotFoundException e1){
        System.out.println("The properties file supposed to contain PowerVC Authorization parameters was not found.");
        e1.printStackTrace();
        System.exit(-1); 
    }
    catch(IOException e1){
        System.out.println("An exception occured while trying to open the properties file");
        e1.printStackTrace();
        System.exit(-1);
    }
    // assign variables from Input file with default value as null
    user = defaultProps.getProperty("UserID", null);
    host = defaultProps.getProperty("PowerVC_IP_ADDRESS", null);
    password = defaultProps.getProperty("UserPass" ,null );

    jsch = new JSch();
    try {
        session = jsch.getSession(user, host, 22);
        session.setPassword(password);
        java.util.Properties config = new java.util.Properties(); 
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel=session.openChannel("exec");
        channel.setInputStream(null);

        try {
            in = channel.getInputStream();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Connection Successful");
    } catch (JSchException e) {
        // TODO Auto-generated catch block
        System.out.println("Unable to connect");
        e.printStackTrace();
    }

}

这就是我调用ImageTypeDeployer

的方式
protected Boolean doInBackground() throws Exception {

    makeAConnection();
    for(String imageName : volIDMap.keySet()){

        String volID = volIDMap.get(imageName);
        String oS = osMap.get(imageName);
        if (oS.equalsIgnoreCase("aix")){

            MainImageDeployer imageDeployer = new ImageTypeDeployer(volID, oS, imageName);

        }


    }
    return null;



}

1 个答案:

答案 0 :(得分:1)

session字段未在ImageTypeDeployer或其任何超类的构造函数中初始化,因此当您尝试调用session.openChannel时它为null。这解释了需要在makeAConnection方法中初始化它。