]> git.aero2k.de Git - tmp/jakarta-migration.git/commitdiff
CSPACE-5564: Adding a test for invoking a report with an invokation context and getti...
authorRichard Millet <remillet@berkeley.edu>
Wed, 23 Jan 2013 18:52:29 +0000 (10:52 -0800)
committerRichard Millet <remillet@berkeley.edu>
Wed, 23 Jan 2013 18:52:29 +0000 (10:52 -0800)
1  2 
services/blob/service/src/main/java/org/collectionspace/services/blob/BlobResource.java
services/common/src/main/java/org/collectionspace/services/common/imaging/nuxeo/NuxeoBlobUtils.java
services/report/client/src/main/java/org/collectionspace/services/client/ReportClient.java
services/report/client/src/main/java/org/collectionspace/services/client/ReportProxy.java
services/report/client/src/test/java/org/collectionspace/services/client/test/ReportServiceTest.java
services/report/service/src/main/java/org/collectionspace/services/report/ReportResource.java
services/report/service/src/main/java/org/collectionspace/services/report/nuxeo/ReportDocumentModelHandler.java

index 091b3a6f4ad6c34dc4e86443d8c9cc126f71bcd5,125d1589d11cdea47b7ef85856ca73385e4e41a0..7f2fdf48be9b8324060a0e1185a8f178f17e7873
@@@ -236,14 -254,46 +254,46 @@@ public class BlobResource extends Resou
      @Path("{csid}/content")
      public Response getBlobContent(   @PathParam("csid") String csid) {
        Response result = null;
-       StringBuffer mimeType = new StringBuffer();
-       InputStream contentStream = getBlobContent(csid, null /*derivative term*/, mimeType /*will get set*/);
-           Response.ResponseBuilder responseBuilder = Response.ok(contentStream, mimeType.toString());
-           
-       result = responseBuilder.build();
+       ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
+       
+       try {
+               ctx = createServiceContext();
+               
+               StringBuffer mimeType = new StringBuffer();
+               InputStream contentStream = getBlobContent(ctx, csid, null /*derivative term*/, mimeType /*will get set*/);
+                   
+               Response.ResponseBuilder responseBuilder = Response.ok(contentStream, mimeType.toString());
+               result = responseBuilder.build();
+       } catch (Exception e) {
+               throw bigReThrow(e, ServiceMessages.CREATE_FAILED);
+       }
+       
        return result;
      }
 -              result = ArticleUtil.publishToRepository(resourceMap, uriInfo, this.getRepositoryClient(ctx), ctx, contentStream, csid);
+     
+     /*
+      * Publish the blob content.
+      */
+     @GET
+     @Path("{csid}/content/publish")
+     public Response publishBlobContent(
+               @Context ResourceMap resourceMap,
+               @Context UriInfo uriInfo,
+               @PathParam("csid") String csid) {
+       Response result = null;
+       ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = null;
+       
+       try {
+                       ctx = createServiceContext();
+               StringBuffer mimeType = new StringBuffer();
+               InputStream contentStream = getBlobContent(ctx, csid, null /*derivative term*/, mimeType /*will get set*/);             
++              result = ArticleUtil.publishToRepository(resourceMap, uriInfo, getRepositoryClient(ctx), ctx, contentStream, csid);
+       } catch (Exception e) {
+               throw bigReThrow(e, ServiceMessages.PUT_FAILED);
+       }
+       
+       return result;
+     }    
  
      @GET
      @Path("{csid}/derivatives/{derivativeTerm}/content")
index 59490726b28928604ea85807d9050c714f25eab2,db2976f136ba9ff8ae049d22778c52f634eed2b3..4b4951e42064b380f1312f35015c5ee747e869d4
   */
  package org.collectionspace.services.client;
  
++import javax.ws.rs.PathParam;
++import javax.ws.rs.core.Response;
++
++import org.collectionspace.services.common.invocable.InvocationContext;
  import org.collectionspace.services.jaxb.AbstractCommonList;
  import org.jboss.resteasy.client.ClientResponse;
  
@@@ -73,4 -69,4 +77,9 @@@ public class ReportClient extends Abstr
          return getProxy().readListFiltered(docType, mode);
      }
      
++    public ClientResponse<Response> publishReport(String csid,
++              InvocationContext invContext) {
++      return getProxy().publishReport(csid, invContext);
++    }
++    
  }
