org.apache.sshd.common.SshException: DefaultOpenFuture - APACHE MINA for SFTP Communication - sftp

I am getting following Exception:
org.apache.sshd.common.SshException: DefaultOpenFuture[ChannelSubsystem[id=0, recipient=-1]-
ClientSessionImpl[app6204#denad534.us.oracle.com/10.88.224.99:22][sftp]]: Failed to get operation result within specified timeout: 15000
at org.apache.sshd.common.future.AbstractSshFuture.formatExceptionMessage(AbstractSshFuture.java:187)
at org.apache.sshd.common.future.AbstractSshFuture.verifyResult(AbstractSshFuture.java:112)
at org.apache.sshd.client.future.DefaultOpenFuture.verify(DefaultOpenFuture.java:39)
at org.apache.sshd.client.future.DefaultOpenFuture.verify(DefaultOpenFuture.java:32)
at org.apache.sshd.client.subsystem.sftp.impl.DefaultSftpClient.<init>(DefaultSftpClient.java:97)
at org.apache.sshd.client.subsystem.sftp.impl.DefaultSftpClientFactory.createDefaultSftpClient(DefaultSftpClientFactory.java:67)
at org.apache.sshd.client.subsystem.sftp.impl.DefaultSftpClientFactory.createSftpClient(DefaultSftpClientFactory.java:47)
at org.apache.sshd.client.subsystem.sftp.SftpClientFactory.createSftpClient(SftpClientFactory.java:46)
at SSHClientExample.main(SSHClientExample.java:76)
Code:
public static void main(String[] args){
SshClient client = SshClient.setUpDefaultClient();
client.start();
try {
// DefaultOpenFuture defaultOpenFuture = new DefaultOpenFuture();
ConnectFuture future = client.connect("user", "Host", 22);
//ClientFactoryManager clientFactoryManager = client.
client.open();
client.start();
client.addPasswordIdentity("PWD");
client.setClientIdentityLoader(ClientIdentityLoader.DEFAULT);
client.setHostConfigEntryResolver(HostConfigEntryResolver.EMPTY);
ServerKeyVerifier serverKeyVerifier = AcceptAllServerKeyVerifier.INSTANCE;
client.setServerKeyVerifier(serverKeyVerifier);
SessionFactory sessionFactory = client.getSessionFactory();
ClientFactoryManager factoryManager =sessionFactory.getFactoryManager();
//.verify is necessary to get session
ClientSession clientSession = future.verify(100L,TimeUnit.SECONDS).getSession();
// ClientChannel clientChannel = clientSession.createChannel("exec");
future.setSession(clientSession);
//KeyPair keyPair = new KeyPair(PublicKey.serialVersionUID);
//clientSession.addPublicKeyIdentity();
clientSession.setAuthenticated();
System.out.println(future.isConnected());
System.out.println(clientSession);
SftpClientFactory sftpFactory = SftpClientFactory.instance();
//SFTP Version
SftpVersionSelector selector = SftpVersionSelector.fixedVersionSelector(6);
//SFTP Client
// clientSession.createChannel("FTP");
System.out.println("Client session opened?"+clientSession.isOpen());
System.out.println("Client is opened?"+client.isOpen());
clientSession.addPasswordIdentity("PWD");
//SftpClient sftpClient = sftpFactory.createSftpClient(clientSession, selector);
//System.out.println(sftpClient.open(" /slot/dummy/appmgr/location").getPath());
System.out.println(clientSession.getClientVersion());
//System.out.println(clientSession.createSubsystemChannel("SFTP").getSubsystem().getBytes());
DefaultSftpClientFactory defaultSftpClientFactory = new DefaultSftpClientFactory();
clientSession.addPublicKeyIdentity(KeyPairGeneratorMethod());
client.addPublicKeyIdentity(KeyPairGeneratorMethod());
//SftpClient sftp = defaultSftpClientFactory.createSftpClient(clientSession);
SftpClient sftp = defaultSftpClientFactory.createSftpClient(clientSession);
//= DefaultSftpClientFactory.INSTANCE.createSftpClient(clientSession);
//SftpClient sftp = new DefaultSftpClient(clientSession);
// SimpleSftpClientImpl sftp = new SimpleSftpClientImpl();
ClientChannel channel = clientSession.createSubsystemChannel(SftpConstants.SFTP_SUBSYSTEM_NAME);
System.out.println(channel.getSession().isAuthenticated());
//System.out.println(sftp.open(" /slot/dummy/appmgr/location").getPath()); //client.close();
}
catch (SshException e){
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//TODO
}
//client.stop();
}

I was able to get rid of this error with following Line.
clientSession.auth().verify();

Related

Confluent Kafka consumer consumes messages only after changing groupId

I have a .Net core console application, that uses Confluent.Kafka.
I build a consumer for consuming messages from specific topic.
the app is intended to run a few times every-day, consume the messages on the specified topic and process them.
It took me a while to understand the consumer's vehavior, but the it will consume messages only if its groupId is a one that was never in use before.
Every time I change the consumer's groupId - the comsumer will fetch the messages in the subscribed topic. But on the next runs - with same groupId - the consumer.Consume returns null.
This behvior seems rlated to rebalance between consumers on same group. But I don't understand why - since the consumer should exist only throughout the application liftime. Before leaving the app, I call to consumer.close() and consumer.Dispose(). These should destoy the consumer, so that on the next run, when I create the consumer, again it will be the first and single consumer on the specified groupId. But as I said, this is not what happens in fact.
I know there are messages on the topic - I check it via command-line. And I also made sure the topic has only 1 partition.
The most weird thing is, that I have another .net core console app, which does the same process - and with no issue at all.
I attach the codes of the 2 apps.
Working app - always consuming:
class Program
{
...
static void Main(string[] args)
{
if (args.Length != 2)
{
Console.WriteLine("Please provide topic name to read and SMTP topic name");
}
else
{
var services = new ServiceCollection();
services.AddSingleton<ConsumerConfig, ConsumerConfig>();
services.AddSingleton<ProducerConfig, ProducerConfig>();
var serviceProvider = services.BuildServiceProvider();
var cConfig = serviceProvider.GetService<ConsumerConfig>();
var pConfig = serviceProvider.GetService<ProducerConfig>();
cConfig.BootstrapServers = Environment.GetEnvironmentVariable("consumer_bootstrap_servers");
cConfig.GroupId = "confluence-consumer";
cConfig.EnableAutoCommit = true;
cConfig.StatisticsIntervalMs = 5000;
cConfig.SessionTimeoutMs = 6000;
cConfig.AutoOffsetReset = AutoOffsetReset.Earliest;
cConfig.EnablePartitionEof = true;
pConfig.BootstrapServers = Environment.GetEnvironmentVariable("producer_bootstrap_servers");
var consumer = new ConsumerHelper(cConfig, args[0]);
messages = new Dictionary<string, Dictionary<string, UserMsg>>();
var result = consumer.ReadMessage();
while (result != null && !result.IsPartitionEOF)
{
Console.WriteLine($"Current consumed msg-json: {result.Message.Value}");
...
result = consumer.ReadMessage();
}
consumer.Close();
Console.WriteLine($"Done consuming messages from topic {args[0]}");
}
}
class ConsumerHelper.cs
namespace AggregateMailing
{
using System;
using Confluent.Kafka;
public class ConsumerHelper
{
private string _topicName;
private ConsumerConfig _consumerConfig;
private IConsumer<string, string> _consumer;
public ConsumerHelper(ConsumerConfig consumerConfig, string topicName)
{
try
{
_topicName = topicName;
_consumerConfig = consumerConfig;
var builder = new ConsumerBuilder<string, string>(_consumerConfig);
_consumer = builder.Build();
_consumer.Subscribe(_topicName);
}
catch (System.Exception exc)
{
Console.WriteLine($"Error on ConsumerHelper: {exc.ToString()}");
}
}
public ConsumeResult<string, string> ReadMessage()
{
Console.WriteLine("ReadMessage: start");
try
{
return _consumer.Consume();
}
catch (System.Exception exc)
{
Console.WriteLine($"Error on ReadMessage: {exc.ToString()}");
return null;
}
}
public void Close()
{
Console.WriteLine("Close: start");
try
{
_consumer.Close();
_consumer.Dispose();
}
catch (System.Exception exc)
{
Console.WriteLine($"Error on Close: {exc.ToString()}");
}
}
}
}
Not working app - consuming only on first run after changing consumer groupId to one never in use:
class Program.cs
class Program
{
private static SmtpClient smtpClient;
private static Random random = new Random();
static void Main(string[] args)
{
try
{
var services = new ServiceCollection();
services.AddSingleton<ConsumerConfig, ConsumerConfig>();
services.AddSingleton<SmtpClient>(new SmtpClient("smtp.gmail.com"));
var serviceProvider = services.BuildServiceProvider();
var cConfig = serviceProvider.GetService<ConsumerConfig>();
cConfig.BootstrapServers = Environment.GetEnvironmentVariable("consumer_bootstrap_servers");
cConfig.GroupId = "smtp-consumer";
cConfig.EnableAutoCommit = true;
cConfig.StatisticsIntervalMs = 5000;
cConfig.SessionTimeoutMs = 6000;
cConfig.AutoOffsetReset = AutoOffsetReset.Earliest;
cConfig.EnablePartitionEof = true;
var consumer = new ConsumerHelper(cConfig, args[0]);
...
var result = consumer.ReadMessage();
while (result != null && !result.IsPartitionEOF)
{
Console.WriteLine($"current consumed message: {result.Message.Value}");
var msg = JsonConvert.DeserializeObject<EmailMsg>(result.Message.Value);
result = consumer.ReadMessage();
}
Console.WriteLine("Done sending emails consumed from SMTP topic");
consumer.Close();
}
catch (System.Exception exc)
{
Console.WriteLine($"Error on Main: {exc.ToString()}");
}
}
class ConsumerHelper.cs
using Confluent.Kafka;
using System;
using System.Collections.Generic;
namespace Mailer
{
public class ConsumerHelper
{
private string _topicName;
private ConsumerConfig _consumerConfig;
private IConsumer<string, string> _consumer;
public ConsumerHelper(ConsumerConfig consumerConfig, string topicName)
{
try
{
_topicName = topicName;
_consumerConfig = consumerConfig;
var builder = new ConsumerBuilder<string, string> (_consumerConfig);
_consumer = builder.Build();
_consumer.Subscribe(_topicName);
//_consumer.Assign(new TopicPartition(_topicName, 0));
}
catch (System.Exception exc)
{
Console.WriteLine($"Error on ConsumerHelper: {exc.ToString()}");
}
}
public ConsumeResult<string, string> ReadMessage()
{
Console.WriteLine("ConsumeResult: start");
try
{
return _consumer.Consume();
}
catch (System.Exception exc)
{
Console.WriteLine($"Error on ConsumeResult: {exc.ToString()}");
return null;
}
}
public void Close()
{
Console.WriteLine("Close: start");
try
{
_consumer.Close();
_consumer.Dispose();
}
catch (System.Exception exc)
{
Console.WriteLine($"Error on Close: {exc.ToString()}");
}
Console.WriteLine("Close: end");
}
}
}

How to call EJB from another app on the same server?

I have java SE sample client which run on desktop (code below). But I have access to WebSphere were called EJB is deployed. How to rewrite below code to work on WebSphere? (When I leave this code just like it is program works but I think this can be done more simple and clear)
Main method:
WSConn connection = new WSConn();
final Plan plan = connection.getPlanBean();
com.ibm.websphere.security.auth.WSSubject.doAs(connection.getSubject(), new java.security.PrivilegedAction<Object>() {
public Object run() {
try {
// App logic
} catch (Throwable t) {
System.err.println("PrivilegedAction - Error calling EJB: " + t);
t.printStackTrace();
}
return null;
}
}); // end doAs
WSConn class:
public class WSConn {
private static final String INITIAL_CONTEXT_FACTORY = "com.ibm.websphere.naming.WsnInitialContextFactory";
private static final String JAAS_MODULE = "WSLogin";
private static final String MODEL_EJB_NAME_LONG = "ejb/com/ibm/ModelHome";
private static final String PLAN_EJB_NAME_LONG = "ejb/com/ibm/PlanHome";
private Subject subject;
private InitialContext initialContext;
private String serverName;
private String serverPort;
private String uid;
private String pwd;
private String remoteServerName;
private Model modelBean;
private Plan planBean;
public WSConn() {
Properties props = new Properties();
try {
props.load(WSConn.class.getClassLoader().getResourceAsStream("WSConn.properties"));
} catch (IOException e) {
e.printStackTrace();
}
serverName = props.getProperty("WSConn.serverName");
serverPort = props.getProperty("WSConn.serverPort");
uid = props.getProperty("WSConn.userID");
pwd = props.getProperty("WSConn.password");
remoteServerName = props.getProperty("WSConn.remoteServerName");
}
private void init() {
if (subject == null || initialContext == null) {
subject = login();
}
}
private Subject login() {
Subject subject = null;
try {
LoginContext lc = null;
// CRATE LOGIN CONTEXT
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "corbaloc:iiop:" + serverName + ":" + serverPort);
initialContext = new InitialContext(env);
// Just to test the connection
initialContext.lookup("");
lc = new LoginContext(JAAS_MODULE, new WSCallbackHandlerImpl(uid, pwd));
lc.login();
subject = lc.getSubject();
} catch (javax.naming.NoPermissionException exc) {
System.err.println("[WSConn] - Login Error: " + exc);
} catch (Exception exc) {
System.err.println("[WSConn] - Error: " + exc);
}
return subject;
}
public wModel getModelBean() {
if (modelBean == null) {
init();
modelBean = (wModel) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wModel>() {
public wModel run() {
wModel session = null;
try {
Object o = initialContext.lookup(MODEL_EJB_NAME_LONG);
wModelHome home = (wModelHome) PortableRemoteObject.narrow(o, wModelHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting model bean: " + exc);
}
return session;
}
}); // end doAs
}
return modelBean;
}
public wPlan getPlanBean() {
if (planBean == null) {
init();
planBean = (wPlan) com.ibm.websphere.security.auth.WSSubject.doAs(subject,
new java.security.PrivilegedAction<wPlan>() {
public wPlan run() {
wPlan session = null;
try {
Object o = initialContext.lookup(PLAN_EJB_NAME_LONG);
wPlanHome home = (wPlanHome) PortableRemoteObject.narrow(o, wPlanHome.class);
if (home != null) {
session = home.create(remoteServerName);
}
} catch (Exception exc) {
System.err.println("Error getting plan bean: " + exc);
}
return session;
}
}); // end doAs
}
return planBean;
}
public Subject getSubject() {
if (subject == null) {
init();
}
return subject;
}
}
As indicated in another answer, the classic mechanism is to lookup and narrow the home interface.
Get the initial context
final InitialContext initialContext = new InitialContext();
Lookup for the home by jndi name, specifying either the full jndi name
Object obj = initialContext.lookup("ejb/com/ibm/tws/conn/plan/ConnPlanHome");
or you can create e reference in your WAR and use java:comp/env/yourname
Then narrow the home to the home interface class
ConnPlanHome planHome = (ConnPlanHome)PortableRemoteObject.narrow(obj, ConnPlanHome.class);
and then create the EJB remote interface
ConnPlan plan = planHome.create();
The about calls should work for IBM Workload Scheduler distributed.
For IBM Workload Scheduler z/OS the JNDI name and the class names are different:
final InitialContext initialContext = new InitialContext();
String engineName = "XXXX";
Object obj = initialContext.lookup("ejb/com/ibm/tws/zconn/plan/ZConnPlanHome");
ZConnPlanHome planHome = (ZConnPlanHome)PortableRemoteObject.narrow(obj, ZConnPlanHome.class);
ZConnPlan plan = planHome.create(engineName);
User credentials are propagated from the client to the engine, the client need to be authenticated otherwise the engine will reject the request.
If you're trying to access an EJB from a POJO class, then there is nothing more simple than lookup+narrow. However, if the POJO is included in an application (EAR or WAR), then you could declare and lookup an EJB reference (java:comp/ejb/myEJB), and then the container would perform the narrow rather than your code. If you change your code to be a managed class like a servlet, another EJB, or a CDI bean, then you could use #EJB injection, and then you would not even need a lookup.

Check Httpconnection is open or not in blackberry

Before making HttpConnection from blackberry application i want to check if it is open or not?. Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
EDIT: Posted the code from the OP's answer.
Below is my code for the http connection.
public String makePostRequest(String[] paramName, String[] paramValue) {
StringBuffer postData = new StringBuffer();
HttpConnection connection = null;
InputStream inputStream = null;
OutputStream out = null;
try {
connection = (HttpConnection) Connector.open(this.url);
connection.setRequestMethod(HttpConnection.POST);
for (int i = 0; i < paramName.length; i++) {
postData.append(paramName[i]);
postData.append("=");
postData.append(paramValue[i]);
postData.append("&");
}
String encodedData = postData.toString();
connection.setRequestProperty("Content-Language", "en-US");
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Length", (new Integer(
encodedData.length())).toString());
connection.setRequestProperty("Cookie", Constants.COOKIE_TOKEN);
byte[] postDataByte = postData.toString().getBytes("UTF-8");
out = connection.openOutputStream();
out.write(postDataByte);
DebugScreen.Log("Output stream..."+out);
DebugScreen.Log("Output stream..."+connection.getResponseCode());
// get the response from the input stream..
inputStream = connection.openInputStream();
DebugScreen.Log("Input stream..."+inputStream);
byte[] data = IOUtilities.streamToBytes(inputStream);
response = new String(data);
} catch ( Exception e) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
Status.show(Constants.CONNETION_ERROR);
}
});
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getMessage());
DebugScreen.Log("Exception inside the make connection..makePostRequest."
+ e.getClass());
}finally {
try {
if(inputStream != null){
inputStream.close();
inputStream = null;
}
if(out != null){
out.close();
out = null;
}
if(connection != null){
connection.close();
connection = null;
}
} catch ( Exception ex) {
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
WaitingScreen.removePopUP();
}
});
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getMessage());
DebugScreen.Log("Exception from the connection2 class.."
+ ex.getClass());
}
}
return response;
}
Before making httpconnection from blackberry application i want to check if it is open or not.
That doesn't make sense. You want to make sure it is open before you open it. You can't. You have to try to open it, and handle the exception if it fails. That's what the exception is for.
The best way to test whether any resource is available is to try to use it. You can't predict that. You have to try it.
Because without checking that when i tried to make a connection i got class net.rim.device.api.io.ConnectionClosedException.
So it wasn't available. So now you know. That's the correct behaviour. You're already doing the right thing. There is no question here to answer.

