Category Archives: apache-mina

Apache MINA client server

I am creating a chat server using apache NIO. If I send one by one message to client->server or server->client then works correctly but whenever I send multiple message to server then server only receive first messsage....How can I create it so that client can send more messages to server and server receive all of them...

    package com.mina;

import java.util.Scanner;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

public class ClientHandler extends IoHandlerAdapter {

    @Override
    public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("In Exception Caught");

    }

    @Override
    public void inputClosed(IoSession arg0) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        System.out.println("In received" + message);
        if (session != null && message != null) {
            String retmsg = Utility.readMessageToUtility(session, message);
            System.out.println(retmsg);

            Scanner sc = new Scanner(System.in);
            String msg = sc.nextLine();
            Utility.sendMessageToUtility(session, msg);

        }

    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        System.out.println("   In messageSent    ");

    }

    @Override
    public void sessionClosed(IoSession arg0) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void sessionCreated(IoSession arg0) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void sessionOpened(IoSession arg0) throws Exception {
        // TODO Auto-generated method stub

    }

}

Server:

package com.mina;

import java.net.InetSocketAddress;
import java.`util`.HashMap;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class Server implements IoHandler {
    private org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(this.getClass().getName());
    HashMap<IoSession, Integer> map = new HashMap<>();

    public static void main(String[] r) throws Exception {
        Server server = new Server();
        server.connect();

    }

    public void connect() throws Exception {
        IoAcceptor acceptor = new NioSocketAcceptor();
        System.out.println(acceptor + "    acceptor");
        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.setHandler(this);
        acceptor.getSessionConfig().setReadBufferSize(2048);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.WRITER_IDLE, 2);

        acceptor.bind(new InetSocketAddress("localhost", 9081));

    }

    @Override
    public void exceptionCaught(IoSession arg0, Throwable arg1) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void inputClosed(IoSession arg0) throws Exception {
        // TODO Auto-generated method stub\

    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (session != null && message != null) {

            ServerHandler serverhandler = new ServerHandler();

            map.put(session, serverhandler.messageHandler(session, message, map.get(session)));
        }

    }

    @Override
    public void messageSent(IoSession arg0, Object arg1) throws Exception {
        System.out.println("In messageSent    ");

    }

    @Override
    public void sessionClosed(IoSession arg0) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        map.put(session, 1);

    }

    @Override
    public void sessionIdle(IoSession arg0, IdleStatus arg1) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {

        String message = "Welcome and give your userName";
        Utility.sendMessageToUtility(session, message);

    }

}

SSHD Server Apache Mina on Android

I tried to run my Android as a SSH Server and connect via terminal to my Android.

I use this example from official website https://mina.apache.org/sshd-project/embedding_ssh.html

and one project from github https://github.com/Keidan/SshServer.

Precisely this file https://github.com/Keidan/SshServer/blob/master/app/src/main/java/org/ralala/android/ssh/server/net/SshServer.java

Everything works correct login to SSH via terminal and that is ok. After login I have problem

/system/bin/sh: can't find: tty fd No such device or address
/system/bin/sh: warning: won't have full job control

In example of official documentation I see, they use

sshd.setShellFactory(new ProcessShellFactory(new String[] { "/bin/sh", "-i", "-l" }));

But in github example I see they use "/system/bin/sh" and I think this is ok for Android.

sshd.setShellFactory(new ProcessShellFactory(new String[] { "/system/bin/sh", "-i", "-l" }));

Now my mobile need to be rooted or not to execute "/system/bin/sh" command.

Without this command

sshd.setShellFactory(new ProcessShellFactory(new String[] { "/system/bin/sh", "-i", "-l" }));

I am unable to write anything into terminal. Terminal is frozen.

Apache camel with mina to proxy tcp messages