index f983b0a181d492249b95d6dee2741d5b24650114,f983b0a181d492249b95d6dee2741d5b24650114..8dc0a5886f6a40d08322d05d8bcebb936769e25e
@@@ -28,10 -28,10 +28,14 @@@ package org.collectionspace.services.cl
  
  import javax.ws.rs.Consumes;
  import javax.ws.rs.GET;
++import javax.ws.rs.POST;
  import javax.ws.rs.Path;
++import javax.ws.rs.PathParam;
  import javax.ws.rs.Produces;
  import javax.ws.rs.QueryParam;
++import javax.ws.rs.core.Response;
  
++import org.collectionspace.services.common.invocable.InvocationContext;
  import org.collectionspace.services.jaxb.AbstractCommonList;
  import org.jboss.resteasy.client.ClientResponse;
  
@@@ -50,4 -50,4 +54,9 @@@ public interface ReportProxy extends Co
                @QueryParam(IQueryManager.SEARCH_TYPE_DOCTYPE) String docType,
                @QueryParam(IQueryManager.SEARCH_TYPE_INVOCATION_MODE) String mode);
      
++    @POST
++    @Path("{csid}/publish")
++    ClientResponse<Response> publishReport(@PathParam("csid") String csid,
++              InvocationContext invContext);
++    
  }
index f6c28ed7e6d76c08a1de9a039a5c59a265c1d4bf,f6c28ed7e6d76c08a1de9a039a5c59a265c1d4bf..6b69486a56c92685c84edb58db44f37db139e6df
@@@ -25,11 -25,11 +25,14 @@@ package org.collectionspace.services.cl
  import java.util.ArrayList;
  import java.util.List;
  
++import javax.ws.rs.core.Response;
++
  import org.collectionspace.services.client.AbstractCommonListUtils;
  import org.collectionspace.services.client.CollectionSpaceClient;
  import org.collectionspace.services.client.PayloadOutputPart;
  import org.collectionspace.services.client.PoxPayloadOut;
  import org.collectionspace.services.client.ReportClient;
++import org.collectionspace.services.common.invocable.InvocationContext;
  import org.collectionspace.services.report.ReportsCommon;
  import org.collectionspace.services.jaxb.AbstractCommonList;
  
@@@ -59,6 -59,6 +62,42 @@@ public class ReportServiceTest extends 
      // Instance variables specific to this test.    
      private String testDocType = "Acquisition";
  
++    @Test(dataProvider = "testName", dependsOnMethods = {"create"})    
++    public void publishReportInstance(String testName) throws Exception {
++        // Perform setup.
++        setupCreate();
++
++        // Submit the request to the service and store the response.
++        ReportClient client = (ReportClient)this.getClientInstance();
++        
++        createReportInstance()
++      
++      //
++      // Hard coded for now, but need to create this test in the Integration test area where
++      // we'll create an Acquisition instance for this test
++      //
++      InvocationContext invocationContext = new InvocationContext();
++      invocationContext.setDocType("Acquisition");
++      invocationContext.setMode("single");
++      invocationContext.setSingleCSID("34abdc63-944c-421d-a585");
++      
++      String reportCsid = "8680d49c-99b8-4788-aa45";
++        ClientResponse<Response> res = client.publishReport(reportCsid, invocationContext);
++        int statusCode = res.getStatus();
++
++        // Check the status code of the response: does it match
++        // the expected response(s)?
++        if (logger.isDebugEnabled()) {
++            logger.debug(testName + ": status = " + statusCode);
++        }
++        Assert.assertTrue(testRequestType.isValidStatusCode(statusCode),
++                invalidStatusCodeMessage(testRequestType, statusCode));
++        Assert.assertEquals(statusCode, testExpectedStatusCode);
++
++        String articleCsid = extractId(res);
++        Assert.assertNotNull(articleCsid);
++    }
++    
      /* (non-Javadoc)
       * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance()
       */
index 8685ff54f3000f8cc0383ad05c668cc1a5e450f4,8685ff54f3000f8cc0383ad05c668cc1a5e450f4..ab3d425e02864b4a4c46ee3842e18dabe1dff77b
@@@ -23,6 -23,6 +23,8 @@@
   */
  package org.collectionspace.services.report;
  
++import java.io.InputStream;
++
  import org.collectionspace.services.jaxb.AbstractCommonList;
  import org.collectionspace.services.report.nuxeo.ReportDocumentModelHandler;
  import org.collectionspace.services.client.IQueryManager;
