Backbone.js View in Client Side Javascript MVC – with Java based Web Project – Part 3


This article is extension of Backbone.js based Application with Java based web project.

The project code can be downloaded here.

Backbone.js views are used to render client side application data model. They are used to listen events and work as per that. We will explain view functionality with JavaScript template library within our application for one of our view.

window.HeaderView = Backbone.View.extend({

    template:_.template($('#tpl-header').html()), // Here template controls the DOM Element in the HTML.

    initialize:function () {
       // This function will be called at the initialisation of a View...
        this.render(); // render function loads the template in the el property of backbone.js
    },

    render:function (eventName) {
        $(this.el).html(this.template());
        // Above el is a property of backbone view. This is created as empty div element in browser and the control on        
        // the Div element is done completely by the Backbone.js. As this binds the container element, all the events 
        // will trigger for this element. 
        return this;
    },

    events:{
        "click .new":"newWine" 
        // here the listening for click event is happening. And it will call the mapped newWine function 
    },

    newWine:function (event) {
        // when Button is clicked, this function is called for the Click event trigger.
        app.navigate("wines/new", true);
        return false;
    }
});

More Resources :

What is a view?

Backbone.js Tutorial: List Views

Other Resources you may have interest :

1> Developing Java web applications with Backbone.js

2> Backbone.js in Client Side Javascript MVC – with Java based Web Project

3> Backbone.js Router in Client Side Javascript MVC – with Java based Web Project – Part 2

Enter your email address:

Delivered by FeedBurner

Creating ListView with Multiple Selection in Android


Today we’ll discuss how to create a simple list view with multiple item selection facility in Android.

I assume that you have already installed Android SDK and Eclipse and your development environment is set up properly.

Create a new project in Eclipse and extend your launcher activity from ListActivity. Please refer to the code below :

import android.app.ListActivity;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
      private String[] listItems = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
}

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      getListView().setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_multiple_choice, listItems));
      getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
      menu.add("Get Selected");
      return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
       // TODO Auto-generated method stub
       SparseBooleanArray positions = getListView().getCheckedItemPositions();
       StringBuilder sb = new StringBuilder();
       for(int i = 0; i < getListView().getCount(); i++){
         if(positions.get(i))
         sb.append(getListView().getAdapter().getItem(i) + "\n");
       }
       Toast.makeText(this, sb, Toast.LENGTH_LONG).show();
       return true;
}

Now run your project on emulator or device. Select the items of your choice press ‘menu’ and select the menu option to get your choices as ‘Toast’. Following is the screenshot of this project:

ss

Enter your email address:

Delivered by FeedBurner

Backbone.js Router in Client Side Javascript MVC – with Java based Web Project – Part 2


This article is extension of Backbone.js based Application with Java based web project.

The project code can be downloaded here.