I am new with Apache Camel and I am trying to create a simple proxy that redirect all messages from localhost:3260 to localhost:3261 using Apache Mina. I am basing on some examples at internet (https://www.youtube.com/watch?v=jZE-YSHK_gw&sns=tw) and changing for what is my propose. In this example is a redirect of a file and I just changed to use mina protocol.

import org.apache.camel.CamelContext;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.simple.MyRouteBuilder;
public class MainTcpApp {
    public static void main(String[] args) throws Exception {
        MyRouteBuilder routeBuilder = new MyRouteBuilder();
        CamelContext context = new DefaultCamelContext();
        try {
            context.addRoutes(routeBuilder);
            context.start();
            for (;;) {
                Thread.sleep(5 * 60 * 50000);
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        } finally {
            context.stop();
        }
    }
}
import org.apache.camel.builder.RouteBuilder;
public class MyTcpRouteBuilder extends RouteBuilder {
    public void configure() throws Exception {
        from("mina:tcp://localhost:3260").to("mina:tcp://localhost:3261");
    }
}

In my example I started a target iSCSI at 3261 "target name: iqn.2014-06.iscsi-dev:disk1 loaded. Address: 127.0.0.1 - port: 3261" and I am trying to connect through 3260.

iscsiadm -m node --login -T iqn.2014-06.ustore-dev:disk1 -p 127.0.0.1:3260
Logging in to [iface: default, target: iqn.2014-06.ustore-dev:disk1, portal: 127.0.0.1,3260] (multiple)
iscsiadm: Could not login to [iface: default, target: iqn.2014-06.ustore-dev:disk1, portal: 127.0.0.1,3260].
iscsiadm: initiator reported error (8 - connection timed out)
iscsiadm: Could not log into all portals

I already could do it with http://netty.io/, but as I want a load balance I will need Apache Camel with Mina. Thanks.

unable to resolve Apache HTTP library to send Request and Receive Response

i am trying to upload image using Apache HTTP Library but i will get this kind of error.

    Caused by: java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter; in class Lorg/apache/http/message/BasicHeaderValueFormatter; or its superclasses (declaration of 'org.apache.http.message.BasicHeaderValueFormatter' appears in /system/framework/ext.jar)

at org.apache.http.entity.ContentType.toString(ContentType.java:153) it will give library error and crashing my application. unable to find solution regarding this problem

here is my logcat.

          E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #5
          Process: com.technotechindia.talknshop, PID: 9660
         java.lang.RuntimeException: An error occured while executing doInBackground()
         at android.os.AsyncTask$3.done(AsyncTask.java:304)
         at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
         at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
         at java.util.concurrent.FutureTask.run(FutureTask.java:242)
         at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
         at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
         at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
         at java.lang.Thread.run(Thread.java:818)
         Caused by: java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/message/BasicHeaderValueFormatter; in class Lorg/apache/http/message/BasicHeaderValueFormatter; or its superclasses (declaration of 'org.apache.http.message.BasicHeaderValueFormatter' appears in /system/framework/ext.jar)
  at org.apache.http.entity.ContentType.toString(ContentType.java:153)
  at org.apache.http.entity.mime.MultipartFormEntity.<init>(MultipartFormEntity.java:53)
  at org.apache.http.entity.mime.MultipartEntityBuilder.buildEntity(MultipartEntityBuilder.java:236)
          at         org.apache.http.entity.mime.MultipartEntity.getEntity(MultipartEntity.java:119)
          at org.apache.http.entity.mime.MultipartEntity.isChunked(MultipartEntity.java:138)
         at org.apache.http.protocol.RequestContent.process(RequestContent.java:84)
  at org.apache.http.protocol.BasicHttpProcessor.process(BasicHttpProcessor.java:295)
  at org.apache.http.protocol.HttpRequestExecutor.preProcess(HttpRequestExecutor.java:165)
  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:427)
  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:580)
  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:503)
  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:481)
  at com.technotechindia.talknshop.AddStoreToLocation$UploadImages.doInBackground(AddStoreToLocation.java:454)
  at com.technotechindia.talknshop.AddStoreToLocation$UploadImages.doInBackground(AddStoreToLocation.java:372)
  at android.os.AsyncTask$2.call(AsyncTask.java:292)
  at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
  at java.lang.Thread.run(Thread.java:818) 

