is A pure javascript framework on J2EE projects possible? - javascript

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...)

Related

where and how to use nodejs with angularjs

I am new to UI framework development. Currently my requirement is to work with anuglarjs and nodejs. I know there are few more like me who want to know the exact use..
I am confused as where i need to use nodejs in my application. I tried to find a simple live demo example(plunker/jsfiddle) which used angularjs and nodejs but i couldn't find one.
Currently i have written a small module using angularjs, which hits the java controller class and saves/get the data and display the data on the webpage. Here i'm no where using nodejs. I tried to search in web to understand the use of nodejs with angularjs.
Any input's would be very helpful.
Below is the sample javascript code i implemented using angularjs.
myDataCOntroller.js
//some code here
$scope.submitFormData = function(myForm){
if(myForm.$valid)
{
MyDataService.saveOrGetData($scope.myReport).then(
function(response) {
$scope.myReport = response;
},
function(errResponse){
console.error('Errorr');
});
}else{
console.log("invalid form data!!");
}
}
myDataService.js
app.factory('myService',function($http,$q,$location){
var MY_SERVICE_URI = $location.protocol()+'://'+$location.host()+':'+$location.port();
var _repServiceFactory={};
_repServiceFactory.saveOrGetData = function(myData){
var deferred = $q.defer();
var url = appURL+'/saveOrGetData.form';
$http.post(url,JSON.stringify(myData))
.then(
function (response) {
deferred.resolve(response.data);
},
function(errResponse){
console.error('Error while fetching data');
deferred.reject(errResponse);
}
);
return deferred.promise;
}
PS: I know that Angularjs is client side, Nodejs is server side, both are using Javascript programming language.
What i want to know is, what is the use of nodejs and where is it used in real time??
If you are writing an AngularJS front end web application, you may never have to use NodeJS.
If you need tooling (build scripts to compile Sass, linters, etc) in your development or deployment process you can use NodeJS task runners like Gulp, Grunt or Webpack.
If you need to build a back end API, that stores and retrieves information, you can use Express or the whole MEAN stack.
* * * Also worth noting-- you mention hitting a Java class. If you are already using Java for the backend, then you probably won't be using any NodeJS for that purpose. If you were just shortening JavaScript to "Java", please note they are separate and distinct languages. * * *
Web dev has 4 primary parts:
Back-End: Node.Js (which will replace or work with your Java server)
Front-End: Angular.js (or React/Polymer/Vue/etc.)
Database: MongoDB (noSQL), mySql/Postgres (sql)
Routing/Server/Middleware: Express.js
For you to create an app that is realtime, you can use websockets, especially Socket.io (which works really well with and is built for Node.js)
WebSockets are essentially bi-directional (low latency) event-based tunnels where data can be passed from client-to-server, and server-to-client without the need to make an AJAX (tcp) request per message.
This paired with a strong data-binding architecture (API -> Angular Binding) allows for customizable single page views, where the same data can be used to create a view, and update the back-end modal when the data gets updated.

Vaadin JavaScript API Integration

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

Javascript function like PHP exec()

I need to be able to execute a shell command through javascript, similar to the php function "exec()". I understand that this may be impractical in javascript because of security reasons, but my javascript code is running on the server, and no clients have direct access to the file.
Users make a request to the server for some data, and the server-side javascript code is called. From the javascript file, I need to execute a program in order to gather data based on user input, then pass this data back.
If this isn't possible in vanilla Javascript, please point me towards a library or tool that can do this, preferably in javascript/frameworks on javascript.
JavaScript has no 'exec' function like PHP does. It's all because JavaScript runs on the client and don't have access to the server part.
However you can create PHP page and send AJAX requests to it to execute particular command.
ALTHOUGH, you need to be VERY, VERY and VERY cautious about which commands to run.
It's very dangerous to do like that. I don't advice you to do like that, however, it's possible.
Good luck!
If it's client side - You can't
If it's node.js:
var exec = require('child_process').exec;
child = exec("command", function (error, stdout, stderr)
{
// handle the output
});
This might be what you're looking for: https://github.com/arturadib/shelljs
Or, if you want to have direct access to commands, perhaps this will help: http://nodejs.org/api/child_process.html

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.

How to design a Library?

We have just started our new assignment - web-based project. Before I get directly on to the question it would be necessary to explain about the project.
We are actually moving a product from desktop to web. This is it. All backend services are web services. Our choice of server technology will be .NET. As we are good with it and also client are equipped with it too. So, we will be doing all the server work in ASP.NET AJAX. PageMethod will be preferred choice to communicate with server (C# 3.0) and client (JavaScipt). There will be a real need of jQuery for parsing DOM and XML parsing. We do not to put effort to reinvent the wheel.
Now, there are things what we have to do and mostly it will be in JavaScript. We would like to package it in one.
E. John did a very useful session on 'Building a JavaScript Library' which is very useful. It surely keep in this way.
A fairly good amount of JavaScript engineers are here. And I would like to have their recommendations and suggestions before we start over.
Do you know some good references on JavaScript Library design? If you every made your own JS Library what you learned from it? Have you look into gmail/googledocs/facebook JavaScript? What have you learned from it?
Thanks.
Start off with something like this:
var yourNamespace = yourNamespace || (function () {
"use strict";
// private variables here
return {{whatever you want yourNamespace to be here}};
}());
To design a javascript library -
Identify what functions you write often.
Save them in a seperate .js file.
Keep a log or comment block on top
of the development version and
update to reflect the contents of
the file.
Done.
Use a webservice for connect to db and exec the queries..
Create SERVICE.JS, in this file call web service with jquery.ajax method
Create a DESIGN.JS, in this file do everythig about user ınterface (onclick, initialize,fill grids,combos etc)
Create a GLOBAL.JS, in this file create global variables for use everywhere(for example: UserId)
Create a HELPER.JS, in this file create useful functions for use anywhere(for example: function DATE_TO_STRING(_date) )
On this all .JS files use namespaces example for GLOBAL.JS:
(function () {
var GLOBAL = {
CurrentUserId:-1
}
if (!window.GLOBAL) { window.GLOBAL = GLOBAL; }
})();
Dont use ASP.NET components. Use html inputs,textarea etc

Categories