I am trying to use JSCH to connect to a remote server and then from that server open a telnet like session over a tcp/ip port. Say connect to server A, and once connected issue a tcp connection to server B over another port. In my webserver logs I see a GET / logged but not GET /foo as I would expect. ANything I m missing here? (I do not need to use Port forwarding since the remote port is accessible to the system I am connected to)
package com.tekmor;
import com.jcraft.jsch.*;
import java.io.BufferedReader;
.
.
public class Siranga {
public static void main(String[] args){
Siranga t=new Siranga();
try{
t.go();
} catch(Exception ex){
ex.printStackTrace();
}
}
public void go() throws Exception{
String host="hostXXX.com";
String user="USER";
String password="PASS";
int port=22;
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
String remoteHost="hostYYY.com";
int remotePort=80;
try {
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig(config);
session.connect();
Channel channel=session.openChannel("direct-tcpip");
((ChannelDirectTCPIP)channel).setHost(remoteHost);
((ChannelDirectTCPIP)channel).setPort(remotePort);
String cmd = "GET /foo";
InputStream in = channel.getInputStream();
OutputStream out = channel.getOutputStream();
channel.connect(10000);
byte[] bytes = cmd.getBytes();
InputStream is = new ByteArrayInputStream(cmd.getBytes("UTF-8"));
int numRead;
while ( (numRead = is.read(bytes) ) >= 0) {
out.write(bytes, 0, numRead);
System.out.println(numRead);
}
out.flush();
channel.disconnect();
session.disconnect();
System.out.println("foo");
}
catch (Exception e){
e.printStackTrace();
}
}
}
Read your HTTP specification again. The request header should end with an empty line. So assuming you have no more header lines, you should at least have to line breaks at the end. (Line break here means a CRLF combination.)
Also, the request line should contain the HTTP version identifier after the URL.
So try this change to your program:
String command = "GET /foo HTTP/1.0\r\n\r\n";
As a hint: Instead of manually piping data from your ByteArrayInputStream to the channel's output stream, you could use the setInputStream method. Also, don't forget to read the result from the channel's input stream.
Related
I have following Java class. When used with CachingConnectionFactory it creates configured number of ConcurrentConsumers set on DefaultMessageListenerContainer. However if PooledConnectionFactory is used instead of CachingConnectionFactory, it just creates concurrentConsumers equals to maximumActiveSessionPerConnection set on PooledConnectionFactory instead of number of concurrentConsumers set on DefaultMessageListenerContainer.
How can I make sure the DefaultMessageListenerContainer uses multiple connections/Sessions provided by PooledConnectionFactory and create configured number of concurrentConsumer provided to DefaultMessageListenerContainer. Below is the simple example to check the same.
import javax.jms.Session;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
public class ActiveMQMainTest {
public static void main(String[] args) {
String queueUrl = "tcp://localhost:61616";
ActiveMQQueue queue = new ActiveMQQueue("request.queue");
final ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(queueUrl);
PooledConnectionFactory pooledConnectionFactory = new PooledConnectionFactory();
pooledConnectionFactory.setConnectionFactory(connectionFactory);
pooledConnectionFactory.setCreateConnectionOnStartup(false);
pooledConnectionFactory.setMaxConnections(5);
pooledConnectionFactory.setMaximumActiveSessionPerConnection(100);
pooledConnectionFactory.start();
// CachingConnectionFactory pooledConnectionFactory = new CachingConnectionFactory(connectionFactory);
DefaultMessageListenerContainer defaultMessageListenerContainer = new DefaultMessageListenerContainer();
defaultMessageListenerContainer.setConnectionFactory(pooledConnectionFactory);
defaultMessageListenerContainer.setDestination(queue);
defaultMessageListenerContainer.setSessionAcknowledgeMode(Session.AUTO_ACKNOWLEDGE);
defaultMessageListenerContainer.setConcurrentConsumers(5);
defaultMessageListenerContainer.setMaxConcurrentConsumers(5 * 2);
defaultMessageListenerContainer.setCacheLevel(DefaultMessageListenerContainer.CACHE_NONE);
defaultMessageListenerContainer.setSessionTransacted(true);
JmsMessageListener messageListener = new JmsMessageListener();
defaultMessageListenerContainer.setMessageListener(messageListener);
defaultMessageListenerContainer.afterPropertiesSet();
defaultMessageListenerContainer.start();
try {
Thread.sleep(1000 * 60 * 10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The DMLC uses a shared connection by default (when there's no transaction manager). It can be disabled using:
dmlc.setCacheLevel(DefaultMessageListenerContainer.CACHE_NONE);
You should also normally have setSessionTransacted(true) with the DMLC, to avoid the possibility of losing messages (with the DMLC, messages are ack'd before the listener is invoked), using local transactions, the ack won't go to the broker until the listener exits normally.
I'm trying to create a partition programmatically. I've tried following the example on the ApacheDS website (https://directory.apache.org/apacheds/basic-ug/1.4.3-adding-partition.html#adding-a-partition-programmatically) , but this example is definitely not correct.
Here is my code:
LdapConnection connection = new LdapNetworkConnection(host, port);
connection.bind(admin, password);
connection.loadSchema();
SchemaManager schemaManager = connection.getSchemaManager();
Dn suffixDn = new Dn(schemaManager, "dc=newParition,dc=com");
JdbmPartition newPartition = new JdbmPartition(schemaManager);
newPartition.setId("newParition");
newPartition.setSuffixDn(suffixDn);
newPartition.setCacheSize(1000);
newPartition.setPartitionPath(new URI("file:///var/lib/apacheds-2.0.0-M15/default/partitions/newParition"));
newPartition.addIndex(new JdbmIndex("objectClass", false));
newPartition.addIndex(new JdbmIndex("dc", false));
Entry contextEntry = new DefaultEntry(schemaManager, suffixDn);
contextEntry.put("objectClass", "domain", "top");
contextEntry.put("dc", "newParition");
newPartition.initialize();
newPartition.add(new AddOperationContext(null, contextEntry));
I'm seeing the following error when I try to add the contextEntry to the partition:
org.apache.directory.api.ldap.model.exception.LdapSchemaViolationException: ERR_219 Entry dc=newParition,dc=com contains no entryCsn attribute: Entry …
It doesn't even look like the partition is being added to my server (when I restart my apacheds server, I don't see any new namingContexts under the Root DSE). I think I'm missing some steps here, but not sure what they are.
An advice from the Apache DS dev's mailing list:
"// ALWAYS add an entry using CoreSession's API". Check http://apaste.info/KHX for a nearly complete example of how to add a partition. The missing class EmbeddedServer is as follows:
private static final class EmbeddedServer {
private DirectoryService directoryService;
private LdapServer ldapService;
public EmbeddedServer(final String host, final int port) throws Exception {
init(host, port);
}
private void init(final String host, final int port) throws Exception {
DefaultDirectoryServiceFactory factory = new DefaultDirectoryServiceFactory();
factory.init("Test");
this.directoryService = factory.getDirectoryService();
this.directoryService.getChangeLog().setEnabled(false);
this.directoryService.setShutdownHookEnabled(true);
this.directoryService.setInstanceLayout(new InstanceLayout("/tmp/ldapServer"));
this.ldapService = new LdapServer();
this.ldapService.setTransports(new TcpTransport(host, port));
this.ldapService.setDirectoryService(this.directoryService);
}
public void start() throws Exception {
this.directoryService.startup();
this.ldapService.start();
}
public void stop() throws Exception {
this.ldapService.stop();
this.directoryService.shutdown();
}
}
I have managed to read a text file over an SSH channel using an Ubuntu Linux to serve as an SSH server. My question is how do i send an image file over and display it in an application like a JPanel? I seem to have problems doing that.
Below is the code that I have used which is from this forum. Credits to user World
public static void main(String []args) throws Exception
{
String user="larry";
String password="123";
String host="192.168.174.131";
int port = 22;
String remoteFile="/home/larry/seohyun.jpg";
try
{
JSch jsch=new JSch();
Session session=jsch.getSession(user,host,port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking","no");
System.out.println("Establishing connection");
session.connect();
System.out.println("Connection Established");
System.out.println("Creating SFTP Channel.");
ChannelSftp sftpChannel=(ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel Established");
InputStream out=null;
out=sftpChannel.get(remoteFile);
BufferedReader br=new BufferedReader(new InputStreamReader(out));
String imageName = br.readLine();
File input = new File(imageName);
image = ImageIO.read(input);
JFrame frame = new JFrame("Display Image");
Panel panel = new TestSSH();
frame.getContentPane().add(panel);
frame.setSize(500,500);
frame.setVisible(true);
}catch(Exception e)
{
System.err.print(e);
}
}
However I cant seem to be able to display the image on theJPanel`.
it gives me the following exception
Establishing connection
Connection Established
Creating SFTP Channel.
SFTP Channel Established
javax.imageio.IIOException: Can't read input file!
however, i have checked the file path countless times. It is correct.
May i know what`s wrong with my code?
I have a simle program shown below which is resonsible to upload a file to a Remote Location
public static void main(String[] args) {
String server = "www.myserver.com";
int port = 21;
String user = "user";
String pass = "pass";
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect(server, port);
ftpClient.login(user, pass);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File firstLocalFile = new File("D:/Test/Projects.zip");
String firstRemoteFile = "Projects.zip";
InputStream inputStream = new FileInputStream(firstLocalFile);
System.out.println("Start uploading first file");
boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
inputStream.close();
}
My question is , is it possible to test this program anyway , as i dont have a Remote Server currently .
Means is it possible to get remote server to upload files for temporary purpose ( Sorry but only open source please )
Is anybody aware of such websites ??
Screen shot
I am working on a simple WCF service, MiniCalcService which has only one operation Add. The client and host are both console applications. The client application takes in the operands necessary for each operation and passes them over to the service. The service returns the result which would be displayed on the client console.
Host is running
I am doing everything in code so far and there is no app.config.
There is no large data being passed, just two or three numbers
This worked for me yesterday. Today when I tried the same thing, it throws the following exception:
There was no endpoint listening at http://localhost:8091/MiniCalcService that could accept the message.
Here is the Stack Trace. Not that it might matter, but MiniCalcClient is developed in Visual Studio and MiniCalcService and MiniCalcHost are developed in SharpDevelop.
MiniCalcHost:
using(ServiceHost host = new ServiceHost(typeof(MiniCalcService.Service), new Uri("http://localhost:8091/MiniCalcService")))
{
host.AddServiceEndpoint(typeof(MiniCalcService.IService),new BasicHttpBinding(),"Service");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("Serving MiniCalcService since {0}", DateTime.Now);
Console.Write("Press ENTER key to terminate the MiniCalcHost . . . ");
Console.ReadKey(true);
}
MiniCalcClient:
static string Calculator(string operation, params string[] strOperands)
{
EndpointAddress ep = new EndpointAddress("http://localhost:8091/MiniCalcService");
IService proxy = ChannelFactory<IService>.CreateChannel(new BasicHttpBinding(), ep);
int[] operands;
string result = string.Empty;
try { operands = Array.ConvertAll(strOperands, int.Parse); }
catch (ArgumentException) { throw; }
switch (operation)
{
case "add":
result = Convert.ToString(proxy.Add(operands));//<---EXCEPTION
break;
default:
Console.WriteLine("Why was this reachable again?");
break;
}
return result;
}
Service Contract IService:
[ServiceContract(Namespace="learning.wcf.MiniCalc")]
public interface IService
{
[OperationContract]
double Add(params int[] operands);
}
Can you please help me identify what's causing this exception?
Solution: I changed this line:
EndpointAddress ep = new EndpointAddress("http://localhost:8091/MiniCalcService");
to this:
EndpointAddress ep = new EndpointAddress("http://localhost:8091/MiniCalcService/Service");
and it worked.
I'm not sure if you can use the params in a WCF service call.... seems unnecessary, anyway....
Could you try these two service contracts instead, just to see if those would work:
[ServiceContract(Namespace="learning.wcf.MiniCalc")]
public interface IService2
{
[OperationContract]
int Add(int op1, int op2);
}
and
[ServiceContract(Namespace="learning.wcf.MiniCalc")]
public interface IService3
{
[OperationContract]
int Add(List<int> operands);
}
I'm just wondering if removing the params from your service contract might make it run - everything seems fine at first glance...
OK, so it wasn't this first attempt ......
Well - quite obvious, really: you're using a using block around the service host instantiation:
using(ServiceHost host = new ServiceHost(typeof(MiniCalcService.Service), new Uri("http://localhost:8091/MiniCalcService")))
{
host.AddServiceEndpoint(typeof(MiniCalcService.IService),new BasicHttpBinding(),"Service");
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
host.Description.Behaviors.Add(smb);
host.Open();
Console.WriteLine("Serving MiniCalcService since {0}", DateTime.Now);
Console.Write("Press ENTER key to terminate the MiniCalcHost . . . ");
}
So by the time the code reaches the closing bracket }, the ServiceHost instance will be disposed and thus the service host closed. There's no running service host anymore!
You need to stop the code execution somewhere after the call to host.Open() by e.g.
Console.ReadLine();
or something else.
So your first claim that Host is running really doesn't hold up - it's running briefly and then is terminated again right away.....