I try to make a second request in the HttpAsyncClient callback. But the second request is on wait state.
Example code:
package com.example.http;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.util.EntityUtils;
import java.util.concurrent.Future;
public class AsyncClientHttpExample {
public static void main(String[] args) {
CloseableHttpAsyncClient httpClient = HttpAsyncClients.createDefault();
httpClient.start();
final HttpGet request1 = new HttpGet("http://httpbin.org/ip");
httpClient.execute(request1, new FutureCallback<HttpResponse>() {
#Override
public void completed(HttpResponse result) {
try {
System.out.println(EntityUtils.toString(result.getEntity()));
final HttpGet anotherRequest = new HttpGet("http://httpbin.org/headers");
Future<HttpResponse> future1 = httpClient.execute(anotherRequest, null);
HttpResponse anotherResponse = future1.get(); //the code get hand up here.
System.out.println("response 1 " + anotherResponse);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
#Override
public void failed(Exception ex) {
System.out.println(ex);
}
#Override
public void cancelled() {
}
});
}
}
I don't quite understand why the second request got hand up in the anotherResponse. I thought the second request is waiting for some lock that has already captured by request 1. But I haven't figure that out.
Related
I am trying to receive an http request using non-blocking io, then make another http request to another server using non-blocking io, and return some response, here is the code for my servlet:
package learn;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.InvocationCallback;
import javax.ws.rs.core.Response;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
#WebServlet(urlPatterns = {"/async"}, asyncSupported = true)
public class AsyncProcessing extends HttpServlet {
private static final long serialVersionUID = -535924906221872329L;
public CompletableFuture<String> readRequestAsync(final HttpServletRequest req) {
final CompletableFuture<String> request = new CompletableFuture<>();
final StringBuilder httpRequestData = new StringBuilder();
try (ServletInputStream inputStream = req.getInputStream()){
inputStream.setReadListener(new ReadListener() {
final int BUFFER_SIZE = 4*1024;
final byte buffer[] = new byte[BUFFER_SIZE];
#Override
public void onError(Throwable t) {
request.completeExceptionally(t);
}
#Override
public void onDataAvailable() {
if(inputStream.isFinished()) return;
System.out.println("----------------------------------------");
System.out.println("onDataAvailable: " + Thread.currentThread().getName());
try {
while(inputStream.isReady()) {
int length = inputStream.read(buffer);
httpRequestData.append(new String(buffer, 0, length));
}
} catch (IOException ex) {
request.completeExceptionally(ex);
}
}
#Override
public void onAllDataRead() throws IOException {
try {
request.complete(httpRequestData.toString());
}
catch(Exception e) {
request.completeExceptionally(e);
}
}
});
} catch (IOException e) {
request.completeExceptionally(e);
}
return request;
}
private Client createAsyncHttpClient() {
ResteasyClientBuilder restEasyClientBuilder = (ResteasyClientBuilder)ClientBuilder.newBuilder();
return restEasyClientBuilder.useAsyncHttpEngine().connectTimeout(640, TimeUnit.SECONDS).build();
}
public CompletableFuture<Response> process(String httpRequest){
System.out.println("----------------------------------------");
System.out.println("process: " + Thread.currentThread());
CompletableFuture<Response> futureResponse = new CompletableFuture<>();
Client client = createAsyncHttpClient();
client.target("http://localhost:3000").request().async().get(new InvocationCallback<Response>() {
#Override
public void completed(Response response) {
System.out.println("----------------------------------------");
System.out.println("completed: " + Thread.currentThread());
futureResponse.complete(response);
}
#Override
public void failed(Throwable throwable) {
System.out.println(throwable);
futureResponse.completeExceptionally(throwable);
}
});
return futureResponse;
}
public CompletableFuture<Integer> outputResponseAsync(Response httpResponseData, HttpServletResponse resp){
System.out.println("----------------------------------------");
System.out.println("outputResponseAsync: " + Thread.currentThread().getName());
CompletableFuture<Integer> total = new CompletableFuture<>();
try (ServletOutputStream outputStream = resp.getOutputStream()){
outputStream.setWriteListener(new WriteListener() {
#Override
public void onWritePossible() throws IOException {
System.out.println("----------------------------------------");
System.out.println("onWritePossible: " + Thread.currentThread().getName());
outputStream.print(httpResponseData.getStatus());
total.complete(httpResponseData.getLength());
}
#Override
public void onError(Throwable t) {
System.out.println(t);
total.completeExceptionally(t);
}
});
} catch (IOException e) {
System.out.println(e);
total.completeExceptionally(e);
}
return total;
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("----------------------------------------");
System.out.println("doGet: " + Thread.currentThread().getName());
final AsyncContext asyncContext = req.startAsync();
readRequestAsync(req)
.thenCompose(this::process)
.thenCompose(httpResponseData -> outputResponseAsync(httpResponseData, resp))
.thenAccept(a -> asyncContext.complete());
}
}
The server at http://localhost:3000 is an http server written in node which just returns a response after 27 seconds, i would like to make a request to the node server and while this request is being processed i would want to make another http request to the servlet to see if the same thread is being used. Currently i'm trying to use payara 5.194 to do this but even if i set the two thread pools to have one thread the app server seems to create another threads. So, i would like to know from your knowledge if this servlet is really doing non-blocking io and not blocking at any time, also it would be amazing if i could do some experiment to ensure this. I think it's important to point out that the class ServletInputStream is a subclass of InputStream, so i really don't know if this is non-blocking io. Thank you.
I'm trying to write an Http Server using Apache Mina.
According to Mina's architecture, there should be 2 filters for this task, one for Http Request Passing and another for processing the request and generating the response. So using the Mina example codes, I came up with the following code, that has an acceptor, logging filter, Http filter, and a filter for processing request.
Initiation of the server runs correctly, but the request does not come to DummyHttpSever filter. I tried to debug, but could not find the issue. What is going wrong here?
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.api.AbstractIoFilter;
import org.apache.mina.api.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filterchain.ReadFilterChainController;
import org.apache.mina.http.DateUtil;
import org.apache.mina.http.HttpDecoderState;
import org.apache.mina.http.HttpServerDecoder;
import org.apache.mina.http.HttpServerEncoder;
import org.apache.mina.http.api.DefaultHttpResponse;
import org.apache.mina.http.api.HttpContentChunk;
import org.apache.mina.http.api.HttpEndOfContent;
import org.apache.mina.http.api.HttpMethod;
import org.apache.mina.http.api.HttpPdu;
import org.apache.mina.http.api.HttpRequest;
import org.apache.mina.http.api.HttpStatus;
import org.apache.mina.http.api.HttpVersion;
import org.apache.mina.transport.nio.NioTcpServer;
public class HttpTest {
public static void main(String[] args) throws Exception {
NioTcpServer httpServer = new NioTcpServer();
httpServer.setReuseAddress(true);
httpServer.setFilters(new ProtocolCodecFilter<HttpPdu, ByteBuffer, Void, HttpDecoderState>(new HttpServerEncoder(),
new HttpServerDecoder()), new LoggingFilter("DECODED"), new DummyHttpSever());
httpServer.getSessionConfig().setTcpNoDelay(true);
httpServer.bind(new InetSocketAddress(8080));
// run for 20 seconds
Thread.sleep(2000000000);
httpServer.unbind();
}
private static class DummyHttpSever extends AbstractIoFilter {
private HttpRequest incomingRequest;
private List<ByteBuffer> body;
#Override
public void messageReceived(IoSession session, Object message, ReadFilterChainController controller) {
if (message instanceof HttpRequest) {
System.out.println("This shit is working");
incomingRequest = (HttpRequest) message;
body = new ArrayList<ByteBuffer>();
// check if this request is going to be followed by and HTTP body or not
if (incomingRequest.getMethod() != HttpMethod.POST && incomingRequest.getMethod() != HttpMethod.PUT) {
sendResponse(session, incomingRequest);
} else {
}
} else if (message instanceof ByteBuffer) {
body.add((ByteBuffer) message);
} else if (message instanceof HttpEndOfContent) {
// we received all the post content, send the crap back
sendResponse(session, incomingRequest);
}
}
public void sendResponse(IoSession session, HttpRequest request) {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Server", "Apache MINA Dummy test server/0.0.");
headers.put("Date", DateUtil.getCurrentAsString());
headers.put("Connection", "Close");
String strContent = "Hello ! we reply to request !";
ByteBuffer content = ByteBuffer.wrap(strContent.getBytes());
// compute content len
headers.put("Content-Length", String.valueOf(content.remaining()));
session.write(new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SUCCESS_OK, headers));
session.write(new HttpContentChunk(content));
session.write(new HttpEndOfContent());
session.close(false);
}
}
}
Also, following are dependencies I am using.
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-core</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-http</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.mina</groupId>
<artifactId>mina-coap</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>LATEST</version>
</dependency>
This is a simple Http web server, which you can modify according to your need. This example is a modification to the example lightweight component of Apache Mina examples.
Main.java
import java.net.InetSocketAddress;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.asyncweb.common.codec.HttpCodecFactory;
import org.apache.asyncweb.examples.lightweight.HttpProtocolHandler;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
public class Main {
public static void main(String[] args) throws Exception {
SocketAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new HttpCodecFactory()));
acceptor.setReuseAddress(true);
acceptor.getSessionConfig().setReuseAddress(true);
acceptor.getSessionConfig().setReceiveBufferSize(1024);
acceptor.getSessionConfig().setSendBufferSize(1024);
acceptor.getSessionConfig().setTcpNoDelay(true);
acceptor.getSessionConfig().setSoLinger(-1);
acceptor.setBacklog(10240);
acceptor.setHandler(new HttpProtocolHandler());
acceptor.bind(new InetSocketAddress(9012));
}
}
HttpProtocalHandler.java
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.future.IoFutureListener;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.future.WriteFuture;
import org.apache.asyncweb.common.HttpRequest;
import org.apache.asyncweb.common.HttpResponseStatus;
import org.apache.asyncweb.common.MutableHttpResponse;
import org.apache.asyncweb.common.DefaultHttpResponse;
import org.apache.asyncweb.common.HttpHeaderConstants;
public class HttpProtocolHandler implements IoHandler {
private static final int CONTENT_PADDING = 0; // 101
private final Map<Integer, IoBuffer> buffers = new ConcurrentHashMap<Integer, IoBuffer>();
private final Timer timer;
public HttpProtocolHandler() {
timer = new Timer(true);
}
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
if (!(cause instanceof IOException)) {
cause.printStackTrace();
}
session.close();
}
public Dictionary extractParameters(Map hashParameters){
Dictionary parameters = new Hashtable();
Iterator it = hashParameters.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
parameters.put(pair.getKey(), ((ArrayList) pair.getValue()).get(0) );
// it.remove(); // avoids a ConcurrentModificationException
}
return parameters;
}
public void messageReceived(IoSession session, Object message)
throws Exception {
HttpRequest req = (HttpRequest) message;
String path = req.getRequestUri().getPath(); //path: /echo
String end_point = path;
Dictionary parameters = this.extractParameters(req.getParameters());
String response = "";
/* switch (end_point) {
case "/io":
response= new IOHandler().handleRequest(parameters);
break;
case "/cpu":
response= new CPUHandler().handleRequest(parameters);
break;
case "/db":
response= new DBHandler().handleRequest(parameters);
break;
case "/memory":
response= new MemoryHandler().handleRequest(parameters);
break;
default:
response = "No end point found";
} */
response = "No end point found";
MutableHttpResponse res;
// if (path.startsWith("/size/")) {
// doDataResponse(session, req);
// } else if (path.startsWith("/delay/")) {
// doAsynchronousDelayedResponse(session, req);
// } else if (path.startsWith("/adelay/")) {
// doAsynchronousDelayedResponse(session, req);
// } else {
res = new DefaultHttpResponse();
IoBuffer bb = IoBuffer.allocate(1024);
bb.setAutoExpand(true);
bb.putString(response.toString(), Charset.forName("UTF-8").newEncoder());
bb.flip();
res.setContent(bb);
// res.setHeader("Pragma", "no-cache");
// res.setHeader("Cache-Control", "no-cache");
res.setStatus(HttpResponseStatus.OK);
WriteFuture future = session.write(res);
if (!HttpHeaderConstants.VALUE_KEEP_ALIVE.equalsIgnoreCase(
res.getHeader( HttpHeaderConstants.KEY_CONNECTION))) {
future.addListener(IoFutureListener.CLOSE);
}
}
private void writeResponse(IoSession session, HttpRequest req,
MutableHttpResponse res) {
res.normalize(req);
WriteFuture future = session.write(res);
if (!HttpHeaderConstants.VALUE_KEEP_ALIVE.equalsIgnoreCase(
res.getHeader( HttpHeaderConstants.KEY_CONNECTION))) {
future.addListener(IoFutureListener.CLOSE);
}
}
private void doDataResponse(IoSession session, HttpRequest req) {
String path = req.getRequestUri().getPath();
int size = Integer.parseInt(path.substring(path.lastIndexOf('/') + 1))
+ CONTENT_PADDING;
MutableHttpResponse res = new DefaultHttpResponse();
res.setStatus(HttpResponseStatus.OK);
res.setHeader("ETag", "W/\"" + size + "-1164091960000\"");
res.setHeader("Last-Modified", "Tue, 31 Nov 2006 06:52:40 GMT");
IoBuffer buf = buffers.get(size);
if (buf == null) {
buf = IoBuffer.allocate(size);
buffers.put(size, buf);
}
res.setContent(buf.duplicate());
writeResponse(session, req, res);
}
private void doAsynchronousDelayedResponse(final IoSession session,
final HttpRequest req) {
String path = req.getRequestUri().getPath();
int delay = Integer.parseInt(path.substring(path.lastIndexOf('/') + 1));
final MutableHttpResponse res = new DefaultHttpResponse();
res.setStatus(HttpResponseStatus.OK);
res.setHeader("ETag", "W/\"0-1164091960000\"");
res.setHeader("Last-Modified", "Tue, 31 Nov 2006 06:52:40 GMT");
timer.schedule(new TimerTask() {
#Override
public void run() {
writeResponse(session, req, res);
}
}, delay);
}
public void messageSent(IoSession session, Object message) throws Exception {
}
public void sessionClosed(IoSession session) throws Exception {
}
public void sessionCreated(IoSession session) throws Exception {
}
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
session.close();
}
public void sessionOpened(IoSession session) throws Exception {
session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 30);
}
}
I am working on an Android app (min API 8) and I want to make an activity where there is a preloader GIF running while some tasks are executed in the background.
These tasks involve connection to a database and queries. So in some way, I want to achieve something that involves techniques like you would use to make a progress bar.
I know I can't make a connection in the main thread in Java so I made a class that does this in another thread. The connection works fine, but I can't make the whole behaviour work properly. More precisely, if I use thread.join()then the main thread is blocked (which is the opposite of what I want) and if I don't use it, the code of the main thread goes on and finishes before the background process has terminated.
Can someone help me with this please ?
This is the class I created to manage POST queries to an URL :
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.concurrent.atomic.AtomicReference;
public class Request
{
private URL m_url;
private StringBuilder m_parameters;
private HttpURLConnection m_connection;
public Request(String url)
{
try
{
m_url = new URL(url);
}
catch(MalformedURLException exception)
{
System.exit(1);
}
m_connection = null;
m_parameters = new StringBuilder();
}
public void put(String key, String value)
{
if(m_parameters.length() != 0)
m_parameters.append('&');
try
{
m_parameters.append(URLEncoder.encode(key, "UTF-8"));
m_parameters.append('=');
m_parameters.append(URLEncoder.encode(value, "UTF-8"));
}
catch(UnsupportedEncodingException exception)
{
System.exit(1);
}
}
private void sendRequest()
{
try
{
byte[] data = m_parameters.toString().getBytes("UTF-8");
m_connection = (HttpURLConnection) m_url.openConnection();
m_connection.setAllowUserInteraction(true);
m_connection.setRequestMethod("POST");
m_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
m_connection.setRequestProperty("Content-Length", String.valueOf(data.length));
m_connection.setDoOutput(true);
m_connection.getOutputStream().write(data);
}
catch(Exception exception)
{
System.exit(1);
}
}
private String getResponse()
{
String response = "";
try
{
if(m_connection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
Reader reader = new BufferedReader(new InputStreamReader(m_connection.getInputStream(), "UTF-8"));
int c;
do {
c = reader.read();
response += (char) c;
}
while (c >= 0);
}
}
catch(IOException exception)
{
System.exit(1);
}
m_connection.disconnect();
return response;
}
public String get()
{
final AtomicReference<String> response = new AtomicReference<>();
Thread thread = new Thread(new Runnable()
{
public void run()
{
sendRequest();
response.set(getResponse());
}
});
thread.start();
/*
try
{
thread.join();
}
catch(InterruptedException exception)
{
System.exit(1);
}
*/
return response.get();
}
}
And this is how I use it in the main thread (the activity) :
Request request = new Request("http://posttestserver.com/post.php?dump&html&sleep=5");
request.put("name", "bob");
String response = request.get();
Thanks.
Okay, I finally solved that problem using standard IntentServiceof Android :
https://developer.android.com/training/run-background-service/create-service.html
This tutorial helped a lot too :
http://code.tutsplus.com/tutorials/android-fundamentals-intentservice-basics--mobile-6183
Here is my new class Request:
import android.app.IntentService;
import android.content.Intent;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Set;
public class Request extends IntentService
{
private URL m_url;
private StringBuilder m_parameters;
private HttpURLConnection m_connection;
public Request()
{
super("Request");
m_url = null;
m_connection = null;
m_parameters = new StringBuilder();
}
public void put(String key, String value)
{
if(m_parameters.length() != 0)
m_parameters.append('&');
try
{
m_parameters.append(URLEncoder.encode(key, "UTF-8"));
m_parameters.append('=');
m_parameters.append(URLEncoder.encode(value, "UTF-8"));
}
catch(UnsupportedEncodingException exception)
{
System.exit(1);
}
}
private void sendRequest()
{
try
{
byte[] data = m_parameters.toString().getBytes("UTF-8");
m_connection = (HttpURLConnection) m_url.openConnection();
m_connection.setAllowUserInteraction(true);
m_connection.setRequestMethod("POST");
m_connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
m_connection.setRequestProperty("Content-Length", String.valueOf(data.length));
m_connection.setDoOutput(true);
m_connection.getOutputStream().write(data);
}
catch(Exception exception)
{
System.exit(1);
}
}
private String getResponse()
{
String response = "";
try
{
if(m_connection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
Reader reader = new BufferedReader(new InputStreamReader(m_connection.getInputStream(), "UTF-8"));
int c;
do {
c = reader.read();
response += (char) c;
}
while (c >= 0);
}
}
catch(IOException exception)
{
System.exit(1);
}
m_connection.disconnect();
return response;
}
protected void onHandleIntent(Intent intent)
{
Bundle bundle = intent.getExtras();
Set<String> keys = bundle.keySet();
for(String key : keys)
put(key, bundle.getString(key));
try
{
m_url = new URL(bundle.getString("url"));
}
catch(MalformedURLException exception)
{
System.exit(1);
}
sendRequest();
String response = getResponse();
Intent broadcast = new Intent();
broadcast.setAction(ReadyActivity.ResponseReceiver.m_broadcastKey);
broadcast.putExtra("response", response);
sendBroadcast(broadcast);
}
}
Here is the ResponseReceiversubclass of my main activity :
public class ResponseReceiver extends BroadcastReceiver
{
public static final String m_broadcastKey = "Uz258e3wZm77Z3Tdebn7PqgW3CLBJ8";
public void onReceive(Context context, Intent intent)
{
String response = intent.getStringExtra("response");
clear();
((TextView) m_widgets.get("text")).setText("Finally found someone !" + response);
show(m_widgets.get("text"));
((Button) m_widgets.get("button1")).setText("OK let's do this !");
show(m_widgets.get("button1"));
((Button) m_widgets.get("button2")).setText("Later ?");
show(m_widgets.get("button2"));
unregisterReceiver(m_receiver);
}
}
Then I also had to instantiate the ResponseReceiver in the activity:
private ResponseReceiver m_receiver;
...
IntentFilter filter = new IntentFilter(ResponseReceiver.m_broadcastKey);
m_receiver = new ResponseReceiver();
registerReceiver(m_receiver, filter);
And finally call the service :
Intent service = new Intent(this, Request.class);
ArrayList<CharSequence> parameters = new ArrayList<>();
service.putExtra("url", "http://posttestserver.com/post.php?dump&html&sleep=10");
service.putExtra("username", "bob");
service.putExtra("age", "20");
startService(service);
Maybe it will help someone in the future.
I am using httpcore libraries 4.3.2 to make a custom http server to communicate with some clients (android devices).
The clients manage to communicate (post an xml) with the server but the response of the server is very slow.
My code is based on the ElementalHttpServer of apache samples. Can i find somewhere else better samples for the httpcore libraries?
Also i can not find how to set the parameteres or to finetune the httpserver because the HttParams lib is deprecated.
If i use the com.sun.net.httpserver.HttpServer httpserver my clients are connecting without problem. It is better to stay with suns libs or to use apaches?
Thanks in advance.
This is the code i used:
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
import org.apache.http.ConnectionClosedException;
import org.apache.http.HttpConnectionFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpServerConnection;
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.DefaultBHttpServerConnection;
import org.apache.http.impl.DefaultBHttpServerConnectionFactory;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpProcessorBuilder;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpService;
import org.apache.http.protocol.ResponseConnControl;
import org.apache.http.protocol.ResponseContent;
import org.apache.http.protocol.ResponseDate;
import org.apache.http.protocol.ResponseServer;
import org.apache.http.protocol.UriHttpRequestHandlerMapper;
import org.apache.http.util.EntityUtils;
public class Thread_Main_httpcore2 implements Runnable {
public Thread_Main_httpcore2() {
}//Thread_Main()
#Override
public void run() {
int port = 20010;
// Set up the HTTP protocol processor
HttpProcessor httpproc = HttpProcessorBuilder.create()
.add(new ResponseDate())
.add(new ResponseServer("Test/1.1"))
.add(new ResponseContent())
.add(new ResponseConnControl()).build();
// Set up request handlers
UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
//// Set up the HTTP service
HttpService httpService = new HttpService(httpproc, reqistry);
reqistry.register("*", new Thread_Main_httpcore2.HttpReqHandler());
SSLServerSocketFactory sf = null;
try {
Thread t = new RequestListenerThread(port, httpService, sf);
t.setDaemon(false);
t.start();
} catch (Exception ex) {
ex.printStackTrace();
}
}
static class HttpReqHandler implements HttpRequestHandler {
public HttpReqHandler() {
super();
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String xml_stream="";
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent;
if (entity == null) {
entityContent = new byte[0];
} else {
entityContent = EntityUtils.toByteArray(entity);
}
//byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
xml_stream = new String(entityContent);
}
StringBuilder resp_xml = new StringBuilder();
resp_xml.append("Returns an xml to the client");
StringEntity entity;
try {
response.setStatusCode(HttpStatus.SC_OK);
entity = new StringEntity(resp_xml.toString(), ContentType.create("text/html", "UTF-8"));
response.setEntity(entity);
} catch (Exception ex_send_resp) {
System.out.println("HttpFileHandler.ex_send_resp "+ ex_send_resp.toString());
}
}
}
static class RequestListenerThread extends Thread {
private final HttpConnectionFactory<DefaultBHttpServerConnection> connFactory;
private final ServerSocket serversocket;
private final HttpService httpService;
public RequestListenerThread(
final int port,
final HttpService httpService,
final SSLServerSocketFactory sf) throws IOException {
this.connFactory = DefaultBHttpServerConnectionFactory.INSTANCE;
this.serversocket = sf != null ? sf.createServerSocket(port) : new ServerSocket(port);
this.httpService = httpService;
}
#Override
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
System.out.println("Incoming connection from " + socket.getInetAddress());
HttpServerConnection conn = this.connFactory.createConnection(socket);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
#Override
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {
}
}
}
}
}
Here is my code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.os.AsyncTask;
import android.util.Log;
public class JsonController
{
private JSONObject inputData, json, finalResult;
private String authentication;
public JsonController()
{
json = new JSONObject();
inputData = new JSONObject();
}
public void createAuthentication(String userName, String apiKey)
{
authentication = "";
}
public void setModel(String model) throws JSONException
{
json.put("model",model);
}
public void setData(String id, String deviceType) throws JSONException
{
inputData.put(id, deviceType);
}
public void getPrediction()
{
new sendJSon().execute("");
return finalResult.toString();
}
private class sendJSon extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(authentication);
httppost.setHeader("Content-type", "application/json; charset=utf-8");
try {
// Add your data
json.put("input_data", inputData);
StringEntity se = new StringEntity( json.toString());
httppost.setEntity(se);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String jsonString = reader.readLine();
JSONTokener tokener = new JSONTokener(jsonString);
finalResult = new JSONObject(tokener);
}
catch(Exception e)
{
Log.d("Error here", "Error is here",e);
}
return null;
}
}
}
This code always crashes in getPrediction() because of NulPointerException. NullPointerException is because the Async task take time to generate the String, and the getPrediction() method returns the string before it is ready. All of these methods get called via external classes, so how can I solve this?
you can check whether ASYNCTASK has finished execution or not until then you can halt the returning of string from method getPrediction();
if(CLASSOBJECT!= null && CLASSOBJECT.getStatus() == Status.RUNNING) {
//DO NOT RETURN ANY VALUE
}else{
//RETURN VALUE
}
Try to return the String in your doInBackground method as :
return jsonString;
As you have pointed
outNullPointerException is because the Async task take time to generate the
String, and the getPrediction() method returns the string before it is ready.
You should run your network based operation in thread in doInBackground and then join that thread. Then you should call getPrediction() in onPostExecute(). Thus you'll have the data before the method is called.
Use onPostExecute() instead. onPostExecute() receives the return value from doInBackground() after it finishes. From there you can do whatever needs to be done with your result.
If onPostExecute() isn't flexible enough for you, consider using a CountDownLatch to stall your main code execution until AsyncTask returns.
Here is an sample code which you can implement
public interface AsyncResponseHandler {
public String resultCall(String resultStr);
}
public class MyMainClass extends Activity implements AsyncResponseHandler{
public void doProcessing(){
new AsynTasker(this).execute(null); //here this is instance of AsyncResponseHandler
}
#Override
public String resultCall(String resultStr) {
//here you will receive results from your async task after execution and you can carry out whatever process you want to do.
}
}
public class AsynTasker extends AsyncTask<String,Void,String>{
AsyncResponseHandler handler=null;
public AsynTasker(AsyncResponseHandler handler){
this.handler = handler
}
#Override
protected String doInBackground(String... params) {
// do your processing
return resultString;
}
#Override
protected void onPostExecute(String result) {
this.handler.resultCall(result);
}
}