mxGraph shows grid, but does not show images - javascript

I'm using the mxGraph to develop a drawable area in a web page.
This is a legacy code and I'm trying to understand it, because the area is not showing any images besides a grid.
Here is my javascript code to show a simple diagram
//define a window to show the image and put a grid as background
container.style.background = 'url("js/src/images/grid.gif")';
//some other definitions here
var model = new mxGraphModel();
var graph = new mxGraph(container, model);
var id = _GET("id");
mxUtils.post("../Diagram",
"action=get&id="+id,
function(req)
{
var node = req.getDocumentElement();
var dec = new mxCodec(node.ownerDocument);
dec.decode(node, graph.getModel());
},
function(error){
console.log("Error in the design area");
console.log(error);
});
The ../Diagram is a servlet Java that you can see below:
try {
BufferedReader buffRead = new BufferedReader(new FileReader("/home/glassfish/mySite/Repository/"+getId()+"/"+getName()+".txt"));
String line = "";
while (true) {
if (line != null) {
file = line;
} else {
break;
}
line = buffRead.readLine();
}
buffRead.close();
} catch(Exception e) {
System.out.println("File not found");
}
return file;
The returned XML (file) is like below:
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="2" parent="1" style="shape=ellipse;fillColor=#33CCFF" value="Objective" vertex="1">
<mxGeometry as="geometry" height="40" width="100" x="262" y="90"/>
</mxCell>
</root>
However, the result in the screen is always the grid only
When I debug the line dec.decode(node, graph.getModel()); to see the node value I got a XML Object that contains the info returned by Java.
In Chrome I don't receive any message in the console, but when I test it in Firefox I receive an warning saying that I have a "XML parsing error in the file graph.properties", but this file is not a XML (actually, I don't know what is this file). I'm also pasting the file here
graph.properties
alreadyConnected=Nodes already connected
containsValidationErrors=Contains validation errors
updatingDocument=Updating Document. Please wait...
updatingSelection=Updating Selection. Please wait...
collapse-expand=Collapse/Expand
doubleClickOrientation=Doubleclick to change orientation
close=Close
error=Error
done=Done
cancel=Cancel
ok=OK
UPDATE
I still have not solved the problem, but I got a new evidence.
When I debug the dec.decode(node, graph.getModel()); line, I have two properties for the dec variable. A XMLDocument and also a empty array. I think that the problem could be in the encoding part, but I not found any tip in the page about mxCodec.

I finally found a solution to the problem.
The error was in the Javascript part, but I don't know why the console did not show any problem. Anyway, replace the original success function for the code below solves the problem.
function(req)
{
var doc = req.getDocumentElement();
var codec = new mxCodec(doc);
var elt = doc.firstChild;
var cells = [];
while (elt != null)
{
cells.push(codec.decode(elt));
elt = elt.nextSibling;
}
graph.addCells(cells);
}

Related

Extracting images from RSS/Atom feeds