@@@ -30,7 -30,7 +32,9 @@@ import org.collectionspace.services.cli
  import org.collectionspace.services.client.PoxPayloadOut;
  import org.collectionspace.services.client.ReportClient;
  import org.collectionspace.services.common.ResourceBase;
++import org.collectionspace.services.common.ResourceMap;
  import org.collectionspace.services.common.ServiceMessages;
++import org.collectionspace.services.common.article.ArticleUtil;
  import org.collectionspace.services.common.context.ServiceContext;
  import org.collectionspace.services.common.document.DocumentFilter;
  import org.collectionspace.services.common.document.DocumentHandler;
@@@ -52,6 -52,6 +56,7 @@@ import javax.ws.rs.core.Context
  import javax.ws.rs.core.MultivaluedMap;
  import javax.ws.rs.core.Response;
  import javax.ws.rs.core.UriInfo;
++import javax.ws.rs.core.Response.ResponseBuilder;
  
  @Path(ReportClient.SERVICE_PATH)
  @Consumes("application/xml")
@@@ -145,13 -145,13 +150,71 @@@ public class ReportResource extends Res
        return invokeReport(ui, csid, invContext);
      }
      
++    /*
++     * Publishes the report to the Articles service.  The response is a URI to the corresponding Article resource instance in
++     * the form of /articles/{csid}.
++     * To access the contents of the report use a form like /articles/published/{csid}?tid={tenant ID}.  For example,
++     * http://localhost:8180/cspace-services/articles/published/2991da78-6001-4f34-b02c?tid=1
++     */
++    @POST
++    @Path("{csid}/publish")
++    public Response invokeReportAndPublish(
++              @Context ResourceMap resourceMap,               
++              @Context UriInfo uriInfo,
++              @PathParam("csid") String csid,
++              InvocationContext invContext) {
++      Response response = null;
++      
++        try {
++            StringBuffer outMimeType = new StringBuffer();
++            StringBuffer outReportFileName = new StringBuffer();
++            ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
++            InputStream reportInputStream = invokeReport(ctx, csid, invContext, outMimeType, outReportFileName);            
++            response = ArticleUtil.publishToRepository(resourceMap, uriInfo, getRepositoryClient(ctx), ctx, 
++                      reportInputStream, outReportFileName.toString());
++        } catch (Exception e) {
++            throw bigReThrow(e, ServiceMessages.POST_FAILED);
++        }
++        
++        return response;
++    }
++    
      @POST
      @Path("{csid}")
--    @Produces("application/pdf")
      public Response invokeReport(
                @Context UriInfo ui,
                @PathParam("csid") String csid,
                InvocationContext invContext) {
++      Response response = null;
++      
++        try {
++            StringBuffer outMimeType = new StringBuffer();
++            StringBuffer outFileName = new StringBuffer();
++            ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
++            InputStream reportInputStream = invokeReport(ctx, csid, invContext, outMimeType, outFileName);
++            
++                      // Need to set response type for what is requested...
++                      ResponseBuilder builder = Response.ok(reportInputStream, outMimeType.toString());
++                      builder = builder.header("Content-Disposition","inline;filename=\""+ outFileName.toString() +"\"");
++              response = builder.build();                                    
++        } catch (Exception e) {
++            throw bigReThrow(e, ServiceMessages.POST_FAILED);
++        }
++        
++        return response;
++    }
++    
++    /*
++     * Does the actual report generation and returns an InputStream with the results.
++     */
++    private InputStream invokeReport(
++              ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
++              String csid,
++              InvocationContext invContext,
++              StringBuffer outMimeType,
++              StringBuffer outReportFileName) throws Exception {
++      InputStream result = null;
++      
          if (csid == null || "".equals(csid)) {
              logger.error("invokeReport: missing csid!");
              Response response = Response.status(Response.Status.BAD_REQUEST).entity(
                      "text/plain").build();
              throw new WebApplicationException(response);
          }
++        
          if (logger.isTraceEnabled()) {
              logger.trace("invokeReport with csid=" + csid);
          }
--        try {
--            ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
--            ReportDocumentModelHandler handler = (ReportDocumentModelHandler)createDocumentHandler(ctx);
--            
--            return handler.invokeReport(ctx, csid, invContext);
--        } catch (Exception e) {
--            throw bigReThrow(e, ServiceMessages.POST_FAILED);
--        }
++      
++        ReportDocumentModelHandler handler = (ReportDocumentModelHandler)createDocumentHandler(ctx);
++        result = handler.invokeReport(ctx, csid, invContext, outMimeType, outReportFileName);
++        
++        return result;
      }
      
