XML Parsing in Alfresco via Javascript - javascript

I want to define a rule in Alfresco -will be a Javascript file- which will get a property of an uploaded XML document and assign that property as a title to that XML document. For instance, the xml file's (myXml) content will be something like this:
<phoneEntry>
<name>John Smith</name>
<phoneNumber>435522</phoneNumber>
</phoneEntry>
I will change the title of xml file to John Smith by the rule. I don't know how to write this rule in Javascript. I have been told that Alfresco uses E4X library. Any help will be appreciated.

Ok, I have found the solution by myself. I hope this helps someone.
var docXml = new XML(document.content);
document.name = docXml.phoneEntry.name;

Share Side Javascript File
var myConfig = new XML();
var configNodeRef = getConfigNodeRef("Data%20Dictionary/Configurations/solution_data.xml");
if (configNodeRef != null) {
logger.log("create new configNodeRef: " + configNodeRef);
var configContent = getConfigContent(configNodeRef);
if (configContent != null && configContent != "") {
try
{
myConfig = new XML(configContent);
}
catch (e)
{
logger.log(e);
}
}
}
model.configNodeRef = configNodeRef;
Shre Side Ftl File.
{
"result" : "<#list result as r>${r.label}<#if r_has_next>,</#if></#list>"
}
Portion Of Xml File
<Human_Resources label="Human_Resources">
<Human_Capital_Management label="Human_Capital_Management" />
<Payroll label="Payroll" />
<Talent_Management label="Talent_Management" />
<HR_Service_Delivery label="HR_Service_Delivery" />
</Human_Resources>
<Information_Technology label="Information_Technology">
<SAP_NetWeaver label="SAP_NetWeaver" />
<Service_Oriented_Architecture label="Service_Oriented_Architecture" />
<Enterprise_Mobility label="Enterprise_Mobility" />
<Cloud_Computing label="Cloud_Computing" />
<SAP_HANA_and_In_Memory_Computing label="SAP_HANA_and_In_Memory_Computing" />
<Content_and_Collaboration label="Content_and_Collaboration" />
<IT_Management label="IT_Management" />
<Custom_Development label="Custom_Development" />
<Database label="Database" />
<SAP_Application_Interface_Framework label="SAP_Application_Interface_Framework" />
</Information_Technology>
Above example is created in alfresco share for reading xml file from alfresco repository.

Related

Javascript type error - The "listener" argument must be of type Function. Received type object

I am trying to create a URL shortener using jsonbase.com and vanilla javascript.
button tag in HTML was not able to recognize the method "shortUrl" from my js file. So, I directly added the code of add event listener in the js file.
index.html
<body>
<div id="app">
<input type="url" id="urlinput">
<input id="mybutton" type="button" value="Short the URL"/>
</input>
</div>
<script src="src/index.js"></script>
</body>
Now, I am getting an error - Javascript type error - The "listener" argument must be of type Function. Received type object - when I am trying to use jsonbase.com for storing the data.
script.js
function shortUrl() {
var longurl = getURL();
genHash();
var uniqueHash = window.location.hash.substr(1);
sendRequest(longurl, uniqueHash);
if (window.location.hash !== "") {
var short = getRequest(uniqueHash);
if (short !== "") {
window.location.herf = "short";
}
}
}
use of jsonbase.com
var jsonbase = require("jsonbase.com");
var token = "mytoken";
var store = jsonbase(token);
var endpoint = `jsonbase.com/${token}`;
//sending request
function sendRequest(longURL, uniqueHash) {
store.write(`${endpoint}/${uniqueHash}`, longURL);
}
//getting request
function getRequest(uniqueHash) {
return store.read(`${endpoint}/${uniqueHash}`).then((response) => {
return response.data;
});
}
generating hash for shorter
function genHash() {
if (window.location.hash === "") {
window.location.hash = getRandomStr();
}
}
Error screenshot -
I have created a reproducible sample code sandbox for my private application - https://codesandbox.io/s/url-shortner-t3ov2
Please let me know if any more info is required.
The issue is not your code, the issue is the package not parsing the JSON correctly, try using a different package
I know this does not answer your question, but it should solve it

XMLHttpRequest ::ERR_CONNECTION_RESET while uploading large (2 Mo & More) files

