//
// @author JbigData.fr (from the 2.2.2 release)
//
package fr.jbigdata.gedsrv.converter.services;
import java.io.IOException;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.document.DocumentFormat;
import org.artofsolving.jodconverter.document.DocumentFormatRegistry;
import fr.jbigdata.gedsrv.converter.WebappContext;
/**
* This servlet offers a document converter service suitable for remote
* invocation by HTTP clients written in any language.
* <p>
* To be valid a request to service must:
* <ul>
* <li>use the POST method and send the input document data as the request body</li>
* <li>specify the correct <b>Content-Type</b> of the input document</li>
* <li>specify an <b>Accept</b> header with the mime-type of the desired output</li>
* </ul>
* <p>
* <pre>
* POST /.../service HTTP/1.1
* Host: x.y.z
* Content-Type: text/plain
* Accept: application/pdf
* </pre>
*/
public class ConverterSS extends HttpServlet
{
private static final long serialVersionUID = -6698481065322400366L;
private final Logger logger = Logger.getLogger(getClass().getName());
/**
*
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
WebappContext webappContext = WebappContext.get(getServletContext());
OfficeDocumentConverter converter = webappContext.getDocumentConverter();
DocumentFormatRegistry registry = converter.getFormatRegistry();
String inputMimeType = request.getContentType();
if (inputMimeType == null)
{
throw new IllegalArgumentException("Content-Type not set in request");
}
DocumentFormat inputFormat = registry.getFormatByMediaType(inputMimeType);
if (inputFormat == null)
{
throw new IllegalArgumentException("Unsupported input mime-type: " + inputMimeType);
}
String outputMimeType = request.getHeader("Accept");
if (outputMimeType == null)
{
throw new IllegalArgumentException("Accept header not set in request");
}
DocumentFormat outputFormat = registry.getFormatByMediaType(outputMimeType);
if (outputFormat == null)
{
throw new IllegalArgumentException("Unsupported output mime-type: " + outputMimeType);
}
response.setContentType(outputFormat.getMediaType());
// response.setContentLength(???); - should cache result in a buffer first
try
{
long startTime = System.currentTimeMillis();
converter.convert(request.getInputStream(), inputFormat, response.getOutputStream(), outputFormat);
long conversionTime = System.currentTimeMillis() - startTime;
logger.info(String.format("Successful conversion: [%s] -> [%s] in [%d]ms", inputFormat, outputFormat, conversionTime));
}
catch (Exception exception)
{
throw new ServletException("Conversion failed", exception);
}
}
}