Sunday, April 24, 2011

Jersey streaming binary data

In the previous post I showed how you can post binary data to a jersey REST api. You can also use Jersey to serve files, although its better done by apache or nginx but sometimes you might want to serve thumbnails stored in a database out of a service and put varnish in front of the REST api to cache the thumbnails. This is just a demonstration of using jersey to serve binary data in streaming fashion.

public class DownaloadService extends SecureRestService {
 private static final AppLogger logger  = AppLogger.getLogger(DownaloadService.class);

 public StreamingOutput getThumbnail(
   @FormParam("securityKey") final String securityKey,
   @FormParam("guid") final String guid) throws JSONException {
  return new StreamingOutput() {
   public void write(OutputStream out) throws IOException {
    try {
     if (!isAuthorized(securityKey)) {
     } else {
      //Read thumbnail out of database and dovetail both streams(IOUtils.copy) to directly stream to the response without storing them in memory.
    } catch (Throwable t) {
     response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, t.getMessage());

To test this code you can again use Jersey client api and to verify against response status or data you can use the ClientResponse class as shown below

  Form form = new Form();
  form.add("securityKey", getSecureToken());
  form.add("guid", guid);

  ClientResponse response = webResource.path(
    "download-service").post(ClientResponse.class, form);
  Assert.assertNotEquals(HttpServletResponse.SC_NOT_AUTHORIZED, response.getStatus());

  ByteArrayOutputStream bos = new ByteArrayOutputStream();
  IOUtils.copy(response.getEntityInputStream(), bos);
  byte[] result = bos.toByteArray();
  Assert.assertArrayEquals(expected, result);

Jersey posting multipart data

This took me sometime to figure out mostly it was because I was only including jersey-multipart-1.6.jar but I was not including mimepull-1.3.jar.

So the intent is to upload a file using REST api and we need pass meta attributes in addition to uploading the file. Also the intent is to stream the file instead of first storing it on the local disk. Here is some sample code.

public class UploadService {
 protected HttpServletResponse response;
 protected HttpServletRequest request;

 public String uploadFile(@PathParam("fileName") final String fileName,
   @FormDataParam("workgroupId") String workgroupId,
   @FormDataParam("userId") final int userId,
   @FormDataParam("content") final InputStream content) throws JSONException {
  //.......Upload the file to S3 or netapp or any storage service

Now to test this service I used Jersey client api and it was easy to test this.

public class UploadServiceTest  extends JerseyTest {
 public UploadServiceTest() {
   super(new WebAppDescriptor.Builder(UploadService.class
    protected TestContainerFactory getTestContainerFactory() {
        return new GrizzlyWebTestContainerFactory();
 public void testUploadService() throws Exception {
  WebResource webResource = resource();

  FormDataMultiPart form = new FormDataMultiPart();
  form.field("fileName", "/Shared/marketing/scrap.txt");
  form.field("workgroupId", "XXX");
  form.field("userId", 1001);
  String content = "This is a binary content";

  FormDataBodyPart fdp = new FormDataBodyPart("content",
    new ByteArrayInputStream(content.getBytes()),

  String responseJson = webResource.path(
    .post(String.class, form);

Saturday, April 16, 2011

Logging to Graphite monitoring tool from java

We use Graphite as a tool for monitoring some stats and watch trends. A requirement is to monitor impact of new releases as build is deployed to app nodes to see if things like
1) Has the memcache usage increased.
2) Has the no of Java exceptions went up.
3) Is the app using more tomcat threads.
Here is a screenshot

We changed the installer to log a deploy event when a new build is deployed. I wrote a simple spring bean to log graphite events using java. Logging to graphite is easy, all you need to do is open a socket and send lines of events.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 
import java.util.HashMap;
import java.util.Map;

public class GraphiteLogger {
private static final Logger logger = LoggerFactory.getLogger(GraphiteLogger.class);
 private String graphiteHost;

 private int graphitePort;

 public String getGraphiteHost() {
  return graphiteHost;

 public void setGraphiteHost(String graphiteHost) {
  this.graphiteHost = graphiteHost;

 public int getGraphitePort() {
  return graphitePort;

 public void setGraphitePort(int graphitePort) {
  this.graphitePort = graphitePort;

 public void logToGraphite(String key, long value) {
  Map stats = new HashMap();
  stats.put(key, value);
 public void logToGraphite(Map stats) {
  if (stats.isEmpty()) {

  try {
   String nodeIdentifier =;
   logToGraphite(nodeIdentifier, stats);
  } catch (Throwable t) {
   logger.warn("Can't log to graphite", t);

 private void logToGraphite(String nodeIdentifier, Map stats) throws Exception {
  Long curTimeInSec = System.currentTimeMillis() / 1000;
  StringBuffer lines = new StringBuffer();
  for (Map.Entry entry : stats.entrySet()) {
   String key = nodeIdentifier + "." + entry.getKey();
   lines.append(key).append(" ").append(entry.getValue()).append(" ").append(curTimeInSec).append("\n"); //even the last line in graphite 

 private void logToGraphite(StringBuffer lines) throws Exception {
  String msg = lines.toString();"Writing [{}] to graphite", msg);
  Socket socket = new Socket(graphiteHost, graphitePort);
  try {
   Writer writer = new OutputStreamWriter(socket.getOutputStream());
  } finally {

 public static void main(String[]args) throws Exception {
  String host = args[0];
  int port = Integer.parseInt(args[1]);
  String nodeIdentifier ="tomcat.UI.planck_8080";
  Map stats = new HashMap();
  stats.put("memcache_calls", 900L);
  stats.put("num_threads", 50L);
  GraphiteLogger graphiteLogger = new GraphiteLogger();
  graphiteLogger.logToGraphite(nodeIdentifier, stats);