so whenever i m going to request server give me this kind of error

How to enter into passive mode with Apache SSHD

I have a following code that creates remote ChannelSubsystem (FTP client) using Apache Mina SSHD:

org.apache.sshd.client.channel.ChannelSubsystem c = session.createSubsystemChannel("sftp");

int authState = ClientSession.WAIT_AUTH;

while ((authState & ClientSession.WAIT_AUTH) != 0) {

    System.out.println("authenticating...");

    authFuture.addListener(new SshFutureListener<AuthFuture>()
    {
        @Override
        public void operationComplete(AuthFuture arg0)
        {
            System.out.println("Authentication completed with " + ( arg0.isSuccess() ? "success" : "failure"));
        }
    });

    authState = session.waitFor(ClientSession.WAIT_AUTH | ClientSession.CLOSED | ClientSession.AUTHED, 0);
}

if ((authState & ClientSession.CLOSED) != 0) {
    System.err.println("error");
    System.exit(-1);
}

OpenFuture openFuture = c.open().await();

How can I via ChannelSubsystem send a command to remote FTP site to enter to passive mode?

Exception caught in SFTP subsystem Apache Mina sshd Server when uploading files to server

I start up a sftp local server using Apache Mina Sshd.Here is my related code.To testing i use winscp as my sftp client.I can connect to the server successfully and can view server root directory also.But the problem was that when i try to upload a file into that server root directory i got a

Exception caught in SFTP subsystem
java.lang.UnsupportedOperationException: null 
at org.apache.sshd.common.file.nativefs.NativeSshFile.setAttributes(NativeSshFile.java:634) ~[sshd-core-0.10.0.jar:0.10.0]
    at org.apache.sshd.server.sftp.SftpSubsystem.process(SftpSubsystem.java:427) ~[sshd-core-0.10.0.jar:0.10.0]
    at org.apache.sshd.server.sftp.SftpSubsystem.run(SftpSubsystem.java:334) ~[sshd-core-0.10.0.jar:0.10.0]
    at java.lang.Thread.run(Unknown Source) [na:1.7.0_75].

Below is my related log files.

10:30:46.758 [Thread-1] DEBUG o.a.s.c.file.nativefs.NativeSshFile - Authorized
10:30:46.767 [Thread-1] ERROR o.a.sshd.server.sftp.SftpSubsystem - Exception caught in SFTP subsystem
java.lang.UnsupportedOperationException: null
    at org.apache.sshd.common.file.nativefs.NativeSshFile.setAttributes(NativeSshFile.java:634) ~[sshd-core-0.10.0.jar:0.10.0]
    at org.apache.sshd.server.sftp.SftpSubsystem.process(SftpSubsystem.java:427) ~[sshd-core-0.10.0.jar:0.10.0]
    at org.apache.sshd.server.sftp.SftpSubsystem.run(SftpSubsystem.java:334) ~[sshd-core-0.10.0.jar:0.10.0]
    at java.lang.Thread.run(Unknown Source) [na:1.7.0_75]
10:30:46.767 [Thread-1] DEBUG o.a.s.server.channel.ChannelSession - Send SSH_MSG_CHANNEL_EOF on channel ChannelSession[id=0, recipient=256]
10:30:46.768 [Thread-1] DEBUG o.a.sshd.common.io.nio2.Nio2Session - Writing 64 bytes

Also my maven dependency,

<dependency>
        <groupId>org.apache.mina</groupId>
        <artifactId>mina-core</artifactId>
        <version>2.0.9</version>
    </dependency>
    <dependency>
        <groupId>org.apache.sshd</groupId>
        <artifactId>sshd-sftp</artifactId>
        <version>0.9.0</version>
    </dependency>

    <dependency>
        <groupId>org.apache.sshd</groupId>
        <artifactId>sshd-core</artifactId>
        <version>0.10.0</version>
    </dependency>

