use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.
the class NodesImpl method writeContent.
private void writeContent(NodeRef nodeRef, String fileName, InputStream stream, boolean guessEncoding) {
try {
ContentWriter writer = contentService.getWriter(nodeRef, ContentModel.PROP_CONTENT, true);
String mimeType = mimetypeService.guessMimetype(fileName);
if ((mimeType != null) && (!mimeType.equals(MimetypeMap.MIMETYPE_BINARY))) {
// quick/weak guess based on file extension
writer.setMimetype(mimeType);
} else {
// stronger guess based on file stream
writer.guessMimetype(fileName);
}
InputStream is = null;
if (guessEncoding) {
is = new BufferedInputStream(stream);
is.mark(1024);
writer.setEncoding(guessEncoding(is, mimeType, false));
try {
is.reset();
} catch (IOException ioe) {
if (logger.isWarnEnabled()) {
logger.warn("Failed to reset stream after trying to guess encoding: " + ioe.getMessage());
}
}
} else {
is = stream;
}
writer.putContent(is);
} catch (ContentQuotaException cqe) {
throw new InsufficientStorageException();
} catch (ContentLimitViolationException clv) {
throw new RequestEntityTooLargeException(clv.getMessage());
} catch (ContentIOException cioe) {
if (cioe.getCause() instanceof NodeLockedException) {
throw (NodeLockedException) cioe.getCause();
}
throw cioe;
}
}
use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.
the class MoveMethod method copyContentOnly.
private void copyContentOnly(FileInfo sourceFileInfo, FileInfo destFileInfo, FileFolderService fileFolderService) throws WebDAVServerException {
ContentService contentService = getContentService();
ContentReader reader = contentService.getReader(sourceFileInfo.getNodeRef(), ContentModel.PROP_CONTENT);
if (reader == null) {
// There is no content for the node if it is a folder
if (!sourceFileInfo.isFolder()) {
// Non-folders should have content available.
logger.error("Unable to get ContentReader for source node " + sourceFileInfo.getNodeRef());
throw new WebDAVServerException(HttpServletResponse.SC_NOT_FOUND);
}
} else {
ContentWriter contentWriter = contentService.getWriter(destFileInfo.getNodeRef(), ContentModel.PROP_CONTENT, true);
contentWriter.putContent(reader);
}
}
use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.
the class NodeContentGet method execute.
/**
* @param req WebScriptRequest
* @param res WebScriptResponse
* @throws IOException
*/
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
ContentReader textReader = null;
Exception transformException = null;
String nodeIDString = req.getParameter("nodeId");
if (nodeIDString == null) {
throw new WebScriptException("nodeID parameter is required for GetNodeContent");
}
long nodeId = Long.valueOf(nodeIDString).longValue();
String propertyQName = req.getParameter("propertyQName");
QName propertyName = null;
if (propertyQName == null) {
propertyName = ContentModel.PROP_CONTENT;
} else {
propertyName = QName.createQName(propertyQName);
}
Pair<Long, NodeRef> pair = nodeDAO.getNodePair(nodeId);
if (pair == null) {
// If the node does not exists we treat it as if it has no content
// We could be trying to update the content of a node in the index that has been deleted.
res.setStatus(HttpStatus.SC_NO_CONTENT);
return;
}
NodeRef nodeRef = pair.getSecond();
// check If-Modified-Since header and set Last-Modified header as appropriate
Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
// May be null - if so treat as just changed
if (modified == null) {
modified = new Date();
}
long modifiedSince = -1;
String modifiedSinceStr = req.getHeader("If-Modified-Since");
if (modifiedSinceStr != null) {
try {
modifiedSince = dateFormat.parse(modifiedSinceStr).getTime();
} catch (Throwable e) {
if (logger.isWarnEnabled()) {
logger.warn("Browser sent badly-formatted If-Modified-Since header: " + modifiedSinceStr);
}
}
if (modifiedSince > 0L) {
// round the date to the ignore millisecond value which is not supplied by header
long modDate = (modified.getTime() / 1000L) * 1000L;
if (modDate <= modifiedSince) {
res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
}
ContentReader reader = contentService.getReader(nodeRef, propertyName);
if (reader == null) {
res.setStatus(HttpStatus.SC_NO_CONTENT);
return;
}
try {
// get the transformer
TransformationOptions options = new TransformationOptions();
options.setUse("index");
options.setSourceNodeRef(nodeRef);
transformerDebug.pushAvailable(reader.getContentUrl(), reader.getMimetype(), MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
long sourceSize = reader.getSize();
List<ContentTransformer> transformers = contentService.getActiveTransformers(reader.getMimetype(), sourceSize, MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
transformerDebug.availableTransformers(transformers, sourceSize, options, "SolrIndexer");
if (transformers.isEmpty()) {
res.setHeader(TRANSFORM_STATUS_HEADER, "noTransform");
res.setStatus(HttpStatus.SC_NO_CONTENT);
return;
}
ContentTransformer transformer = transformers.get(0);
// Perform transformation catering for mimetype AND encoding
ContentWriter writer = contentService.getTempWriter();
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
// Expect transformers to produce UTF-8
writer.setEncoding("UTF-8");
try {
long start = System.currentTimeMillis();
transformer.transform(reader, writer, options);
long transformDuration = System.currentTimeMillis() - start;
res.setHeader(TRANSFORM_DURATION_HEADER, String.valueOf(transformDuration));
} catch (ContentIOException | UnsupportedTransformationException e) {
transformException = e;
}
if (transformException == null) {
// point the reader to the new-written content
textReader = writer.getReader();
// Check that the reader is a view onto something concrete
if (textReader == null || !textReader.exists()) {
transformException = new ContentIOException("The transformation did not write any content, yet: \n" + " transformer: " + transformer + "\n" + " temp writer: " + writer);
}
}
if (transformException != null) {
res.setHeader(TRANSFORM_STATUS_HEADER, "transformFailed");
res.setHeader(TRANSFORM_EXCEPTION_HEADER, transformException.getMessage());
res.setStatus(HttpStatus.SC_NO_CONTENT);
} else {
res.setStatus(HttpStatus.SC_OK);
streamContentImpl(req, res, textReader, null, null, false, modified, String.valueOf(modified.getTime()), null, null);
}
} finally {
transformerDebug.popAvailable();
}
}
use of org.alfresco.service.cmr.repository.ContentWriter in project alfresco-remote-api by Alfresco.
the class CommentsPost method addComment.
/**
* add the comment from json to given nodeRef
*
* @param nodeRef
* @param json
* @return
*/
private NodeRef addComment(NodeRef nodeRef, JSONObject json) {
// fetch the parent to add the node to
NodeRef commentsFolder = getOrCreateCommentsFolder(nodeRef);
// get a unique name
String name = getUniqueChildName("comment");
// create the comment
NodeRef commentNodeRef = nodeService.createNode(commentsFolder, ContentModel.ASSOC_CONTAINS, QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, QName.createValidLocalName(name)), ForumModel.TYPE_POST).getChildRef();
// fetch the title required to create a comment
String title = getOrNull(json, JSON_KEY_TITLE);
HashMap<QName, Serializable> props = new HashMap<QName, Serializable>(1, 1.0f);
props.put(ContentModel.PROP_TITLE, title != null ? title : "");
nodeService.addProperties(commentNodeRef, props);
ContentWriter writer = contentService.getWriter(commentNodeRef, ContentModel.PROP_CONTENT, true);
// fetch the content of a comment
String contentString = getOrNull(json, JSON_KEY_CONTENT);
writer.setMimetype(MimetypeMap.MIMETYPE_HTML);
writer.putContent(contentString);
return commentNodeRef;
}
use of org.alfresco.service.cmr.repository.ContentWriter 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);
}
Aggregations