--
--
  }
index 426014e4637fc61b78cfeaba05b66987e5f88959,b1db3f8e09759135c414394ebd0cba9cfffa4aab..d3628e85b9f0bff99ccf5ae46cccf58d9815a66d
   */
  package org.collectionspace.services.report.nuxeo;
  
++import java.io.ByteArrayInputStream;
 +import java.io.ByteArrayOutputStream;
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
++import java.io.InputStream;
  import java.sql.Connection;
  import java.sql.SQLException;
  import java.util.HashMap;
  import java.util.List;
- import javax.ws.rs.core.Response.ResponseBuilder;
 +import java.util.Map;
 +
 +import javax.ws.rs.core.MediaType;
  
  import javax.naming.NamingException;
  import javax.ws.rs.WebApplicationException;
@@@ -94,10 -79,11 +95,12 @@@ public class ReportDocumentModelHandle
      private static String REPORTS_STD_CSIDLIST_PARAM = "csidlist";
      private static String REPORTS_STD_TENANTID_PARAM = "tenantid";
        
--      public Response invokeReport(
++      public InputStream invokeReport(
                        ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
                        String csid,
-                       InvocationContext invContext) throws Exception {
+                       InvocationContext invContext,
 -                      boolean isPublishing) throws Exception {
++                      StringBuffer outMimeType,
++                      StringBuffer outReportFileName) throws Exception {
                RepositoryInstance repoSession = null;
                boolean releaseRepoSession = false;
  
                        releaseRepoSession = true;
                }
  
--              String reportFileName = null;
                // Get properties from the batch docModel, and release the session
++              String reportFileNameProperty;
                try {
                        DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, csid);
                        DocumentModel docModel = wrapper.getWrappedObject();
                                                +invContext.getDocType());
                        }
                }
--                      reportFileName = (String)docModel.getPropertyValue(ReportJAXBSchema.FILENAME);
++              reportFileNameProperty = ((String)docModel.getPropertyValue(ReportJAXBSchema.FILENAME)); // Set the outgoing param with the report file name
 +                      String reportOutputMime = (String)docModel.getPropertyValue(ReportJAXBSchema.OUTPUT_MIME);
 +                      if(!Tools.isEmpty(reportOutputMime)) {
-                               outputMimeType = reportOutputMime;
++                              outMimeType.append(reportOutputMime);
++                      } else {
++                              outMimeType.append(ReportClient.DEFAULT_REPORT_OUTPUT_MIME);
 +                      }
                } catch (PropertyException pe) {
                        if (logger.isDebugEnabled()) {
                                logger.debug("Property exception getting batch values: ", pe);
                                repoClient.releaseRepositorySession(ctx, repoSession);
                        }
                }
-               return buildReportResponse(csid, params, reportFileName, outputMimeType);
 -              return buildReportResponse(csid, params, reportFileName, isPublishing);
++              
++              return buildReportResult(csid, params, reportFileNameProperty, outMimeType.toString(), outReportFileName);
 +      }
 +      
 +      private void setParamsFromContext(Map<String, Object> params, InvocationContext invContext) {
 +              InvocationContext.Params icParams = invContext.getParams();
 +              if(icParams!= null) {
 +                      List<InvocationContext.Params.Param> icParamList = icParams.getParam();
 +                      if(icParamList != null) {
 +                              for(InvocationContext.Params.Param param:icParamList) {
 +                                      String key = param.getKey();
 +                                      String value = param.getValue();
 +                                      if(!Tools.isEmpty(key) && !Tools.isEmpty(value)) {
 +                                              params.put(key, value);
 +                                      }
 +                              }
 +                      }
 +              }
 +              
        }
  
--
-     private Response buildReportResponse(String reportCSID, 
-               HashMap<String, Object> params, String reportFileName, String outputMimeType)
 -    private Response buildReportResponse(String reportCSID, HashMap<String, Object> params, String reportFileName, boolean isPublishing)