In Backbone.js Javascript MVC Frameworks, router are used to navigate web site URL’s by using hash tags(#).

All routers in Backbone.js contain route and function to map to that route. In our case, the route refers to –

// Router
var AppRouter = Backbone.Router.extend({

	initialize:function () {
        // Function is called at the time of initialization of Router.
    },

    routes:{
        "wines/new":"newWine", // a router mapping to a particular function newWine
        // Other code snippets // Other route paths...
    },

    list:function () {
        // Code to fetch the value from database using the REST based web service.
        $('#sidebar').html(this.wineListView.render().el); // Rendering a html fragment - template by Backbone View.
    },

    // Other code snippets....
    newWine:function () {
        // mapped function from route. 
        // New Model initialisation and html template rendering code to be here.
    }
});

var app = new AppRouter(); // Backbone router initialisation
Backbone.history.start(); //  Start Backbone history to capture navigation pattern in browser for later use.

More Resources :

1> What is a router?

Other Resources you may have interest :

1> Developing Java web applications with Backbone.js

2> Backbone.js in Client Side Javascript MVC – with Java based Web Project

3> Backbone.js View in Client Side Javascript MVC – with Java based Web Project – Part 3

Enter your email address:

Delivered by FeedBurner

Backbone.js in Client Side Javascript MVC – with Java based Web Project


This article is extension of Backbone.js based Application with Java based web project.

The project code can be downloaded here.

In Backbone.js Javascript MVC Frameworks, The Model is referred to the intermediate data holding objects in client side which is required for data manipulation, validation on client side, fetching data from server side and finally required for submission to server side.

In our case, the Model Code is –


window.Wine = Backbone.Model.extend({
urlRoot:"http://localhost:8080/brandserver/rest/wines",
     defaults:{
     "id":null,
     "name":"",
     "grapes":"",
     "country":"USA",
     "region":"California",
     "year":"",
     "description":"",
     "picture":""
    }
});

Here, the defaults attributes are for the data at the time of new Model data instansiation.

Also we can see the model data instantiation in newwine function of AppRouter –

 
app.wineView = new WineView({model:new Wine( {id:null,name:"",grapes:"",country:"",region:"",year:"",description:"", picture:"generic.jpg" })}); // instantiation of model

Here we have passed some values to the Attributes of the Wine Model.

In a Model, the urlRoot specifies the main url path for the REST based web service.

In our case, it is –

urlRoot:”http://localhost:8080/brandserver/rest/wines”

Now in –

 
window.WineCollection = Backbone.Collection.extend({
    model:Wine,
    url:"http://localhost:8080/brandserver/rest/wines"
});

The collection, named as WineCollection is initialised with Model Wine by expecting same json data from server by calling the REST based web service.

Interesting to see, the AppRouter calls the list function, which actually takes A REST based web service call internally, when the following code is executed –

 
this.wineList = new WineCollection();
this.wineListView = new WineListView({model:this.wineList});
this.wineList.fetch(); // Call to Server for all data selecting (REST Web Service)

Now interesting is Model Saving function – saveWine –

 

    var win = new Wine(this.model);

    win.set({
        name:$('#name').val(),
        grapes:$('#grapes').val(),
        country:$('#country').val(),
        region:$('#region').val(),
        year:$('#year').val(),
        description:$('#description').val()
   });
   // Some code snippet
   app.wineList.create(win, {  //REST Web Service calling internally
       success:function () {
            	alert('Wine saved successfully');
               	app.navigate('', true);// to initialize the state
                window.history.back(); 
             }
      });
   // The above Code snippet is used for saving a new model to the server. The create function is important. This     
   // callback function is called after instantiating a new model and set values to it's attributes. 

   win.save(); //REST Web Service calling internally
   alert('Wine updated successfully');
   app.navigate('', true); // to initialize the state
   window.history.back();
   // The above Code snippet is used for updating a model to the server. The save function is important. This     
   // callback function is called after setting values to an existing model attributes. 

Now the deleteWine Function –

 
    var win = new Wine(this.model); // Instantiate variable with current model.
    win.destroy({ // REST Web Service Calling
         success:function () {  
                alert('Wine deleted successfully');
                app.navigate('', true);
                //window.history.back();
            }
        });

   // The above Code snippet is used for deleting a model to the server. The destory function is important. This     
   // callback function is called to delete corresponding row in database of the current model. 

Other Resources you may have interest :

1> Developing Java web applications with Backbone.js

2> Backbone.js Router in Client Side Javascript MVC – with Java based Web Project – Part 2

3> Backbone.js View in Client Side Javascript MVC – with Java based Web Project – Part 3

Enter your email address:

Delivered by FeedBurner

Developing Java REST web applications with Backbone.js


Recently in our J2ee based web application development, we had explored Javascript MVC frameworks to develop structured User Interface Development. Within javascript frameworks, we have found sufficient documentation for Backbone.js to develop sample Proof of Concept with J2ee based Application Back End.

We are writing post as we have not found a full-fledged Java based web application with backbone.js as UI development tool in Web.  While working on the POC, we have changed codes in backbone.js section.

We have learned the where-about from Backbone.js Wine Cellar Tutorial — Part 2: CRUD by Christophe Coenraets and used his sample POC to develop a J2ee web application with Backbone.js as web tier development framework. The main Application credit goes to him.

We have uploaded the Sample Application in GitHub (here is the Link).

Now below is the basic understanding for the overall project –

The J2ee Project is based on java jersey REST based framework. The database schema is attached in the project source code, which is named – cellar.sql

Development  environment –

1> Database – MySql

2> Rest based Web Services Development –  Java Jersey.

3> UI Development – Backbone.js

Deployment Environment –

1> Apache Tomcat 7 (We have tested on it.)

We are trying to give the concepts and code snippet for both Server side development and Client Side Development below.

Server Side –

A> ConnectionHelper.java – it is used for making connection with MySql Database.

B> Wine.java – it is used as simple POJO class for the table in database.

C> WineDAO.java – it is used to write JDBC related codes for insert/update/delete/select in the MySql Table. All the DB manipulation methods are written here.

D> WineResource.java – Important Class related to REST API Based Web Services. Method Signatures are given below –

@GET @Path("wines")
@Produces(MediaType.APPLICATION_JSON) 
public List findAll() {

    // to fetch all data from DB

}
@GET @Path("search/{query}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public List<Wine> findByName(@PathParam("query") String query) {
   // to fetch particular data from DB on basis of product name.

}
@GET 
@GET @Path("{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Wine findById(@PathParam("id") String id) {
	//to fetch particular data from DB on basis of ID.
}
@POST
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Wine create(Wine wine) {
       // To insert the data in db with the simple POJO Wine
}
@PUT @Path("{id}")
@Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Wine update(Wine wine) {
	// For updating the Data with particular ID	
}
@DELETE @Path("{id}")
@Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public void remove(@PathParam("id") int id) {
	// to Delete the particular record with the selected ID
}

All the REST based API can be tested with the class

6>Test.java – 

particular line to test here –

System.out.println(service.path("rest").path("wines").accept(MediaType.APPLICATION_JSON).get(String.class));

Now a simple explanation on how the testing is happening for Jersey based REST Web Service –

We can dig into the web.xml further to see the lines –

<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>org.webphlox.brandserver.sample</param-value>
</init-param>

– for scanning the packages for REST based web service resources by Java Jersey Server.

<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>

– for identifying the path for REST based web services which is here – /rest/

So in the above testing method,

service.path("rest")

is for url-pattern
and .path(“wines”) is for getting the particular method. And also it will send the output in json format.

Client Side –

HTML Part –

In client side, the index.html is for the backbone.js templates –

<script type="text/template" id="tpl-header">
<button class="new">New Wine</button>
</script>

– Here the Button is for New Data Add.

<script type="text/template" id="tpl-wine-list-item">
<a href='#wines/<%= id %>'><%= name %></a>
<!-- <%= id %> and <%= name %> are used as template variables.
</script>

– to show the Data list in a tabular format.

<script type="text/template" id="tpl-wine-details">

<div class="form-left-col">
<label>Id:</label>
<input type="text" id="wineId" name="id" value="<%= id %>" disabled />
<label>Name:</label>
<input type="text" id="name" name="name" value="<%= name %>" required/>
<label>Grapes:</label>
<input type="text" id="grapes" name="grapes" value="<%= grapes %>"/>
<label>Country:</label>
<input type="text" id="country" name="country" value="<%= country %>"/>
<label>Region:</label>
<input type="text" id="region" name="region" value="<%= region %>"/>
<label>Year:</label>
<input type="text" id="year" name="year" value="<%= year %>"/>
<button class="save">Save</button>
<button class="delete">Delete</button>
</div>

<div class="form-right-col">
<img height="300" src="pics/<%= picture %>"/>
<label>Notes:</label>
<textarea id="description" name="description"><%= description %></textarea>
</div>

</script>

– to show the particular data item details.

Javascript part (Backbone.js)

All the javascript related codes can be found in main.js.

First, we have to define the Model of Data to be handled by backbone javascript.

// Models 

window.Wine = Backbone.Model.extend({
urlRoot:"http://localhost:8080/brandserver/rest/wines",
defaults:{
"id":null,
"name":"",
"grapes":"",
"country":"USA",
"region":"California",
"year":"",
"description":"",
"picture":""
}
});

window.WineCollection = Backbone.Collection.extend({
model:Wine,
url:"http://localhost:8080/brandserver/rest/wines"
});

urlRoot is the REST based web service calling point (endpoint). Here we have specified the url which is needed to data select/insert/update/delete. Also the Model is Wine – which will be used to store data from web service endpoint and manipulate the data and it is part of collection – WineCollection.

The default parameter is used to initialize a new Model while adding the data.

There are three views in the Application

A> WineListView – contains a collection of Item View – WineListItemView

B> WineListItemView – responsible for rendering the  model template – WineView

C> WineView – contains core methods for adding,deleting and updating –

The interesting methods are – 1> saveWine and 2> deleteWine

D> HeaderView -responsible for initialize the view for adding a new template.

The interesting method is – newWine 

Router – AppRouter is responsible for initial routing of the Application.

So this is the Proof of Concept of Backbone.js with a Java based web Application.

We will dig in deeper for backbone.js data coding for Model, Collection, View and Router in context of this tutorial in separate posts.

So for now it is all.

Comments are welcome.

More Resources :

1> Backbone.js Lessons Learned and Improved Sample App

2> Learn Backbone.js Completely

Other Resources you may have interest :

1> Backbone.js in Client Side Javascript MVC – with Java based Web Project

2> Backbone.js Router in Client Side Javascript MVC – with Java based Web Project – Part 2

3> Backbone.js View in Client Side Javascript MVC – with Java based Web Project – Part 3

Enter your email address:

Delivered by FeedBurner

A Complete J2ee Project UML


I have created UML for Different Projects in my earlier works.  I thought that it is worth to share a complete Project UML which is based on some imaginary scenario on a flight system. I had created it earlier for my Sun Certified Enterprise Architect Examination.

Below are the Content links –

I shared this here for academic purposes and it is aimed to show an example of software applications.

Enter your email address:

Delivered by FeedBurner

How to insert data from wordpress page using wordpress api


We are trying to discuss here about

Insert data in WordPress site, using WordPress API .

Steps for creating such a functionality will be –

1.  Goto WordPress theme root folder of your choice.

2. Create a PHP page with your choice.

3. Create the WordPress Page Template code at beginning of the Page (need to do this because

wordpress will recognise this php page as wordpress page by this template code.


/*
* Template Name: User Registration
*
* The "Template Name:" bit above allows this to be selectable
* from a dropdown menu on the edit page  screen.
*/

4. Make a html form in that page.

 <form action="<?php $templateurl= bloginfo('template_url');?>/processwpdbuserreg.php" method="post">
      <label for="name">User Name:</label> 
      <input type="text" name="username" required placeholder="Name" />
      <label for="name">Password:</label>
      <input type="password" name="password" required />
      <label for="name">Confirm Password:</label>
      <input type="password" name="password" required />
      <label for="email">Email:</label> 
      <input type="email" name="email" required placeholder="email@example.com" />
      <label for="number">Interests (separate with ,):</label> 
      <input type="text" name="interests" placeholder="like J2ee, Java">
      <input type="submit" value="Create" />
  </form>

Here we have attached the action with

<?php $templateurl= bloginfo('template_url');?> because we want to get 
the template root path and then the corresponding page.

5.Now as we have specified the action in the HTML form we should show the processwpdbuserreg.php.

 <?php 
  //get the required configuration of WordPress
  require( dirname(__FILE__) . '/../../../wp-load.php' );
  //get the form elements and store them in variables
  $name=$_POST["username"]; 
  $password=$_POST["password"]; 
  $email=$_POST["email"];
  $interests=$_POST["interests"]; 
  function insertData($name,$email,$password,$interests){
    global $wpdb;
    $wpdb = new wpdb("root","","wordpress",localhost);
    $wpdb->show_errors();
    $sql = $wpdb->prepare( "INSERT INTO pb_user (name,password, email,
           interest_education ) VALUES ( %s, %s ,%s,%s )", $name,$password,
           $email,$interests );
    $wpdb->query($sql);
  }
  insertData($name,$email,$password,$interests);
  //Redirects to the specified page
  header("Location: http://localhost/wordpress/userregistration/"); 
  ?>

The process page is self-explanatory.

So that is all for saving data in database from a WordPress page.

Also you can read –

How to insert data in wordpress without using wordpress api.

Comments are welcome.

Enter your email address:

Delivered by FeedBurner

How to insert data from wordpress page without using wordpress api


We are trying to discuss here about

Insert data in WordPress site, without using WordPress API .

Steps for creating such a functionality will be –

1.  Goto WordPress theme root folder of your choice.

2. Create a PHP page with your choice.

3. Create the WordPress Page Template code at beginning of the Page (need to do this because

wordpress will recognise this php page as wordpress page by this template code.


/*
* Template Name: User Registration
*
* The "Template Name:" bit above allows this to be selectable
* from a dropdown menu on the edit page  screen.
*/

4. Make a html form in that page.

 <form action="<?php $templateurl= bloginfo('template_url');?>/process.php" method="post">
      <label for="name">User Name:</label> 
      <input type="text" name="username" required placeholder="Name" />
      <label for="name">Password:</label>
      <input type="password" name="password" required />
      <label for="name">Confirm Password:</label>
      <input type="password" name="password" required />
      <label for="email">Email:</label> 
      <input type="email" name="email" required placeholder="email@example.com" />
      <label for="number">Interests (separate with ,):</label> 
      <input type="text" name="interests" placeholder="like J2ee, Java">
      <input type="submit" value="Create" />
  </form>

Here we have attached the action with

<?php $templateurl= bloginfo('template_url');?> because we want to get 
the template root path and then the corresponding page.

5.Now as we have specified the action in the HTML form we should show the process.php.

 <?php 
  //get the form elements and store them in variables
  $name=$_POST["name"];
  $email=$_POST["email"]; 
  //establish connection
  $con = mysqli_connect("localhost","root","","wordpress"); 
  //on connection failure, throw an error
  if(!$con) {  
     die('Could not connect: '.mysql_error()); 
  } 
  $sql="INSERT INTO `wordpress`.`contact` ( `name` , `email` ) VALUES ( '$name','$email')"; 
  mysqli_query($con,$sql); 
  //Redirects to the specified page
  header("Location: http://localhost/wordpress/contact-us/"); 
  ?>

The process page is self-explanatory.

So that is all for saving data in database from a WordPress page.

On next article we will show,

How to insert data in wordpress using wordpress api.

Comments are welcome.

Enter your email address:

Delivered by FeedBurner

How to add Shortcode in WordPress


Sometimes in work there are some common html block which are needed to be placed in all pages.

In this case we have a option – SHORTCODE  in wordpress, which is quite useful.

Now below is an working example, by which we can add footer section to all of pages in wordpress.

First –

We have to open or create Function.php in wordpress theme.

Below is a code snippet where we have written a hello function.

 

function hello() {
    $footer = "This is our example footer";

    return $footer;
}

Also we should use the add_shortcode function to make it available in wordpress themes.

 

add_shortcode('hw', 'hello');

Now in a particular page we should write the shortcode as –

[hw]

to use the footer snippet in every post.

This is a minimal example of using shortcode in wordpress.

Comments are welcome.

Enter your email address:

Delivered by FeedBurner