Hi,
I'm currently devloping a REST API for our software and I need streaming
functionality.
I'm using CXF with Jetty and wiring with Spring.
I tried it with the attached code, but if I do a curl on the address ti
blocks until Message 5 and the prints all lines.
I expected it to print each line on its own with 1 second break.
Can anybody give me a hint what I am doing wrong?
Regards and thanks
Thorsten
/**
*
*/
package de.cinovo.crest.identity.rest;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import org.apache.cxf.jaxrs.ext.MessageContext;
import java.util.concurrent.Executors;
import de.cinovo.crest.identity.oauth.OAuthUtil;
@Path("/echo")
public class EchoService {
@GET
@Produces(MediaType.TEXT_PLAIN)
@Path("/stream")
public InputStream stream() {
try {
final PipedOutputStream src = new PipedOutputStream();
final PipedInputStream is = new PipedInputStream(src,
10);
Executors.newCachedThreadPool().execute(new Runnable() {
@Override
public void run() {
try {
int count = 0;
while (count < 5) {
try {
count++;
final String m
= "Message " + count + "\r\n";
System.out.println("Sending message: " + m);
src.write(m.getBytes("UTF-8"));
src.flush();
Thread.sleep(1000);
} catch (final
Exception e) {
e.printStackTrace();
}
}
src.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
});
System.out.println("Returning InputStream");
return is;
} catch (final Exception e) {
e.printStackTrace();
}
throw new WebApplicationException(Status.INTERNAL_SERVER_ERROR);
}
}