/** * Streams content back to client from a given resource path. * * @param req The request * @param res The response * @param resourcePath The classpath resource path the content is required for. * @param attach Indicates whether the content should be streamed as an attachment or not * @param attachFileName Optional file name to use when attach is <code>true</code> * @throws IOException */ protected void streamContent( WebScriptRequest req, WebScriptResponse res, String resourcePath, boolean attach, String attachFileName, Map<String, Object> model) throws IOException { if (logger.isDebugEnabled()) logger.debug( "Retrieving content from resource path " + resourcePath + " (attach: " + attach + ")"); // get extension of resource String ext = ""; int extIndex = resourcePath.lastIndexOf('.'); if (extIndex != -1) { ext = resourcePath.substring(extIndex); } // We need to retrieve the modification date/time from the resource itself. StringBuilder sb = new StringBuilder("classpath:").append(resourcePath); final String classpathResource = sb.toString(); long resourceLastModified = resourceLoader.getResource(classpathResource).lastModified(); // create temporary file File file = TempFileProvider.createTempFile("streamContent-", ext); InputStream is = resourceLoader.getResource(classpathResource).getInputStream(); OutputStream os = new FileOutputStream(file); FileCopyUtils.copy(is, os); // stream the contents of the file, but using the modifiedDate of the original resource. streamContent(req, res, file, resourceLastModified, attach, attachFileName, model); }
/** * Returns a writer to a thread-unique file. It's always the same file per thread so you must * use and close the writer before getting another. */ @Override protected ContentWriter getWriterInternal( ContentReader existingContentReader, String newContentUrl) { File file = hammeredFile.get(); if (file == null) { file = TempFileProvider.createTempFile("NullContentStore", ".txt"); hammeredFile.set(file); } return new FileContentWriter(file); }
private TFile getFile(String extension, String location) { File file = TempFileProvider.createTempFile("moduleManagementToolTest-", extension); InputStream is = this.getClass().getClassLoader().getResourceAsStream(location); assertNotNull(is); OutputStream os; try { os = new FileOutputStream(file); FileCopyUtils.copy(is, os); } catch (IOException error) { error.printStackTrace(); } return new TFile(file); }
@Override protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) { // Check we got a valid Multi-Part Form Upload FormData form = (FormData) req.parseContent(); if (form == null || !form.getIsMultiPart()) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Bad Upload"); } // Look for a file, we're quite flexible! File spreadsheet = null; for (FormData.FormField field : form.getFields()) { if (field.getIsFile()) { String ext = ".xls"; if (field.getFilename() != null && field.getFilename().endsWith(".xlsx")) { ext = ".xlsx"; } try { spreadsheet = TempFileProvider.createTempFile("spreadsheet", ext); FileOutputStream sout = new FileOutputStream(spreadsheet); IOUtils.copy(field.getInputStream(), sout); sout.close(); } catch (IOException e) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Upload Failed"); } break; } } // Process String[] sheetnames = null; if (spreadsheet != null) { try { sheetnames = excerpter.getSheetNames(spreadsheet); } catch (IOException e) { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Spreadsheet Corrupt", e); } } else { throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Spreadsheet Missing"); } // Report Map<String, Object> model = new HashMap<String, Object>(); model.put("file", spreadsheet.getName()); model.put("sheets", sheetnames); return model; }
private File convertPdfToPdfA(final InputStream source) throws IOException, DocumentException { final File pdfAFile = TempFileProvider.createTempFile("digitalSigning-" + System.currentTimeMillis(), ".pdf"); // Reads a PDF document. PdfReader reader = new PdfReader(source); // PdfStamper: Applies extra content to the pages of a PDF document. This extra content can be // all the objects allowed in // PdfContentByte including pages from other Pdfs. PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(pdfAFile)); // A generic Document class. Document document = new Document(); // we create a writer that listens to the document PdfWriter writer = stamper.getWriter(); int numberPages = reader.getNumberOfPages(); writer.setPDFXConformance(PdfWriter.PDFA1A); document.open(); // PdfDictionary:A dictionary is an associative table containing pairs of objects. // The first element of each pair is called the key and the second element is called the value // <CODE>PdfName</CODE> is an object that can be used as a name in a PDF-file PdfDictionary outi = new PdfDictionary(PdfName.OUTPUTINTENT); outi.put(PdfName.OUTPUTCONDITIONIDENTIFIER, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.INFO, new PdfString("sRGB IEC61966-2.1")); outi.put(PdfName.S, PdfName.GTS_PDFA1); writer.getExtraCatalog().put(PdfName.OUTPUTINTENTS, new PdfArray(outi)); // Add pages PdfImportedPage p = null; Image image; for (int i = 0; i < numberPages; i++) { p = writer.getImportedPage(reader, i + 1); image = Image.getInstance(p); document.add(image); } writer.createXmpMetadata(); document.close(); // Add Metadata from source pdf HashMap<String, String> info = reader.getInfo(); stamper.setMoreInfo(info); stamper.close(); return pdfAFile; }
public static File copy(InputStream inputStream) { ParameterCheck.mandatory("inputStream", inputStream); File tempFile = TempFileProvider.createTempFile("acav_tempfile_", ".tmp"); OutputStream outputStream = null; try { outputStream = new FileOutputStream(tempFile); IOUtils.copy(inputStream, outputStream); return tempFile; } catch (Exception ex) { tempFile.delete(); throw new AlfrescoRuntimeException(ex.getMessage(), ex); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } }
private File tempfile() { File file = TempFileProvider.createTempFile("cached-content", ".bin"); file.deleteOnExit(); return file; }
/** * @see * org.alfresco.repo.content.transform.AbstractContentTransformer2#transformInternal(org.alfresco.service.cmr.repository.ContentReader, * org.alfresco.service.cmr.repository.ContentWriter, * org.alfresco.service.cmr.repository.TransformationOptions) */ @Override public void transformInternal( ContentReader reader, ContentWriter writer, TransformationOptions options) throws Exception { final String outputMimetype = writer.getMimetype(); final String outputFileExt = getMimetypeService().getExtension(outputMimetype); // We need to keep a reference to thrown exceptions as we're going to catch them and // then move on to the next transformer. In the event that they all fail, we will throw // the final exception. Exception transformationException = null; for (int i = 0; i < transformers.size(); i++) { int oneBasedCount = i + 1; ContentTransformer transf = transformers.get(i); ContentWriter currentWriter = null; File tempFile = null; try { if (logger.isDebugEnabled()) { logger.debug( "Transformation attempt " + oneBasedCount + " of " + transformers.size() + ": " + transf); } if (!transf.isTransformable( reader.getMimetype(), reader.getSize(), outputMimetype, options)) { throw new UnsupportedTransformationException( "Unsupported transformation: " + reader.getMimetype() + " to " + outputMimetype); } // We can't know in advance which transformer in the sequence will work - if any. // Therefore we can't write into the ContentWriter stream. // So make a temporary file writer with the current transformer name. tempFile = TempFileProvider.createTempFile( "FailoverTransformer_intermediate_" + transf.getClass().getSimpleName() + "_", "." + outputFileExt); currentWriter = new FileContentWriter(tempFile); currentWriter.setMimetype(outputMimetype); currentWriter.setEncoding(writer.getEncoding()); // attempt to transform transf.transform(reader, currentWriter, options); // TODO Could add a check for zero-length output and treat that as a failure // final long writtenSize = currentWriter.getSize(); } catch (Exception are) { if (transformationException == null) { transformationException = are; } if (logger.isDebugEnabled()) { logger.debug("Transformation " + oneBasedCount + " was unsuccessful."); if (i != transformers.size() - 1) { // We don't log the last exception as we're going to throw it. logger.debug("The below exception is provided for information purposes only.", are); } } // Set a new reader to refresh the input stream. reader = reader.getReader(); // and move to the next transformer continue; } // No need to close input or output streams // At this point the current transformation was successful i.e. it did not throw an exception. // Now we must copy the content from the temporary file into the ContentWriter stream. if (tempFile != null) { writer.putContent(tempFile); } if (logger.isInfoEnabled()) { logger.info("Transformation was successful"); } return; } // At this point we have tried all transformers in the sequence without apparent success. if (transformationException != null) { transformerDebug.debug(" No more transformations to failover to"); if (logger.isDebugEnabled()) { logger.debug( "All transformations were unsuccessful. Throwing first exception.", transformationException); } throw transformationException; } }