Problem
I'm trying to upload file using XMLHttpRequest and it seems to work only with small file (such as under 2MO of size). I tried many things so far and came to code shown at the end of the post. But, there is nothing to do; I keep getting the ::ERR_CONNECTION_RESET error. It is not a code issue as under 2MO files are getting unploaded correctly... What am I forgetting? I know this is probably a IIS or web.config issues but I can put my finger on it by googling this problem.
Error given by Chrome
POST WEBSITEANDSERVICEURL/Service/MyService.asmx/UploadFilesWithAJAX net::ERR_CONNECTION_RESET
handleFileSelect
x.event.dispatch
v.handle
Javascript
<script type="text/javascript">
$(function() {
$('#<%= files.ClientID %>').change(handleFileSelect);
});
function handleFileSelect(e) {
if (!e.target.files || !window.FileReader) return;
var fd = new FormData();
var file = document.getElementById("<%= files.ClientID %>");
for (var i = 0; i < file.files.length; i++) {
fd.append('_file', file.files[i]);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', '<%= ResolveURL("~/Services/MyService.asmx/UploadFilesWithAJAX") %>', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
};
xhr.upload.addEventListener("progress", updateProgress, false);
xhr.send(fd);
}
function updateProgress(oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
$("#progress").text(oEvent.loaded + " ON " + oEvent.total);
}
}
</script>
HTML Markup
<asp:FileUpload ID="files" runat="server" multiple="true" />
<br />
<table id="selectedFiles">
</table>
<span id="progress"></span>
MyService.asmx
<ScriptService()> _
<ToolboxItem(False)> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
Public Class AJAXServices : Inherits WebService
<WebMethod(EnableSession:=True)> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Xml)> _
Public Function UploadFilesWithAJAX()
' Some code which work fine, I'm sure of it.
End Function
End Class
Web.config
<!-- [...] -->
<system.web>
<httpRuntime maxRequestLength="2097151" executionTimeout="180" /><!-- MAXIMUM DURING TESTING -->
<!-- [...] -->
</system.web>
<!-- [...] -->
Ok, I solved it...
Solution
If this happen to someone else, be sure to at least access to Context.Request.Files once in your WebService.
Because, during my tests, I was simply :
Public Function UploadFilesWithAJAX()
Return "RETURN SOMETHING"
End Function
But it was not enough... If I only access to Context.Request.Files like :
Public Function UploadFilesWithAJAX()
Dim files = Context.Request.Files '<---- Simply adding this... make it works :|
Return "RETURN SOMETHING"
End Function
It works.
Hope it helps someone else.
By the way, if someone can explain me why it is working by doing this.
In your web config, you defined maxRequestLength="2097151" which is around 2mb, for this reason if you try to upload files more than 2mb it will fail eventually.
Example config below( it will allow up to 2gb )
<httpRuntime maxRequestLength="2048576000" executionTimeout="300" />

how to Convert a var to xml content using jquery

I am currently working with Jquery and my entire project needs to be done only using sharepoint Client Object Model (so i cant make use of server side coding). I have created a xml structure (by appending some string together) and stored it in a jquery var variable. Now my variable content looks like this
<Collection xmlns="http://schemas.microsoft.com/collection/metadata/2009"
xmlns:ui="http://schemas.microsoft.com/livelabs/pivot/collection/2009"
SchemaVersion="1" Name="listname">
<FacetCategories>
<FacetCategory Name="Title" Type="String" />
<FacetCategory Name="Created By" Type="String" />
<FacetCategory Name="Modified By" Type="String" />
</FacetCategories>
<Items ImgBase="http://460d87.dzc">
<Item Id="0" Img="#0" Name="Name1" Href="http://site/1_.000">
<Facets>
<Facet Name="Title">
<String Value="Name1" />
</Facet>
</Facets>
</Item>
</Items>
</collection>
I want to convert this variable in to xml content purely based on jquery.I have used ParseXml() Method but i'm not able to see the output in alert(). Please help me out with this.
Just use native built-in XML parser:
var parser, xml;
if (window.DOMParser) {
parser = new DOMParser();
xml = parser.parseFromString(str, "text/xml");
}
else { // IE
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = "false";
xml.loadXML(str);
}
var nodes = xml.getElementsByTagName('FacetCategory');
var i, l = nodes.length, items = [];
for (i = 0; i < l; i++) {
console.log(nodes[i].getAttribute('Name'));
}
http://jsfiddle.net/QqtMa/
Your xml is invalid, your root element is Collection but the closing tag is collection with small c, so the parser is failing

Image size validation