I would like to know that how can i overcome above problem when uploading files into my local sftp server.Thanks.

Apache Camel-Mina2 ExchangePattern – InOptionalOut

I am trying to build a prototype using Apache Camel-Mina2 component. We have our own protocol implementation on TCP and I need to intercept Client - Server messages using a proxy Component. Existing - TCP Client ----> TCP Server

New - TCP Client ----> Proxy Server -----> TCP Server

One of the issue in our protocol is that each Request is not guaranteed a reply from the server, so some requests will be sent on the channel with an optional response. However some requests will also get back a response.

Protocol Semantics : Hi ----> <---- Hello How Are You ------> Are You okay -----> <-----Yes

As you can see messages with ----> are from client to server and <---- are responses from Server ( on a single stream /line).

Now given the above problem, Camel-Mina2 works on a InOut message exchange pattern. The ExchangePattern Enumeration also has an InOptionalOut use case.

Any suggestions how I can configure my endpoints?

Sample implementation is as below:

SimpleRegistry reg = new SimpleRegistry();
        reg.put("ProtocolCodec", new ProtocolCodec());
        CamelContext context = new DefaultCamelContext(reg);

        context.addRoutes(new RouteBuilder() {

            @Override
            public void configure() throws Exception {
                // TODO Auto-generated method stub
                from("mina2:tcp://localhost:9888?sync=true&codec=#ProtocolCodec&disconnectOnNoReply=false").
                to("mina2:tcp://localhost:9889?sync=true&codec=#ProtocolCodec&disconnectOnNoReply=false&clientMode=true");

            }
        }); 

        context.start();

Apache Mina SSHD Server – How to get the list of forwarded ports

I have built a server/client system with Apache Mina SSHD. Clients connect the server by creating a session. Then they request port forwarding:

session.startRemotePortForwarding(ssaRemote,ssaLocal);

What i need is that: In server side, i should be able to tell which client's which port is forwarded to server's which port.

For example, if the client A requested a remote forwarding between its port 12345 and server's port 67890; and client B requested a remote forwarding between its port 11111 and server's port 22222; i need a list like:

  • ClientA 67890
  • ClientB 22222

Thanks

Apache Mina UDP Client: java.net.PortUnreachableException

There seems to be no documentation anywhere about the java.net.PortUnreachableException.

I've made a simple Apache Mina UDP Server and ran it. I then used telnet 127.0.0.1 3450 to check whether it was listening, and the connection was not refused, so the server definitely works.

The client consisits of the following files.

This is the main class below:

public static void main(String[] args) {
    System.out.println("started");
    NioDatagramConnector connector = new NioDatagramConnector();

    connector.setHandler(new PacketHandler());
    ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 3450));
}

This is part of the PacketHandler class:

@Override
public void sessionOpened(IoSession s) {
    System.out.println("opened " + s.getId() + " " + s.getLocalAddress().toString() + " " + s.getRemoteAddress().toString());
    byte[] data = new byte[]{(byte) 0x01};
    System.out.println("Sending " + data.length);
    IoBuffer buffer = IoBuffer.allocate(data.length);
    buffer.put(data);
    buffer.flip();
    s.write(buffer);
}

When the client is ran, I get the following error:

started
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
created 1
opened 1 /127.0.0.1:56777 /127.0.0.1:3450
Sending 1
java.net.PortUnreachableException
    at sun.nio.ch.DatagramDispatcher.read0(Native Method)
    at sun.nio.ch.DatagramDispatcher.read(DatagramDispatcher.java:43)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:197)
    at sun.nio.ch.DatagramChannelImpl.read(DatagramChannelImpl.java:560)
    at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:311)
    at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:45)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:702)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:668)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:657)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$600(AbstractPollingIoProcessor.java:67)
    at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:1121)
    at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:64)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
closed 1

The server also logs connections and when the client is ran, no connections are logged. However, when the telnet 127.0.0.1 3450 is ran from my Terminal, a connection is logged in the server logs. So apparently, the client isn't actually connecting.