How to get Alfresco webscript JSON response in JavaScript file - javascript

I'm working on alfresco maven sdk project.
So i have a repo webscript who return a json response template containinng the list of files contained in a specific folder (in my case it's: Espace%20racine/Dictionnaire%20de%20données/Dossier%20Workflow).
The template response.json.ftl is here:
{
"Files" : [
<#list folder.children as child>
<#if child.isDocument>
{
"name" : "${child.name}"
}
<#if child_has_next>,</#if>
</#if>
</#list>
]
}
My webscript works fine, and when i run it through the commande line or the browser, i get a response like:
{
"Files" : [
{
"name" : "test"
}
,
{
"name" : "test2"
}
,
{
"name" : "test3"
}
]
}
Now, i want to invoke my webscript from a javascript file who reside in the folder web of share, but i haven't idea to how achieve this. I searched on the net but i don't find a consistant example to how manage this.
It'll help me lot if anyone can tell me the way to achieve this or take me an example to how achieve this.

Below is the code for making an ajax call in alfresco share.There are other methods also available like Alfresco.util.Ajax.jsonPost,Alfresco.util.Ajax.jsonPut etc..In below console.log(response.json) will print the response in console.
var fnSuccess = function RESPONSE_functionName(response)
{
console.log(response.json)//Here you will get response json.
};
var fnFailure = function RESPONSE_functionName(response)
{
Alfresco.util.PopupManager.displayMessage({text:"Failure"});
};
Alfresco.util.Ajax.jsonGet(
{
url: Alfresco.constants.PROXY_URI + "REPOSITORY_WEBSCRIPT_URL",
successCallback:
{
fn: fnSuccess,
scope: this
},
failureCallback:
{
fn: fnFailure,
scope: this
}
});

Related

JavaScript url in json returns 501 but string url does not

So I have the following problem:
I try to pull data from iCloud using CloudKit (HTTP requests)
The iCloud entity contains a CKAsset and I need the download URL which a POST request to https://api.apple-cloudkit.com/database/1/... returns. However, if I try to download the data from this URL, it returns a 501 error but if I print the URL to the console and paste that into the browser, the browser downloads the file.
It gets even weirder because if I implement the URL I printed to the console directly into the code everything works! I am converting the URL in the JSON response to a string so IDK what's wrong.
CloudKit response:
{ "records" : [ { "recordName" : "xxxxxxxxxxxx", "recordType" : "xxxxxxx", "fields" : { "file" : { "value" : { "fileChecksum" : "AZJ1FbmpL7caqaksfwrFm3586o5+", "size" : 303, "downloadURL" : "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..." }, "type" : "ASSETID" },},} ] }
I shorted the response so that it only contains the relevant stuff.
I tried to get the URL with the following code: var url = data["records"][0]["fields"]["file"]["value"]["downloadURL"];
Already tried with .toString() and var url == "" + data["records"]....
It works if I do var url = "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..." but obviously this is no real solution.
Help is really appreciated!
EDIT:
Here is the code that downloads the file from downloadURL. I'm using a library called zip.js because the file is a zip file (with a different file extension):
zip.createReader(
new zip.HttpReader(url),
function (reader) {
reader.getEntries(async function (entries) {
if (entries.length) {
entries[0].getData(
new zip.TextWriter(),
async function (text) {
reader.close(function () {
// onclose callback
});
},
function (current, total) {
// onprogress callback
}
);
} else {
}
});
},
function (error) {
// onerror callback
}
);
EDIT 2:
I found out something that might be interesting: If I paste the URL directly into the code, status code 200 returns from disk cache. I tried loading the website in incognito mode and I had to reload once to get it working. Because I receive a new download ID on every refresh, it can't cache a status code.
This works if the URL is valid
You need to look in the network tab to see what is the matter. For example the ${f} looks suspicious
const data = {
"records": [{
"recordName": "xxxxxxxxxxxx",
"recordType": "xxxxxxx",
"fields": {
"file": {
"value": {
"fileChecksum": "AZJ1FbmpL7caqaksfwrFm3586o5+",
"size": 303,
"downloadURL": "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..."
},
"type": "ASSETID"
},
},
}]
}
location = data.records[0].fields.file.value.downloadURL;
The code that you have above does work to pull the URL out of the object (run code below). Are you sure that data holds the information in the format you're expecting and that the URL is correct?
var data = { "records" : [ { "recordName" : "xxxxxxxxxxxx", "recordType" : "xxxxxxx", "fields" : { "file" : { "value" : { "fileChecksum" : "AZJ1FbmpL7caqaksfwrFm3586o5+", "size" : 303, "downloadURL" : "https://cvws.icloud-content.com/B/AZJ1Fbmpxxxaxxxxxxx/${f}?xxxxxxxx..." }, "type" : "ASSETID" },},} ] };
// Original
var url = data["records"][0]["fields"]["file"]["value"]["downloadURL"];
// Object notation
var url2 = data.records[0].fields.file.value.downloadURL;
console.log(url);
console.log(url2);
Ok so I found a solution. This has nothing to do with the actual URL, it is fine, but rather the way how zip.js downloads data. It first makes a HEAD request and because the iCloud servers do not support these, it returns 501. The static domains worked because it somehow cached 200 OK, even though 501 returned.
Thank you to everyone for their help!

set processor in $http PUT request not saving proper data

Relatively new to javascript and angular. I'm using an elasticsearch instance to ingest/index different files. The webapp should have the capability to allow the user to upload multiple files, which will then be processed using the ingest processor and indexed into ES. I'm using angular-base64-upload to extract the base64 data. The following is what I've tried so far.
The html:
<div ng-switch-when="upload">
...
<input type="file" ng-model="obj.files" name="files"
base-sixty-four-input multiple>
...
<div ng-show="obj.files.length != 0">
<button class="btn btn-primary" type="submit" ng-click="ingest()">
Index All {{obj.files.length}} Files
</button> <br><br>
</div>
</div>
The javascript ingest() function code in my controller:
//Ingesting multiple files
$scope.obj = {files: []};
$scope.ingest = function () {
$scope.obj.files.forEach(function (file){
var fname = file.filename.replace(/\.[^/.]+$/, "");
var fdata = file.base64;
//Creating the pipeline
console.log('filename is: ' + fname);
$http({
url: 'http://192.168.100.30:9200/_ingest/pipeline/attachment',
method: "PUT",
data: {
"description" : "Indexing files",
"processors" : [
{
"set" : {
"field" : "filename",
"value" : fname
},
"attachment" : {
"field" : "data"
}
}
]
}
})
.then(function(allowed){
//Indexing the document
$http({
url: 'http://192.168.100.30:9200/my_index4/my_type/'+fname+'?pipeline=attachment', //unique ID for every document, ensures that there are no overlaps
method: "PUT",
data: {
"data": fdata
}
})
})
})
}
The console logging is just used for debug purposes.
The issue I'm running into is while elastic stores the file under the proper _id, which in my case is the filename, it does not store the proper field: filename. For instance, if I upload 2 files called hello.txt and world.txt, ES will store both files with hello and world as their respective _ids, but the filename field is often swapped or just generally, incorrect. I've ran the code multiple times to see if there was a pattern, and I can't really seem to find one.
The console.logs show that fname is the proper filename before the first http, after it, and after the second http, which is why I'm confused as to why the set processor is not storing it properly.
I may not have clearly explained the issue very well, as it's kind of convoluted. Let me know if anything needs extra explanation. Thanks!

TypeError: c[a] is undefined in CKEditor

I am loading ckeditor.js file using $.getScript and in callback I am initiating CKEditor. But it is showing an error TypeError: c[a] is undefined. Here is my code. How can I solve this issue?
$.getScript("ckeditor.js", function (data, textStatus, jqxhr) {
if (textStatus == 'success' && jqxhr.status == 200) {
CKEDITOR.replace( 'commentBox',
{
toolbar :
[
{ name: 'basicstyles', items : [ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ] },
{ name: 'paragraph', items : [ 'NumberedList','BulletedList','-','Blockquote'] },
{ name: 'insert', items : [ 'Table','HorizontalRule','SpecialChar' ] },
{ name: 'styles', items : [ 'Styles','Format','Font','FontSize' ] },
{ name: 'colors', items : [ 'TextColor','BGColor' ] }
]
});
}
});
I was getting the same error in similar circumstances.
I checked the formatted source in Chrome and discovered that this was being caused by the Format plugin trying to load its labels from the CKEDITOR.language object.
Turns out I didn't have en-gb included in my build and apparently it won't automatically fall back to straight en. Adding English (United Kingdom) to the build corrected the issues.
Re. https://stackoverflow.com/a/50719171/6462713
I had same issue. I have also loaded all supported languages in "/lang" folder. Basically my issue was - CKEditor isn't identifying properly its own folder path. So I set a CKEDITOR_BASEPATH variable before loading CKEditor.
It's briefly said here: (but there might be other places where it's explained better.) http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.html#.basePath
Therefore implementation will be like this:
<script>
window.CKEDITOR_BASEPATH = 'http://example.com/path/to/libs/ckeditor/';
</script>
In my case i used window.CKEDITOR_BASEPATH = '/app/storereport/ckeditor/';
Then load the main ckeditor.js script. Hope this may help you.
<script type="application/javascript"/>
$(document).ready(function (){
CKEDITOR.replace( 'product_content' ); // ID of element
});
</script>