I'm wondering how to extract images from RSS and Atom feeds so I can use them as a thumbnail when display the feed in a container with it's relative Title, Description and Link. So far my code, (shown below), grabs images from only certain feed types, I'm wondering how I can grab every image my script comes across.
if (feed_image_type == "description") {
item_img = $($(this).find('description').text()).find("img").attr("src");
} else if (feed_image_type == "encoded") {
item_img = $($(this).find('encoded').text()).find("img").attr("src");
} else if (feed_image_type == "thumbnail") {
item_img = $(this).find('thumbnail').attr('url');
} else {
item_img = $(this).find('enclosure').attr('url');
}
For example, I cannot figure out how I would grab the image link from the code rss feed snippet below:
<description>
<![CDATA[
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p>Read more...</p>
]]>
</description>
Using these sources:
parse html inside cdata using jquery or javascript
jQuery.parseXML
https://www.w3schools.com/xml/dom_cdatasection.asp
It is essential that you get your content correctly as XML, by setting the dataType to 'xml'.
This code is self-contained and works:
var xmlString = '<Customer><![CDATA[ <img src="y1" /> ]]></Customer>';
var xmlObj = $.parseXML(xmlString);
var cdataText = xmlObj.firstChild.firstChild.textContent;
var jqueryObj = $(cdataText);
var imgUrl = jqueryObj.find('img').attr('src');
console.log(imgUrl);
This is slightly imprecise because you don't give quite enough information to exactly reproduce your situation. I will start as though this from your question is the only part of your code:
if (feed_image_type == "description") {
item_img = $($(this).find('description').text()).find("img").attr("src");
}
This ought to get close:
if (feed_image_type == "description") {
var cdataText = $(this).firstChild.firstChild.textContent;
var jqueryObj = $(cdataText);
item_img = jqueryObj.find('img').attr('src');
}
You can also try this.
let str = `<description>
<![CDATA[
<img src="https://i.kinja-img.com/gawker-media/image/upload/s--E93LuLOd--/c_fit,fl_progressive,q_80,w_636/hd6cujrvf1d72sbxsbnr.jpg" /><p>With a surprise showing of skill and, at one point, a miracle, the bottom-ranked team in the European <em>League </em>Championship Series will not end the summer winless.<br></p><p>Read more...</p>
]]>
</description>`;
//We need to strip CDATA in our case. Otherwise the parser will not parse the contents inside it.
str = str.replace("<![CDATA[", "").replace("]]>", "")
let parser = new DOMParser();
let xmlDoc = parser.parseFromString(str,"text/xml");
let images = [...xmlDoc.querySelectorAll('img')].map(image=>image.getAttribute('src'))

Convert hexadecimal string to Blob and display PNG image with AngularJS

