Vaadin JavaScript API Integration - javascript

I am looking for any type of help, generic or specific, producing a Vaadin client-side Java implementation of the Braintree Payments API for the client library.
I can do all the server-side Java requirements of the Braintree protocol and also do RPC between a piece of inline JavaScript code yet it fails to use the Braintree .js API.
The client side code, all summarized in here, suggests using their "hosted fields" to which I am open as well as their Drop-In UI. Anything goes, really.
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
// Handle error in Hosted Fields tokenization
return;
}
// Put `payload.nonce` into the `payment-method-nonce` input, and then
// submit the form. Alternatively, you could send the nonce to your server
// with AJAX.
document.querySelector('input[name="payment-method-nonce"]').value = payload.nonce;
It should also be possible to directly tokenize the credit card information which is the most crucial step for me to continue. This should be a different process to integrate in Vaadin, perhaps someone knew this way better?
How would I go about something like this?

The easiest and fastest way may be using a AbstractJavascriptComponent
or AbstractJavasciptExtension. These are subclass-able and provide a easy way to link JS code to a component you can manipulate server side. AbstractJavascriptComponent might be the best of the two because they give you a div element that you can control completely with js without vaadin touching it. This is easier IMO because you can avoid GWT and using there connector classes.
Here are some links to get you started
https://vaadin.com/blog/-/blogs/vaadin-7-loves-javascript-components
https://vaadin.com/wiki/-/wiki/Main/Integrating%20a%20JavaScript%20library%20as%20an%20extension

Related

Dart wrapper over js library and use it in flutter app

Put it simple I want to make small currency exchange app (pet project- I want free API( 1000 requests per month including more currency is a perfect option)). I dont like the free APIs I have found so far but I have found this website https://bg.coinmill.com/ and I wanna use it for my purpose. Reading an answer to similar question:
The only way to make use of JS in Flutter is using WebView.
Dart compiles to JS only for browser applications, for Flutter it compiles >to native machine code.
convert js code direcly to dart, using package js
package JS doesn't convert JS, it just creates proxies for JS functions to >be able to call them from Dart, but that is also only supported in Dart web >applications.
Put it simple it isn't possible without hitting some compilation errors and some workarounds. However https://github.com/pichillilorenzo/flutter_inappbrowser looks promissing. Embedding the webpage that will look ugly and I won't have any control over ui/settings. My options now are looking for another free currency API or trying to find a workaround. I incline for another API, but not sure which one. Any suggestions ?
So basically what you actually want to do is use that website to do the currency conversion in the background (enter value, press "Convert"), then display the result in your Flutter app? You don't need javascript for that.
After entering pressing the submit button, the site simply redirects you to a different page (GET request) with an URL like this:
https://bg.coinmill.com/CAD_USD.html?CAD=22
Use dart's http library to perform the same request with the right currency/value parameters. The result of the request contains the source code of the web page.
Instead of displaying the web page, you just need to read the value you need from the source code of the web page:
<div id="currencyBox1">
<input class="currencyField" ... value="16.46" ...>
САЩ долар (USD)
</div>
So, how I understand your question, you have some js library, and you want to use it from Dart?
If question so, yes, you can do it using Dart JS Intertop. The more information in the link.
Edit
Yes, you are right, you can call js from Flutter only using evalJavascript function from flutter_webview_plugin.
You can use Firebase Cloud Functions and wrap your function in a callable function. You'll have all node js environment and Dart code will only call a function.

Implement Autosuggest/Typeahead in Custom UI built on AngularJS

