use of org.alfresco.service.cmr.model.FileExistsException in project alfresco-remote-api by Alfresco.
the class PutMethod method executeImpl.
/**
* Execute the WebDAV request
*
* @exception WebDAVServerException
*/
protected void executeImpl() throws WebDAVServerException, Exception {
if (logger.isDebugEnabled()) {
String path = getPath();
String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
logger.debug("Put node: \n" + " user: " + userName + "\n" + " path: " + path + "\n" + "noContent: " + noContent);
}
FileFolderService fileFolderService = getFileFolderService();
// Get the status for the request path
LockInfo nodeLockInfo = null;
try {
contentNodeInfo = getNodeForPath(getRootNodeRef(), getPath());
// make sure that we are not trying to use a folder
if (contentNodeInfo.isFolder()) {
throw new WebDAVServerException(HttpServletResponse.SC_BAD_REQUEST);
}
nodeLockInfo = checkNode(contentNodeInfo);
// 'Unhide' nodes hidden by us and behave as though we created them
NodeRef contentNodeRef = contentNodeInfo.getNodeRef();
if (fileFolderService.isHidden(contentNodeRef) && !getDAVHelper().isRenameShuffle(getPath())) {
fileFolderService.setHidden(contentNodeRef, false);
created = true;
}
} catch (FileNotFoundException e) {
// the file doesn't exist - create it
String[] paths = getDAVHelper().splitPath(getPath());
try {
FileInfo parentNodeInfo = getNodeForPath(getRootNodeRef(), paths[0]);
// create file
contentNodeInfo = getDAVHelper().createFile(parentNodeInfo, paths[1]);
created = true;
} catch (FileNotFoundException ee) {
// bad path
throw new WebDAVServerException(HttpServletResponse.SC_CONFLICT);
} catch (FileExistsException ee) {
// ALF-7079 fix, retry: it looks like concurrent access (file not found but file exists)
throw new ConcurrencyFailureException("Concurrent access was detected.", ee);
}
}
String userName = getDAVHelper().getAuthenticationService().getCurrentUserName();
LockInfo lockInfo = getDAVLockService().getLockInfo(contentNodeInfo.getNodeRef());
if (lockInfo != null) {
if (lockInfo.isLocked() && !lockInfo.getOwner().equals(userName)) {
if (logger.isDebugEnabled()) {
String path = getPath();
String owner = lockInfo.getOwner();
logger.debug("Node locked: path=[" + path + "], owner=[" + owner + "], current user=[" + userName + "]");
}
// Indicate that the resource is locked
throw new WebDAVServerException(WebDAV.WEBDAV_SC_LOCKED);
}
}
// ALF-16808: We disable the versionable aspect if we are overwriting
// empty content because it's probably part of a compound operation to
// create a new single version
boolean disabledVersioning = false;
try {
// Disable versioning if we are overwriting an empty file with content
NodeRef nodeRef = contentNodeInfo.getNodeRef();
ContentData contentData = (ContentData) getNodeService().getProperty(nodeRef, ContentModel.PROP_CONTENT);
if ((contentData == null || contentData.getSize() == 0) && getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
getDAVHelper().getPolicyBehaviourFilter().disableBehaviour(nodeRef, ContentModel.ASPECT_VERSIONABLE);
disabledVersioning = true;
}
// Access the content
ContentWriter writer = fileFolderService.getWriter(contentNodeInfo.getNodeRef());
// set content properties
writer.guessMimetype(contentNodeInfo.getName());
writer.guessEncoding();
// Get the input stream from the request data
InputStream is = m_request.getInputStream();
// Write the new data to the content node
writer.putContent(is);
// - the node does not have any content (zero length binaries included)
if (nodeLockInfo != null && nodeLockInfo.isExclusive() && !(ContentData.hasContent(contentData) && contentData.getSize() > 0)) {
getNodeService().addAspect(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_NO_CONTENT, null);
}
// Ask for the document metadata to be extracted
Action extract = getActionService().createAction(ContentMetadataExtracter.EXECUTOR_NAME);
if (extract != null) {
extract.setExecuteAsynchronously(false);
getActionService().executeAction(extract, contentNodeInfo.getNodeRef());
}
// from the original specified in the request, update it.
if (m_strContentType == null || !m_strContentType.equals(writer.getMimetype())) {
String oldMimeType = m_strContentType;
m_strContentType = writer.getMimetype();
if (logger.isDebugEnabled()) {
logger.debug("Mimetype originally specified as " + oldMimeType + ", now guessed to be " + m_strContentType);
}
}
// Record the uploaded file's size
fileSize = writer.getSize();
// Set the response status, depending if the node existed or not
m_response.setStatus(created ? HttpServletResponse.SC_CREATED : HttpServletResponse.SC_NO_CONTENT);
} catch (AccessDeniedException e) {
throw new WebDAVServerException(HttpServletResponse.SC_FORBIDDEN, e);
} catch (Throwable e) {
// we are about to give up
if (noContent && RetryingTransactionHelper.extractRetryCause(e) == null) {
// remove the 0 bytes content if save operation failed or was cancelled
final NodeRef nodeRef = contentNodeInfo.getNodeRef();
getTransactionService().getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<String>() {
public String execute() throws Throwable {
getNodeService().deleteNode(nodeRef);
if (logger.isDebugEnabled()) {
logger.debug("Put failed. DELETE " + getPath());
}
return null;
}
}, false, false);
}
throw new WebDAVServerException(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} finally {
if (disabledVersioning) {
getDAVHelper().getPolicyBehaviourFilter().enableBehaviour(contentNodeInfo.getNodeRef(), ContentModel.ASPECT_VERSIONABLE);
}
}
postActivity();
}
use of org.alfresco.service.cmr.model.FileExistsException in project acs-community-packaging by Alfresco.
the class MySpacesBean method createSpace.
@InvokeCommand.ResponseMimetype(value = MimetypeMap.MIMETYPE_HTML)
public void createSpace() throws Exception {
FacesContext fc = FacesContext.getCurrentInstance();
ResponseWriter out = fc.getResponseWriter();
Map<String, String> requestMap = fc.getExternalContext().getRequestParameterMap();
String path = (String) requestMap.get("path");
String name = (String) requestMap.get("name");
String title = (String) requestMap.get("title");
String description = (String) requestMap.get("description");
if (logger.isDebugEnabled())
logger.debug("MySpacesBean.createSpace() path=" + path + " name=" + name + " title=" + title + " description=" + description);
try {
if (path != null && name != null) {
NodeRef containerRef = FileUploadBean.pathToNodeRef(fc, path);
if (containerRef != null) {
NodeService nodeService = Repository.getServiceRegistry(fc).getNodeService();
FileFolderService ffService = Repository.getServiceRegistry(fc).getFileFolderService();
FileInfo folderInfo = ffService.create(containerRef, name, ContentModel.TYPE_FOLDER);
if (logger.isDebugEnabled())
logger.debug("Created new folder: " + folderInfo.getNodeRef().toString());
// apply the uifacets aspect - icon, title and description properties
Map<QName, Serializable> uiFacetsProps = new HashMap<QName, Serializable>(4, 1.0f);
uiFacetsProps.put(ApplicationModel.PROP_ICON, CreateSpaceWizard.DEFAULT_SPACE_ICON_NAME);
uiFacetsProps.put(ContentModel.PROP_TITLE, title);
uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, description);
nodeService.addAspect(folderInfo.getNodeRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);
out.write("OK: " + folderInfo.getNodeRef().toString());
}
}
} catch (FileExistsException ferr) {
out.write("ERROR: A file with that name already exists.");
} catch (Throwable err) {
out.write("ERROR: " + err.getMessage());
}
}
use of org.alfresco.service.cmr.model.FileExistsException in project acs-community-packaging by Alfresco.
the class WorkspaceClipboardItem method paste.
/**
* @see org.alfresco.web.bean.clipboard.ClipboardItem#paste(javax.faces.context.FacesContext, java.lang.String, int)
*/
public boolean paste(final FacesContext fc, String viewId, final int action) {
final ServiceRegistry serviceRegistry = getServiceRegistry();
final RetryingTransactionHelper retryingTransactionHelper = serviceRegistry.getTransactionService().getRetryingTransactionHelper();
if (super.canCopyToViewId(viewId) || WORKSPACE_PASTE_VIEW_ID.equals(viewId) || FORUMS_PASTE_VIEW_ID.equals(viewId) || FORUM_PASTE_VIEW_ID.equals(viewId)) {
NavigationBean navigator = (NavigationBean) FacesHelper.getManagedBean(fc, NavigationBean.BEAN_NAME);
final NodeRef destRef = new NodeRef(Repository.getStoreRef(), navigator.getCurrentNodeId());
final DictionaryService dd = serviceRegistry.getDictionaryService();
final NodeService nodeService = serviceRegistry.getNodeService();
final FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
final CopyService copyService = serviceRegistry.getCopyService();
final MultilingualContentService multilingualContentService = serviceRegistry.getMultilingualContentService();
final boolean isPrimaryParent;
final ChildAssociationRef assocRef;
if (getParent() == null) {
assocRef = nodeService.getPrimaryParent(getNodeRef());
isPrimaryParent = true;
} else {
NodeRef parentNodeRef = getParent();
List<ChildAssociationRef> assocList = nodeService.getParentAssocs(getNodeRef());
ChildAssociationRef foundRef = null;
if (assocList != null) {
for (ChildAssociationRef assocListEntry : assocList) {
if (parentNodeRef.equals(assocListEntry.getParentRef())) {
foundRef = assocListEntry;
break;
}
}
}
assocRef = foundRef;
isPrimaryParent = parentNodeRef.equals(nodeService.getPrimaryParent(getNodeRef()).getParentRef());
}
// initial name to attempt the copy of the item with
String name = getName();
String translationPrefix = "";
if (action == UIClipboardShelfItem.ACTION_PASTE_LINK) {
// copy as link was specifically requested by the user
String linkTo = Application.getMessage(fc, MSG_LINK_TO);
name = linkTo + ' ' + name;
}
// Loop until we find a target name that doesn't exist
for (; ; ) {
try {
final String currentTranslationPrefix = translationPrefix;
final String currentName = name;
// attempt each copy/paste in its own transaction
retryingTransactionHelper.doInTransaction(new RetryingTransactionCallback<Void>() {
public Void execute() throws Throwable {
if (getMode() == ClipboardStatus.COPY) {
if (action == UIClipboardShelfItem.ACTION_PASTE_LINK) {
// LINK operation
if (logger.isDebugEnabled())
logger.debug("Attempting to link node ID: " + getNodeRef() + " into node: " + destRef.toString());
// create the node using the nodeService (can only use FileFolderService for content)
if (checkExists(currentName + LINK_NODE_EXTENSION, destRef) == false) {
Map<QName, Serializable> props = new HashMap<QName, Serializable>(2, 1.0f);
String newName = currentName + LINK_NODE_EXTENSION;
props.put(ContentModel.PROP_NAME, newName);
props.put(ContentModel.PROP_LINK_DESTINATION, getNodeRef());
if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT)) {
// create File Link node
ChildAssociationRef childRef = nodeService.createNode(destRef, ContentModel.ASSOC_CONTAINS, QName.createQName(assocRef.getQName().getNamespaceURI(), newName), ApplicationModel.TYPE_FILELINK, props);
// apply the titled aspect - title and description
Map<QName, Serializable> titledProps = new HashMap<QName, Serializable>(2, 1.0f);
titledProps.put(ContentModel.PROP_TITLE, currentName);
titledProps.put(ContentModel.PROP_DESCRIPTION, currentName);
nodeService.addAspect(childRef.getChildRef(), ContentModel.ASPECT_TITLED, titledProps);
} else {
// create Folder link node
ChildAssociationRef childRef = nodeService.createNode(destRef, ContentModel.ASSOC_CONTAINS, assocRef.getQName(), ApplicationModel.TYPE_FOLDERLINK, props);
// apply the uifacets aspect - icon, title and description props
Map<QName, Serializable> uiFacetsProps = new HashMap<QName, Serializable>(4, 1.0f);
uiFacetsProps.put(ApplicationModel.PROP_ICON, "space-icon-link");
uiFacetsProps.put(ContentModel.PROP_TITLE, currentName);
uiFacetsProps.put(ContentModel.PROP_DESCRIPTION, currentName);
nodeService.addAspect(childRef.getChildRef(), ApplicationModel.ASPECT_UIFACETS, uiFacetsProps);
}
}
} else {
// COPY operation
if (logger.isDebugEnabled())
logger.debug("Attempting to copy node: " + getNodeRef() + " into node ID: " + destRef.toString());
// first check that we are not attempting to copy a duplicate into the same parent
if (destRef.equals(assocRef.getParentRef()) && currentName.equals(getName())) {
// manually change the name if this occurs
throw new FileExistsException(destRef, currentName);
}
if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT) || dd.isSubClass(getType(), ContentModel.TYPE_FOLDER)) {
// copy the file/folder
fileFolderService.copy(getNodeRef(), destRef, currentName);
} else if (dd.isSubClass(getType(), ContentModel.TYPE_MULTILINGUAL_CONTAINER)) {
// copy the mlContainer and its translations
multilingualContentService.copyTranslationContainer(getNodeRef(), destRef, currentTranslationPrefix);
} else {
// copy the node
if (checkExists(currentName, destRef) == false) {
copyService.copyAndRename(getNodeRef(), destRef, ContentModel.ASSOC_CONTAINS, assocRef.getQName(), true);
}
}
}
} else {
// MOVE operation
if (logger.isDebugEnabled())
logger.debug("Attempting to move node: " + getNodeRef() + " into node ID: " + destRef.toString());
if (dd.isSubClass(getType(), ContentModel.TYPE_CONTENT) || dd.isSubClass(getType(), ContentModel.TYPE_FOLDER)) {
// move the file/folder
fileFolderService.moveFrom(getNodeRef(), getParent(), destRef, currentName);
} else if (dd.isSubClass(getType(), ContentModel.TYPE_MULTILINGUAL_CONTAINER)) {
// copy the mlContainer and its translations
multilingualContentService.moveTranslationContainer(getNodeRef(), destRef);
} else {
if (isPrimaryParent) {
// move the node
nodeService.moveNode(getNodeRef(), destRef, ContentModel.ASSOC_CONTAINS, assocRef.getQName());
} else {
nodeService.removeChild(getParent(), getNodeRef());
nodeService.addChild(destRef, getNodeRef(), assocRef.getTypeQName(), assocRef.getQName());
}
}
}
return null;
}
});
// We got here without error, so no need to loop with a new name
break;
} catch (FileExistsException fileExistsErr) {
// If mode is COPY, have another go around the loop with a new name
if (getMode() == ClipboardStatus.COPY) {
String copyOf = Application.getMessage(fc, MSG_COPY_OF);
name = copyOf + ' ' + name;
translationPrefix = copyOf + ' ' + translationPrefix;
} else {
// we should not rename an item when it is being moved - so exit
throw fileExistsErr;
}
}
}
return true;
} else {
return false;
}
}
use of org.alfresco.service.cmr.model.FileExistsException in project records-management by Alfresco.
the class RecordsEntityResource method fileRecord.
@Operation("file")
@WebApiDescription(title = "File record", description = "File a record into fileplan.")
public Record fileRecord(String recordId, TargetContainer target, Parameters parameters, WithResponse withResponse) {
checkNotBlank("recordId", recordId);
mandatory("target", target);
mandatory("targetParentId", target.getTargetParentId());
mandatory("parameters", parameters);
// Get record and target folder
NodeRef record = apiUtils.validateRecord(recordId);
NodeRef targetRecordFolder = apiUtils.lookupAndValidateNodeType(target.getTargetParentId(), RecordsManagementModel.TYPE_RECORD_FOLDER);
// Get the current parent type to decide if we link or move the record
NodeRef primaryParent = nodeService.getPrimaryParent(record).getParentRef();
if (RecordsManagementModel.TYPE_RECORD_FOLDER.equals(nodeService.getType(primaryParent))) {
recordService.link(record, targetRecordFolder);
} else {
try {
fileFolderService.moveFrom(record, primaryParent, targetRecordFolder, null);
} catch (FileExistsException e) {
throw new IntegrityException(e.getMessage(), null);
} catch (FileNotFoundException e) {
throw new ConcurrencyFailureException("The record was deleted while filing it", e);
}
}
// return record state
FileInfo info = fileFolderService.getFileInfo(record);
return nodesModelFactory.createRecord(info, parameters, null, false);
}
use of org.alfresco.service.cmr.model.FileExistsException in project acs-community-packaging by Alfresco.
the class DocumentPropertiesDialog method save.
/**
* Event handler used to save the edited properties back to the repository
*
* @return The outcome
*/
public String save() {
String outcome = "cancel";
UserTransaction tx = null;
try {
tx = Repository.getUserTransaction(FacesContext.getCurrentInstance());
tx.begin();
NodeRef nodeRef = this.browseBean.getDocument().getNodeRef();
Map<String, Object> props = this.editableNode.getProperties();
// get the name and move the node as necessary
String name = (String) props.get(ContentModel.PROP_NAME);
if (name != null) {
getFileFolderService().rename(nodeRef, name);
}
Map<QName, Serializable> properties = getNodeService().getProperties(nodeRef);
// we need to put all the properties from the editable bag back into
// the format expected by the repository
// Deal with the special mimetype property for ContentData
String mimetype = (String) props.get(TEMP_PROP_MIMETYPE);
if (mimetype != null) {
// remove temporary prop from list so it isn't saved with the others
props.remove(TEMP_PROP_MIMETYPE);
ContentData contentData = (ContentData) props.get(ContentModel.PROP_CONTENT);
if (contentData != null) {
contentData = ContentData.setMimetype(contentData, mimetype);
props.put(ContentModel.PROP_CONTENT.toString(), contentData);
}
}
// Deal with the special encoding property for ContentData
String encoding = (String) props.get(TEMP_PROP_ENCODING);
if (encoding != null) {
// remove temporary prop from list so it isn't saved with the others
props.remove(TEMP_PROP_ENCODING);
ContentData contentData = (ContentData) props.get(ContentModel.PROP_CONTENT);
if (contentData != null) {
contentData = ContentData.setEncoding(contentData, encoding);
props.put(ContentModel.PROP_CONTENT.toString(), contentData);
}
}
// extra and deal with the Author prop if the aspect has not been applied yet
String author = (String) props.get(ContentModel.PROP_AUTHOR);
if (author != null && author.length() != 0) {
// add aspect if required
if (getNodeService().hasAspect(nodeRef, ContentModel.ASPECT_AUTHOR) == false) {
Map<QName, Serializable> authorProps = new HashMap<QName, Serializable>(1, 1.0f);
authorProps.put(ContentModel.PROP_AUTHOR, author);
getNodeService().addAspect(nodeRef, ContentModel.ASPECT_AUTHOR, authorProps);
}
// else it will get updated in the later setProperties() call
}
// deal with adding the "titled" aspect if required
String title = (String) props.get(ContentModel.PROP_TITLE);
String description = (String) props.get(ContentModel.PROP_DESCRIPTION);
if (title != null || description != null) {
// add the aspect to be sure it's present
getNodeService().addAspect(nodeRef, ContentModel.ASPECT_TITLED, null);
// props will get added later in setProperties()
}
// add the remaining properties
Iterator<String> iterProps = props.keySet().iterator();
while (iterProps.hasNext()) {
String propName = iterProps.next();
QName qname = QName.createQName(propName);
// make sure the property is represented correctly
Serializable propValue = (Serializable) props.get(propName);
// check for empty strings when using number types, set to null in this case
if ((propValue != null) && (propValue instanceof String) && (propValue.toString().length() == 0)) {
PropertyDefinition propDef = getDictionaryService().getProperty(qname);
if (propDef != null) {
if (propDef.getDataType().getName().equals(DataTypeDefinition.DOUBLE) || propDef.getDataType().getName().equals(DataTypeDefinition.FLOAT) || propDef.getDataType().getName().equals(DataTypeDefinition.INT) || propDef.getDataType().getName().equals(DataTypeDefinition.LONG)) {
propValue = null;
}
}
}
properties.put(qname, propValue);
}
// send the properties back to the repository
getNodeService().setProperties(this.browseBean.getDocument().getNodeRef(), properties);
// we also need to persist any association changes that may have been made
// add any associations added in the UI
Map<String, Map<String, AssociationRef>> addedAssocs = this.editableNode.getAddedAssociations();
for (Map<String, AssociationRef> typedAssoc : addedAssocs.values()) {
for (AssociationRef assoc : typedAssoc.values()) {
getNodeService().createAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName());
}
}
// remove any association removed in the UI
Map<String, Map<String, AssociationRef>> removedAssocs = this.editableNode.getRemovedAssociations();
for (Map<String, AssociationRef> typedAssoc : removedAssocs.values()) {
for (AssociationRef assoc : typedAssoc.values()) {
getNodeService().removeAssociation(assoc.getSourceRef(), assoc.getTargetRef(), assoc.getTypeQName());
}
}
// add any child associations added in the UI
Map<String, Map<String, ChildAssociationRef>> addedChildAssocs = this.editableNode.getAddedChildAssociations();
for (Map<String, ChildAssociationRef> typedAssoc : addedChildAssocs.values()) {
for (ChildAssociationRef assoc : typedAssoc.values()) {
getNodeService().addChild(assoc.getParentRef(), assoc.getChildRef(), assoc.getTypeQName(), assoc.getTypeQName());
}
}
// remove any child association removed in the UI
Map<String, Map<String, ChildAssociationRef>> removedChildAssocs = this.editableNode.getRemovedChildAssociations();
for (Map<String, ChildAssociationRef> typedAssoc : removedChildAssocs.values()) {
for (ChildAssociationRef assoc : typedAssoc.values()) {
getNodeService().removeChild(assoc.getParentRef(), assoc.getChildRef());
}
}
// commit the transaction
tx.commit();
// set the outcome to refresh
outcome = "finish";
// reset the document held by the browse bean as it's just been updated
this.browseBean.getDocument().reset();
} catch (FileExistsException e) {
// rollback the transaction
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception ex) {
}
// print status message
String statusMsg = MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), "error_exists"), e.getName());
Utils.addErrorMessage(statusMsg);
// no outcome
outcome = null;
} catch (InvalidNodeRefException err) {
// rollback the transaction
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception ex) {
}
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { this.browseBean.getDocument().getId() }));
// this failure means the node no longer exists - we cannot show the doc properties screen
outcome = "browse";
} catch (Throwable e) {
// rollback the transaction
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception ex) {
}
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), e.getMessage()), e);
}
return outcome;
}
Aggregations