use of org.alfresco.service.cmr.repository.ContentReader in project alfresco-remote-api by Alfresco.
the class GetMethod method executeImpl.
/**
* Exceute the WebDAV request
*
* @exception WebDAVServerException
*/
protected void executeImpl() throws WebDAVServerException, Exception {
FileFolderService fileFolderService = getFileFolderService();
NodeRef rootNodeRef = getRootNodeRef();
String path = getPath();
if (!m_returnContent) {
// There are multiple cases where no content is sent (due to a HEAD request).
// All of them require that the content length is set appropriately.
m_response.setContentLength(0);
}
FileInfo nodeInfo = null;
try {
nodeInfo = getDAVHelper().getNodeForPath(rootNodeRef, path);
} catch (FileNotFoundException e) {
throw new WebDAVServerException(HttpServletResponse.SC_NOT_FOUND);
}
FileInfo realNodeInfo = nodeInfo;
// This is at least consistent with the way the CIFS server handles links. See org.alfresco.filesys.repo.ContentDiskDriver.openFile().
if (realNodeInfo.isLink()) {
Path pathToNode = getNodeService().getPath(nodeInfo.getLinkNodeRef());
if (pathToNode.size() > 2) {
pathToNode = pathToNode.subPath(2, pathToNode.size() - 1);
}
String rootURL = getDAVHelper().getURLForPath(m_request, pathToNode.toDisplayPath(getNodeService(), getPermissionService()), true);
if (rootURL.endsWith(WebDAVHelper.PathSeperator) == false) {
rootURL = rootURL + WebDAVHelper.PathSeperator;
}
String fname = (String) getNodeService().getProperty(nodeInfo.getLinkNodeRef(), ContentModel.PROP_NAME);
StringBuilder urlStr = new StringBuilder(200);
urlStr.append("[InternetShortcut]\r\n");
urlStr.append("URL=file://");
urlStr.append(m_request.getServerName());
// Only append the port if it is non-default for compatibility with XP
int port = m_request.getServerPort();
if (port != 80) {
urlStr.append(":").append(port);
}
urlStr.append(rootURL).append(WebDAVHelper.encodeURL(fname, m_userAgent));
urlStr.append("\r\n");
m_response.setHeader(WebDAV.HEADER_CONTENT_TYPE, "text/plain; charset=ISO-8859-1");
m_response.setHeader(WebDAV.HEADER_CONTENT_LENGTH, String.valueOf(urlStr.length()));
m_response.getWriter().write(urlStr.toString());
} else // Check if the node is a folder
if (realNodeInfo.isFolder()) {
// is content required
if (!m_returnContent) {
// ALF-7883 fix, HEAD for collection (see http://www.webdav.org/specs/rfc2518.html#rfc.section.8.4)
return;
}
// Generate a folder listing
m_response.setContentType("text/html;charset=UTF-8");
generateDirectoryListing(nodeInfo);
} else {
// Return the node details, and content if requested, check that the node passes the pre-conditions
checkPreConditions(realNodeInfo);
// Build the response header
m_response.setHeader(WebDAV.HEADER_ETAG, getDAVHelper().makeQuotedETag(nodeInfo));
Date modifiedDate = realNodeInfo.getModifiedDate();
if (modifiedDate != null) {
long modDate = DefaultTypeConverter.INSTANCE.longValue(modifiedDate);
m_response.setHeader(WebDAV.HEADER_LAST_MODIFIED, WebDAV.formatHeaderDate(modDate));
}
m_response.setHeader("Content-Disposition", getContentDispositionHeader(nodeInfo));
ContentReader reader = fileFolderService.getReader(realNodeInfo.getNodeRef());
// ensure that we generate something, even if the content is missing
reader = FileContentReader.getSafeContentReader((ContentReader) reader, I18NUtil.getMessage(FileContentReader.MSG_MISSING_CONTENT), realNodeInfo.getNodeRef(), reader);
readContent(realNodeInfo, reader);
}
}
use of org.alfresco.service.cmr.repository.ContentReader 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.ContentReader 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.ContentReader 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.service.cmr.repository.ContentReader in project acs-community-packaging by Alfresco.
the class EditUserDetailsDialog method getPersonDescription.
public String getPersonDescription() {
if (personDescription == null) {
ContentService cs = Repository.getServiceRegistry(FacesContext.getCurrentInstance()).getContentService();
ContentReader reader = cs.getReader(this.person.getNodeRef(), ContentModel.PROP_PERSONDESC);
if (reader != null && reader.exists()) {
personDescription = reader.getContentString();
}
}
return personDescription;
}
Aggregations