i want to call the node/nest api in crafter cms - node.js

iam trying to call the nest/node api in crafter cms but it is throwing errors
1)This is my Groovy controller code
import groovy.json.JsonSlurper
def apiUrl = "http://localhost:3000/"
def json = new URL(apiUrl).text //assuming it's json
def object = new JsonSlurper().parseText(json)
templateModel.myObject
2)This is my ftl code
<#import "/templates/system/common/crafter.ftl" as crafter />
<#assign x = contentModel.name_s!"" />
<#crafter.h1>${myObject.x}<#crafter.h1 />
3)after saving the above codes iam getting this error
!(https://i.stack.imgur.com/XQb7f.png)

Is the response at http://localhost:3000/ the following URL JSON?
If not, trying to parse it is going to throw an error.
Also, in your Freemarker template you have an error here:
<#crafter.h1>${myObject.x}<#crafter.h1 />
Since you assigned contentModel.name_s to x, this should simply be:
<#crafter.h1>${x}<#crafter.h1 />
Assuming the response from Node is JSON, and for the sake of the example, let's say it looks like this:
{ mySum: 42, myMessage: "Hello World", theBest: "CrafterCMS" }
Then you can use these values in your freemarker template with:
${myObject.mySum}
myObject is available in the template as myObject because you added it to the template in the controller.

This is my JSON data:
{
"_id": "632833ecf89459939bd47dd5",
"name": "Random Blood Sugar",
"price": 350,
"description": "Random Blood SugarTimely screening can help you in avoiding illnesses and with Healthians Random Blood Sugar you can keep a track of your health in the best way because Healthians is India's leading health test # home service with more than 20 lac satisfied customers across 140+ cities.",
"imgURL": "https://i0.wp.com/post.healthline.com/wp-content/uploads/2021/10/blood-test-sample-tube-1296-728-header.jpg?w=1155&h=1528",
"__v": 0
},
This is my ftl code:
<#import "/templates/system/common/crafter.ftl" as crafter />
<!doctype html>
<html lang="en">
<head>
<#-- Insert your head markup here -->
<#crafter.head />
</head>
<body>
<#crafter.body_top />
<#-- Insert your body markup here -->
<#crafter.h1 $field="demo_s">${myObject.price}</#crafter.h1>
<#crafter.body_bottom />
</body>
</html>
but iam getting the same error. #Russ Danner

Related

Issue: Datatable Server Side Processing in Django

I am totally new in Django. I am trying to implement datatable server side processing.I have written some codes in my models.py , views.py and urls.py and followed Datatables official documentation also. But unfortunately I am getting error in my terminal and cant able to figure it out how to fix it.
Here is ,
models.py
from django.db import models
class Products(models.Model):
title = models.CharField(max_length=100, blank=True)
description = models.TextField(blank=True)
price = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from ajax_crud.models import Products
from django.http import JsonResponse
def product_json(request):
products_json = Products.objects.all().values('title', 'description', 'price')
data = list(products_json)
value = JsonResponse(data, safe=False)
print(value)
return value
urls.py
from django.urls import path
from ajax_crud.views import product_json
urlpatterns = [
path('json/',product_json,name='json'),
]
demo-datatbles.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<h1>List of Products</h1>
<hr>
<table id="demo-table">
<thead>
<tr>
<th>title</th>
<th>description</th>
<th>price</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
$('#demo-table').DataTable( {
"processing":true,
"serverSide": true,
"ajax": {
"type" : "GET",
"url": "{% url 'json' %}",
"dataSrc": "objects"
},
"columns": [
{ "data": "title" },
{ "data": "description" },
{ "data": "price" },
]
} );
} );
</script>
</body>
</html>
My error in terminal.
[03/Sep/2020 05:31:49] "GET /json/?draw=1&columns%5B0%5D%5Bdata%5D=title&columns%5B0%5D%5Bname%5D=&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=description&columns%5B1%5D%5Bname%5D=&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=price&columns%5B2%5D%5Bname%5D=&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1599111109862 HTTP/1.1" 200 97
Please someone help me to get rid of it. Help will be highly appreciated.
I recommend working on this in two steps:
Display the basic data (as if you were not using server-side processing).
Add your specific server-side logic.
Background
I will assume your application is processing the HTML template correctly, and building a valid URL in this expression: {% url 'json' %}.
I will also assume that the response being sent to the HTML page from the ajax request is exactly as follows (i.e. the exact JSON data you provided):
[{
"id": 1,
"title": "Neutrogena Oil-Free Acne Wash, 177ML",
"description": "Nice products",
"price": 300
}, {
"id": 2,
"title": "Product one hello2",
"description": "Notes",
"price": 400
}]
If either of these assumptions is false, then the following will probably not help.
(You can use your browser's console to check that the JSON data response is received in the web page. it F12 to open the browser console and inspect the "Network" tab.)
Step 1
We will continue to use "serverSide": true for this step - so, do not remove it.
Your DataTable definition includes the following line:
"dataSrc": "objects"
This means DataTables will look in your JSON for an object using that name. But there is no object named objects - so no data is found.
Therefore you need to remove that line from your template.
But because you are using "serverSide": true, there are more changes needed.
Look at the link I mentioned in my comments (this one). This describes the JSON data you need to pass from the server to DataTables when you respond to the ajax request. There is also an example on the same page (here).
We can therefore take your JSON and make it conform to that requirement:
{
"draw": 1,
"recordsTotal": 1000,
"recordsFiltered": 1000,
"data": [{
"id": 1,
"title": "Neutrogena Oil-Free Acne Wash, 177ML",
"description": "Nice products",
"price": 300
}, {
"id": 2,
"title": "Product one hello2",
"description": "Notes",
"price": 400
}]
}
We have wrapped your data in some additional data, as required for server-side processing. Your data is now in an object named data - which is where DataTables expects to find it, to populate the rows of your table. So, we do not need to use "dataSrc": "data" here - because data is the default (expected) value.
In the above example I used values of 1, 1000 and 1000 - just for testing. You can use these values - and then we will fix them in step 2 below.
So you need to change your Django logic so that it builds the above JSON and returns that to DataTables.
Step 2
Normally (when you do not use server-side processing), the server sends all its data to DataTables at once. DataTables handles all logic for pagination, filtering, and sorting.
But now, with server-side processing, your Django code will be responsible for all of that work. It will not send all the data - it will only one small subset at a time. This is the power of server-side processing: You don't send all 1,000,000 records to the browser (which would crash it). You send only a small, fast subset for each request.
To do this, Django needs to read the request from DataTables. A request is automatically sent by DataTables whenever the user moves to a new page, or performs a sort operation, or filters the data.
Here is one such request - the one you provided in your question:
draw=1
&columns[0][data]=title
&columns[0][name]=
&columns[0][searchable]=true
&columns[0][orderable]=true
&columns[0][search][value]=
&columns[0][search][regex]=false
&columns[1][data]=description
&columns[1][name]=
&columns[1][searchable]=true
&columns[1][orderable]=true
&columns[1][search][value]=
&columns[1][search][regex]=false
&columns[2][data]=price
&columns[2][name]=
&columns[2][searchable]=true
&columns[2][orderable]=true
&columns[2][search][value]=
&columns[2][search][regex]=false
&order[0][column]=0
&order[0][dir]=asc
&start=0
&length=10
&search[value]=
&search[regex]=false
I manually URL-decoded the request, to make it easier to read.
This request contains all the information Django needs in order to build the required response.
For example:
start=0
length=10
This tells you that you need to provide 10 records in the response - and those will be the first 10 records (page 1 has an index of 0).
And this:
order[0][dir]=asc
This tells you that the data needs to be sorted by column 0 (the first column - title) in ascending order.
See here for full details.
So, you need to write all this logic in your Django application - to read the request, and then implement the instructions it contains, to build the correct response.

Cannot get PubNub EON chart to work

I have run into a dead end trying to get the following HTML to work. I am trying to use the real time gauge chart to display a value coming from a photon. This is the snippet code from the pubnub site.
(I have proven that the published value is arriving in the Javascript using the commented out pubnub code in the Javascript. The value is displayed in the P tag.)
The P tag is displayed on the screen, but no gauge is displayed.
Could you please have a look at my code and guide me on where I have made a mistake. I have not worked with EON before, so I may be making very basic mistake.
<!DOCTYPE html>
<html>
<!-- <script type="text/javascript" src="http://cdn.pubnub.com/pubnub-3.16.1.min.js"></script> -->
<script type="text/javascript" src="//pubnub.github.io/eon/v/eon/0.0.10/eon.js"></script>
<link type="text/css" rel="stylesheet" href="//pubnub.github.io/eon/v/eon/0.0.10/eon.css"/>
<div id="chart"></div>
<script type="text/javascript">
*var pubnub = PUBNUB.init({subscribe_key: 'xxxxxxx'});
/*
pubnub.subscribe ({channel : "datatest", message : function(tempmsg)
{document.getElementById("x").innerHTML = tempmsg.eon.data;}});
*/
var channel 'datatest';
eon.chart({
channel: channel,
generate: {
bindto: '#chart',
data: {
type: 'gauge',
},
gauge: {
min: 0,
max: 100
},
color: {
pattern: ['#FF0000', '#F6C600', '#60B044'],
threshold: {
values: [30, 60, 90]
}
}
}
});
</script>
<body>
<p id ="x"> This is my text that will be replaced by the value from the photon </p>
</body>
</html>
The output from the photon looks like this:
publishing message: {"eon": {"data":56}}
publishing message: {"eon": {"data":56}}
publishing message: {"eon": {"data":56}}
publishing message: {"eon": {"data":56}}
There is a missing line of code in the PubNub EON JavaScript embed code for the Gauge Chart.
You must add pubnub: pubnub, to bind the graph instance to the PubNub stream.

Parsing XML in Groovy with namespace and entities

Parsing XML in Groovy should be a piece of cake, but I always run into problems.
I would like to parse a string like this:
<html>
<p>
This is a <span>test</span> with <b>some</b> formattings.<br />
And this has a <ac:special>special</ac:special> formatting.
</p>
</html>
When I do it the standard way new XmlSlurper().parseText(body), the parser complains about the &nbsp entity. My secret weapon in cases like this is to use tagsoup:
def parser = new org.ccil.cowan.tagsoup.Parser()
def page = new XmlSlurper(parser).parseText(body)
But now the <ac:sepcial> tag will be closed immediatly by the parser - the special text will not be inside this tag in the resulting dom. Even when I disable the namespace-feature:
def parser = new org.ccil.cowan.tagsoup.Parser()
parser.setFeature(parser.namespacesFeature,false)
def page = new XmlSlurper(parser).parseText(body)
Another approach was to use the standard parser and to add a doctype like this one:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
This seems to work for most of my files, but it takes ages for the parser to fetch the dtd and process it.
Any good idea how to solve this?
PS: here is some sample code to play around with:
#Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')
def processNode(node) {
def out = new StringBuilder("")
node.children.each {
if (it instanceof String) {
out << it
} else {
out << "<${it.name()}>${processNode(it)}</${it.name()}>"
}
}
return out.toString()
}
def body = """<html>
<p>
This is a <span>test</span> with <b>some</b> formattings.<br />
And this has a <ac:special>special</ac:special> formatting.
</p>
</html>"""
def parser = new org.ccil.cowan.tagsoup.Parser()
parser.setFeature(parser.namespacesFeature,false)
def page = new XmlSlurper(parser).parseText(body)
def out = new StringBuilder("")
page.childNodes().each {
out << processNode(it)
}
println out.toString()
""
You will have to decide whether you want parsing to conform to standards, going the DTD path, or accept just anything with a permissive parser.
Tagsoup in my experience is fine for the latter and it rarely creates any problems, so I was surprised to read your remark about its handling of "special". A quick test also showed that I could not reproduce it: when running this command
java net.sf.saxon.Query -x:org.ccil.cowan.tagsoup.Parser -s:- -qs:. !encoding=ASCII !indent=yes
on your sample, I received this result
<?xml version="1.0" encoding="ASCII"?>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:html="http://www.w3.org/1999/xhtml">
<body>
<p>
This is a <span>test</span> with <b>some</b> formattings.<br clear="none"/>
And this has a <ac:special xmlns:ac="urn:x-prefix:ac">special</ac:special> formatting.
</p>
</body>
</html>
from both TagSoup 1.2 and 1.2.1. So for me that behaved as expected, the text "special" appearing inside of the "ac:special" tag.
As for the DTD variant, you could look after going through a caching proxy for resolving the DTD, refer to a local copy, or even reduce the DTD to the bare minimum that you need. The following should be sufficient to get you across the entity:
<!DOCTYPE DOC[<!ENTITY nbsp " ">]>

Is it possible to get URL parameters in JavaFX?

I'm building a JavaFX application which will run in browser.
Is it possible to get the app URL, like localhost/Java/MyApp/dist/index.html?x=123, in JavaFX?
I need to receive that "x" parameter.
You can get url parameters from the page: Get escaped URL parameter
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
Once you have the parameters you can pass the parameters to the embedded JavaFX application using the JavaFX deployment toolkits DTJava.js functions. See section 7.3.3 Pass Parameters to a Web Application of the JavaFX deployment guide.
<!-- Example 7-7 Pass Parameters to an Embedded Application -->
<head>
<script type="text/javascript" src="http://java.com/js/dtjava.js"></script>
<script>
function deployIt() {
// deployment guide sample modified by me to show
// getting the zipcode parameter from the url instead of hardcoding it.
//var zipcode = 95054;
var zipcode = getURLParameter("zipcode");
dtjava.embed(
{ id: "myApp",
url: "Map.jnlp",
width: 300,
height: 200,
placeholder: "place",
params: {
mode: "streetview",
zip: zipcode
}
},
{ javafx: "2.1+" },
{}
);
}
dtjava.addOnloadCallback(deployIt);
</script>
</head>
<body>
<div id="place"></div>
</body>
http://docs.oracle.com/javafx/2/deployment/deployment_toolkit.htm#BABJHEJA
As the JavaFX deployment guide says, to access parameters in the application code, use the getParameters() method of the Application class. For example:
String zipcode = app.getParameters().getNamed("zip");

passing objects parameter to facebook open graph custom actions in C#

I am posting custom action with facebook open graph api and I am successfully posted that on my timeline with facebook c# sdk.
Here is my action code
curl -F 'access_token=AccessToken' \
-F 'job=http://samples.ogp.me/476622222351784' \
'https://graph.facebook.com/me/sajidap:apply'
Here is my object code
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# sajidap: http://ogp.me/ns/fb/sajidap#">
<meta property="fb:app_id" content="APPID" />
<meta property="og:type" content="sajidap:job" />
<meta property="og:url" content="Put your own URL to the object here" />
<meta property="og:title" content="Sample Job" />
<meta property="og:image" content="https://s-static.ak.fbcdn.net/images/devsite/attachment_blank.png" />
I am posting in this way.
var fb = new FacebookClient(AccessToken);
var parameters = new Dictionary<string, object>
{
{ "og:type", "sajidap:job"},
{ "og:url" , "http://www.google.com"},
{ "og:image", "http://www.theappdynamics.com/images/babafooka.jpg" },
{ "og:title" , "Arslan Job"},
{ "job" , "http://samples.ogp.me/476622222351784"}
};
var Response = fb.post(me/NameSpace:ActionName,Parameters);
Its posting an activity on my timeline but its showing Sample activity of an object that is like this url http://samples.ogp.me/476622222351784
How I can give my own url, image and title of that object by passing with parameter dynamically from C#.
Please guide me on this thing
Its Simple i have done this. You have one page like that which have your Open graphs tags in it like this. Mean It should be some content page on your web.
Let me clear more.. Like I have one resturant and I am selling some chicken burgers and I want to make one action "Buy" Mean In facebook it should be like this Arslan buy chicken lawa on link.
In This Arslan is user who performed the action
And Action is buy
And Object was chicken lawa
And URL is my below page who have all open graph tags in it to show in feeds.
Here is ASPX Page
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server" prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# myapp: http://ogp.me/ns/fb/myapp#"> // Your app name will be replaced with this "myapp"
<title>Buy Falafeel</title>
<meta property="fb:app_id" content="4735" /> // Your APP ID
<meta property="og:type" content="myapp:falafeel" /> // YourAppName:Action Type
<meta property="og:url" content="http://demo.anything.net/buy.aspx" />
<meta property="og:title" content="Chicken Lawa Falafeel" />
<meta property="og:image" content="http://www.theappdynamics.com/images/babafooka.jpg" />
</head>
<body>
<form id="form1" runat="server">
<div>
This is Falafeel Page. Demo Demo......
</div>
</form>
</body>
</html>
Here I am Performing The action on button click from my code behind.
void PostAction(string URL, string Token, string Action, string objects)
{
var fb = new FacebookClient(Token);
var parameters = new Dictionary<string, object>
{
{ objects , URL}
};
try
{
dynamic result = fb.Post("me/myapp:" + Action, parameters); // again here should be your app name instead of "myapp"
}
catch { }
}
PostAction("URL", "AccessToken", "Action", "Object"); // Here is The Above Method Call
// Here is URL That URL Who Have Open Graph Tags Like we have created one page with tags named buy.aspx and it should be full link like "http://xyz.com/buy.aspx"
//Access Token Of User On Behalf we are going to create This Action
//Action The One Created On facebook App Setting Of OpenGraph Tag Like "Buy"
//Object That We Also Created On Facebook App Setting For OpenGraph Like "ChickeLawa"
Just publish an action with your object set to the OG URL of your object, as described here: https://developers.facebook.com/docs/opengraph/actions/#create
Anything else (picture, title etc.) will be fetched from the og:tags of the URL.

Resources