1

I'm trying to build a simple Webscript Endpoint in Alfresco that gets a pdf using a Java Webscript controller. We eventually want to expand this endpoint to take multiple pdfs and do some manipulation, but for right now we are just trying to read in and save 1 pdf.

The problem is the resulting InputStream is empty. This is despite it working just fine for xml files.

This is our uploadpdf.get.desc

<webscript>
    <shortname>Upload PDFs</shortname>
    <description>Upload PDFs</description>
    <url>/uploadpdf</url>
    <authentication>user</authentication>
    <format default="html"></format>  
</webscript>

This is our uploadpdf.get.html.ftl

<html>
  <body>
    <form action="${url.service}" method="post" enctype="multipart/form-data">
      PDF1: <input type="file" name="pdf1"><br>
      XML1: <input type="file" name="xml1"><br>
      <input type="submit" name="submit" value="Upload">
    </form>
  </body>
</html>

This is our uploadpdf.post.dec

<webscript>
    <shortname>Upload PDFs</shortname>
    <description>Upload PDFs</description>
    <url>/uploadpdf</url>
    <authentication>user</authentication>
    <format default="json"></format>  
</webscript>

This is our uploadpdf.post.json.ftl (currently just returning a test string)

${newFile}

This is our Webscript-context.xml

<?xml version='1.0' encoding='UTF-8'?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at
    
    http://www.apache.org/licenses/LICENSE-2.0
    
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="webscript.alfresco.tutorials.helloworld.get"
          class="com.test.platformsample.HelloWorldWebScript"
          parent="webscript">
    </bean>
    <bean id="webscript.uploadpdf.get"
          class="com.test.UploadPdfWebScript"
          parent="webscript">
    </bean>
    <bean id="webscript.uploadpdf.post"
          class="com.test.UploadPdfWebScript"
          parent="webscript">
    </bean>
</beans>

And this is our UploadPdfWebscript.java (notice for testing purposes we are using org.springframework.extensions.webscripts.servlet.FormData; This is to easily get the file. The code then saves the file to the local docker container. The problem is that file and by extention the InputStream is empty.

package com.test;

import org.springframework.extensions.webscripts.Cache;
import org.springframework.extensions.webscripts.DeclarativeWebScript;
import org.springframework.extensions.webscripts.Status;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.servlet.FormData;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import java.io.File;
import java.io.OutputStream;
import java.io.FileOutputStream;

public class UploadPdfWebScript extends DeclarativeWebScript {
    private static Log logger = LogFactory.getLog(UploadPdfWebScript.class);

    protected Map<String, Object> executeImpl(
            WebScriptRequest req, Status status, Cache cache) {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("fromJava", "HelloFromJava");

        logger.debug("Your 'UploadPdf' Web Script was called!");

        final FormData form = (FormData)req.parseContent();

        InputStream file1 = null;

        if(form == null || form.getFields() == null) {
           return model;
        }

        for (FormData.FormField field : form.getFields())
        {
            if (field.getName().equals("pdf1"))
            {
                file1 = field.getInputStream();
            }

        }

        String result = "this should be overwritten";
        try{
            
            result = processFile(file1);
        } catch(Exception e) {
            logger.error(e.getMessage());
        }

        if(result == null || result.equals("")) {
           result = "No result";
        }
        
        model.put("newFile", result);
        return model;

       }

 public String processFile(InputStream file) {
        String ret = "{\”Result\": Success}”;
        try {
        byte[] buffer = new byte[file.available()];
            file.read(buffer);
     
            File targetFile = new File("targetFile.pdf");
            OutputStream outStream = new FileOutputStream(targetFile);  
            outStream.write(buffer2);
        } catch (Exception e) {
        ret = "{\”Result\": Failure}”;
            logger.error(e.getMessage(), e);
        }
        return ret;
}

How can I get a pdf or other arbitrary file type from the InputStream? Again the InputStream that is returned from the form is empty whenever I try to upload a pdf and as a result so is the saved pdf.

Note: If I try to read the pdf from the local file system rather than sending it via a post request, this works fine. The pdf I'm uploading is definitely valid and not empty. I also know the webscript is being properly called as it is posting a log message, returning Success, and creating the targetFile.pdf which is empty.

Alex Parker
  • 125
  • 1
  • 11

1 Answers1

2

Change this line:

outStream.write(buffer2);

To:

outStream.write(buffer);

Here's what shows up in the tomcat dir on my Docker container:

-rw-r----- 1 root root     117249 Aug  7 19:28 targetFile.pdf

Looks like it works!

Jeff Potts
  • 10,468
  • 17
  • 40