is it possible to validate file image size with jquery class orjavascript ?
Can i do that ? I made some research but did not reach anything
Thank you
If you want to check image file being uploaded on client side, check HTML5 File API. Here are some samples at:
http://www.html5rocks.com/en/tutorials/file/dndfiles/
You can get file size, find it's type and access binary content.
I was using File API to read EXIF headers from image without uploading image to server.
Here is a source code:
https://gist.github.com/980275/85da4a96a3bb23bae97c3eb7ca777acdea7ed791
Try this:
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="Size()" />
Script:
function Size() {
if ( $.browser.msie ) {
var a = document.getElementById('loadfile').value;
$('#myImage').attr('src',a);
var imgbytes = document.getElementById('myImage').fileSize;
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}else {
var fileInput = $("#loadfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}
}

Translation in JavaScript like gettext in PHP?

I am using gettext in my PHP code, but I have a big problem. All my JavaScript files are not affected by the translation, can somebody tell me an easy way to get the translations in the chosen language into JavaScript as well.
The easiest way is having a PHP file write the translations from gettext into JavaScript variables.
js_lang.php:
word_hello = "<?php echo gettext("hello"); ?>"
word_world = "<?php echo gettext("world"); ?>"
word_how_are_you = "<?php echo gettext("how_are_you"); ?>"
and then include it:
<script type="text/javascript" src="js_lang.php"></script>
I would also recommend this method in conjunction with the translation plugins S.Mark mentions (which are very interesting!).
You can define the dictionary in the current page's header, too, without including an external file, but that way, you would have to look up and send the data on every page load - quite unnecessary, as a dictionary tends to change very rarely.
I generally export the translations in a JavaScript structure:
var app = {};
var app.translations = {
en: {
hello: "Hello, World!",
bye: "Goodbye!"
},
nl: {
hello: "Hallo, Wereld!",
bye: "Tot ziens!"
}
};
The current language of the page texts can be defined using: <html xml:lang="en" lang="nl">
This can be read in JavaScript:
var currentLanguage = document.documentElement.lang || "en";
app.lang = app.translations[ currentLanguage ] || app.translations.en;
And then you can write code like this:
alert( app.lang.hello );
Optionally, a i18n() or gettext() function can bring some intelligence, to return the default text if the key does not exist). For example:
function gettext( key )
{
return app.lang[ key ] || app.translations.en[ key ] || "{translation key not found: " + key + "}";
}
Try, jQuery i18n or jQuery localisation
An example for jQuery i18n, and of course you need to generate JSON based dictionary from language file from php
var my_dictionary = {
"some text" : "a translation",
"some more text" : "another translation"
}
$.i18n.setDictionary(my_dictionary);
$('div#example').text($.i18n._('some text'));
JSGettext (archived link) is best implementation of GNU gettext spec.
First download JSGETTEXT package and include in your page
/js/Gettext.js
<?php
$locale = "ja_JP.utf8";
if(isSet($_GET["locale"]))$locale = $_GET["locale"];
?>
<html>
<head>
<link rel="gettext" type="application/x-po" href="/locale/<?php echo $locale ?>/LC_MESSAGES/messages.po" />
<script type="text/javascript" src="/js/Gettext.js"></script>
<script type="text/javascript" src="/js/test.js"></script>
</head>
<body>
Test!
</body>
</html>
javascript code for example
window.onload = function init(){
var gt = new Gettext({ 'domain' : 'messages' });
alert(gt.gettext('Hello world'));
}
For reference find below link. It's working fine without converting .js file to .php.
Click here
You can make your life much easier if you get rid of bad habit to use string literals in your code. That is, instead of
alert("Some message")
use
alert($("#some_message_id").text())
where "#some_message_id" is a hidden div or span generated on the server side.
As a further hint there's a perl script called po2json which will generate json from a .po file.
For JavaScript implementation of GNU gettext API these links can be also useful:
http://tnga.github.io/lib.ijs
http://tnga.github.io/lib.ijs/docs/iJS.Gettext.html
//set the locale in which the messages will be translated
iJS.i18n.setlocale("fr_FR.utf8") ;
//add domain where to find messages data. can also be in .json or .mo
iJS.i18n.bindtextdomain("domain_po", "./path_to_locale", "po") ;
//Always do this after a `setlocale` or a `bindtextdomain` call.
iJS.i18n.try_load_lang() ; //will load and parse messages data from the setting catalog.
//now print your messages
alert( iJS.i18n.gettext("messages to be translated") ) ;
//or use the common way to print your messages
alert( iJS._("another way to get translated messages") ) ;
This library seems the best implementation of getText in javascript:
http://messageformat.github.io/Jed/
https://github.com/messageformat/Jed
example from the documentation:
<script src="jed.js"></script>
<script>
var i18n = new Jed({
// Generally output by a .po file conversion
locale_data : {
"messages" : {
"" : {
"domain" : "messages",
"lang" : "en",
"plural_forms" : "nplurals=2; plural=(n != 1);"
},
"some key" : [ "some value"]
}
},
"domain" : "messages"
});
alert( i18n.gettext( "some key" ) ); // alerts "some value"
</script>

Categories