/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.web.loader;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jersey.multipart.BodyPartEntity;
import com.sun.jersey.multipart.FormDataBodyPart;
import com.sun.jersey.multipart.FormDataMultiPart;

/**
 * REST resource that uploads a CSV file containing a portfolio definition and passes it to a portfolio loader.
 * TODO currently it doesn't do anything except read the file and send back some made-up data to the client
 */
@Path("portfolioupload")
public class PortfolioLoaderResource {

  private static final Logger s_logger = LoggerFactory.getLogger(PortfolioLoaderResource.class);

  @Path("{updatePeriod}/{updateCount}")
  @POST
  @Consumes(MediaType.MULTIPART_FORM_DATA)
  public void uploadPortfolio(FormDataMultiPart formData,
                              // TODO according to the docs this should work but jersey won't start with them uncommented
                              //@FormDataParam("file") FormDataBodyPart fileBodyPart,
                              //@FormDataParam("dataField") String dataField,
                              @PathParam("updatePeriod") long updatePeriod,
                              @PathParam("updateCount") int updateCount,
                              @Context HttpServletResponse response) throws IOException {
    FormDataBodyPart fileBodyPart = formData.getField("file");
    if (fileBodyPart == null) {
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    FormDataBodyPart dataFieldBodyPart = formData.getField("dataField");
    if (dataFieldBodyPart == null) {
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    String dataField = dataFieldBodyPart.getValue();
    Object fileEntity = fileBodyPart.getEntity();
    if (!(fileEntity instanceof BodyPartEntity)) {
      response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
      return;
    }
    InputStream fileStream = ((BodyPartEntity) fileEntity).getInputStream();
    String fileContent = IOUtils.toString(fileStream);
    s_logger.warn("Portfolio uploaded. dataField: {}, portfolio: {}", dataField, fileContent);
    ServletOutputStream outputStream = response.getOutputStream();
    for (int i = 0; i < updateCount; i++) {
      try {
        Thread.sleep(updatePeriod);
      } catch (InterruptedException e) {
        s_logger.warn("This shouldn't happen");
      }
      outputStream.write("uploading portfolio...\n".getBytes());
      outputStream.flush();
    }
    response.setStatus(HttpServletResponse.SC_OK);
  }
}

@@ -222,17 +222,16 @@
 Stream;%0A
-%0A
 import j
@@ -237,85 +237,26 @@
 java
-x.servlet.ServletOutputStream;%0Aimport javax.servlet.http.HttpServletResponse;
+.io.OutputStream;%0A
 %0Aimp
@@ -384,20 +384,31 @@
 .rs.
-core.Context
+WebApplicationException
 ;%0Aim
@@ -439,16 +439,91 @@
 diaType;
+%0Aimport javax.ws.rs.core.Response;%0Aimport javax.ws.rs.core.StreamingOutput;
 %0A%0Aimport
@@ -1257,12 +1257,23 @@
 lic 
-void
+StreamingOutput
  upl
@@ -1313,16 +1313,27 @@
 rmData,%0A
+           
         
@@ -1446,16 +1446,27 @@
 mmented%0A
+           
         
@@ -1565,32 +1565,43 @@
                 
+           
 //@FormDataParam
@@ -1654,32 +1654,43 @@
                 
+        
+   
 @PathParam(%22upda
@@ -1699,16 +1699,22 @@
 Period%22)
+ final
  long up
@@ -1747,32 +1747,43 @@
                 
+          
+ 
 @PathParam(%22upda
@@ -1791,16 +1791,22 @@
 eCount%22)
+ final
  int upd
@@ -1817,77 +1817,8 @@
 ount
-,%0A                              @Context HttpServletResponse response
 ) th
@@ -1941,38 +1941,42 @@
     
-response.setStatus(HttpServlet
+throw new WebApplicationException(
 Resp
@@ -1973,34 +1973,38 @@
 ption(Response.S
-C_
+tatus.
 BAD_REQUEST);%0A  
@@ -1997,38 +1997,24 @@
 D_REQUEST);%0A
-      return;%0A
     %7D%0A    Fo
@@ -2127,38 +2127,42 @@
     
-response.setStatus(HttpServlet
+throw new WebApplicationException(
 Resp
@@ -2159,34 +2159,38 @@
 ption(Response.S
-C_
+tatus.
 BAD_REQUEST);%0A  
@@ -2183,38 +2183,24 @@
 D_REQUEST);%0A
-      return;%0A
     %7D%0A    St
@@ -2357,38 +2357,42 @@
     
-response.setStatus(HttpServlet
+throw new WebApplicationException(
 Resp
@@ -2397,18 +2397,22 @@
 sponse.S
-C_
+tatus.
 BAD_REQU
@@ -2421,22 +2421,8 @@
 T);%0A
-      return;%0A
     
@@ -2658,71 +2658,150 @@
     
-ServletOutputStream outputStream = response.getOutputStream();%0A
+return new StreamingOutput() %7B%0A      @Override%0A      public void write(OutputStream output) throws IOException, WebApplicationException %7B%0A    
     
@@ -2846,16 +2846,20 @@
 %7B%0A      
+    
 try %7B%0A  
@@ -2864,16 +2864,20 @@
         
+   
+ 
 Thread.s
@@ -2896,16 +2896,20 @@
 eriod);%0A
+    
       %7D 
@@ -2945,24 +2945,28 @@
 ) %7B%0A        
+  
+  
 s_logger.war
@@ -2995,26 +2995,34 @@
 en%22);%0A      
-%7D%0A
+    %7D%0A    
       output
@@ -3021,22 +3021,16 @@
   output
-Stream
 .write(%22
@@ -3055,10 +3055,8 @@
 o...
-%5Cn
 %22.ge
@@ -3066,16 +3066,20 @@
 tes());%0A
+    
       ou
@@ -3082,22 +3082,16 @@
   output
-Stream
 .flush()
@@ -3100,59 +3100,27 @@
     
+ 
+   
 %7D%0A    
-response.setStatus(HttpServletResponse.SC_OK)
+  %7D%0A    %7D
 ;%0A  

Refactor PortfolioLoaderResource