I have one data webscript at alfresco side which return json response.
i want this json response in share webscript to display that json data on share.
following is the my code written in getLocation.get.js file # share.
var result1 = new Array();
var connector = remote.connect("alfresco");
var data = connector.get("/com/portfolio/ds/getlocation");
// create json object from data
if(data.status == 200){
var result = jsonUtils.toJSONString(eval(data.response));
model.docprop = result ;
}else{
model.docprop = "Failed";
}
Following is the output from alfresco side
{
"subgroups": [
{
"name": "grp_pf_india_user" ,
"label": "INDIA"
},
{
"name": "grp_pf_israil_user" ,
"label": "ISRAIL"
},
{
"name": "grp_pf_usa_user" ,
"label": "USA"
}
]
}
use this code to call repo webscripts from share side by using the concept or RMI. (Alfresco.constants.PROXY_URI) = (http://host:port/share/proxy/alfresco/)
var xurl=Alfresco.constants.PROXY_URI+"HR-webscripts/createHRDocument/"+JSON.stringify(o);
//alert(xurl);
var request = $.ajax({
url: xurl ,
type: "POST",
//data: { "groupname" : o},
beforeSend : function(xhr){
/*
Alfresco.util.Ajax & alfresco/core/CoreXhr – will automatically take the token from the cookie and add it as a request header for every request.
Alfresco.forms.Form – will automatically take the token from the cookie and add it as a url parameter to when submitting an multipart/form-data request.
(When submitting a form as JSON the Alfresco.util.Ajax will be used internally)
*/
if (Alfresco.util.CSRFPolicy && Alfresco.util.CSRFPolicy.isFilterEnabled()){
xhr.setRequestHeader(Alfresco.util.CSRFPolicy.getHeader(), Alfresco.util.CSRFPolicy.getToken() );
}
},
dataType: "html"
});
request.done(function(msg) {
//alert( "Request OK: " + msg );
$("#res").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Related
I want to create a new document in Firestore using the REST API.
Very good examples here using Axios to send the POST request with some fields:
https://www.jeansnyman.com/posts/google-firestore-rest-api-examples/
axios.post(
"https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/<COLLECTIONNAME>",
{
fields: {
title: { stringValue: this.title },
category: { stringValue: this.category },
post: { stringValue: this.post },
summary: { stringValue: this.description },
published: { booleanValue: this.published },
created: { timestampValue: new Date() },
modified: { timestampValue: new Date() }
}
}
).then(res => { console.log("Post created") })
And an example here using Python Requests:
Using the Firestore REST API to Update a Document Field
(this is a PATCH request but the field formatting is the same as in a POST request)
import requests
import json
endpoint = "https://firestore.googleapis.com/v1/projects/[PROJECT_ID]/databases/(default)/documents/[COLLECTION]/[DOCUMENT_ID]?currentDocument.exists=true&updateMask.fieldPaths=[FIELD_1]"
body = {
"fields" : {
"[FIELD_1]" : {
"stringValue" : "random new value"
}
}
}
data = json.dumps(body)
headers = {"Authorization": "Bearer [AUTH_TOKEN]"}
print(requests.patch(endpoint, data=data, headers=headers).json())
I am using Google Apps Script UrlFetchApp.fetch to send my requests. I am able to use GET requests with no problems. For example, to get all the documents in a collection (in Google Apps Script):
function firestore_get_documents(){
var options = {
headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
method:'GET'
}
var response = UrlFetchApp.fetch('https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/myCollection', options);
var parsed = JSON.parse(response.getContentText());
return parsed;
}
This works nicely. And changing 'method' to 'POST' creates a new document in myCollection as expected. Then I try to add a POST body with some fields (or just one field):
function firestore_create_new_document(){
var options = {
headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
method:'POST',
payload: {fields: { title: { stringValue: 'newTitle' } } }, // If you comment out this line, it works as expected
muteHttpExceptions:true
}
var response = UrlFetchApp.fetch('https://firestore.googleapis.com/v1/projects/<PROJECTIDHERE>/databases/(default)/documents/myCollection', options);
var contentText = response.getContentText();
var parsed = JSON.parse(response.getContentText());
return parsed;
}
I get the following errors:
code: 400 message: "Request contains an invalid argument."
status: "INVALID_ARGUMENT"
details[0][#type]: "type.googleapis.com/google.rpc.BadRequest"
details[0][fieldViolations][0][field]: "{title={stringValue=newTitle}}"
details[0][fieldViolations][0][description]: "Error expanding 'fields' parameter. Cannot find matching fields for path '{title={stringValue=newTitle}}'."
Documentation is available here:
https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents/createDocument
https://firebase.google.com/docs/firestore/reference/rest/v1/projects.databases.documents#Document
The problem may be the formatting of my 'fields' object - I've tried several different formats from the documentation and examples
The problem may be that the fields don't exist yet? I think I should be able to create a new document with new fields
The problem may be with the way UrlFetchApp.fetch sends my JSON body. I have tried using payload = JSON.stringify(payload_object) and that doesn't work either.
I think UrlFetchApp is doing something slightly different than Axios or Python Requests - the body is getting sent differently, and not parsing as expected.
How about the following modification?
From:
var options = {
headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
method:'POST',
payload: {fields: { title: { stringValue: 'newTitle' } } }, // If you comment out this line, it works as expected
muteHttpExceptions:true
}
To:
var options = {
headers: { 'Authorization': 'Bearer ' + ScriptApp.getOAuthToken() },
method:'POST',
payload: JSON.stringify({fields: { title: { stringValue: 'newTitle' } } }),
contentType: "application/json",
muteHttpExceptions:true
}
When I tested above modified request, I could confirm that it worked. But if other error occurs, please tell me.
Reference:
Class UrlFetchApp
I'm following the facebook messenger develop QuickStart to create a Node.js project, and I improved it to work in quick reply. Then when I tried the Generic Template and List Template, but it didn't work.
As the following source code, when I input the work "generic" or "list", the messenger should reply me with the template messege. But there was nothing happened.
} else if (received_message.text === 'generic') {
console.log('generic in');
response = {
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome!",
"image_url":"http://webapplication120181023051009.azurewebsites.net/colorcar1.jpg",
"subtitle":"We have the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://www.taobao.com/",
"messenger_extensions": false,
"webview_height_ratio": "tall",
"fallback_url": "https://www.taobao.com/"
},
"buttons":[
{
"type":"web_url",
"url":"https://www.taobao.com/",
"title":"View Website"
},{
"type":"postback",
"title":"Start Chatting",
"payload":"DEVELOPER_DEFINED_PAYLOAD"
}
]
}
]
}
}
}
// Sends the response message
callSendAPI(sender_psid, response);
// Sends response messages via the Send API
function callSendAPI(sender_psid, response) {
// Construct the message body
let request_body = {
"recipient": {
"id": sender_psid
},
"message": response
}
console.log('PAGE_ACCESS_TOKEN:');
console.log(PAGE_ACCESS_TOKEN);
console.log('request body:');
console.log(request_body);
// Send the HTTP request to the Messenger Platform
request({
"uri": "https://graph.facebook.com/v2.6/me/messages?access_token=" + PAGE_ACCESS_TOKEN,
"qs": { "access_token": PAGE_ACCESS_TOKEN },
"method": "POST",
"json": request_body
}, (err, res, body) => {
if (!err) {
console.log('message sent!')
} else {
console.error("Unable to send message:" + err);
}
});
}
Sorry, I forgot to add the url into whiltelist.
I'm trying to send push notifications (at 12 PM the next day) to installations whose "updatedAt" field is not older than two days. Here's the code:
var two_days_ago_date = new Date()
two_days_ago_date.setDate(two_days_ago_date.getDate() - 2)
var push_time = new Date()
push_time.setDate(push_time.getDate() + 1)
push_time.setHours(12)
push_time.setMinutes(00)
push_time = push_time.toISOString()
push_time = push_time.substring(0, push_time.length - 1)
Parse.Cloud.httpRequest({
method: "POST",
headers: {
"X-Parse-Application-Id": "XXX",
"X-Parse-REST-API-Key": "XXX",
"Content-Type": "application/json"
},
body: {
"where":{
"appVersion":"1.4",
"updatedAt" : {"$gte" : two_days_ago_date}
},
"push_time": push_time,
"data": {
"alert":"",
"sound": ""
}
},
url: "https://api.parse.com/1/push"
}).then(function() {
console.log("Successful push");
}, function(error) {
console.log(error);
})
If I remove the restriction the code works fine, otherwise not.
I am trying to make an ajax call using the enyo framework and I am running headlong in to a problem. The error message I am getting is 0. That's it just a 0. I made sure my link to the json file was correct and I built this jsfiddle to test it out http://jsfiddle.net/mmahon512/CPU8n/2/ Any help is greatly appreciated. My host is GoDaddy and I made sure that I added the json extension to my web config correctly. The link to the json file is correct and it returns valid json. I checked it using jsonlint. Here is what the code looks like on jsfiddle:
enyo.kind({
name: "AjaxSample",
components: [
{ kind: "Button", content: "Fetch Users", ontap: "fetch" },
{ name: "repos", content: "Not loaded...", allowHtml: true }
],
fetch: function() {
var ajax = new enyo.Ajax({
url: "http://atxapps.com/_sites/atxapps.com/dev/jetstream/assets/dataUsers.json"
});
ajax.go();
ajax.response(this, "gotResponse");
ajax.error(this, this.gotError);
},
gotResponse: function(inSender, inResponse) {
var output = "";
for(i = 0; i < inResponse.length; i++) {
output += inResponse[i].Id + "";
}
output += Date.now();
this.$.repos.setContent(output);
},
gotError: function(inSender, inError) {
alert(inError);
this.$.repos.setContent(inError + " " + Date.now());
}
});
Looks like a CORS issue. I see the following in the console:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin fiddle.jshell.net is therefore not allowed access.
I wrapped it as a jsonp request successfully.
http://jsfiddle.net/CPU8n/3/
enyo.kind({
name: "AjaxSample",
components: [
{ kind: "Button", content: "Fetch Users", ontap: "fetch" },
{ name: "repos", content: "Not loaded...", allowHtml: true }
],
fetch: function() {
var ajax = new enyo.JsonpRequest({
url: "http://jsonpwrapper.com/?urls%5B%5D=http%3A%2F%2Fatxapps.com%2F_sites%2Fatxapps.com%2Fdev%2Fjetstream%2Fassets%2FdataUsers.json"
});
ajax.go();
ajax.response(this, "gotResponse");
ajax.error(this, this.gotError);
},
gotResponse: function(inSender, inResponse) {
var output = "";
var body = enyo.json.parse(inResponse[0].body); // jsonpwrapper.com wraps the results in a array with an index for each URL. The actual data is in the body param of that index but it isn't parsed (at least in this example)
for(i = 0; i < body.length; i++) {
output += body[i].Id + "<br />";
}
output += Date.now();
this.$.repos.setContent(output);
},
gotError: function(inSender, inError) {
alert(inError);
this.$.repos.setContent(inError + " " + Date.now());
}
});
If you're running this on the same server in prod, you wouldn't see the error (since it's not cross-origin). If it'll be on a different server, you can either convert the server-side to support jsonp or adds the appropriate CORS headers.
I've been pouring over this for hours and I've yet to make much headway so I was hoping one of the wonderful denizens of SO could help me out. Here's the problem...
I'm implementing a tree via the jstree plugin for jQuery. I'm pulling the data with which I populate the tree programatically from our webapp via json dumped into an asp:HiddenField, basically like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(Items);
json = json.ToLower();
data.Value = json;
Then, the tree pulls the json from the hidden field to build itself. This works perfectly fine up until I try to persist data for which nodes are selected/opened. To simplify my problem I've hardcoded some json data into the tree and attempted to use the cookie plugin to persist the tree state data. This does not work for whatever reason. I've seen other issues where people need to load the plugins in a specific order, etc, this did not solve my issue. I tried the same setup with html_data and it works perfectly. With this working persistence I converted the cookie plugin to persist the data in a different asp:hiddenfield (we can't use cookies for this type of thing in our application.)
essentially the cookie operations are identical, it just saves the array of nodes as the value of a hidden field. This works with the html_data, still not with the json and I have yet to be able to put my finger on where it's failing.
This is the jQuery.cookie.js replacement:
jQuery.persist = function(name, value) {
if (typeof value != 'undefined') { // name and value given, set persist
if (value === null) {
value = '';
}
jQuery('#' + name).attr('value', value);
} else { // only name given, get value
var persistValue = null;
persistValue = jQuery('#' + name).attr('value');
return persistValue;
}
};
The jstree.cookie.js code is identical save for a few variable name changes.
And this is my tree:
$(function() {
$("#demo1").jstree({
"json_data": {
"data" : [
{
"data" : "A node",
"children" : [ "Child 1", "Child 2" ]
},
{
"attr": { "id": "li.node.id" },
"data" : {
"title": "li.node.id",
"attr": { "href": "#" }
},
"children": ["Child 1", "Child 2"]
}
]
},
"persistence": {
"save_opened": "<%= open.ClientID %>",
"save_selected": "<%= select.ClientID %>",
"auto_save": true
},
"plugins": ["themes", "ui", "persistence", "json_data"]
});
});
The data -is- being stored appropriately in the hiddenfields, the problem occurs on a postback, it does not reopen the nodes. Any help would be greatly appreciated.
After looking through this some more, I just wanted to explain that it appears to me that the issue is that the tree has not yet been built from the JSON_data when the persistence operations are being attempted. Is there any way to postpone these actions until after the tree is fully loaded?
If anyone is still attempting to perform the same type of operation on a jsTree version 3.0+ there is an easier way to accomplish the same type of functionality, without editing any of the jsTree's core JavaScript, and without relying on the "state" plugin (Version 1.0 - "Persistence"):
var jsTreeControl = $("#jsTreeControl");
//Can be a "asp:HiddenField"
var stateJSONControl = $("#stateJSONControl");
var url = "exampleURL";
jsTreeControl.jstree({
'core': {
"data": function (node, cb) {
var thisVar = this;
//On the initial load, if the "state" already exists in the hidden value
//then simply use that rather than make a AJAX call
if (stateJSONControl.val() !== "" && node.id === "#") {
cb.call(thisVar, { d: JSON.parse(stateJSONControl.val()) });
}
else {
$.ajax({
type: "POST",
url: url,
async: true,
success: function (json) {
cb.call(thisVar, json);
},
contentType: "application/json; charset=utf-8",
dataType: "json"
}).responseText;
}
}
}
});
//If the user changes the jsTree, save the full JSON of the jsTree into the hidden value,
//this will then be restored on postback by the "data" function in the jsTree decleration
jsTreeControl.on("changed.jstree", function (e, data) {
if (typeof (data.node) != 'undefined') {
stateJSONControl.val(JSON.stringify(jsTreeControl.jstree(true).get_json()));
}
});
This code will create a jsTree and save it's "state" into a hidden value, then upon postback when the jsTree is recreated, it will use its old "state" restored from the "HiddenField" rather than make a new AJAX call and lose the expansions/selections that the user has made.
Got it working properly with JSON data. I had to edit the "reopen" and "reselect" functions inside jstree itself.
Here's the new functioning reopen function for anyone who needs it.
reopen: function(is_callback) {
var _this = this,
done = true,
current = [],
remaining = [];
if (!is_callback) { this.data.core.reopen = false; this.data.core.refreshing = true; }
if (this.data.core.to_open.length) {
$.each(this.data.core.to_open, function(i, val) {
val = val.replace(/^#/, "")
if (val == "#") { return true; }
if ($(("li[id=" + val + "]")).length && $(("li[id=" + val + "]")).is(".jstree-closed")) { current.push($(("li[id=" + val + "]"))); }
else { remaining.push(val); }
});
if (current.length) {
this.data.core.to_open = remaining;
$.each(current, function(i, val) {
_this.open_node(val, function() { _this.reopen(true); }, true);
});
done = false;
}
}
if (done) {
// TODO: find a more elegant approach to syncronizing returning requests
if (this.data.core.reopen) { clearTimeout(this.data.core.reopen); }
this.data.core.reopen = setTimeout(function() { _this.__callback({}, _this); }, 50);
this.data.core.refreshing = false;
}
},
The problem was that it was trying to find the element by a custom attribute. It was just pushing these strings into the array to search when it was expecting node objects. Using this line
if ($(("li[id=" + val + "]")).length && $(("li[id=" + val + "]")).is(".jstree-closed")) { current.push($(("li[id=" + val + "]"))); }
instead of
if ($(val).length && $(val).is(".jstree-closed")) { current.push(val); }
was all it took. Using a similar process I was able to persist the selected nodes this way as well.
Hope this is of help to someone.