I got a web page (I/m using angularjs 1.4.8) and I'm trying to show an image which comes from my GET url request.
Here is the page code (I got a grid and I/m displaying previews if they are applicable):
<div ng-show="message.message == null && message.is_image != null">
<a href="#" ng-click="downloadFile(message.id_message)">
<img data-ng-src="data:image/{{message.image_resolution}};base64,{{message.image_preview}}"/>
</a>
</div>
So, I got cassandra DB with this blob field and my Json looks like:
created_date:"2017-03-31 22:05:42.284Z"
id_message:"e6e2a5cb-ec25-472f-a59b-3f16a3a8afa9"
id_user_link:"47ed65bf-5520-4901-88c8-01980ffbcd4d"
id_user_sent:"3495c2de-c93c-4323-8e48-1fcecbfde625"
image_length:174443
image_name:"5.png"
image_preview:"0x89504e470d0a1a0a0000000d49484452000007800000039a080600000079a04f28000038714944415478daecd9496e55570045d13bfff124d442c654016320c4d4219832046308a132087199c26ba4f1fed65ad29ec0e99e71ec97635392244992244992244992b4f90d23489224499
...
... some other 90 lines of symbols
...
00000108401d8006c0096244906600000000008c2006c0036004b922403300000000004610036001b802549920118000000008230001b800dc09224c9000c000000004118800dc00660499264000600000080200cc0066003b024493200030000004010066003b001589224198001000000200803b001d8002c49920cc000000000108401d8006c0096244906600000000008c2006c0036004b92a4ff95fe0ffc7d46dd1b63a2b10000000049454e44ae426082"
image_resolution:"png"
is_image:1
message:null
But I have no images in my web page (only icon of broken link to image):
I researched
Angularjs showing image blob
Display blob image in html with angularjs
AngularJS - Show byte array content as image
but this won't help.I tried some varieties of this code:
page:
<img data-ng-src="data:image/{{message.image_resolution}};base64,{{b64encoded(message.image_preview)}}"/>
js:
$scope.b64encoded = function(image_preview){
//btoa(String.fromCharCode.apply(null, response.data[0].ClassImage.data));
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|file|ftp|blob):|data:image_preview\//);
return btoa(String.fromCharCode.apply(null, image_preview));
}
RESOLVED
Finally, that was not the issue about AngularJS or blob - that was a Java issue:
byte[] previewSizeByte = baos.toByteArray(); and I stored this one as blob, so, now I got a text field and my Java code looks like (I decided to use BufferedImage for preview):
String base64String = imgToBase64String(preview, fileFormat);
and
private String imgToBase64String(BufferedImage preview, String fileFormat) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(preview, fileFormat, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
I really appreciate stackoverflow members for their comments and answers, they were extremely helpful
It appears that the CassandraDB is sending the image data as a hexadecimal string. It would be more efficient to send it as a base64 string and it would be easier to use.
Here is a function to convert a hexadecimal string to an image/png Blob and display the image:
angular.module("myApp",[]).controller("myVm", function($scope) {
var vm = $scope;
var testHex =
["0x89504e470d0a1a0a0000000d494844520000003c00000028040300000050",
"9584cc0000001b504c5445000000ffffff1f1f1f7f7f7f3f3f3f9f9f9f5f",
"5f5fdfdfdfbfbfbf2cb790f6000000097048597300000ec400000ec40195",
"2b0e1b000000b749444154388ded90cf0a83300cc63faaf5394a5defc56c",
"ee2a0c760e2a3b0b6e3ec7c0175f5aff1e77da657ea40dcd2ff90a010efd",
"9772a2f3f6ea4b830e121915b1a04e859999066a4b1801562dec544c3d36",
"cc723506ac9791809538f564af54055c33f8861d76d0cacfd30efc9450c3",
"b0e20189e28847aac5397458b7e2175d4cde4ed37252cff7d83ce367c849",
"b56014ecf638fa28bf62cd49b7c3e9a384f86764269cbde5bf665b969230",
"31adb25feffdd02ff50109f91bbd7897f34a0000000049454e44ae426082"]
.join('');
vm.hex = testHex;
vm.imgUrl = URL.createObjectURL(toPngBlob(testHex));
function toPngBlob(str){
var hexStr = str.slice(2);
var buf = new ArrayBuffer(hexStr.length/2);
var byteBuf = new Uint8Array(buf);
for (let i=0; i<hexStr.length; i+=2) {
byteBuf[i/2] = parseInt(hexStr.slice(i,i+2),16);
}
var blob = new Blob([byteBuf], {type: "image/png"});
return blob;
};
});
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app="myApp" ng-controller="myVm">
<h1>Convert hex string to PNG Blob</h1>
{{hex}}<br>
{{imgUrl}}<br>
<img ng-src="{{imgUrl}}">
</body>

actuate.Parameter is not a constructor

I am integrating JSF with Birt report and able to connect with IHub server from Java code. Also got all the reports file inside some particular folder and displaying the report file name it into the JSF Datalist .Now when anyone will click on report file name i am calling a JavaScript method which will display the parameters required for report generation and using below code
function displayParams(reportName) {
prmRptName = reportName;
param = new actuate.Parameter("panel");
console.log("Display Params"+param);
alert(param);
document.getElementById("reportsForm1:reportsTable").style.display = 'none';
param.setReportName("Applications/Sure Project/Report Designs/"
+ prmRptName);
param.submit(function() {
document.getElementById("backbutton").style.visibility = 'visible';
document.getElementById("run").style.visibility = 'visible';
});
// console.log("Display Params");
}
but this line of code
param = new actuate.Parameter("panel");
throwing exception
actuate.Parameter is not a constructor
Any idea what i am doing wrong . here panel is a id of DIV component which is inside the XHTML page
Issue is resolve ,cause of problem is Birt Server URL
i was trying this code
function initReportExplr() {
actuate.load("viewer");
actuate.load("parameter");
var reqOps = new actuate.RequestOptions();
actuate.initialize("http://locahost:8700", reqOps,
"administrator", "", "");
}
while it should be like this
function initReportExplr() {
actuate.load("viewer");
actuate.load("parameter");
var reqOps = new actuate.RequestOptions();
actuate.initialize("http://locahost:8700/iportal", reqOps,
"administrator", "", "");
}

cannot get xmlDoc to load any value. Keep getting null values

I have an xml file that I retreive via terminal emulation. I want to parse the results into a textarea in html. I am able to view the file in the textarea in xml format but have been unable to parse it into lines of the inner text.
Here is the javascript/jquery:
var x = ""
var y = ""
var Command="";
var cmd=""
$(document).ready(function() {
alert('jquery working');
$('#tester').click(function() {
$("#disptext").val("");
var APOresp = new ActiveXObject("DAT32COM.TERMINALEMULATION");
var Command = "<FORMAT>>*IA</FORMAT>";
APOresp.MakeEntry(Command);
//APOresp.GetMore(true,false);
var x = APOresp.ResponseXML;
APOresp.Close();
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(x);
$(x).find('RESPONSE').each(function() { //these lines do not work. I get null xmlDoc reference
$("#disptext").val($(this).text() + "<br />");
});
//$("#disptext").val(xmlDoc.xml); //disptext is the textarea
});
Here is what a portion of the text file looks like:
?xml version="1.0"?>
<!--This is a host terminal response-->
<RESPONSE xmlns="x-schema:C:\fp\swdir\Content\emulation-schema.xml">
<LINE INDEX="1"><![CDATA[SIGN IN ]]><CARRIAGE_RETURN/></LINE>
<LINE INDEX="2"><SOM/></LINE>
</RESPONSE>
Most files are much longer.
I want to get the text for each "LINE: tag and loop it into the textarea. It does put in the whole xml file in xml format if I use the last commented out line in the javascript file. For some unknown reason, I am unable to use the xmlDoc. I keep getting errors that the xmlDoc has null values. I have been trying to fix this for a number of days without success. Any help would be greatly appreciated.

Javascript JSON object acess error

I've recently been working on a phonegap application using JSONP to create a dynamic feel. I have however recently hit a bit of a brick wall...
The following function is used to parse some delivery data (irrelevant) into jquery mobile:
function parseProdData(results) {
var html = '';
for (day in results.deliveries) {
var today = results.deliveries[day].delivery;
var today_date_arr = today.date.split('-');
var today_date = today_date_arr[2]+'/'+today_date_arr[1]+'/'+today_date_arr[0];
html += '<li><a href="#">';
html += today.delivery_day+', '+today_date;
html += '</a></li>';
console.log(html);
}
$('#JSON-list').append(html);
$('#JSON-list').trigger('create');
$('#JSON-list').listview('refresh');
}
Now all this looks like its working fine as when I check the console log I get:
<li>Thursday, 27/02/2014</li><li>Friday, 28/02/2014</li><li>Monday, 03/03/2014</li><li>Tuesday, 04/03/2014</li><li>Wednesday, 05/03/2014</li><li>Thursday, 06/03/2014</li><li>Friday, 07/03/2014</li>
Thus showing that it is accessing both the date and time attributes correctly. However, straight after this I get an uncaught type error:
Uncaught TypeError: Cannot read property 'date' of undefined
From my understanding of JS this should only happen when the relevant attribute is unset. As we can see from the html output in console, this is not the case as it is being accessed correctly.
Finally, I get exactly the same error (with delivery_day as the 'undefined' attribute) if I restrict the code to just the delivery day.
For those who would like it, below is a sample of the JSON code used:
{
"deliveries":[
{
"delivery":{
"delivery_day":"Thursday",
"date":"2014-02-27"
}
},
{
"delivery":{
"delivery_day":"Friday",
"date":"2014-02-28"
}
}
]
}
Does anyone have any idea why this error is popping up?
*EDIT*
Just to say, I'm fairly confident that the error is in the top part rather than the JQuery mobile elements as if I comment out the block $('#JSON-list').append(html); with $('#JSON-list').append(<li>Thursday, 27/02/2014</li><li>Friday, 28/02/2014</li>); then it works fine, but thats obviously not a solution.
*EDIT 2*
The issue was just that there was an empty element at the end of the 'deliveries' block, this was causing the uncaught error. I didn't notice it because the element was empty. Credit to #eithedog for pointing me in the right direction
I saved json data in result.json file then used this
$.getJSON('result.json', function(result, status){
var today = result.deliveries;
var html = "";
$.each(today, function(key, value){
$.each(value, function(key, value){
var today_date_arr = value.date.split('-');
var today_date = today_date_arr[2]+'/'+today_date_arr[1]+'/'+today_date_arr[0];
html += '<li>'+value.delivery_day+', '+today_date+'</li>';
})
})
$('#JSON-list').append(html);
$('#JSON-list').trigger('create');
$('#JSON-list').listview('refresh');
})
.success(function(result) {})
.fail(function(jqXHR, textStatus, errorThrown) {
})
.complete(function() { });
The issue was just that there was an empty element at the end of the 'deliveries' block, this was causing the uncaught error. I didn't notice it because the element was empty.
Credit to #eithedog for pointing me in the right direction.

Categories