How to import an xquery module using Saxon

I am having some troubles running an Xquery with Saxon9HE, which has a reference to an external module.
I would like Saxon to resolve the module with a relative path rather absolute.
the module declaration
module namespace common = "http://my-xquery-utils";
from the main xquery
import module namespace common = "http://my-xquery-utils" at "/home/myself/common.xquery";
from my java code
public class SaxonInvocator {
private static Processor proc = null;
private static XQueryEvaluator xqe = null;
private static DocumentBuilder db = null;
private static StaticQueryContext ctx = null;
/**
* Utility for debug, should not be called outside your IDE
*
* #param args xml, xqFile, xqParameter
*/
public static void main(String[] args) {
XmlObject instance = null;
try {
instance = XmlObject.Factory.parse(new File(args[0]));
} catch (XmlException ex) {
Logger.getLogger(SaxonInvocator.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex){
Logger.getLogger(SaxonInvocator.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.print(transform(instance, args[1], args[2]));
}
public static String transform(XmlObject input, String xqFile, String xqParameter) {
String result = null;
try {
proc = new Processor(false);
proc.getUnderlyingConfiguration().getOptimizer().setOptimizationLevel(0);
ctx = proc.getUnderlyingConfiguration().newStaticQueryContext();
ctx.setModuleURIResolver(new ModuleURIResolver() {
#Override
public StreamSource[] resolve(String moduleURI, String baseURI, String[] locations) throws XPathException {
StreamSource[] modules = new StreamSource[locations.length];
for (int i = 0; i < locations.length; i++) {
modules[i] = new StreamSource(getResourceAsStream(locations[i]));
}
return modules;
}
});
db = proc.newDocumentBuilder();
XQueryCompiler comp = proc.newXQueryCompiler();
XQueryExecutable exp = comp.compile(getResourceAsStream(xqFile));
xqe = exp.load();
ByteArrayInputStream bais = new ByteArrayInputStream(input.xmlText().getBytes("UTF-8"));
StreamSource ss = new StreamSource(bais);
XdmNode node = db.build(ss);
xqe.setExternalVariable(
new QName(xqParameter), node);
result = xqe.evaluate().toString();
} catch (SaxonApiException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
public static InputStream getResourceAsStream(String resource) {
InputStream stream = SaxonInvocator.class.getResourceAsStream("/" + resource);
if (stream == null) {
stream = SaxonInvocator.class.getResourceAsStream(resource);
}
if (stream == null) {
stream = SaxonInvocator.class.getResourceAsStream("my/project/" + resource);
}
if (stream == null) {
stream = SaxonInvocator.class.getResourceAsStream("/my/project/" + resource);
}
return stream;
}
}
If a change it into a relative path like
import module namespace common = "http://my-xquery-utils" at "common.xquery";
I get
Error on line 22 column 1
XQST0059: java.io.FileNotFoundException
I am not sure how the ModuleURIResolver should be used.
Saxon questions are best asked on the Saxon forum at http://saxonica.plan.io - questions asked here will probably be noticed eventually but sometimes, like this time, they aren't our first priority.
The basic answer is that for the relative URI to resolve, the base URI needs to be known, which means that you need to ensure that the baseURI property in the XQueryCompiler is set. This happens automatically if you compile the query from a File, but not if you compile it from an InputStream.
If you don't know a suitable base URI to set, the alternative is to write a ModuleURIResolver, which could for example fetch the module by making another call on getResourceAsStream().

JSch/SSHJ - Connecting to SSH server on button click

I'm trying to connect to SSH Unix server on button click (code written in actionPerformed() method). I'm using JSch for connecting to SSH server. The code is written in SwingWorker class as it is a network operation.
private void testConnectionButtonActionPerformed(java.awt.event.ActionEvent evt) {
SwingWorker<Boolean, Void> sw = new SwingWorker<Boolean, Void>(){
#Override
protected Boolean doInBackground() throws Exception {
JSch jsch = new JSch();
String host = "ServerHost";
String username = "username";
String password = "password";
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return true;
}
#Override
public void done(){
try {
System.out.println(get().toString());
} catch (Exception ex) {
System.out.err(ex);
}
}
};
sw.execute();
}
But after running the with correct host, username and password details, I get the below error all the time:
com.jcraft.jsch.JSchException: timeout: socket is not established
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
But whenever I run the same code in standalone program, I mean instead for writing actionPerformed() method, If I write it in normal method and calling from main() method. It will work. when I integrate the same code with Button Click's actionPerformed() method, it will give me above exception.
Can anyone suggest what I'm doing wrong here or any modification should be made to the code.
I tried to connect to SSH Server using "SSHJ" implementation, but I get the below error:
java.net.SocketException: Connection reset
at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
at java.util.concurrent.FutureTask.get(FutureTask.java:83)
at javax.swing.SwingWorker.get(SwingWorker.java:583)
Can someone help me - how to move forward?
I took your code, wrapped it in some GUI code (and converted it to non-generics to be able to compile it with the same settings as the rest of the JSch examples). It works for me. Try this, and report what exception you get (it has a bit more exception logging).
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import com.jcraft.jsch.*;
class SwingWorkerExample {
JTextField hostField;
JTextField userNameField;
JTextField passwordField;
JPanel panel;
public SwingWorkerExample() {
JPanel p = panel = new JPanel(new GridLayout(0,2));
hostField = new JTextField(20);
userNameField = new JTextField(20);
passwordField = new JPasswordField(20);
JButton testButton = new JButton("connect!");
testButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
testConnectionButtonActionPerformed(ev);
}
});
p.add(new JLabel("host:"));
p.add(hostField);
p.add(new JLabel("user:"));
p.add(userNameField);
p.add(new JLabel("password:"));
p.add(passwordField);
p.add(testButton);
}
public JPanel getPanel() {
return panel;
}
private void testConnectionButtonActionPerformed(ActionEvent evt) {
SwingWorker sw = new SwingWorker(){
protected Object doInBackground() throws Exception {
try {
JSch jsch = new JSch();
String host = hostField.getText();
String username = userNameField.getText();
String password = passwordField.getText();
Session session = jsch.getSession(username, host);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.setTimeout(20000);
System.out.println("Connecting to server...");
session.connect();
return session;
}
catch(Exception ex) {
ex.printStackTrace();
throw ex;
}
}
public void done(){
try {
System.out.println(get());
} catch (Exception ex) {
ex.printStackTrace();
}
}
};
sw.execute();
}
public static void main(String[] egal) {
EventQueue.invokeLater(new Runnable(){public void run() {
SwingWorkerExample ex = new SwingWorkerExample();
JFrame f = new JFrame("bla");
f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
f.setContentPane(ex.getPanel());
f.pack();
f.setVisible(true);
}});
}
}

Resources