How to create a new document in Alfresco via REST API? - alfresco

How to create a certain type of document in Alfresco with using the Rest API. I would like to receive the URL to which to send the request and the list of required parameters. Tried to use http://wiki.alfresco.com/wiki/Repository_RESTful_API_Reference#Create_folder_or_document_.28createDocument.2C_createFolder.29 but it did not work out, because it could not determine which parameters to send to this API

Here are some links to get started with Alfresco + CMIS - These should help to solve your question in general: https://forums.alfresco.com/forum/developer-discussions/alfresco-api/cmis-resources-tutorials-and-examples-03212012-1456

Would use the Rest API, not CIMS
import json
import requests
import os, sys
strUrl = 'http://your.site.com:8080/alfresco/service/api/'
strAuth = ('username', 'password')
strFilename = "somethingtoupload.pdf"
objFile= {'filedata' : open(strFilename,'rb')}
strData={'siteid': 'site','containerid': 'documentlibrary', 'uploaddirectory': 'somefolder'}
result = requests.post (strUrl+'upload',files=objFile,data=strData,auth=strAuth)
print result.status_code

You can create your owen webscript REST and personnalize your processing as you like or you can use this webscript "/api/upload".

To create a document you need to use a query of cmis family. The query looks like:
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>name</title>' +
'<summary>name</summary>' +
'<cmisra:object>' +
'<cmis:properties>' +
'<cmis:propertyId propertyDefinitionId="cmis:objectTypeId">' +
'<cmis:value>type</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
name - document name;
type - document type;
nodeRef - folder id in Alfresco.
To create a document in type specify cmis:document. Other queries you can find here:
http://jazzteam.org/en/technical-articles/list-of-alfresco-services/

def post():
cms_repo_url = current_app.config.get("CMS_REPO_URL")
cms_repo_username =current_app.config.get("CMS_REPO_USERNAME")
cms_repo_password =current_app.config.get("CMS_REPO_PASSWORD")
if cms_repo_url is None:
return {
"message": "CMS Repo Url is not configured"
}, HTTPStatus.INTERNAL_SERVER_ERROR
if "upload" not in request.files:
return {"message": "No upload files in the request"}, HTTPStatus.BAD_REQUEST
contentfile = request.files["upload"]
filename = contentfile.filename
files = {'filedata': contentfile.read()}
if filename != "":
try:
url = cms_repo_url + "1/nodes/-root-/children"
document = requests.post(
url,data = request.form,files= files,auth=HTTPBasicAuth(cms_repo_username, cms_repo_password)
)
return (
(
),
HTTPStatus.OK,
)
except UpdateConflictException:
return {
"message": "The uploaded file already existing in the repository"
}, HTTPStatus.INTERNAL_SERVER_ERROR
else:
return {"message": "No upload files in the request"}, HTTPStatus.BAD_REQUEST

Related

Can't Move DriveItem in Mocrosoft Graph