I am trying to build a typeahead/suggestion feature similar to the one developed using App Builder.
My XQuery is:
xquery version "1.0-ml";
import module namespace search = "http://marklogic.com/appservices/search"
at "/MarkLogic/appservices/search/search.xqy";
let $options :=
<options xmlns="http://marklogic.com/appservices/search">
<additional-query>{cts:and-query((cts:collection-query("NY"),cts:element-value-query(xs:QName("Office"),"47","exact"),cts:element-value-query(xs:QName("Person"),"15","exact")))}
</additional-query>
<constraint name="Search_Element">
<range collation="http://marklogic.com/collation/"
type="xs:string" >
<element name="Account"/>
</range>
</constraint>
<suggestion-source ref="Search_Element">
<range collation="http://marklogic.com/collation/"
type="xs:string" facet="true" >
<element name="NUM_ACCT"/>
</range>
</suggestion-source>
</options>
return
search:suggest("Search_Element:103", $options)
This returns the desired suggestions.
But, now when i wish to integrate this in UI, I am unable to understand how it could be implemented.
REST API doesnt seem to be rich enough for above query as its does key/value, element value search etc.I want to implement typehead for instance,for account element in NY collection,for a particular office-person element values as in the above XQUERY
The App Builder uses extsuggest extension, but i could not get much information on this.
I have a text box, which on typeahead, will query marklogic server via REST or JSON/XML wayaround whichever can be implemented and display the results.
I am currently trying to use AngularJS typeahead feature as given here.
Please Advise !!!
From the looks of it, the extsuggest extension is just a convenience wrapper around search:suggest, mainly to easily get hold of the search options of an App Builder app, and returning any results as JSON.
Otherwise I am a little confused by your question. You say the above code gives the correct suggestions, but the second paragraph below the code seems to indicate it doesn't?
Or is your problem that you have correct suggestions, but don't know how to visualize them in the UI?
HTH!
To your first point about the REST API, you put the XQuery code above in a REST extension, as described here. If you call it "suggest", you'll end up accessing it at /v1/resources/suggest.
I'm not clear on your overall architecture, but you mentioned AngularJS and XCC for Java, so I'm guessing you have something like Tomcat serving up the UI and implementing business logic, with Java using XCC to talk to MarkLogic to get data. (An aside: since you're using the REST API, you might want to go with the MarkLogic Java API, which sits on top of the REST API.)
From the AngularJS side, the typeahead is going to need to work with a service that sends what has been typed so far back to your Java server, which will forward the request onto the MarkLogic endpoint. I found another StackOverflow question that shows how to set up the directive to send the request to a server.
The REST API in V7 has suggestions built in. You can access that directly.
http://docs.marklogic.com/REST/GET/v1/suggest
One of the things I've not yet covered in my MLJS JavaScript wrapper for MarkLogic[1] is auto suggest for the text search query bar widget. I have built this for the semantic (SPARQL) query bar widget though. If you're writing in JavaScript, MLJS has all the hard work done for you. Easy to plug in new rest functions of your own using the mljs core API's do() function. There's also a search widget API too.
[1] https://github.com/adamfowleruk/mljs/blob/master/README.md

Ajax integrating in Struts with jQuery

I am familier with jQuery,Ajax and JSP Servlets but new to Struts2.I want to know a complete reference of Ajax integration in Struts 2, preferred with jQuery. In stackoverflow also has more quesitons and answers, but still there are few things remaining to know.I need to know few things.
(1) Is there a complete reference how to use Ajax in Struts2 applications. struts2-jquery-plugin (and their showcase also) has many sample codes and demos. But I couldn't find how to handle it in Java classes.Their all samples found in itself are on client side- JSP samples only, no demo shows how the action classes work. No idea what the application returns(XML/JSON or what the server side returns) Their site demos only core functionalities. I want know how to how to handle both side; [in Struts framework] and [how to customize more struts ajax tags in JSP]. If there is any link or advice,it ll be highly appreciated.
(2)
I read Struts 2 In Action book. It has sample codes and demo.Its chapter 8 explains how to work with Ajax( used Actionsupport, another one extending Result class ... ). In Internet,few sample codes found, and they had used in some different way( directly PrintWriter print() the result). But in JSP side, normal javascript had been used. So, according to your best practises (may be more ways), what is your most preferred way to use Ajax? (that means,you use as jquery plugin shows or not depends on Struts ajax tags and just use javascript/jQuery in JSP pages, and the best practices to handle struts classes Write Result class or just use PrintWriter to print the result? Here you may say, it depends on the situation and the taste of the develoer, but what would be according to the industry standards?)
IF someone downvote. please leave a comment, WHY?
You should be using this jquery plugin instead; it is the closest thing the S2 project has to an official jQuery plugin. The one you link to isn't the same.
The most common way to return data to JavaScript (jQuery or not) is to use the JSON plugin or the REST plugin. There are very few reasons to ever write responses manually.

is A pure javascript framework on J2EE projects possible?

I've been working in the j2ee field for several years and tired of writing all those AJAX functions which downloading some data from server-side and render on the client-side.
Is it possible to only write javascript codes that run on both server-side and client-side.
like, if I need to develop a login page, I can write a piece of code kinda like this:
ORIGINAL CODE:
remote checkPassword;
function checkPassword(username, password){
if(existsRecord("select 1 from staff_t where user_name=? and password=?",username, password))
return true;
return false;
};
var main(){
var userName=$("username").val();
var password=$("password").val();
if(checkPassword(userName,password))
alert("Welcome, "+ user);
}else{
alert("sorry, wrong username or password.");
}
}
In the code above, javascript gets the data from dababase directly, isn't it clearer and easier to understand?
While this code actually runs on production mode, it is separated by an engine to two pieces:
SERVER-SIDE:
function checkPassword(username, password){
if(existsRecord("select 1 from staff_t where user_name=? and password=?",username, password))
return true;
return false;
};
CLIENT-SIDE:
var userName=$("username").val();
var password=$("password").val();
// 'checkPassword' has been translated to an AJAX function.
if(checkPassword(userName,password))
alert("Welcome, "+ user);
}else{
alert("sorry, wrong username or password.");
}
This way, we can use a single piece of code for a single business without separating them into java and javascript. The engine will separate the code and determine which parts should run on the server and others run on browsers.
I've searched all the internet, but didn't find any framework like that which can provide accessibility to database/EJB/WEBSERVICE.
Google Web Toolkit (GWT) enables us to write pure JAVA code for a browser-based application, but it seems a little clumsy for me. :)
Rhino is a javascript engine running on j2ee projects, but it doesn't provide any means to access both client-side data and server-side data.
does anyone know a framework like this, or is it possible to develop one all by ourselves? what's the pros and cons?
thanks.
Is it possible to only write javascript codes that run on both server-side and client-side.
Sure, drop J2EE and come join the node.js community
As for frameworks, no. You can't magically communicate between the two. The best I've seen is automated RPC like nodeQuery where the server sends DOM commands over RPC to a client.
Alternatively, who needs a server when you can write couchapps and serve HTML directly from your database.
A lazy solution to this is to use frameworks which have a direct binding between UI presentation and server object model. This makes it a lot easier to write validation only on server-side: you just specify the validation code in Java. AJAX makes this validation available on client side automatically (before the submit actually took place!)
If you think about it, the password example is very minimal. Most validation cases require more code and even more data. Suppose you validate the address of a user using a geographical database; will you push this full database to client side? No, you send the address to the server using AJAX and display the validation result to the user in realtime.
JSF uses this approach quite nicely (RichFaces, ICEFaces...)