++    private InputStream buildReportResult(String reportCSID, 
++              HashMap<String, Object> params, String reportFileName, String outputMimeType, StringBuffer outReportFileName)
                                throws Exception {
                Connection conn = null;
--              Response response = null;
++              InputStream result = null;
++              
        try {
                        String fullPath = ServiceMain.getInstance().getServerRootDir() +
                                                                File.separator + ConfigReader.CSPACE_DIR_NAME + 
              }
                        FileInputStream fileStream = new FileInputStream(fullPath);
        
 -              // fill the report
 -                      JasperPrint jasperprint = JasperFillManager.fillReport(fileStream, params,conn);
                        // export report to pdf and build a response with the bytes
 -                      byte[] pdfasbytes = JasperExportManager.exportReportToPdf(jasperprint);
 +                      //JasperExportManager.exportReportToPdf(jasperprint);
                        
 -                      if (isPublishing == tru) {
 -                              
 -                      } else {
 -                      // Need to set response type for what is requested...
 -                              response = Response.ok(pdfasbytes, "application/pdf").build();
 +                      // Report will be to a byte output array.
 +                      ByteArrayOutputStream baos = new ByteArrayOutputStream();
 +
 +                      JRExporter exporter = null;
 +                      // Strip extension from report filename.
 +                      String outputFilename = reportFileName;
 +                      // Strip extension from report filename.
 +                      int idx = outputFilename.lastIndexOf("."); 
 +                      if(idx>0)
 +                              outputFilename = outputFilename.substring(0, idx);
 +                      // Strip any sub-dir from report filename.
 +                      idx = outputFilename.lastIndexOf(File.separator); 
 +                      if(idx>0)
 +                              outputFilename = outputFilename.substring(idx+1);
 +                      if(outputMimeType.equals(MediaType.APPLICATION_XML)) {
 +                              params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
 +                              exporter = new JRXmlExporter();
 +                              outputFilename = outputFilename+".xml";
 +                      } else if(outputMimeType.equals(MediaType.TEXT_HTML)) {
 +                              exporter = new JRHtmlExporter();
 +                              outputFilename = outputFilename+".html";
 +                      } else if(outputMimeType.equals(ReportClient.PDF_MIME_TYPE)) {
 +                              exporter = new JRPdfExporter();
 +                              outputFilename = outputFilename+".pdf";
 +                      } else if(outputMimeType.equals(ReportClient.CSV_MIME_TYPE)) {
 +                              params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
 +                              exporter = new JRCsvExporter();
 +                              exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, ",");
 +                              outputFilename = outputFilename+".csv";
 +                      } else if(outputMimeType.equals(ReportClient.TSV_MIME_TYPE)) {
 +                              params.put(JRParameter.IS_IGNORE_PAGINATION, Boolean.TRUE);
 +                              exporter = new JRCsvExporter();
 +                              exporter.setParameter(JRCsvExporterParameter.FIELD_DELIMITER, "\t");
 +                              outputFilename = outputFilename+".csv";
                        }
-                       byte[] reportAsBytes = baos.toByteArray();
-                       // Need to set response type for what is requested...
-                       ResponseBuilder builder = Response.ok(reportAsBytes, outputMimeType);
-                       builder = builder.header("Content-Disposition","inline;filename=\""+outputFilename+"\"");
-               response = builder.build();
++                      outReportFileName.append(outputFilename); // Set the out going param to the report's final file name
 +              // fill the report
 +                      JasperPrint jasperPrint = JasperFillManager.fillReport(fileStream, params,conn);
 +                              
 +                      exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
 +                      exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, baos);
 +                      exporter.exportReport();
++                      result = new ByteArrayInputStream(baos.toByteArray());
        
--              return response;        
++              return result;
          } catch (SQLException sqle) {
              // SQLExceptions can be chained. We have at least one exception, so
              // set up a loop to make sure we let the user know about all of them
                        tempException = tempException.getNextException();
                    }
              }
--            response = Response.status(
++            Response response = Response.status(
                      Response.Status.INTERNAL_SERVER_ERROR).entity(
                                "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
              throw new WebApplicationException(response);
              if (logger.isDebugEnabled()) {
                logger.debug("JR Exception: " + jre.getLocalizedMessage() + " Cause: "+jre.getCause());
              }
--            response = Response.status(
++            Response response = Response.status(
                      Response.Status.INTERNAL_SERVER_ERROR).entity(
                                "Invoke failed (Jasper problem) on Report csid=" + reportCSID).type("text/plain").build();
              throw new WebApplicationException(response);
              if (logger.isDebugEnabled()) {
                logger.debug("FileNotFoundException: " + fnfe.getLocalizedMessage());
              }
--            response = Response.status(
++            Response response = Response.status(
                      Response.Status.INTERNAL_SERVER_ERROR).entity(
                                "Invoke failed (SQL problem) on Report csid=" + reportCSID).type("text/plain").build();
              throw new WebApplicationException(response);