use of org.alfresco.repo.content.filestore.FileContentReader in project acs-community-packaging by Alfresco.
the class FileUploadBean method uploadFile.
/**
* Ajax method to upload file content. A multi-part form is required as the input.
*
* "return-page" = javascript to execute on return from the upload request
* "currentPath" = the cm:name based server path to upload the content into
* and the file item content.
*
* @throws Exception
*/
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void uploadFile() throws Exception {
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext externalContext = fc.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
upload.setHeaderEncoding("UTF-8");
List<FileItem> fileItems = upload.parseRequest(request);
FileUploadBean bean = new FileUploadBean();
String currentPath = null;
String filename = null;
String returnPage = null;
File file = null;
for (FileItem item : fileItems) {
if (item.isFormField() && item.getFieldName().equals("return-page")) {
returnPage = item.getString();
} else if (item.isFormField() && item.getFieldName().equals("currentPath")) {
currentPath = URLDecoder.decode(item.getString());
} else {
filename = FilenameUtils.getName(item.getName());
file = TempFileProvider.createTempFile("alfresco", ".upload");
item.write(file);
}
}
if (logger.isDebugEnabled())
logger.debug("Ajax file upload request: " + filename + " to path: " + currentPath + " return page: " + returnPage);
try {
if (file != null && currentPath != null && currentPath.length() != 0) {
NodeRef containerRef = pathToNodeRef(fc, currentPath);
if (containerRef != null) {
// Guess the mimetype
String mimetype = Repository.getMimeTypeForFileName(fc, filename);
// Now guess the encoding
String encoding = "UTF-8";
InputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file));
encoding = Repository.guessEncoding(fc, is, mimetype);
} catch (Throwable e) {
// Bad as it is, it's not terminal
logger.error("Failed to guess character encoding of file: " + file, e);
} finally {
if (is != null) {
try {
is.close();
} catch (Throwable e) {
}
}
}
// Try and extract metadata from the file
ContentReader cr = new FileContentReader(file);
cr.setMimetype(mimetype);
// create properties for content type
String author = null;
String title = null;
String description = null;
Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(5, 1.0f);
if (Repository.extractMetadata(fc, cr, contentProps)) {
author = (String) (contentProps.get(ContentModel.PROP_AUTHOR));
title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE));
description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION));
}
// default the title to the file name if not set
if (title == null) {
title = filename;
}
ServiceRegistry services = Repository.getServiceRegistry(fc);
FileInfo fileInfo = services.getFileFolderService().create(containerRef, filename, ContentModel.TYPE_CONTENT);
NodeRef fileNodeRef = fileInfo.getNodeRef();
// set the author aspect
if (author != null) {
Map<QName, Serializable> authorProps = new HashMap<QName, Serializable>(1, 1.0f);
authorProps.put(ContentModel.PROP_AUTHOR, author);
services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_AUTHOR, authorProps);
}
// apply the titled aspect - title and description
Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f);
titledProps.put(ContentModel.PROP_TITLE, title);
titledProps.put(ContentModel.PROP_DESCRIPTION, description);
services.getNodeService().addAspect(fileNodeRef, ContentModel.ASPECT_TITLED, titledProps);
// get a writer for the content and put the file
ContentWriter writer = services.getContentService().getWriter(fileNodeRef, ContentModel.PROP_CONTENT, true);
writer.setMimetype(mimetype);
writer.setEncoding(encoding);
writer.putContent(file);
}
}
} catch (Exception e) {
returnPage = returnPage.replace("${UPLOAD_ERROR}", e.getMessage());
} finally {
if (file != null) {
logger.debug("delete temporary file:" + file.getPath());
// Delete the temporary file
file.delete();
}
}
Document result = XMLUtil.newDocument();
Element htmlEl = result.createElement("html");
result.appendChild(htmlEl);
Element bodyEl = result.createElement("body");
htmlEl.appendChild(bodyEl);
Element scriptEl = result.createElement("script");
bodyEl.appendChild(scriptEl);
scriptEl.setAttribute("type", "text/javascript");
Node scriptText = result.createTextNode(returnPage);
scriptEl.appendChild(scriptText);
if (logger.isDebugEnabled()) {
logger.debug("File upload request complete.");
}
ResponseWriter out = fc.getResponseWriter();
XMLUtil.print(result, out);
}
use of org.alfresco.repo.content.filestore.FileContentReader in project records-management by Alfresco.
the class EagerContentStoreCleaner method cleanseContent.
/**
* Cleanse content
*
* @param contentUrl content url
* @param store content store
*/
private void cleanseContent(String contentUrl, ContentStore store) {
if (contentCleanser == null) {
logger.error("No content cleanser specified. Unable to cleanse: \n" + " URL: " + contentUrl + "\n" + " Source: " + store);
} else {
// First check if the content is present at all
ContentReader reader = store.getReader(contentUrl);
if (reader != null && reader.exists()) {
// Call to implementation's shred
if (logger.isDebugEnabled()) {
logger.debug("About to cleanse: \n" + " URL: " + contentUrl + "\n" + " Source: " + store);
}
try {
if (reader instanceof FileContentReader) {
// get file content
FileContentReader fileReader = (FileContentReader) reader;
File file = fileReader.getFile();
// cleanse content
contentCleanser.cleanse(file);
}
} catch (Exception e) {
logger.error("Content cleansing failed: \n" + " URL: " + contentUrl + "\n" + " Source: " + store + "\n" + " Reader: " + reader, e);
}
} else {
logger.error("Content no longer exists. Unable to cleanse: \n" + " URL: " + contentUrl + "\n" + " Source: " + store);
}
}
}
use of org.alfresco.repo.content.filestore.FileContentReader in project acs-community-packaging by Alfresco.
the class AddContentDialog method finishImpl.
// ------------------------------------------------------------------------------
// Dialog implementation
@Override
protected String finishImpl(FacesContext context, String outcome) throws Exception {
// Try and extract metadata from the file
ContentReader cr = new FileContentReader(this.file);
cr.setMimetype(this.mimeType);
cr.setEncoding(this.encoding);
// create properties for content type
Map<QName, Serializable> contentProps = new HashMap<QName, Serializable>(5, 1.0f);
if (Repository.extractMetadata(FacesContext.getCurrentInstance(), cr, contentProps)) {
this.author = (String) (contentProps.get(ContentModel.PROP_AUTHOR));
this.title = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_TITLE));
this.description = DefaultTypeConverter.INSTANCE.convert(String.class, contentProps.get(ContentModel.PROP_DESCRIPTION));
}
// default the title to the file name if not set
if (this.title == null) {
this.title = this.fileName;
}
// determine whether inline editing should be enabled by default.
// if the mime type of the added file is in the list of mime types
// configured in "Content Wizards" then enable inline editing
List<String> mimeTypes = getInlineEditableMimeTypes();
if (mimeTypes.contains(this.mimeType)) {
this.inlineEdit = true;
}
saveContent(this.file, null);
// return default outcome
return outcome;
}
use of org.alfresco.repo.content.filestore.FileContentReader in project acs-community-packaging by Alfresco.
the class Repository method getMimeTypeForFile.
/**
* Return the mimetype for the specified file, based on both the
* file name and the file's contents.
* <p>
* The file extension will be extracted from the filename and used
* along with the file contents to identify the mimetype.
*
* @param context FacesContext
* @param filename Non-null filename to process
* @param file The File object (used to read the contents)
*
* @return mimetype for the specified filename - falls back to 'application/octet-stream' if not found.
*/
public static String getMimeTypeForFile(FacesContext context, String filename, File file) {
String mimetype = MimetypeMap.MIMETYPE_BINARY;
MimetypeService mimetypeService = (MimetypeService) getServiceRegistry(context).getMimetypeService();
// Use the file contents if available
if (file != null) {
FileContentReader reader;
try {
reader = new FileContentReader(file);
mimetype = mimetypeService.guessMimetype(filename, reader);
return mimetype;
} catch (Throwable t) {
// Not terminal
logger.warn("Error identifying mimetype from file contents ", t);
}
}
// If the contents aren't available, go with the filename,
// falling back to the Binary Mimetype if needed
mimetype = mimetypeService.guessMimetype(filename);
return mimetype;
}
use of org.alfresco.repo.content.filestore.FileContentReader in project alfresco-remote-api by Alfresco.
the class ContentStreamer method streamContent.
/**
* Streams content back to client from a given File.
*
* @param req The request
* @param res The response
* @param file The file whose content is to be streamed.
* @param modifiedTime The modified datetime to use for the streamed content. If <tt>null</tt> the
* file's timestamp will be used.
* @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
*/
public void streamContent(WebScriptRequest req, WebScriptResponse res, File file, Long modifiedTime, boolean attach, String attachFileName, Map<String, Object> model) throws IOException {
if (logger.isDebugEnabled())
logger.debug("Retrieving content from file " + file.getAbsolutePath() + " (attach: " + attach + ")");
// determine mimetype from file extension
String filePath = file.getAbsolutePath();
String mimetype = MimetypeMap.MIMETYPE_BINARY;
int extIndex = filePath.lastIndexOf('.');
if (extIndex != -1) {
mimetype = mimetypeService.getMimetype(filePath.substring(extIndex + 1));
}
// setup file reader and stream
FileContentReader reader = new FileContentReader(file);
reader.setMimetype(mimetype);
reader.setEncoding("UTF-8");
long lastModified = modifiedTime == null ? file.lastModified() : modifiedTime;
Date lastModifiedDate = new Date(lastModified);
streamContentImpl(req, res, reader, null, null, attach, lastModifiedDate, String.valueOf(lastModifiedDate.getTime()), attachFileName, model);
}
Aggregations