How to create folder in Alfresco by RESTful API - alfresco

I am using Freshdocs for Android
I can login to the Alfresco server using this API call:
GET /alfresco/service/api/login?u={username}&pw={password?}
But how do I create a new folder in Alfresco?

There are two main options, but it'll depend on what else you want to do, and what version of Alfresco you're running.
Assuming you want to keep things very simple, and you just want to create one folder, and you're using Alfresco 4.1 or later, then you can use the org.alfresco.repository.node.folder.post webscript. For this, simply post JSON like either
{ "name": "NewNodeName" }
or
{
"name": "NewNodeName",
"title": "New Node Title",
"description": "A shiny new node",
"type": "cm:folder"
}
To the API, which takes a URL like /api/site/folder/{site}/{container}/{path}
Alternately, if you want to do a number of different file and folder operations (eg navigate the folder structure, create a folder, upload a file to it etc), then you should instead use CMIS. Apache Chemistry is a great library to use for CMIS, and it even has an Android client! The docs for the android client are still being written thought (the Android port was only just added), so you might need to ask on the mailing list if you don't have time to wait for the docs.

To create a folder through api you can use the following queries:
a) To create defined type folder using full path to parent folder
url: "/../alfresco/service/api/site/folder/" + siteName + "/documentLibrary/" + parentFolderPath
method: "POST"
json: {
name: name
type: folderType
}
siteName - website name created in Alfresco;
parentFolderPath - path to parent folder;
name -folder name;
type - folder type.
Example:
url: "/../alfresco/service/api/site/folder/example/documentLibrary/books"
method: "POST"
json: {
name: "Pushkin"
type: "cm:folder"
}
After making the request "Pushkin" folder is created. This folder is situated in “books” folder of documents library on the "example" website.
b) To create folder by nodeRef
nodeRef is an object id in Alfresco. Each object has its own nodeRef. This request creates new object inside given object of folder type.
xml = '<?xml version="1.0" encoding="utf-8"?>' + '<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">' +
'<title>' + folderName + '</title>' +
'<summary>' + folderName + '</summary>' +
'<cmisra:object>' +
'<cmis:properties>' +
'<cmis:propertyId
propertyDefinitionId="cmis:objectTypeId">' +
'<cmis:value>' + folderType + '</cmis:value>' +
'</cmis:propertyId>' +
'</cmis:properties>' +
'</cmisra:object>' +
'</entry>';
url: "/../alfresco/service/api/node/workspace/SpacesStore/" +
nodeRef + "/children"
method: "POST"
headers: {
"Content-Type": "application/atom+xml;type=entry"
},
xml: xml
folderName - folder name;
folderType - folder type;
nodeRef - folder id in Alfresco.
Example:
nodeRef = b544cd67-e839-4c60-a616-9605fa2affb7;
xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<entry xmlns="http://www.w3.org/2005/Atom"
xmlns:cmisra="http://docs.oasis-open.org/ns/cmis/restatom/200908/"
xmlns:cmis="http://docs.oasis-open.org/ns/cmis/core/200908/">' +
'<title>Example of creating a folder</title>' +
'<summary>Example of creating a folder</summary>' +
'<cmisra:object>' +
'<cmis:properties>' +
'<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">' +
'<cmis:value>cm:folder</cmis:value>' +
'</cmis:propertyId>' +
'</cmis:properties>' +
'</cmisra:object>' +
'</entry>';
url: "/../alfresco/service/api/node/workspace/SpacesStore/" + nodeRef + "/children"
method: "POST"
headers: {
"Content-Type": "application/atom+xml;type=entry"
},
xml: xml
Other services and their description you can find here:
http://jazzteam.org/en/technical-articles/list-of-alfresco-services/

You should use
POST /alfresco/service/api/path/{store_type}/{store_id}/{id}/children
Read the docs for detailed information:
http://wiki.alfresco.com/wiki/Repository_RESTful_API_Reference#Create_folder_or_document_.28createDocument.2C_createFolder.29

Related

How to add timestamp to Cucumber report

