Playframework Ning WS and thread - java

I have simple java method to upload file from local disk to remote web service, and it's working great in controller class.
Now I moved this method into separated class. I try to call this method from thread :
public void run(){
while (true){
System.out.println("Geting next Task for processing ...");
try {
CommonUtils.uploadVideo(32);
Thread.sleep(20000);
} catch (InterruptedException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Inject
static
WSClient ws;
synchronized static void uploadVideo(int taskId) throws InterruptedException, ExecutionException, IOException {
....
....
...
com.ning.http.client.AsyncHttpClient underlyingClient = (com.ning.http.client.AsyncHttpClient) ws.getUnderlying();
final String response;
response = underlyingClient.preparePost("http://192.16.10.125:9001/publish").
setHeader("watermark", "0").
addBodyPart(new FilePart("file", file)).execute().get().getResponseBody().toString();
}
And I got an error :
Exception in thread "Thread-8" java.lang.NullPointerException
at utils.CommonUtils.uploadVideo(CommonUtils.java:308)
at utils.TaskRunner.run(TaskRunner.java:88)
at java.lang.Thread.run(Unknown Source)
What is wrong? Is the problem Asynchronous call web service?

Related

How to shutdown an ExecutorService from one of its threads?

I want to stop the whole ExecutorService if one (specific thread) of the threads managed by it fails with an exception. Is it ok to simply call ExecutorService#shutdown from within the thread?
With Executorservice , if getting returned data from a thread ( using .get() method ) fails with an Exception , an ExecutionException will be thrown .
You have 2 case : passing Runnable to the submit method , or passing a Callable , in both of those cases you can use .get() method to retrieve data from the thread after execution.
So you can add .get() method to all the execution of threads and surround the calls of the submit method with a try catch block that handle ExecutionException .
This example will explain the idea :
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
static ExecutorService service = Executors.newFixedThreadPool(3);
public static void main(String[] args) {
try {
// Callable
System.out.println(service.submit(() -> {
return "Hello";
}).get());
} catch (ExecutionException e) {
System.out.println(e.getMessage());
// shutDown the service : if you delete the next line , service will still
// working
service.shutdownNow();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// Runnable
service.submit(() -> {
throw new IOException();
}).get();
} catch (ExecutionException e) {
System.out.println(e.getMessage());
// shutDown the service : if you delete the next line , service will still
// working
service.shutdownNow();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Connection reset by peer: socket write error While tring to send object

So I'm getting Connection reset by peer: socket write error while tring to send object and I don't know why. This is small part of my university project, I have spent a lot of time tring to make it work but I'm really out of ideas. I would be really greatful for your help.
I tried to send a simple string message to client and it works fine.
Server code:
public class Server {
static ServerSocket serverSocket;
public static void main(String args[]) {
try {
serverSocket = new ServerSocket(7777);
Map map = new Map();
while(true)
{
Socket incoming = serverSocket.accept();
System.out.println(incoming.toString());
Runnable r = new ServerConnection(incoming, map);
Thread t = new Thread(r);
t.start();
}
}
}
ServerConnection code:
public class ServerConnection implements Runnable {
private Socket s;
private ObjectOutputStream out;
private Map map;
public ServerConnection(Socket out, Map map){
this.s = out;
this.map = map;
System.out.println(map);
}
public void sendMap(){
//map.setRotation(rotated);
try {
out = new ObjectOutputStream(s.getOutputStream());
System.out.println(out);
System.out.println(this.map);
out.writeObject(this.map);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeSocket(){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
//this.connect();
this.sendMap();
}
}
The print stacktrace gives this information :
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(Unknown Source)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(Unknown Source)`
at java.io.ObjectOutputStream.writeFatalException(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
at Server.ServerConnection.sendMap(ServerConnection.java:39)
at Server.ServerConnection.run(ServerConnection.java:59)
at java.lang.Thread.run(Unknown Source)
Yes, I checked if Map is not null and if output exists etc. I don't know what triggers the problem.
Edit: - Object Map is serializable.
Client Console output:
Exception in thread "main" java.lang.NullPointerException
at Client.ClientConnection.getMap(ClientConnection.java:37)
at Client.Client.main(Client.java:28)
Client code:
public static void main(String[] args) {
ClientConnection c = new ClientConnection();
c.connect();
Map map = c.getMap();
System.out.println(map);
c.closeSocket();
}
ClientConnection: - serverString is local adres "127.0.0.1"
public void connect(){
try
{
Socket s = new Socket(serverString,7777);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Map getMap(){
Map map;
try {
input = new ObjectInputStream(s.getInputStream());
map = (Map)(input.readObject());
return map;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public void closeSocket(){
try {
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Connection reset by peer means that the other side closed the connection. Since you are showing the server side program, then the client side must be the one closing it. Check the client side code and console output.
EDIT: you are not assigning s to the class field, so it is always null when getMap is called.
Change to this:
Socket s = new Socket(serverString,7777);
this.s = s;

Why do I need try-catch with throws in my example?

Could someone please help me to understand why do I need to use (inner) try catch if the method is declared as throwing the same exception.
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
try {
producer();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
t1.start();
t1.join();
}
syntax of producer() is
private static void producer() throws InterruptedException
The answer is that you are defining an anonymous class.
Thread t1 = new Thread(new Runnable() {
public void run() {
try {
producer(); //This is called in run method!
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
The declaration of the method that calls producer() is public void run() and this method does not throw the checked exception. Therefore, you have to catch it.
It's logical, because you start new thread, which can live after execution leaves the creating method(if it wasn't main method and if you didn't use Thread.join()). So you should handle exception independently.

How to start and stop Stream using AsyncHttpClient

I have implemented a Steaming API for twitter. I get the streams perfectly. However, My program never ends. I have tried many combinations but can't figure out why. I am suing Apache AsyncHttpClient in java. My goal is to start the stream for example for 10 seconds, get the streams, and gracefully close the stream and exit the application (I am expecting this to happen when my Main method ends naturally). This is the code below:
public static void main(String[] args) throws Exception
{
TwitterStreamingHttpClient client = new TwitterStreamingHttpClient();
Executor ex = Executors.newSingleThreadExecutor();
ex.execute(client);
Thread.sleep(5000);
client.ceaseStream();
LOG.debug("Keeps running");
}
and this:
public class TwitterStreamingHttpClient extends DefaultHttpAsyncClient implements Runnable
{
private final static Logger LOG = LoggerFactory.getLogger(TwitterStreamingHttpClient.class);
/**
* #throws IOReactorException
*/
public TwitterStreamingHttpClient() throws IOReactorException
{
super();
// TODO: parametrize it, load from config file, spring config file?
this.getCredentialsProvider().setCredentials(new AuthScope("stream.twitter.com", 80),
new UsernamePasswordCredentials("username", "password"));
this.start();
}
public void initiateStream() throws UnsupportedEncodingException, InterruptedException, ExecutionException
{
String requestContent = new String();
requestContent = "track=NothingFeelsBetterThan";
Future future = this.execute(HttpAsyncMethods.createPost(
"https://stream.twitter.com/1.1/statuses/filter.json", requestContent,
ContentType.APPLICATION_FORM_URLENCODED), new TwitConsumer(), null);
Boolean result = future.get();
if(result==null)
{
LOG.error("Requested to close stream!");
return;
}
}
public void ceaseStream()
{
try
{
this.shutdown();
LOG.info("Shutting down the stream");
}
catch (InterruptedException e)
{
LOG.debug("InterruptedException {}", e);
}
}
/*
* (non-Javadoc)
*
* #see java.lang.Runnable#run()
*/
public void run()
{
Thread.currentThread().setName("initiateSTream Thread");
try
{
initiateStream();
Thread.currentThread().interrupt();
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (ExecutionException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I tried to add a return whereever I though it mightbe helpful. but no luck. Can someone help me with this?
Edit 1: When I use the debug mode, I can see that the "initiateSTream Thread" thread. is still running while the main thread is gone!
Edit 2 (Solution): In the main method, I replaced:
Executor ex = Executors.newSingleThreadExecutor();
ex.execute(client);
with:
Thread thread = new Thread(client);
thread.start();
Now my programs ends after the designated time of streaming. But why? What is the difference between the two approaches?!

Databinding in AXIS2

I have created a web service for the following method using AXIS 1.4
public class SoapTest {
public String test(String param) {
System.out.println("soap activity check "+param);
return param+" return from soap";
}
}
I am calling it using AXIS2 Wsdl2java utility. The client i am using is:
public static void main(String argv[]) {
try {
SoapTestServiceStub obj = new SoapTestServiceStub();
SoapTestServiceStub.Test obj2 = new SoapTestServiceStub.Test();
obj2.setParam("hello");
try {
SoapTestServiceStub.TestResponse res = obj.test(obj2);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
catch (AxisFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
On running the client SOP is working fine but then Getting the following error:
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement testReturn
at org.apache.axis2.AxisFault.makeFault

Categories

Resources