use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.
the class NodesImpl method upload.
@Override
public Node upload(String parentFolderNodeId, FormData formData, Parameters parameters) {
if (formData == null || !formData.getIsMultiPart()) {
throw new InvalidArgumentException("The request content-type is not multipart: " + parentFolderNodeId);
}
NodeRef parentNodeRef = validateOrLookupNode(parentFolderNodeId, null);
if (!nodeMatches(parentNodeRef, Collections.singleton(ContentModel.TYPE_FOLDER), null, false)) {
throw new InvalidArgumentException("NodeId of folder is expected: " + parentNodeRef.getId());
}
String fileName = null;
Content content = null;
boolean autoRename = false;
QName nodeTypeQName = ContentModel.TYPE_CONTENT;
// If a fileName clashes for a versionable file
boolean overwrite = false;
Boolean versionMajor = null;
String versionComment = null;
String relativePath = null;
String renditionNames = null;
Map<String, Object> qnameStrProps = new HashMap<>();
Map<QName, Serializable> properties = null;
for (FormData.FormField field : formData.getFields()) {
switch(field.getName().toLowerCase()) {
case "name":
String str = getStringOrNull(field.getValue());
if ((str != null) && (!str.isEmpty())) {
fileName = str;
}
break;
case "filedata":
if (field.getIsFile()) {
fileName = (fileName != null ? fileName : field.getFilename());
content = field.getContent();
}
break;
case "autorename":
autoRename = Boolean.valueOf(field.getValue());
break;
case "nodetype":
nodeTypeQName = createQName(getStringOrNull(field.getValue()));
if (!isSubClass(nodeTypeQName, ContentModel.TYPE_CONTENT)) {
throw new InvalidArgumentException("Can only upload type of cm:content: " + nodeTypeQName);
}
break;
case "overwrite":
overwrite = Boolean.valueOf(field.getValue());
break;
case "majorversion":
versionMajor = Boolean.valueOf(field.getValue());
break;
case "comment":
versionComment = getStringOrNull(field.getValue());
break;
case "relativepath":
relativePath = getStringOrNull(field.getValue());
break;
case "renditions":
renditionNames = getStringOrNull(field.getValue());
break;
default:
{
final String propName = field.getName();
if (propName.indexOf(QName.NAMESPACE_PREFIX) > -1) {
qnameStrProps.put(propName, field.getValue());
}
}
}
}
// result in a success message, but the files do not appear.
if (formData.getFields().length == 0) {
throw new ConstraintViolatedException("No disk space available");
}
// destination, or site + container or updateNodeRef
if ((fileName == null) || fileName.isEmpty() || (content == null)) {
throw new InvalidArgumentException("Required parameters are missing");
}
if (autoRename && overwrite) {
throw new InvalidArgumentException("Both 'overwrite' and 'autoRename' should not be true when uploading a file");
}
// if requested, make (get or create) path
parentNodeRef = getOrCreatePath(parentNodeRef, relativePath);
final QName assocTypeQName = ContentModel.ASSOC_CONTAINS;
final Set<String> renditions = getRequestedRenditions(renditionNames);
try {
// Map the given properties, if any.
if (qnameStrProps.size() > 0) {
properties = mapToNodeProperties(qnameStrProps);
}
/*
* Existing file handling
*/
NodeRef existingFile = nodeService.getChildByName(parentNodeRef, assocTypeQName, fileName);
if (existingFile != null) {
// File already exists, decide what to do
if (autoRename) {
// attempt to find a unique name
fileName = findUniqueName(parentNodeRef, fileName);
// drop-through !
} else if (overwrite && nodeService.hasAspect(existingFile, ContentModel.ASPECT_VERSIONABLE)) {
// overwrite existing (versionable) file
BasicContentInfo contentInfo = new ContentInfoImpl(content.getMimetype(), content.getEncoding(), -1, null);
return updateExistingFile(parentNodeRef, existingFile, fileName, contentInfo, content.getInputStream(), parameters, versionMajor, versionComment);
} else {
// name clash (and no autoRename or overwrite)
throw new ConstraintViolatedException(fileName + " already exists.");
}
}
// Note: pending REPO-159, we currently auto-enable versioning on new upload (but not when creating empty file)
if (versionMajor == null) {
versionMajor = true;
}
// Create a new file.
NodeRef nodeRef = createNewFile(parentNodeRef, fileName, nodeTypeQName, content, properties, assocTypeQName, parameters, versionMajor, versionComment);
// Create the response
final Node fileNode = getFolderOrDocumentFullInfo(nodeRef, parentNodeRef, nodeTypeQName, parameters);
// RA-1052
try {
List<ThumbnailDefinition> thumbnailDefs = getThumbnailDefs(renditions);
requestRenditions(thumbnailDefs, fileNode);
} catch (Exception ex) {
// Note: The log level is not 'error' as it could easily fill out the log file, especially in the Cloud.
if (logger.isDebugEnabled()) {
// Don't throw the exception as we don't want the the upload to fail, just log it.
logger.debug("Asynchronous request to create a rendition upon upload failed: " + ex.getMessage());
}
}
return fileNode;
// Do not clean formData temp files to allow for retries.
// Temp files will be deleted later when GC call DiskFileItem#finalize() method or by temp file cleaner.
} catch (AccessDeniedException ade) {
throw new PermissionDeniedException(ade.getMessage());
}
/*
* NOTE: Do not clean formData temp files to allow for retries. It's
* possible for a temp file to remain if max retry attempts are
* made, but this is rare, so leave to usual temp file cleanup.
*/
}
use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.
the class BufferedRequest method getContent.
/* (non-Javadoc)
* @see org.springframework.extensions.webscripts.WebScriptRequest#getContent()
*/
@Override
public Content getContent() {
final Content wrapped = req.getContent();
return new Content() {
@Override
public String getContent() throws IOException {
return wrapped.getContent();
}
@Override
public String getEncoding() {
return wrapped.getEncoding();
}
@Override
public String getMimetype() {
return wrapped.getMimetype();
}
@Override
public long getSize() {
return wrapped.getSize();
}
@Override
public InputStream getInputStream() {
if (BufferedRequest.this.contentReader != null) {
throw new IllegalStateException("Reader in use");
}
if (BufferedRequest.this.contentStream == null) {
try {
BufferedRequest.this.contentStream = bufferInputStream();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return BufferedRequest.this.contentStream;
}
@Override
public BufferedReader getReader() throws IOException {
if (BufferedRequest.this.contentStream != null) {
throw new IllegalStateException("Input Stream in use");
}
if (BufferedRequest.this.contentReader == null) {
String encoding = wrapped.getEncoding();
InputStream in = bufferInputStream();
BufferedRequest.this.contentReader = new BufferedReader(new InputStreamReader(in, encoding == null ? "ISO-8859-1" : encoding));
}
return BufferedRequest.this.contentReader;
}
};
}
use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.
the class BulkMetadataGet method execute.
@Override
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
JSONObject jsonIn;
JSONArray nodeRefsArray;
try {
Content c = req.getContent();
if (c == null) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing POST body.");
}
jsonIn = new JSONObject(c.getContent());
nodeRefsArray = jsonIn.getJSONArray("nodeRefs");
if (nodeRefsArray == null || nodeRefsArray.length() == 0) {
throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Must provide node refs");
}
JSONWriter jsonOut = new JSONWriter(res.getWriter());
res.setContentType("application/json");
// TODO: Should be settable on JSONWriter
res.setContentEncoding(Charset.defaultCharset().displayName());
jsonOut.startObject();
{
jsonOut.startValue("nodes");
{
jsonOut.startArray();
{
for (int i = 0; i < nodeRefsArray.length(); i++) {
NodeRef nodeRef = new NodeRef(nodeRefsArray.getString(i));
if (nodeService.exists(nodeRef)) {
NodeRef parentNodeRef = null;
ChildAssociationRef childAssocRef = nodeService.getPrimaryParent(nodeRef);
if (childAssocRef != null) {
parentNodeRef = childAssocRef.getParentRef();
}
QName type = nodeService.getType(nodeRef);
String shortType = type.toPrefixString(services.getNamespaceService());
Map<QName, Serializable> properties = nodeService.getProperties(nodeRef);
jsonOut.startObject();
{
jsonOut.writeValue("nodeRef", nodeRef.toString());
jsonOut.writeValue("parentNodeRef", parentNodeRef.toString());
jsonOut.writeValue("type", type.toString());
jsonOut.writeValue("shortType", shortType);
TypeDefinition typeDef = dictionaryService.getType(type);
jsonOut.writeValue("typeTitle", typeDef.getTitle(dictionaryService));
jsonOut.writeValue("name", (String) properties.get(ContentModel.PROP_NAME));
jsonOut.writeValue("title", (String) properties.get(ContentModel.PROP_TITLE));
jsonOut.writeValue("mimeType", getMimeType((ContentData) properties.get(ContentModel.PROP_CONTENT)));
jsonOut.writeValue("hasWritePermission", permissionService.hasPermission(nodeRef, PermissionService.WRITE) == AccessStatus.ALLOWED);
jsonOut.writeValue("hasDeletePermission", permissionService.hasPermission(nodeRef, PermissionService.DELETE) == AccessStatus.ALLOWED);
}
jsonOut.endObject();
} else {
jsonOut.startObject();
{
jsonOut.writeValue("nodeRef", nodeRef.toString());
jsonOut.writeValue("error", "true");
jsonOut.writeValue("errorCode", "invalidNodeRef");
jsonOut.writeValue("errorText", I18NUtil.getMessage("msg.invalidNodeRef", nodeRef.toString()));
}
jsonOut.endObject();
}
}
}
jsonOut.endArray();
}
jsonOut.endValue();
}
jsonOut.endObject();
} catch (JSONException jErr) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Unable to parse JSON POST body: " + jErr.getMessage());
}
res.getWriter().close();
res.setStatus(Status.STATUS_OK);
}
use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.
the class ChangePasswordPost method executeImpl.
/* (non-Javadoc)
* @see org.alfresco.web.scripts.DeclarativeWebScript#executeImpl(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.Status)
*/
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status) {
// Extract user name from the URL - cannot be null or webscript desc would not match
String userName = req.getExtensionPath();
// Extract old and new password details from JSON POST
Content c = req.getContent();
if (c == null) {
throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Missing POST body.");
}
JSONObject json;
try {
json = new JSONObject(c.getContent());
String oldPassword = null;
String newPassword;
// admin users can change/set a password without knowing the old one
boolean isAdmin = authorityService.hasAdminAuthority();
if (!isAdmin || (userName.equalsIgnoreCase(authenticationService.getCurrentUserName()))) {
if (!json.has(PARAM_OLDPW) || json.getString(PARAM_OLDPW).length() == 0) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Old password 'oldpw' is a required POST parameter.");
}
oldPassword = json.getString(PARAM_OLDPW);
}
if (!json.has(PARAM_NEWPW) || json.getString(PARAM_NEWPW).length() == 0) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "New password 'newpw' is a required POST parameter.");
}
newPassword = json.getString(PARAM_NEWPW);
// an Admin user can update without knowing the original pass - but must know their own!
if (!isAdmin || (userName.equalsIgnoreCase(authenticationService.getCurrentUserName()))) {
authenticationService.updateAuthentication(userName, oldPassword.toCharArray(), newPassword.toCharArray());
} else {
authenticationService.setAuthentication(userName, newPassword.toCharArray());
}
} catch (AuthenticationException err) {
throw new WebScriptException(Status.STATUS_UNAUTHORIZED, "Do not have appropriate auth or wrong auth details provided.");
} catch (JSONException jErr) {
throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Unable to parse JSON POST body: " + jErr.getMessage());
} catch (IOException ioErr) {
throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Unable to retrieve POST body: " + ioErr.getMessage());
}
Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
model.put("success", Boolean.TRUE);
return model;
}
use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.
the class AclsGet method buildModel.
private Map<String, Object> buildModel(WebScriptRequest req) throws JSONException, IOException {
List<Long> aclChangeSetIds = null;
Content content = req.getContent();
if (content == null) {
throw new WebScriptException("Request content is empty");
}
JSONObject o = new JSONObject(content.getContent());
JSONArray aclChangeSetIdsJSON = o.has("aclChangeSetIds") ? o.getJSONArray("aclChangeSetIds") : null;
if (aclChangeSetIdsJSON == null) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter 'aclChangeSetIds' not provided in request content.");
} else if (aclChangeSetIdsJSON.length() == 0) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter 'aclChangeSetIds' must hold from 1 or more IDs.");
}
aclChangeSetIds = new ArrayList<Long>(aclChangeSetIdsJSON.length());
for (int i = 0; i < aclChangeSetIdsJSON.length(); i++) {
aclChangeSetIds.add(aclChangeSetIdsJSON.getLong(i));
}
String fromIdParam = req.getParameter("fromId");
String maxResultsParam = req.getParameter("maxResults");
Long fromId = (fromIdParam == null ? null : Long.valueOf(fromIdParam));
int maxResults = (maxResultsParam == null ? 1024 : Integer.valueOf(maxResultsParam));
// Request according to the paging query style required
List<Acl> acls = solrTrackingComponent.getAcls(aclChangeSetIds, fromId, maxResults);
Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
model.put("acls", acls);
if (logger.isDebugEnabled()) {
logger.debug("Result: \n\tRequest: " + req + "\n\tModel: " + model);
}
return model;
}
Aggregations