Meteor collection find() does not retrieve any data

I'm working through a meteor tutorial : https://www.meteor.com/tutorials/blaze/collections
I have a collection defined,
Tasks = new Mongo.Collection("tasks");
I've added two items to it, one directly from meteor mongo command line, and another one using:
Tasks.insert({ text: "Testing JS", createdAt: new Date() });
Here are the results from running db.tasks.find() on the backend:
{ "_id" : ObjectId("559e9569abbb64fe1d5fd89a"), "text" : "Hello world!", "createdAt" : ISODate("2015-07-09T15:38:17.742Z") }
{ "_id" : "obRN8Rcssa9yJqXzA", "text" : "Testing JS", "createdAt" : ISODate("2015-07-09T17:00:13.285Z") }
But when I run Tasks.find({}); on the front end, I get empty result. It just gives me a long JSON but no data from the database.
In meteor, you can view the documents returned by a cursor by calling fetch on it. For example:
console.log(Tasks.find().fetch());
Looking at your code, you are not publishing anything:
if (Meteor.isServer) {
Meteor.publish("tasks", function () {
console.log(Tasks.find());
});
}
needs to be
if (Meteor.isServer) {
Meteor.publish("tasks", function () {
console.log(Tasks.find());
return Tasks.find();
});
}
or just remove it if you use autopublish.
Did you import the .js file of collection in front-end .js ?
import { Tasks } from '/your_path_goes_here/filename_goes_here.js';
If not import it and try below,
Add Publish like
if (Meteor.isServer) {
Meteor.publish('tasks', function task() {
return Task.find({});
});
}
Subscribe it in Front-End .js
Meteor.subscribe('task');