Ajax Design/Refactoring help when rendering new content - like list items and divs

I consistently come across this code smell where I am duplicating markup, and I'm not really sure how to fix it. Here's a typical use case scenario:
Let's say we'd like to post comments to some kind of article. Underneath the article, we see a bunch of comments. These are added with the original page request and are generated by the templating engine (Freemarker in my case, but it can be PHP or whatever).
Now, whenever a user adds a comment, we want to create a new li element and inject it in the current page's list of comments. Let's say this li contains a bunch of stuff like:
The user's avatar
Their name
A link to click to their profile or send them a private message
The text they wrote
The date they wrote the comment
Some "edit" and "delete" links/buttons if the currently logged in user has permission to do these actions.
Now, all of these things were already written in our template that originally generated the page... so now we have to duplicate it inside of Javascript!
Sure, we can use another templating language - like Jquery's Template plugin - to ease the pain generating and appending this new li block... but we still end up with duplicate html markup that is slightly different because we can't use macros or other conveniences provided to us by the templating language.
So how do we refactor out the duplication? Is it even possible, or do we just put up with it? What are the best practices being used to solve this problem?
This is a common problem and becomes more obvious as the UI complexity increases, and changes have to be done on both the server and client templates. This problem is fixable by using a the same template markup on both the client and server sides. The template processors must be written in both JavaScript and the server side language.
Two other solutions that are cleaner than the above approach, but both have their own problems:
Do everything client side
Do everything server side
If all markup generation is done on the client side, then the server acts more or less like a web service which only sends back data in whatever formats suits the application. JSON, and XML are really popular formats for most web services nowadays. The client always generates the necessary HTML and JS. If going with this approach, the boundary between the client and server must be well defined. Since the client has limited knowledge of what happens on the server, this means that proper error codes must be defined. State management will become harder since most/all server interaction will be happening asynchronously. An example of adding a comment with this approach may look like:
$('#add-comment').click(function() {
var comment = $('#comment-box').text();
$.ajax('http://example.com/add', {
success: function() {
addCommentRow(comment);
},
...
});
});
function addCommentRow(comment) {
var user = currentUser().name;
var html = "<li><b>{user}</b> says {comment}</li>";
html = html.replace("{user}", user).replace("{comment}", comment);
var item = $('<li>').html(html);
$('#comments').append(item);
}
The other approach is to do everything server side. Whenever a change happens, shoot a request to the server, and ask it for the updated view. With a fast backend, response times under a second, and proper indicators of network activity, the application should seem very responsive despite everything happening on the server. The above example would be simplified to:
$('#add-comment').click(function() {
$.ajax('http://example.com/add', {
success: function(response) {
$('#comments').html(response);
},
...
});
});
Although this seems a lot more cleaner on the client side than the previous approach, we have just moved the markup generation up to the server. However, if the application is not very AJAXy like Google Maps, then this approach may be easier to work with. Again, it's a matter of how complicated the application is, and perhaps maintaining state client side is a necessity for you, in which case you may want to go with the previous approach.

Categories