How can I add timestamps to the HTML report for the test run start/end and for scenario start/end in Cucumber-JVM?
Is there a Cucumber option I can add to RunWith JUnit runner?
It's simple!!!!!!
Don't mention any folder path in plugin com.cucumber.listener.ExtentCucumberFormatter.
Example :
plugin= { "pretty", "html:FeaturesReport", "html:target/site/cucumber-pretty", "json:target/cucumber.json",
"com.cucumber.listener.ExtentCucumberFormatter:",
},
Run project and refresh it.
check report will generate in default folder output/Run_with system time/report.html
If you want to generate a report in a specified path with a timestamp
just follow the below steps.
goto maven dependencies.
search cucumber-extentsreport.jar
extend jar and select com.cucumber.listener package
copy entire code in ExtentProperties class
right on package and create new enum with name of ExtentProperties
then paste ExtentProperties class code in the created enum.
search below method
ExtentProperties() {
this.reportPath = "output" + File.separator + "Run_" + System.currentTimeMillis() +File.separator+ "report.html";
this.projectName = "default";
}
8.And Replace With below code
String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());
String userDir =System.getProperty("user.dir");
ExtentProperties()
{
this.reportPath = "Extent_Reports" + File.separator + "" +
timeStamp.replace(":","").replace(".","_") + File.separator + "Execution
report.html";
this.projectName = "default";
}
Run the project then refresh the project.
10.check report will generate in specified path with the name.
Extent_Reports/_2020_06_16_19_14_07/Execution report.html
Please comment if you have any questions
Work with latest cucumber version, you can get start timestamp of each scenario in json report as below:
"elements": [
{
"start_timestamp": "2019-11-18T11:06:15.606Z",
....
}

Ionic2: get image form URL and save to native storage

Let's say I have a JSON object containing users' profile including firstname, lastname,..., and profileUrl from a web API. I've already saved the text data using Sqlite, and now I want to save those images in native storage and put the file path into the sqlite database replacing the profileUrl.
You can use cordova-plugin-file-transfer for that. There is even an Ionic Native wrapper available: https://ionicframework.com/docs/native/transfer/
Example:
download() {
const url = 'http://www.example.com/file.pdf';
fileTransfer.download(url, this.file.dataDirectory + 'file.pdf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
}

How do I upload a image to my server with meteor?

I have a logo somewhere on my application page.
The application admin should be able to adjust the logo within the webapplication by simply upload a new one. What would be the best practice to achieve this?
How would I handle the upload on the server. It should replace the old logo with the new one. The name and location should stay the same.
Here is my approach:
I use the package UploadFS:
jalik:ufs
jalik:ufs-local
autopublish //it is still on, so the code below works without publish/subscribe I know that I will have to change that.
My code:
Upload
*.js Server & Client
//Almost Standard initialization - works so far
Logo = new Mongo.Collection('logo');
LogoStore = new UploadFS.store.Local({
collection: Logo,
name: 'logo',
path: '/uploads/logo',
mode: '0744', // directory permissions
writeMode: '0744', // file permissions
filter: new UploadFS.Filter({
minSize: 1,
maxSize: 1024 * 1000, // 1MB,
contentTypes: ['image/*'],
extensions: ['png']
})
});
*.html
//Standard initialization - works so far
<template name="upload">
<button type="button" name="upload">Select files</button>
</template>
*.js Client
//Almost Standard initialization - works so far
Template.upload.events({
'click button[name=upload]': function (ev) {
var self = this;
UploadFS.selectFiles(function (file) {
// Prepare the file to insert in database, note that we don't provide an URL,
// it will be set automatically by the uploader when file transfer is complete.
var logo = {
name: 'logo.png', //all uploaded images will have the same name
size: file.size,
type: file.type,
};
// Create a new Uploader for this file
var uploader = new UploadFS.Uploader({
// This is where the uploader will save the file
store: LogoStore,
// Optimize speed transfer by increasing/decreasing chunk size automatically
adaptive: true,
// Define the upload capacity (if upload speed is 1MB/s, then it will try to maintain upload at 80%, so 800KB/s)
// (used only if adaptive = true)
capacity: 0.8, // 80%
// The size of each chunk sent to the server
chunkSize: 8 * 1024, // 8k
// The max chunk size (used only if adaptive = true)
maxChunkSize: 128 * 1024, // 128k
// This tells how many tries to do if an error occurs during upload
maxTries: 5,
// The File/Blob object containing the data
data: file,
// The document to save in the collection
file: logo,
// The error callback
onError: function (err) {
console.error(err);
},
onAbort: function (file) {
console.log(file.name + ' upload has been aborted');
},
onComplete: function (file) {
console.log(file.name + ' has been uploaded');
},
onCreate: function (file) {
console.log(file.name + ' has been created with ID ' + file._id);
},
onProgress: function (file, progress) {
console.log(file.name + ' ' + (progress*100) + '% uploaded');
},
onStart: function (file) {
console.log(file.name + ' started');
},
onStop: function (file) {
console.log(file.name + ' stopped');
}
});
// Starts the upload
uploader.start();
// Stops the upload
uploader.stop();
// Abort the upload
uploader.abort();
});
}
});
Show uploaded Logo
*.html
<template name="whatever">
<img src="{{logoUrl}}" alt="Logo" >
</template>
*.js client only
Template.whatever.helpers({
logoUrl: function(){
return Logo.findOne().url;
}
})
So If I understand it right, what the code does is uploading the img to somewhere on the server. Also it stores some info about that image in a Mongo.Collection - Logo.
But I do not exactly know where those images are stored, in which folder. They are not stored in my default Project - Folder.
The url of an example img is: http://localhost:3000/ufs/logo/B4Fv5etkr7xQbvs5v/logo.png. That random string in the middle is the _id of that img. So I can not use a hardcoded url for that images to access them, because as soon as a new img is uploaded, that url will change completely.
Q1: So the first question is: Can I upload to the myProject/public/img folder directly? So that the url of the img would be something like:
http://localhost:3000/img/logo.png
Then I would need just to replace the old logo on the upload.
For now I have to deal with the generic url. So as next, I select the url of the now present image on the server from the Logo - collection and pass that url to my template to the place where the logo has to be placed. The problem with that is, that the url is loaded after everything else was loaded, so for several seconds I get an tag without an url in it. So that place shows the alt text only until the url is loaded. That is very ugly...
Q2: The question is, how could I get the url, before the tag is loaded. So that the logo appears with/before everything else, as if the url would be hardcoded in advance.
Q3: Is it possible to replace the old logo with the new uploaded one, on the upload? How?
Q4: If I delete the entry for the img from the Logo - Collection, is the image actually deleted from the server? Or do I have to delete it manually/in another way?
You can send a base64 encode image on server then using fs your can overwrite the file.
Like:
Client
readAsDataURL has base64 encoded data in the format of
data:image/jpeg;base64,/9j/4AAQSkZJRgABA...
So you need to get rid of the mime type and encoding information at the front.
contents = contents.split(',')[1];
Now you can send this base64 encoded data to server.
Server
Since you're receiving base64 encoded data, you can convert it buffer and write to file:
fs.writeFile(filepath, Buffer(argument,'base64'), err => {
//
})
In case the file name same as another file then it will completely overwrite your file.
Answer for question 1:
default image will be stored hide folder in your project .meteor/local/build/programs/server/ufs/uploads/
You can change destination by "path" as below code
new UploadFS.store.Local({
collection: Csvs.collection,
name: 'csv',
path: '../../../../../uploads/csv', //here change destination folder stored file
filter: new UploadFS.Filter({
maxSize: 1024 * 3000, // 3MB,
contentTypes: ['text/csv']
})
});
When doing the "Client" step in Pankaj Javav's answer, you may want to use the base64-image-upload package I whipped up, as I was having the same problem. It simplifies the process of uploading any base64 string to a server, and you do not need to get rid of the MIME type this way.

How to get site's name from WP API

I'm trying to get WordPress website title using javascript and WP API plugin
I didn't find any example on how to get the site's name but I found the variable name under the entities section in the developer guide
function _updateTitle(documentTitle) {
document.querySelector('title').innerHTML =
documentTitle + ' | '+ $http.get('wp-json/name');
}
The output string of $http.get('wp-json/name') is [object Object]
Does anyone know how to use fix this?
You didn't get enough context. What's $http? What happens when you go to wp-json/name directly in your browser? Here's what I see:
[{
"code":"json_no_route",
"message":"No route was found matching the URL and request method"
}]
Here's a simple example to get you the title:
var siteName;
$.getJSON( "/wp-json", function( data ) {
siteName = data.name;
});
See more elegant solution here https://wordpress.stackexchange.com/a/314767/94636
response will not contain extra data like:
authentication: []
namespaces: ["oembed/1.0", "akismet/v1", "acf/v3", "wp/v2"]
routes: {/: {namespace: "", methods: ["GET"],…},…}
timezone_string: ""
...
_links: {help: [{href: "http://v2.wp-api.org/"}]}

How to list files in folder

How can I list all files inside a folder with Meteor.I have FS collection and cfs:filesystem installed on my app. I didn't find it in the doc.
Another way of doing this is by adding the shelljs npm module.
To add npm modules see: https://github.com/meteorhacks/npm
Then you just need to do something like:
var shell = Meteor.npmRequire('shelljs');
var list = shell.ls('/yourfolder');
Shelljs docs:
https://github.com/arturadib/shelljs
The short answer is that FS.Collection creates a Mongo collection that you can treat like any other, i.e., you can list entries using find().
The long answer...
Using cfs:filesystem, you can create a mongo database that mirrors a given folder on the server, like so:
// in lib/files.js
files = new FS.Collection("my_files", {
stores: [new FS.Store.FileSystem("my_files", {"~/test"})] // creates a ~/test folder at the home directory of your server and will put files there on insert
});
You can then access this collection on the client to upload files to the server to the ~test/ directory:
files.insert(new File(['Test file contents'], 'my_test_file'));
And then you can list the files on the server like so:
files.find(); // returns [ { createdByTransform: true,
_id: 't6NoXZZdx6hmJDEQh',
original:
{ name: 'my_test_file',
updatedAt: (Date)
size: (N),
type: '' },
uploadedAt: (Date),
copies: { my_files: [Object] },
collectionName: 'my_files'
}
The copies object appears to contain the actual names of the files created, e.g.,
files.findOne().copies
{
"my_files" : {
"name" : "testy1",
"type" : "",
"size" : 6,
"key" : "my_files-t6NoXZZdx6hmJDEQh-my_test_file", // This is the name of the file on the server at ~/test/
"updatedAt" : ISODate("2015-03-29T16:53:33Z"),
"createdAt" : ISODate("2015-03-29T16:53:33Z")
}
}
The problem with this approach is that it only tracks the changes made through the Collection; if you add something manually to the ~/test directory, it won't get mirrored into the Collection. For instance, if on the server I run something like...
mkfile 1k ~/test/my_files-aaaaaaaaaa-manually-created
Then I look for it in the collection, it won't be there:
files.findOne({"original.name": {$regex: ".*manually.*"}}) // returns undefined
If you just want a straightforward list of files on the server, you might consider just running an ls. From https://gentlenode.com/journal/meteor-14-execute-a-unix-command/33 you can execute any arbitrary UNIX command using Node's child_process.exec(). You can access the app root directory with process.env.PWD (from this question). So in the end if you wanted to list all the files in your public directory, for instance, you might do something like this:
exec = Npm.require('child_process').exec;
console.log("This is the root dir:");
console.log(process.env.PWD); // running from localhost returns: /Users/me/meteor_apps/test
child = exec('ls -la ' + process.env.PWD + '/public', function(error, stdout, stderr) {
// Fill in this callback with whatever you actually want to do with the information
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if(error !== null) {
console.log('exec error: ' + error);
}
});
This will have to run on the server, so if you want the information on the client, you'll have to put it in a method. This is also pretty insecure, depending on how you structure it, so you'd want to think about how to stop people from listing all the files and folders on your server, or worse -- running arbitrary execs.
Which method you choose probably depends on what you're really trying to accomplish.

Resources