I am using Python to download PDF files from OneDrive to a local folder, and also moving the files to a different folder in OneDrive after they have been downloaded.
I am able to download the files from OneDrive to a local folder, however, I get a 400 response when trying to move (PATCH) the files to another OneDrive Folder.
Here is my successful code to download the files:
download_url = 'https://graph.microsoft.com/v1.0/me/drive/items/{item-id}/content'
headers = {'Authorization': 'Bearer ' + json_response['access_token']}
download_url_data = requests.get(download_url, headers=headers)
with open('/Users/Name/Folder/file_name, 'wb') as f:
f.write(download_url_data.content)
Here is my unsuccessful PATCH request to move the files:
move_url = 'https://graph.microsoft.com/v1.0/me/drive/items/{item-id}
move_headers = {'Authorization': 'Bearer ' + json_response['access_token'],
'Content-Type' : 'application/json'}
move_body = {'parentReference' : {'id' : '01EV3NG2F6Y2GOVW7775BZO354PUSELRRZ'}}
move_file = requests.patch(move_url, headers=move_headers, data=move_body)
return move_file.status_code
I have followed the documentation here https://learn.microsoft.com/en-us/graph/api/driveitem-move?view=graph-rest-1.0&tabs=http and I have tried different parentReference id's, but no luck.
Please help! Cheers.
What is the response you're getting (the actual content beside the 400 status code)?
I believe that requests.patch should receive it's data as a string, not a dictionary (json).
Try:
move_file = requests.patch(move_url, headers=move_headers, data=json.dumps(move_body))
And of course don't forget to import json

How to retrieve the API Gateway URI upon post

I'm developing a system in a microservices architecture using java8 and Spring Cloud. I implemented a post rest controller that receives an object in json and then saves it in the database. The problem is; how do I get the URI containing the API Gateway of the just saved object so I can return it on the created responde body?
Like, when I use
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(savedProfile.getId()).toUri();
I get http://Boss.mshome.net:8081/profile/1 instead of localhost:8765/nukr-profile-service/profile/1 which is the endpoint with the API Gateway's path.
What's the best practice to retrieve this URI?
So, I came to a solution I just don't know if it's best practice or not.
My post method ended up being like:
#PostMapping("/profile")
public ResponseEntity<Object> createProfile(#Valid #RequestBody Profile profile) {
UriComponents requestComponents = ServletUriComponentsBuilder.fromCurrentRequest().path("").build();
InstanceInfo gatewayService = this.eurekaClient.getNextServerFromEureka(NUKR_API_GATEWAY_SERVICE, false);
Profile savedProfile = this.profileRepository.save(profile);
String uriStr = requestComponents.getScheme() + "://" + gatewayService.getIPAddr() + ":" + gatewayService.getPort() + "/" + this.profileServiceName +
requestComponents.getPath() + "/" + savedProfile.getId();
return ResponseEntity.created(URI.create(uriStr)).build();
}

Is there a way to add a post in wordpress via googlescript?

I have a form in googlescript where I can add a user to a sheet.
Is there a way to implement some lines in that code so the script adds a post on a wordpress page?
I read that it's possible via wp_insert_post , but I have no idea how that works in my case.
EDIT:
As Spencer suggested I tried to do it via WP REST API.
The following code seems to be working .............
function httpPostTemplate() {
// URL for target web API
var url = 'http://example.de/wp-json/wp/v2/posts';
// For POST method, API parameters will be sent in the
// HTTP message payload.
// Start with an object containing name / value tuples.
var apiParams = {
// Relevant parameters would go here
'param1' : 'value1',
'param2' : 'value2' // etc.
};
// All 'application/json' content goes as a JSON string.
var payload = JSON.stringify(apiParams);
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true
};
var response = UrlFetchApp.fetch(url, params)
// Check return code embedded in response.
var rc = response.getResponseCode();
var responseText = response.getContentText();
if (rc !== 200) {
// Log HTTP Error
Logger.log("Response (%s) %s",
rc,
responseText );
// Could throw an exception yourself, if appropriate
}
else {
// Successful POST, handle response normally
Logger.log( responseText );
}
}
But I get the error:
[16-09-28 21:24:29:475 CEST] Response (401.0)
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to
create new posts.","data":{"status":401}}
Means: I have to authenticate first.
I installed the plugin: WP REST API - OAuth 1.0a Server
I setup a new user and got a client key and client user.
But from here I have no clue what to do : /
It is possible. Wordpress has a REST API. I can be found at:
http://v2.wp-api.org/
You will use the UrlFetchApp Service to access this api. Documentation can be found at:
https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app
Read the docs and try to write some code. It you get stuck post the code that is confusing you here and I'll update this answer.
You should add you authentification in the header :
var headers = {
... ,
'Authorization' : 'Basic ' + Utilities.base64Encode('USERNAME:PASSWORD'),
};
And then add your header in your parameters :
var params = {
'method': 'POST',
'headers': headers,
'payload': JSON.stringify(payload),
'muteHttpExceptions': true
}
And then use UrlfetchApp.fetch
var response = UrlFetchApp.fetch("https://.../wp-json/wp/v2/posts/", params)
Logger.log(response);
You need to pass the basic auth, like this:
// Construct `fetch` params object
var params = {
'method': 'POST',
'contentType': 'application/json',
'payload': payload,
'muteHttpExceptions' : true,
"headers" : {
"Authorization" : "Basic " + Utilities.base64Encode(username + ":" + password)+"",
"cache-control": "no-cache"
}
};
thank you for giving me these important links.
<3
I installed WP REST API and the OAuth plugin.
In the documentation is written:
Once you have WP API and the OAuth server plugins activated on your
server, you’ll need to create a “client”. This is an identifier for
the application, and includes a “key” and “secret”, both needed to
link to your site.
I couldn't find out how to setup a client?
In my GoogleScriptCode according to the WP API I get the error:
{"code":"rest_cannot_create","message":"Sorry, you are not allowed to create new posts.","data":{"status":401}}
Edit: I found it - it's under User/Application
I'll try to figure it out and get back to you later.

export excel from extjs grid

I want to export extjs grid content to excel file. So what i have done already:
i send to the servlet json content of the grid through Ext.Ajax.request, like
Ext.Ajax.request({
url : 'ExportToExcel',
method:'POST',
jsonData: this.store.proxy.reader.rawData,
scope : this,
success : function(response,options) {
this.onExportSuccess(response, options);
},
//method to call when the request is a failure
failure: function(response, options){
alert("FAILURE: " + response.statusText);
}
});
Then in servlet i get json in servlet do some stuff, e.g. create excel file, convert it to bytes array and try to put into response.
In Ext.Ajax.request in success method when i try to do something like this:
var blob = new Blob([response.responseText], { type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet});
var downloadUrl = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
it downloads excel file, but when i open it error occurs, saying format or extension is invalid.
WHY??
Whether it may depend on the encoding?
What i'm doing wrong?
Ext comes with an excel exporter built in. You may want to try using that to see if you get the desired results
grid.saveDocumentAs({
type: 'excel',
title: 'My Excel Title',
fileName: 'MyExcelFileName.xml'
});
From the toolkit : Ext.grid.plugin.Exporter

Python post urlencoded from file

When i trying to post data from file
headers = {'content-type': 'text/plain'}
files = {'Content': open(os.getcwd()+'\\1.txt', 'rb')}
contentR = requests.post("http://" + domain +"index.php", params=payload, data=files, headers=headers)
I get something like urlencoded string
Content=%3C%3Fphp+echo%28%22Hello+world%22+%29%3B+%3F%3E
instead of
<?php echo("Hello world" ); ?>
How to post data as is in text file?
If you read the docs closely, you can either use the file object:
headers = {'content-type': 'text/plain'}
file = open(os.getcwd()+'\\1.txt', 'rb')
contentR = requests.post("http://" + domain +"index.php", params=payload, data=file, headers=headers)
Or you can just pass a string with the file contents like so:
file_contents = open(os.getcwd() + '\\`.txt', 'rb').read()
contentR = requests.post("http://" + domain +"index.php", params=payload, data=file_contents, headers=headers)
If you pass a dictionary it will always be urlencoded so that is not what you want to do.

Resources