How can I get wikimedia's jquery.i18n plugin to work with external files?

I can't get wikimedia's jquery.i18n plugin to work with external files.
This :
// Localisation
$.i18n.debug = true;
$.i18n().load( {
'fr' : {
'message-hello' : 'bonjour!'
},
'en': '/assets/i18n/en.json'
} );
$.i18n().locale = 'fr';
console.log($.i18n('message-hello'));
is working perfectly. Console says:
Loading messages from: /assets/i18n/en.json jquery.i18n.js:269
bonjour!
but this :
// Localisation
$.i18n.debug = true;
$.i18n().load( {
'fr' : {
'message-hello' : 'bonjour!'
},
'en': '/assets/i18n/en.json'
} );
$.i18n().locale = 'en';
console.log($.i18n('message-hello'));
is not. Console says:
Loading messages from: /assets/i18n/en.json jquery.i18n.js:269
message-hello
What am I missing ?
Here is my /assets/i18n/en.json file :
{
"#metadata": {
"authors": [
"Alice",
"David",
"Santhosh"
],
"last-updated": "2012-09-21",
"locale": "en",
"message-documentation": "qqq",
"AnotherMetadata": "AnotherMedatadataValue"
},
"appname-title": "Example Application",
"appname-sub-title": "An example application with jquery.i18n",
"appname-header-introduction": "Introduction",
"appname-about": "About this application",
"appname-footer": "Footer text",
"message-hello": "hello!"
}
EDIT : If i do $.i18n('message-hello') from the console, it works. Could this be because the json file is not yet loaded when I call $.i18n('message-hello') from my script ? And if so, how can I tell the script to wait until it is ?
OK so it seems that when I call console.log($.i18n('message-hello'));, the JSON file has not been loaded yet. The workaround I've found is to use the done() method and wrap all my other code inside.
$.i18n.debug = true;
$.i18n().locale = 'en';
$.i18n().load( {
'fr' : {
'message-hello' : 'bonjour!'
},
'en': '/assets/i18n/en.json'
}).done( function() {
// All my other JS code
});
If someone has a better solution, I'll take it.

Categories

Resources