| 20 last updates Anurag Jain |
|
|
JQuery is a very popular language over the programmers because of its amazing functionalities. It has a wonderful community of software engineer that create incredible things and designs. JQuery works like a scripting language. This is why, in this article, you will introduce some jQuery pluggin, which save tremendous effort from programmers. You know that query can be very useful over the web browser. Therefore, for this post, we have rounded up some jQuery plug-in that can help you accomplish some amazing things when it comes to enhancing web page layouts and user interfaces.
jQuery Avgrund
The jQuery Avgrund is fresh dialog explanation-language. It is not as feature-rich as acetify, but it has the amazing factor that your web app needs. The dialog is shown by the impressive animation that brings it into a focal point, while blurring and darkening the background field.
The forms are tedious and boring. Everyone hates filling them. The plug-in in this section attempts to make things better by enhancing your forms with useful functionality. And this plug-in has the power to process the client side validation.
Figure 1: jQuery Avgrund
Alertify.js
Alertify.js is another kind of jQuery plug-in. It is a small library for presenting beautiful dialog bog through the window frame and shows notifications. It is easy to customize with a Cascade style sheet, has a simple API and doesn’t depend on third party libraries but it can play sweetly with them. To call global object the plug-in is used nicely.
Listing 1: Alertify
[code]
// alert dialog
alertify.alert("Message");
// confirm dialog
alertify.confirm("Message", function (e) {
if (e) {
// user clicked "ok"
} else {
// user clicked "cancel"
}
});
[/code]
Figure 2: Alertify.js
iCheck:
iCheck is another kind of jQuery plug-in. It is a jQuery plugin that changes the frame control of your browser and help you a lot. It is perfectly customizable, works on mobile and comes with beautiful flat-style skins point. To use it, include the JavaScript and CSS files in your page, and convert all your radio and check boxes with a few lines of jQuery. Therefore this is a very useful plug-in and widely used framework nowadays.
Listing 2: iCheck
[code]
$(document).ready(function(){
$('input').iCheck({
checkboxClass: ' icheckbox_minimal ',
radioClass: 'iradio_minimal'
});
});
[/code]
Figure 3: iCheck
jQuery File Upload:
The file upload is an important feature for any programming language. The jQuery File Upload provides an excellent feature over the developers. It has widget with multiple file assortment, drag and drop support, progress bars and preview images. It also wires cross-domain, chunked and reusable file uploads and client-side image resizing. Therefore, it is an amazing plug-in that provides by jQuery. If you work with any server-side platform like PHP, Python, and Ruby on Rails, Java, Node.js and Go, you will get more flexibility by using it.
Figure 4: jQ
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
In another article, I showed how a typical web application using the Model-View-Controller can be updated to support the framework required for handling live updates: I added an update timestamp field to each object in one of the application’s database tables, and modified its data access object to support publication of changes to the objects it manages via the Observer (or Listener) pattern.
In this article, I take this groundwork and expand on it, using it to implement a web page that displays live updating data, specifically the balance in each of an account operated by a single customer. In order to simplify this process, I am using the jQuery javascript library (version 1.9.1, which can be downloaded from the official website).
What is this Comet, anyway?
Comet is an unlikely name for a family of related but simple processes (the name is actually a joke based on the brand name of a popular US cleaning product). The technique I will be using is also known as “long polling”. Immediately after the page finishes loading, it sends a new request to the server requesting details of updates. If any updates have occurred, the server sends them immediately, but in the more common case where there are no updates, it shelves the query, and does not send a response until there are updates available. While you could implement this by waiting inside a servlet’s doGet() method, doing so would be extremely inefficient: it would block the service thread until the update occurred, which if done for many clients would result in the server running out of available threads and no longer being able to service additional requests. Fortunately, the Servlet 3.0 API added a new feature to allow you to do it more efficiently.
Figure 1: Comet
Preparing the Spring servlet configuration for asynchronous requests
Unfortunately, the Servlet 3.0 API requires servlets to be explicitly configured to allow asynchronous operation, but as we are registering them dynamically by fetching them from a Spring dependency injection container this configuration cannot be done in the usual way (either in web.xml or with a field in an annotation on the servlet class). In order to allow a servlet to configure itself, I modify my SpringServletConfig class like this:
Listing 1: new code in SpringServletConfig.contextInitialized
[code]
for (Map.Entry<String,HttpServlet> entry :
((Map<String,HttpServlet>)springContext.getBean("servlets")).entrySet())
{
Dynamic reg = servletContext.addServlet (entry.getKey (), entry.getValue ());
if (entry.getValue() instanceof ServletSelfConfig)
((ServletSelfConfig)entry.getValue()).configure(servletContext, reg);
reg.addMapping (entry.getKey ());
}
[/code]
The code in italic is original code for context: I have added a new interface ServletSelfConfig (containing only the method configure()), and if the servlet object implements it I call it passing it the servlet context and the dynamic registration object, to allow it to set configuration options on either.
Implementing long polling
I start by creating a servlet that configures itself to allow asynchronous requests. Then, in its doGet() method, I call HttpServletRequest.startAsync():
Listing 2: Setting up an asynchronous request
[code]
public class AccountChangeNotifier extends HttpServlet implements ServletSelfConfig
{
AccountDAO accountDAO;
ObjectWriter objectWriter;
public void setAccountDAO(AccountDAO accountDAO)
{
this.accountDAO = accountDAO;
}
public void setObjectWriter(ObjectWriter objectWriter)
{
this.objectWriter = objectWriter;
}
@Override
public void configure(ServletContext servletContext, Dynamic reg)
{
reg.setAsyncSupported(true);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
AsyncContext asyncContext = req.startAsync();
asyncContext.setTimeout(0); // do not time requests out
t
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
It is hard to overestimate the importance of having correct data. Whether supporting executives in business decision making, providing customer support operatives with up-to-date status information, or allowing customers to make purchase decisions, accurate data is essential. And because the nature of data in a modern business is to change rapidly, accurate means up-to-date. It is therefore becoming more important than ever that information displays are updated when the data they show changes.
There are a variety of methods that can be used to update a display in a web site with new information. These vary from the simplest (prompting automatic page reloads using either the Refresh HTTP response header or its equivalent HTML “meta” tag) to much more advanced systems (using server push techniques with javascript-initiated HTTP requests, a combination commonly known as Comet, or more recently alternative data streaming APIs like WebSockets). The result is that what would once have been achieved with an ActiveX object, Java applet or even a Flash application is now much more likely to be achieved with a pure Javascript option.
In this article, I will describe a few of the possible methods of implementing this kind of feature, but before beginning we need to ensure we have a suitable application. I will describe the variation in more detail later, but for now you may consider it important to understand the basic approach that I describe in that article. I am also using Jackson for JSON serialization;
Figure 1: Database
Laying the groundwork: update timestamps and publish/subscribe
The first thing we need to consider is that our application will be attempting to retrieve a list of changes that have happened since the page that is updating itself was generated. In order to achieve this, we often need to be able to examine a record and tell if it has been updated. There are two basic approaches we can use: we can add a timestamp field to each record and update it whenever we update the record, or we can use a sequentially-incremented number. I have chosen the former, because it is simpler to implement, but it is worth bearing in mind that this approach has a few drawbacks: it only works if all the servers the application runs on have synchronized clocks, and it can become confused if updates occur multiple times within the resolution of your clock. For an application with a single server, infrequent updates, and a tolerance for occasional failures, it is appropriate however.
Update sequence numbers are more complicated to implement, because you need a source of sequence numbers that is guaranteed to increase monotonically. One possible source that may be worth considering is the numbering of records in a database table whose primary key column is set up to be auto-generated using an appropriate sequence (e.g. in MySQL, a table whose key field is declared as “INT PRIMARY KEY AUTO_INCREMENT”, or in PostgreSQL a SERIAL column).
I’ve chosen to set up the balance field in the ‘accounts’ table of my example application for live updates, so the changes I need to make are as follows:
Listing 1: SQL changes
[code]
alter table accounts add balanceUpdated datetime not null;
update accounts set balanceUpdated=now();
[/code]
I’ve chosen to use MySQL’s “datetime” type despite the fact that its resolution is only whole seconds because it allows for easier debugging (as times are presented in an understandable format). For a final application, I would consider the alternative of storing mi
...
Post view interrupted. To view full content, click here
|
|
|
|
The Zend Framework has become one of the most popular frameworks recently. You know that the PHP is an object oriented language and it has become very popular. The PHP stands at the top of the dominant languages. It was installed on most UNIX and Linux based web servers. And if you were a programmer, it was easy to get a hosting account that would let you use it. You can easily communicate it Java, J2EE, Perl languages.
Some features of Zend Framework:
- This is based on PHP language
- This is object oriented Language
- Uses the MVC pattern
- Have open source contributor
Zend is a PHP based framework. Recently, web development has become a very bloodthirsty arena for programming languages and by using the framework, user can do various kinds of activities. As a result, there has been an excess of options for programmers to choose from. Most of the time, a significant amount of time can be spent on searching for tools to speed up development instead of recreating from scratch. This writing is aimed at PHP developers who are looking to learn more about how to acquire knowledge of Zend based framework. This is not a comparative list of all PHP frameworks, as there are many new options like CakePHP and Symphony to name two. Zend framework seems to fit nicely with my requirements and it may not too long time to become familiar with this.
If we want to work with Zend Framework, this has the following requirements:
- PHP 5.2.4 or higher version than that
- A web based server supporting mod_rewrite or similar functionality.
I have assumed that you are running the PHP 5.2.3 or higher with the Apache web server then your Apache installation must have the mod_rewrite extension installed and configured. This time, you must also ensure that Apache is configured to support .Htaccess files.
This is normally done by changing the setting:
Listing 1: Changing settings
[code]
AllowOverride None
to
AllowOverride All
in your
httpd.conf
[/code]
Download:
If you want, you can download the zip Zend framework from any website. The Zend Framework is supplied with a new command line tool.
Zend tool for window:
- Now create a new directory in Program Files that is called ZendFrameworkCli
- Click on the downloaded archive file, ZendFramework-1.8.4PL1-minimal.zi
- This time copy the bin and library folders from within the Zend Framework-1.7. 4PL1-minimal.zip
- Folder window to the C:\Program Files\ZendFrameworkCli folder. You will get two sub folders: bin and library within it.
- Now you add the bin to the path of:
- Within the Control Panel find out the System section.
- Choose Advanced and then press the Environment Variables button within it.
- In the “System variables” list and find the Path variable and double click on it. Page
- This time adds; C:\Program Files\ZendFrameworkCli\bin to the end of the input box and press okay.
By this way you will able to configure the
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
It does however have drawbacks: it is a relatively heavyweight format, with a degree of flexibility that can make manipulating it in environments where we either don’t have or don’t want to use object binding somewhat daunting. In web client scripting (i.e. AJAX) environments, JSON is often preferred. JSON is a format designed specifically for use by Javascript applications, which has a one-to-one mapping with Javascript’s native object model, meaning that object mapping of the kind we have been using with XML is not necessary when working in Javascript with JSON.
With this in mind, if you are developing a dynamic web client for your services as well as the mobile client, you may prefer to use JSON to integrate both parts, thus reducing the amount of work required on the server.
Jackson is the most popular Java library for handling JSON data. It can be downloaded from http://jackson.codehaus.org/, and I have used version 2.1 in the code for this article (although other versions should be similar).
Switching the server side
In preparation to switch to using Jackson, I removed the SimpleXML jar files from my server project and fixed the errors that occurred by removing the references. I then set up Spring to create and configure the necessary Jackson objects:
Listing 1: Spring configuration to create Jackson objects
[code]
<bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" />
<bean id="objectWriter" factory-bean="objectMapper" factory-method="writerWithDefaultPrettyPrinter" />
<bean id="objectReader" factory-bean="objectMapper" factory-method="reader" />
<util:map id="servlets">
… other servlets configured here ….
<entry key="/json/customers"><bean class="com.example.jsonservice.CustomerList" /></entry>
<entry key="/json/customerAccounts">
<bean class="com.example.jsonservice.CustomerAccounts" /></entry>
<entry key="/json/newCustomer"><bean class="com.example.jsonservice.NewCustomer" /></entry>
</util:map>
[/code]
It is possible to just use the Jackson ObjectMapper object directly, rather than creating ObjectWriter and ObjectReader instances, but I wanted to use Jackson’s “pretty printer” feature to get formatted JSON output, and this requires configuration that cannot be performed directly on the ObjectMapper. I therefore decided to use both ObjectWriter (which is required to use the pretty printer) and ObjectReader (which is not) in order to maintain symmetry in the way my application creates and consumes JSON documents.
Having done this, I switched my first servlet over to using the Jackson interface:
Listing 2: The CustomerList servlet
[code]
public class CustomerList extends HttpServlet
{
CustomerDAO customerDAO;
ObjectWriter objectWriter;
public void setCustomerDAO (CustomerDAO customerDAO)
{
this.customerDAO = customerDAO;
}
public void setObjectWriter (ObjectWriter objectWriter)
{
this.objectWriter = objectWriter;
}
@Override
protected void doGet (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType ("application/json");
try
{
objectWriter.writeValue(resp.getWriter(),
Result.customers (customerDAO.getAll ()));
}
catch (JsonGenerationException|JsonMappingException|SQLException e)
{
throw new ServletException ("Error sending list of customers", e);
}
}
}
[/code]
The changes are, as you can see, minimal. Running it, I got this output:
Listing 3: JSON output from the first run
[code]
{}
[/code]
This highlights an important difference between SimpleXML and Jackson that it is important to understand and can help work with either of them: SimpleXML is a field-based serializer, i.e. when looking at an object it examines a list of its fields and queries them directly (under control of annotations on those fields). Jackson, however, works with getter and setter methods instead. As I had not defined public getters for fields in my Result class, it did not list any values. Adding the necessary getters and retesting produces the expected output:
Listing 4: JSON
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
In order to build a working application, there are a handful of additional features that are required. In this article, I will discuss:
- Sending structured data back to the server (using the example of a form to create a new customer)
- Displaying structured data (using the example of Listing a customer’s accounts)
I will also discuss a problem that can occur when developing XML and date handling code for Android and how to work around it.
Creating new customers
To add a new Activity, it is best to use the Eclipse wizard for the purpose. Right click on your source folder and choose New / Other… from the menu. In the Android category, choose “Android Activity”. I called my activity NewCustomerActivity, and based it on the blank activity template. I also deleted the options menu it created, and the method it created to initialise the menu. My layout XML looks like this:
Listing 1: The layout for NewCustomerActivity
[code]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".NewCustomerActivity" >
<TextView
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name" />
<EditText
android:id="@+id/edtName"
android:layout_below="@id/txtName"
android:layout_alignLeft="@id/txtName"
android:layout_marginTop="4dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords"
/>
<Button
android:id="@+id/btnCreate"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="@string/create" />
</RelativeLayout>
[/code]
I also created strings in the res/values/strings.xml file matching the two strings I used above with content “Name:” and “Create”.
The activity code is quite similar to the customer list activity code. onCreate() looks like this:
Listing 2: Initializing the NewCustomerActivity
[code]
Serializer xml;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_customer);
findViewById(R.id.btnCreate).setOnClickListener(create);
xml = new Persister();
}
[/code]
I set the create button’s OnClickListener to an event handler I store in the field “create”. I initialise this in the field declaration using an anonymous class:
Listing 3: Handling the create button press event
[code]
ProgressDialog progressDialog;
AsyncTask<Customer, Void, Result> actionInProgress;
private View.OnClickListener create = new View.OnClickListener() {
@Override
public void onClick(View v)
{
if (actionInProgress != null) return;
Customer customer = new Customer();
customer.setName(((EditText)findViewById(R.id.edtName)).getText().toString());
actionInProgress = new CreateCustomerTask().execute(customer);
progressDialog = new ProgressDialog(NewCustomerActivity.this);
progressDialog.setCancelable(true);
progressDialog.setOnCancelListener(onCancelListener);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setMessage("Creating customer");
progressDialog.show();
}
};
[/code]
This is quite similar to the download() method from this article, except that I create a new Customer and initialise its name field, then pass it to the execute method of CreateCustomerTask. onCancelListener is identical to the event handler of the same name in the CustomerListActivity, except that I have renamed the downloadInProgress field to actionInProgress.
CreateCustomerTask is, like the CustomerListActivity’s DownloadTask, a subclass of AsyncTask. Its structure is very similar to DownloadTask.
Listing 4: Creating the customer on the server
[code]
class CreateCustomerTask extends AsyncTask<Customer, Void, Result>
{
@Override
protected Result doInBackground (Customer... params)
{
HttpClient client = new DefaultHttpClient ();
try
{
HttpPost request = new HttpPost (
"http://192.168.1.101:8080/simplespring/xml/newCustomer");
StringWriter buffer = new StringWriter();
xml.write(params[0], buffer);
StringEntity requestEntity = new StringEntity(buffer.toString());
requestEntity.setContentType("text/xml");
request.setEntity(requestEntity);
HttpResponse response = client.execute (request);
if (response.getStatusLine ().getStatusCode () != 200)
return Result.error (
response.getStatusLine ().getReasonPhrase ());
HttpEntity entity = response.getEntity();
String contentType = entity.getContentType().getValue();
if (!contentType.startsWith("text/xml"))
return Result.error (
"Did not receive XML response (content type was: " +
contentType + ")");
return xml.read(Result.class, entity.getContent());
}
catch (Exception e)
{
return Result.error (e.toString());
}
}
@Override
protected void onPostExecute(Result result)
{
super.onPostExecute(result);
progressDialog.dismiss();
actionInProgress = null;
if (result.isError())
{
Toast.makeText(NewCustomerActivity.this,
result.getError(),
Toast.LENGTH_LONG).show ();
}
else
{
finish();
}
}
};
[/code]
Like DownloadTask, we use a DefaultHttpClient to send our request. This time, we’re sending a POST request rather than a GET request, and this means we need to encode our request’s data in XML. We use a StringWriter to capture the results of the SimpleXML serialization in a string, and then wrap this in an HttpClient StringEntity object. We give the object a content type of text/xml and send the request to the client. Checking the result from the server precedes similarly to DownloadTask. Back in the main application thread, we check for and display errors, and if the creation was successful we instruct the activity to finish, which will return us to the customer list (which will refresh automatically, so we can see our new customer). Now we just need to hook this activity in to the customer list activity so we can reach it. Add an item “New customer” to the customer list’s options menu, and handle it like this:
Listing 5: Updated menu handling for the customer list activity
[code]
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item)
{
switch (item.getItemId())
{
case R.id.refresh:
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
With smartphones and tablet computers rapidly become a common fixture of most business’s IT strategy, integration of mobile applications with existing server-side systems is now among the most common kinds of development project. With a variety of mobile platforms to cater for, it can be a daunting task, but by standardising on a single client platform the scope of the project can be managed. For Java developers, Android presents a tempting platform, as the system is based around familiar Java APIs. Unfortunately for the Java developer, Android is far from a complete implementation of Java, and resource constraints on devices (particularly lower-cost smartphones) often mean that familiar enterprise APIs cannot be easily adapted to use on the clients. By careful choice of technology, however, it is still possible to rapidly develop client applications using Android, and by choosing standard data transfer techniques (e.g. XML entities passed over HTTP requests) we can leave open the possibility of supporting other platforms without requiring modifications to the server side.
To familiarise yourself with the site and data, I recommend you read my previous articles during which it was developed, especially Framework-free patterns: Model View Controller, which describes the most recent changes to the site that are built upon by this article (other articles in the series have modified the site since, but those changes are tangential to the changes introduced here).
Selecting an XML library
Many developers would choose to dive straight into an XML development project by first designing an XML schema for the requests and responses and then implementing that schema using the XML APIs they are familiar with (typically either the Document Object Model or JAXB, the Java Architecture for XML Binding). In my experience, this is a mistake.
Android runs on a very constrained implementation of Java, and is missing several parts of the standard Java SE API. Unfortunately, this includes several components that are required for supporting JAXB. While these components can be added (or, as in the case of the lack of support for reflection on packages, their absence worked around), doing so inflates the size of an application using JAXB by several megabytes; in resource constrained smartphones this is often an unacceptable cost. The standard alternative would be to use the DOM, but developing applications using the DOM is much slower than using a data binding API.
Fortunately, there are several alternatives available, including an implementation of XML as an output transformation for the data-format agnostic Jackson library (originally written as a data binder for JSON, but offering a choice of several formats now) and the XML-specific SimpleXML framework. I have chosen to use the latter in this article, as it has the lower resource requirements of the two (Jackson, while smaller than JAXB, still consumes more than a megabyte of space in your .apk files, while SimpleXML only requires a few hundred kilobytes). It can be downloaded from http://simple.sourceforge.net/.
With the choice of SimpleXML made, now I work on designing my schema. I have delayed this until now because SimpleXML and Jackson both allow very simple configuration if I chose to work with their default behaviour but can become quite complicated to use if I chose to try to force them to work with an arbitrary schema. By designing my Java objects and working with the format that the library naturally produces when passed those objects, I can save myself a substantial headache later.
Implementing the server
While it would be possible to add XML-based interfaces to my existing servlets (e.g. by including a mechanism for switching between multiple view implementations in a Model-View-Controller architecture), for the sake of simplicity I have chosen to implement new servlets in a parallel structure. All of the application specific logic for my site has already been moved into my Model objects; the existing servlets merely serve as an interface between the external world of HTTP requests and the business-domain world seen through the eyes of my model objects, so the duplication of effort is actually relatively small compared to the extra complexity that would be introduced by adding such view switching logic, along with the possibility of needing to decode requests from multiple formats.
I start with the simplest servlet, which is also the main gateway into the site, and will provide the data required for th
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
I have chosen to target low-end current generation (as of 2013) smartphones . These devices are typically fairly resource-constrained (free storage space on the phone’s integrated flash is typically counted in the low tens of megabytes, and application run time heaps are generally limited to 32MB) and often run older versions of Android (typically version 2.2 or 2.3) with low resolution displays (320x240 is common). It is important to bear in mind these restrictions while developing applications for this kind of device. It goes without saying that a developer should have a device of the lowest specification targeted for testing purposes; it is also important, however, to use the device along with the application being developed on a day to day basis, as this is the only way to get a true feel for how the other applications on the phone will affect its performance.
In this article, I will implement a simple Android client for this API. I assume that the client will have an always-available connection to the server, so I do not need to worry about offline storage of data. Data is downloaded on-demand immediately prior to display, and requests are sent back to the server immediately in response to user commands.
Figure 1: XML File
Developing the app
To develop the application, I am using Eclipse with the Android Developer Tools plugin. I highly recommend this combination as it is Google’s only officially-supported integrated environment, so most of the Android documentation and samples as well as many third-party books and articles will assume that this is the environment you are using.
To begin, allow Eclipse to set up an Android Application project; it will ask for a variety of information. As well as naming the project, you need to specify a package name (I used com.example.simplespringclient, as I had called the web application’s project simplespring), and choose the versions of Android you want to target. You can choose to use a higher SDK version than your minimum targeted version; doing so allows you to use more modern features of Android when they are available.
Create an initial Activity object using Eclipse’s wizard, selecting a “blank” activity from the list of options. Blank is the simplest and most portable option, as it does not require any advanced features. Of the other types, only the “master and details” activity is really suitable for this kind of application, but as it requires a higher minimum version of Android than I have chosen I cannot use it. I called my first activity CustomerListActivity. Once it has finished creating the Activity, Eclipse automatically opens the layout it has created for it, which you will need to edit. My plan for this activity is to just present a list of customers as the main interface; extra commands will be added to the activity’s options menu. Delete the text view control Eclipse places on the layout by default, and replace it with a ListView object, and give it a useful id.
Now we have a suitable layout, we need to look at some code. The first place to start with an Android activity is usually its onCreate method. Eclipse has generated a stub for us that fulfils the basic requirements: it calls super.onCreate - Android will throw an exception if we fail to do this - and loads the layout it created for us. We’ll also need to set up any event handlers we want on the controls, create extra objects we need, and initiate a data download.
Listing 1: The finished onCreate method
[code]
private ListView customerList;
private Serializer xml;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer_list);
customerList = (ListView) findViewById (R.id.customerList);
customerList.setOnItemClickListener(viewAccounts);
xml = new Persister ();
download();
}
[/code]
We find the customer list and set a handler for what to do when an item is clicked (We’ll actually define viewAccounts later; for now you can jus
...
Post view interrupted. To view full content, click here
|
|
|
|
We know that BIRT is a lightweight reporting tool. Here we will show how to incorporate chart like pie chart, bar chart, line charts and others. The BIRT charting is an integral part of data summation, data summation, and analysis and data management. BIRT introduce an excellent combination for charting, allowing diverse chart types such as bar charts, pie charts, line charts, scatter charts, and stock charts. By using this chart we can preview the data in our required optimization way.
Each chart type is also customizable, offering a wide valid range of features to better represent data. The preview is very glossy and mind blowing. Here we will show an example how to represent a birt chat report. That example mentions the use of BIRT's integrated charting information within the report designer. The example builds a two-dimensional pie chart and summarizing product revenue by product line.
This is the screen shot of Bar chart.
Figure 1: This is the screen shot of Bar chart.
This is the screen shot of Pie chart.
Figure 2: This is the screen shot of Pie chart.
The BIRT is a reporting tool that mainly focuses on Eclipse. But we can connect it with other suit like net beans. We easily can use BIRT to create table, chart, list, and cross tab reports to display data sets. It is very easy to incorporate JavaScript and any condition what we like. We can also develop reports that are more complex and elaborate by using scripts. We present the code of JavaScript and jsp how to interconnect thus with BIRT report. At first, we present a simple JavaScript code that works with Birt Report.
If you want to pass any parameter; you can send it through the jsp page. The BIRT development environment generally includes a report designer, a charting engine, and a run time environment and much more fixtures. By using the java script code, you call a birt report viewer. Birt Framework has the building facilities to run Birt report internally.
Listing 1: Javascript code:
[code]
<script language="javascript">
function previewBirtReport(){
var url="http://#{facesContext.externalContext.request.serverName}:#{facesContext.externalContext.request.serverPort}"+"/portal-web/help/vms/Vehicle.jsp"
window.open(url,'Help','top=80,left=140,width=900,height=700,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,true');
}
function helpAdmin(){
var url="http://#{facesContext.externalContext.request.serverName}:#{facesContext.externalContext.request.serverPort}"+"/portal-web/help/vms/help_admin. jsp"
window.open(url,'Help','top=80,left=140,width=900,height=700,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=1,true');
}
</script>
[/code]
This above script uses to preview the birt report.
Now, we show a Jsp page. The Jsp page is used to preview the Birt report, which contains pie char. ‘String viDocId=String.valueOf(request.getParameter("docId"));’ use to receive the parameter that provide by a jsp pages. Therefor in than way, you can manipulate your parameter and able to pass it within the birt report design and layout. The birt viewer ‘birt: viewer’ opens the birt report. Within the birt viewer tag, you can put the Birt report name that you want to preview when you run it.
Listing 2: Now, we show a Jsp page.
[code]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="org.jboss.seam.international.LocaleSelector" %>
<%@ taglib uri="/WEB-INF/tlds/birt.tld" prefix="birt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Notes</title>
</head>
<body>
<%
String viDocId=String.valueOf(request.getParameter("docId"));
String viRecordId=String.valueOf(request.getParameter("recordId"));
%>
<birt:viewer id="birtViewer" reportDesign="/fts/reports/filenotes.rptdesign"
pattern="frameset"
isHostPage="true"
format="html"
>
<birt:param name="docId" value="<%=viDocId%>" >
</birt:param>
<birt:param name="recordId" value="<%=viRecordId%>" >
</birt:param>
</birt:viewer>
</body>
</html>
[/code]
BIRT is an open source reporting tools. It is very user friendly and quite lightweight. BIRT provides core reporting feature such as report layout, data access and scripting, chats, bar, some others facilities as well. We can try BIRT to building report easily. We can use the Business Intelligence and Reporting Tools like BIRT report development tool to develop a range of reports. When you design the report, vary on your requirements, you can design the chart what you like to add.
It provides an excellent feature to add the chart by dragging option. You need to connect the data source name with the pie chart. We know there is two dimension in the pie chart, as one is ‘X’ dimension and the other are ‘Y’ dimension. We need to assassin the table field with the each dimension. This way helps us to create a Birt chart report and this is very user friendly.
Listing 3: Xml file
[code]
<?xml version="1.0" encoding="UTF-8"?>
<report xmlns="http://www.
...
Post view interrupted. To view full content, click here
|
|
|
|
BIRT is an open source-reporting tool. It is very user friendly and quite lightweight reporting tool. BIRT provides some core reporting feature such as report layout, data access and scripting, chats, bar, some others facilities as well. We can try BIRT to building report easily. We can use the Business Intelligence and Reporting Tools like BIRT report development tool to develop a range of reports. BIRT provides all kinds of facilities to build and preview report. After ringing the birt report on report viewer, we can download it in any format like Microsoft word, Microsoft Excel, Pdf and HTML.
Now we will show how to develop a BIRT report. The name of the report is “division.rptdesign”. The extension of BIRT is ‘. Rptdesign’. We start with a blank report design.
Before you start designing your report in the layout editor, you build a BIRT data source to connect your report to a database or other types of data sources. When you build a data source, you specify the driver class, data source name and other connection information, such as user name and password. For this article, you use the sample database as as oracle or Mysql to design a simple report. BIRT Report Designer provides an easy sheet that contains systematic instructions, to help. You can create the report.
Now, you start with a blank report design.
Choose File->New->Report. New Report appears. There you write the name of the report.
To establish the connection you Right-click Data Sources, then choose New Data Source from the context menu. New Data Source displays the types of data sources you can create now select Classic Models Inc. Sample Database from the list of data source types. Use the default data source name, and then choose next. Connection information about the new data source appears. By this way, you can create a database connection with Birt Report.
Figure 1: Build Data Source.
In the text area, type the following SQL SELECT statement to specify the data to retrieve:
Listing 1: Data retrieval
[code]
Select divisionName,
DivisionNameBen,
ContactFirstName,
Phone
From ConfDivision
Or
Select *
From ConfDivision
[/code]
Although the dataset editor shows table and column names in capital letters, you can type the names how you prefer, because SQL is not case-sensitive. If you do not want to type the query, you can drag columns and tables from the Available Items to the text area.
Before you start designing your report in the layout editor, you build a BIRT report data source to connect your report to a database or some other types of data sources. At the time, when you build a data source, you specify the driver class, data source name, and other connection information, such as user name and password. Of these articles, you use the sample database, Classic Models that is already configured for use with BIRT Report Designer. You do not need to specify the connection. At first need to make a data source. Depending on our requirement, we will develop a SQL query. Here we will provide the screen shot of it. As per your requirement, you generate the data source. Most of the time, ‘Jsp’ pages use pass any parameter. You can add any filter as per your requirement; this helps you to retrieve some data which want to show. Parameters and filters are important to design a report.
When you go to preview the Birt report, you can incorporate chart and other things with on it, to make this very interactive. We can use and filter or add some parameter depending on our requirement.
BIRT report designing is easy and less time consuming. We add features like table, grid, and text area and text field by drag and drop. The BIRT development environment generally includes a report designer, a charting engine, and a run time environment and much more fixtures. The BIRT is a reporting tool that mainly focuses on Eclipse. But we can connect it with other suit like net beans. We easily can use BIRT to create tables, chart, list, and cross tab reports to display data sets. It is very easy to incorporate JavaScript and any condition what we like. We can also develop reports that are more complex and elaborate by using scripts.
The layout of BIRT report
Figure 2: Birt Report Layout
When the query is finished then choose Finish to save the data set. Edit Data Set displays the columns you specified in the query, and provides options for editing the data set. Then, choose Preview Results to make sure the query is valid and that it returns the correct data. If you typed the SELECT statement correctly, you should see the results that are shown in the preview. This helps you to design the Birt report.
In the layout editor, you can design as per your requirement. The table cell in which you dropped the confDivision field contains a data element that displays [divisinName]. Above this data element is a label element that the layout editor automatically added to the header row. This label displays the field name as static text. It serves as the column heading. In this way you can design the Birt Report.
We can run BIRT reports by using the BIRT report viewer or Maximo Reports viewer or by using the Report List box in the Maximo Assistance Management Start Center. That is one of the ways to run a BIRT report. The mention figures imply the BIRT development environment components and the interfaces between them. We here want to view the steps.
If we want to build BIRT report, we need to add the BIRT plug-in with our eclipse. The BIRT community provides eclipse, which have built facilities of BIRT. BIRT jars and ‘tiled’ files can work with J2EE structure. Now we will show how to create a Simple BIRT report. We will provide step by step process.
This xml code creates by the time of Birt report design. The Birt generates a huge amount of xml code by the time of design. You can add some your customize design on it by editing it. There the xml code previews some sql code that we mentioned in data source. This is very important also to edit the xml when requires.
Now we show the xml file of “Division. Rptdesign”.
Listing 2: Full code for xml file of “Division.rptdesign”.
[code]
<? Xml version="1.0" encoding="UTF-8"? >
<Report xmlns="http://www.eclipse.org/birt/2005/design" version="3.2.20" id="1">
<Property name="createdBy">Eclipse BIRT Designer Version 2.5.1. v20090903 Build < 2.5.1. v20090917-1447></property>
<property name="units">in</property>
<property name="iconFile">/templates/blank_report.gif</property>
<property name="layoutPreference">auto layout</property>
<property name="bidiLayoutOrientation"&g
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
Before I start, I should clarify something. There are two design patterns that are generally known as “Model-View-Controller”. They are closely related, but are not the same. The elder of the two is the one described in the book Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson and Vlissides (commonly referred to as “Gang of Four” or “GoF”). In this pattern, View objects monitor a Model using the Observer pattern so that they are notified when the Controller objects introduce changes to it. This is not the pattern I am discussing. The Model-View-Controller architecture used by many web application frameworks has a slightly different structure. In order to adapt the pattern for the stateless nature of web applications, the relationship between the components has changed slightly:
The Model is still the same as it ever was, a representation of the basic data that makes up the system being interacted with. It no longer needs to support the Observer pattern, however, as we will not be using it like that anymore.
The Controllers adopt an extra responsibility: as well as performing any updates that are required to the Model, they must also select an appropriate View to present to the user, extract any Model data that is required by the View and pass control to the View.
The View no longer actively monitors the Model, so like the Model no longer needs to implement Observer, but is instead purely reactive to being invoked by the Controller.
This article expands our knowledge about MVC. It also uses the Spring framework with a method that I described in Servlet dependency injection with Spring.
Refactoring to the Model-View-Controller pattern
At its heart, implementing the MVC pattern for web applications is extremely simple. Taking an example servlet from the previous article, the changes required are quite simple:
- We are already using Model objects, which we load via Data Access Objects.
- The servlet class is performing the roles of Controller and View already. We simply need to separate these, and take advantage of the separation to rewrite them using more appropriate techniques for their two functions.
Because we separate all interaction with the model from the presentation of the results to the user, the View object is free to be changed from standard Java code to something more focussed on data presentation. We could, in fact, use any suitable templating or HTML rendering library for the view. For this article, I have decided to use JSP as the view rendering system. This is because it is simple, demonstrates effectively the techniques required, and I suspect most of my readers will already be familiar with its operation. You could however easily substitute Velocity, FreeMarker, or any other Java templating system you prefer.
Having decided how we’re going to render the view, the next thing is to work out what information it is going to need. This is often very simple: for example, the controller for the “customer list” action needs to provide a list of all customers to the view – this is readily available from a single method call to the Customer Data Access Object.
...
Post view interrupted. To view full content, click here
|
|
|
|
Seam provides some facilities of Advanced Searching. We all know that Seam is a strong component based framework. Searching is very important for any framework.
There are many frameworks, which allow implement their first crack at content searching. It works independently but does not give the search experience users expect today. However, seam can provide a specific searching component. For example, if the search query is computer software and the blog contains text or other like "what we supply both by the parameter computers and software", the normal like query that will not work, because of the word and is in the middle point. Therefore, trying to solve such kind of problems with complex type of SQL constructions becomes a nightmare and gives poor results. SEAM provides even worse and these types of like-based queries that have severe performance problems as the data set grows, because it does not use any type of indexing. It must search through the entire corpus, one character at a time.
Seam integrates many technologies like JavaScript, JSP, JSTL, Ajax, JPA, JBPM and servlet. Seam is an application development framework for Java EE that connected the component and other models of JSF and EJB 3.0 that is a strong component dependent framework, providing a streamlined searching model for web-based java and j2ee enterprise applications.
Listing 1: JSP code:
[code]
package com.domtech.domain.config;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import org.jboss.seam.annotations.Name;
@Entity
@Table(name = "ADMIN_UNION")
@Name("union")
public class AdminUnion implements java.io.Serializable {
private long unionId;
private AdminUpazila adminUpazila;
private String unionNameEng;
public AdminUnion() {
}
public AdminUnion(long unionId, AdminUpazila adminUpazila) {
this.unionId = unionId;
this.adminUpazila = adminUpazila;
}
public AdminUnion(long unionId, AdminUpazila adminUpazila
) {
this.unionId = unionId;
this.adminUpazila = adminUpazila;
this.unionNameEng = unionNameEng;
}
@Id@GeneratedValue
@Column(name = "UNION_ID", unique = true, nullable = false, precision = 20, scale = 0)
@NotNull
public long getUnionId() {
return this.unionId;
}
public void setUnionId(long unionId) {
this.unionId = unionId;
}
@Column(name = "UNION_NAME_ENG", length = 250)
@Length(max = 250)
public String getUnionNameEng() {
return this.unionNameEng;
}
public void setUnionNameEng(String unionNameEng) {
this.unionNameEng = unionNameEng;
}
[/code]
Now we will show the ‘AdpSectorList’, which extends ‘Entity
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
My previous article, Framework-free enterprise patterns: Active Record , introduced the Active Record pattern and showed a simple implementation. This implementation has the advantage of being simple, easy to understand, quick to write, and has a high degree of isolation between the logic required to deal with different types: everything about one type is encapsulated within its class.
It does, however, have one serious problem: lack of performance. Every request we make for an Account record triggers an extra database query for its corresponding Customer record. If we have a million accounts and request the list of all of them, we’ll get a million database queries. Obviously, in a large system this is totally unacceptable.
Active Record with Joins
The obvious solution is to use a join in the implementation of the query methods to obtain the Customer’s data at the same time as we get the Account. While this is relatively simple if we ensure that each table has column names that are unique, we would like to not have such a constraint on column naming Column names should, in my opinion, be natural and correspond to the data they describe, not artificially forced into a naming scheme that has only structural benefits. But unfortunately, unlike other database APIs like Microsoft’s ADO.NET, JDBC doesn’t allow us to retrieve data from a result set using a “table.column” syntax. We’re therefore going to have to rename any conflicting columns in the query.
The first change is to change Customer’s ResultSet constructor to default protection rather than private, so it can be created from Account. Now we have to change the queries to rename the columns, and at the same time change the constructor to extract its data using the new names; I’ve decided to rename all of the columns in the queries as we don’t know what tables or columns will be added to the database in future, and I don’t want to have to check every table each time for columns that might conflict in a join. I’ve decided on a simple scheme of renaming each column to “entity_column”, where “entity” is the singular name for an entity (i.e. the class name in lower case, or the name of the table in singular rather than plural). Changing over the “get” method my results look like this:
Listing 1: First set of changes to the Customer class
[code]
Customer (ResultSetrs) throwsSQLException
{
id = rs.getInt ("customer_id");
name = rs.getString ("customer_name");
}
....
publicstatic Customer get (Connection connection, int id) throwsSQLException
{
try (PreparedStatement s = connection.prepareStatement (
"select customers.id customer_id, customers.name customer_name"+
" from customers where customers.id=?"))
{
s.setInt (1, id);
try (ResultSet r = s.executeQuery ())
{
if (r.next ())
returnnew Customer (r);
returnnull;
}
}
}
[/code]
A similar change can be made to getAll(). No changes need to be made to the writer methods update() and create().
Now we can look at the changes to Account. Its constructor changes similarly to Customer’s, only we extend it so that if its ResultSet includes columns for customer (we check by searching for the customer_id column) we create a Customer directly rather than querying for a new one:
Listing 2: Account’s updated constructor
[code]
private Account (Connection connection, ResultSetresultSet) throwsSQLException
{
id = resultSet.getInt ("account_id");
balance = resultSet.getDouble ("account_balance");
if (resultSet.findColumn ("customer_id") > 0)
customer = new Customer (resultSet);
else
customer = Customer.get (connection, resultSet.getInt ("account_customer"));
}
[/code]
We can now change the get*() methods in Account to use the necessary field renaming and
...
Post view interrupted. To view full content, click here
|
|
|
|
Crystal Reports is a dynamic reporting tool. It is a business intelligence reporting tools that used to design and generate reports from a range of data sources like oracle and MySQL. Crystal Reports establish a connection with Java and j2ee framework to display variety of report. Crystal Reports can works with .Net framework. Crystal Reports for Visual Studio .NET is one of the standard reporting tool for Visual Studio .NET; the main facility of it the light weight. It can produce interactive and dynamic report, deplorable presentation quality content that has been the strength and powerful mechanism of Crystal Reports for years to the .NET platform. So, if we think dynamically, Crystal Reports can works with Java and .Net framework.
Now, in these articles we will show how to generate a crystal report. We need to install the Crystal Report software to our machine to use the reporting tool. At first, we need to make a connection with the database server. We open a report design file and establish a connection with the required database.
Figure 1: Database
After establish the connection, we need to write down the SQL query, depending on our requirement. We can able to pass any parameter, if we need to preview data upon any condition. Crystal Reports has Database Expert. By using the Database Expert, anyone can select and link variety of tables from the data sources, including Microsoft PowerPoint and Microsoft Excel spreadsheets, Oracle databases, Business Objects Enterprise business views, and local file system information. The Database Expert helps you to add any parameters and filters within the report. . At first need to make a data source. Depending on our requirement, we will develop a SQL query. Here we will provide the screen short of it. As per your requirement, you generate the data source. Most of the time, ‘Jsp’ pages use pass any parameter. You can add any filter as per your requirement; this helps you to retrieve some data which want to show. Parameters and filters are important to design a report.
Figure 2: Sql query Examples
With the preview of SQL, we find two parameters named ‘bo_folio’ and ‘mdate’. We will show the process how to send the parameter’s value and make interconnection with jsp and Crystal Report.
We can able to drag and drop facilities in this reporting section. Crystal Reports provide the facilities of graphically design data connection(s) and design report layout. Crystal Reports provides the facilities to generate chart report like pie chart, bar chat, line chart etc. In the Crystal Reports design pattern we can add labels, grid, table and chart by drag and drop process. So, we just need to follow how to add the fields in the design layout.
Figure 3: Table
Fields from these tables can be placed on the report design surface, and can also be used in custom formulas, using either BASIC or Crystal's own syntax, that is then placed on the design surface. Formulas can be evaluated at several phases during report generation as specified by the developer. This jsp page is used to call the ‘Omnibus.jsp’ page. When we call the jsp page we will send two parameters that must for building the report. In the next jsp page there is show down two fields that’s inter connect with Crystal Report. Edit Data Set displays the columns you specified in the query, and provides options for editing the data set. Then, choose Preview Results to make sure the query is valid and that it returns the correct data. If you typed the SELECT statement correctly, you should see the results that are shown in the preview. This helps you to design the Crystal Report. It is very east to add any line and label in the report. This helps the designer lots to develop Crystal Report easily.
Listing 1: JSPcode:
[code]
<%@ pageerrorPage="CommonError.jsp" %>
<jsp:useBean id="cm" class="batbsms.conBean"/>
<LINK REL=stylesheet "<%=request.getContextPath()%>/js/common.css" TYPE="text/css"></LINK>
<% if(String.valueOf(session.getAttribute("UserName")).equals("null"))
{
%><script>top.location = "<%=request.getContextPath()%>/Index.jsp"</script>
<%}%><html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Omnibus Group List<
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
In the previous article, I introduced Spring’s support for aspect-oriented programming, and discussed a particular application for it: automatically wrapping each request to any servlet in an application with a transaction. In this article, I will show how to implement that with the building blocks introduced in the last part, and describe the similar (albeit more advanced) support integrated into Spring for managing transactions.
An application that needs transactions
In order to demonstrate this technique, we need an application that can take advantage of it. So, I’ll add to the application that was built in the previous article a new servlet, and this one will need a database. I’m using MySQL because I have a copy on my development machine already, but any modern relational database management system should do the job. You do obviously need a database that supports transactional updates, so I’m going to configure my MySQL table to use the InnoDB engine (MySQL’s default MyISAM engine does not support transactions).
Listing 1: The SQL statements to configure the database
[code]
create database test;
use test
grant all on test.* to 'test'@'localhost' identified by 'test';
create table accounts (
id int primary key not null,
balance decimal(9,2) not null
) engine=innodb;
insert into accounts values (1, 0);
insert into accounts values (2, 0);
insert into accounts values (3, 0);
[/code]
Now we need to configure a data source in our Spring context. I’ll also configure a simple connection manager bean, because we need to ensure that all code within each transaction always uses the same connection to the database. My code will use the connection manager to get a database connection object, and the connection manager will get the object from the data source.
Listing 2: new bean definitions in applicationContext.xml
[code]
<bean id="dataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
<property name="driver"><bean class="com.mysql.jdbc.Driver"/></property>
<property name="url" value="jdbc:mysql://localhost/test"/>
<property name="username" value="test"/>
<property name="password" value="test"/>
</bean>
<bean id="connectionManager" class="com.example.springtransactions.ConnectionManager" />
[/code]
Listing 3: The ConnectionManager class
[code]
public class ConnectionManager
{
private DataSource dataSource;
private ThreadLocal<Connection> connections = new ThreadLocal<Connection> () {
@Override
protected Connection initialValue ()
{
return getNewConnection ();
}
};
public void setDataSource (DataSource dataSource)
{
this.dataSource = dataSource;
}
@SuppressWarnings ("resource")
public Connection getConnection ()
{
Connection result = connections.get ();
try
{
if (result.isClosed ())
connections.set (result = getNewConnection ());
}
catch (SQLException e)
{
connections.set (result = getNewConnection ());
}
return result;
}
public Connection getNewConnection ()
{
try
{
return dataSource.getConnection ();
}
catch (SQLException e)
{
throw new RuntimeException ("Couldn't get SQL connection", e);
}
}
}
[/code]
The connection manager simply uses the data source (which Spring autowires for us as it is stored in a property with the same name as the bean, and I’ve set default-autowire=“byName” in applicationContext.xml) to get one connection per thread. It also checks before returning the connection for some obvious error conditions and gets new connections in those cases. If it fails, it throws a runtime exception so we don’t have to catch it in our code (we could use an @AfterThrow advice to catch such exceptions and handle them neatly if we wanted, but for now the debugging information shown in the default error pages is helpful).
So now we have a database, we need some code that uses it. We’ll add a new servlet as follows:
Listing 4: Add new servlet
[code]
public cl
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
Most modern enterprise applications are written using a variety of frameworks to provide basic services: a web framework for presenting data to the user, a persistence framework for storing it to the database, perhaps a data binding framework to make moving data between different layers of the application easier, a logging framework so you know what it’s done, a testing framework so you know it does something at least vaguely resembling what it’s supposed to, and usually a dependency injection framework to make putting all the frameworks together easier.... You could say modern development is overloaded with frameworks. We tend to reach for them instinctively, but we don’t always need them. That’s not to say using them is necessarily bad, but that we should think about what we’re achieving with each framework we use, and question whether we can achieve the same result another way and whether that way might be better. Sure, Hibernate can make storing your data much easier, but if it stops working for any reason the extra layer of complexity can make finding the source of the trouble so much harder.
In this article, and the articles to follow, I present some alternatives to the frameworks we use with such abandon. In the current article, I’ll describe the Active Record pattern. Active Record is a very old pattern (it was commonplace for a very long time before Martin Fowler gave it its name in his book Patterns of Enterprise Application Architecture), and one of the simplest ways of keeping your database access code neat and organised.
Just to show I’m not a total luddite, and because it lets me concentrate on what’s important in the article, I’m using one framework here: I use Spring to connect my objects with their dependencies, including my Servlets. If you’re not familiar with the techniques available to cause Spring to create Servlet objects for you, you should read my earlier article Servlet dependency injection with Spring which describes in depth how I’m using it. You may also want to read my article Spring transaction handling: transaction-per-request with AOP which describes the approach I’m taking to connecting to the database and attaching transactions to user requests. Because these are handled automatically, this is the last time I’ll mention them.
The Active Record pattern
Fowler defines the Active Record pattern thus:
“An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.”
This sounds simple enough. Let’s start with a database. Here’s the SQL to set up a simple database for a simple application. I’m using MySQL because it’s what I have installed on my development machine, but you could use any modern SQL implementation for the purpose with only minor changes.
Listing 1: SQL to create the database
[code]
create database test;
use test
grant all on test.* to 'test'@'localhost' identified by 'test';
create table customers (
id int primary key auto_increment not null,
name varchar(255) not null
) engine=innodb;
insert into customers values (1, "Joe");
insert into customers values (2, "Carinna");
create table accounts (
id int primary key auto_increment not null,
balance decimal(9,2) not null,
customer int not null references customers
) engine=innodb;
insert into accounts values (1, 0, 1);
insert into accounts values (2, 0, 1);
insert into accounts values (3, 0, 2);
[/code]
I’ve created two rather simple tables, with one reference between them. We’ll see how that’s implemented soon, but let’s start by implementing a class for the simpler of the two tables, customers. We’ll start with a simple class with fields for the database columns, and we’ll have a constructor to build one from a ResultSet.
Listing 2: Starting the ‘Customer’ class
[code]
public class Customer
{
private final int id;
private String name;
private Customer (ResultSet rs) throws SQLException
{
id = rs.getInt ("id");
name = rs.getString ("name");
}
public String getName ()
{
ret
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
This article discusses applications of the Spring framework in configuring Servlets that have database interactions and need to use transactions. Before beginning, it is important to understand in practice how Spring can be used to configure Servlet object instances provided to a Servlet 3.0 container. I discussed this in detail in an earlier article, Servlet dependency injection with Spring; if you are not familiar with the techniques available to cause Spring to create Servlet objects for you, you should read this article now.
Most Java Enterprise applications interact with some form of database. This is typically achieved by presenting some set of “model” objects to the interface code. The model objects are often managed by a framework like Hibernate or an alternative implementation of the Java Persistence API, which typically communicates with a relational database to store them.
Because such applications often run in parallel and modifications to model objects can often change many objects simultaneously (e.g. adding credit to one account while deducting from another) with a requirement that the changes be atomic (i.e. it is not permissible if credit is added to one account but the corresponding deduction not made on the other) and isolated (i.e. the state of the database used to make decisions while processing a request must remain consistent over multiple steps of the process), the use of database transactions is a common requirement. Even in simpler applications, where controllers might access an SQL database directly, transactions are often a requirement. And while transactions are not typically difficult to manage, programmer effort can be saved by automating the process of managing them.
In a web-based environment, it is highly unusual for transactions to persist outside of the scope of a single request. Clients are not generally considered reliable, and server software is not usually notified when they disappear, so allowing a transaction to persist pending a second request that may never arrive is not often a good idea.
It is also unusual to need more than one transaction within a single request: a request encapsulates a logical unit of work, and if there is a need for more than one transaction this is perhaps a sign that the request should be split into multiple requests (perhaps using a technology such as AJAX, or simply by refreshing the browser page periodically) which would allow a better user experience - the ability to cancel an operation in progress, for example, along perhaps with a display of progress.
It therefore seems sensible to automate transactions by automatically generating them on a per-request basis. The transaction would thereafter be committed on successful completion of the request (or rolled back if the request failed, for example by throwing an exception).
Aspect-oriented programming in Spring
In addition to its primary focus on dependency injection, the Spring framework provides support for a variety of additional features, and aspect-oriented programming is one of the most useful. Aspect-oriented programming, or AOP, is a system that provides an ability to declare that certain code is to be executed when certain events occur in other code. For example, we can instruct Spring to execute one method any time some other method is executed. In particular, we can have our own code executed before and after the HttpServlet.service() method is called, which corresponds exactly to the lifespan we want our transactions to have. Let’s see some code that shows how this would work (we’ll not complicate matters with a database just yet, so we won’t gene
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction
This article picks up where the previous article, Servlet dependency injection with Spring, left off. It is highly recommended you read that article first as the technique described in this article is heavily based on the technique that article describes.
At the end of the last article, we had successfully found a way to configure Spring and a servlet container (supporting the Servlet 3.0 API) without duplicating effort by maintaining entries for each servlet in two different configuration files. But, as I hinted in that article, there is another way that involves even less configuration - it is possible to set up a Servlet 3.0 container and Spring with no XML configuration required at all.
To achieve this, we need to replace some of the code from the previous article. If we no longer have a web.xml file, we can no longer use it to load Spring’s ContextLoaderListener. We can present our own listener to the container, however, by annotating it with @WebListener, so we will just have to set up the Spring context ourselves. This works out OK, because it also turns out we need to adjust some of the servlet context’s init parameters before Spring initialises, and without a web.xml file there’d be no way of doing this other than having our own listener run first anyway. So let’s take a look at some code:
Listing 1: Initialising the Spring context
[code]
@WebListener
public class SpringAnnotationBasedServletRegistrationListener implements ServletContextListener
{
ContextLoader contextLoader = new ContextLoader ();
@Override
public void contextInitialized (ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext ();
// configure the necessary parameters in the servlet context to get
// Spring to configure the application without needing an XML file
servletContext.setInitParameter (
"contextClass",
"org.springframework.web.context.support.AnnotationConfigWebApplicationContext");
servletContext.setInitParameter (
"contextConfigLocation",
"com.example.springnoconfig");
WebApplicationContext context = contextLoader.initWebApplicationContext (servletContext);
[/code]
We start by creating a ContextLoader which we will use to create the Spring application context. But before we do, we have to change the type of context it will create - the default type would try to load an XML configuration file, but we want to use annotations instead, so we specify a class that works purely on annotations. And then we tell that class where to find its configuration, which it will do by scanning all classes in the package com.example.springnoconfig for annotations. Finally, we create the context.
The next step is registering the servlets, and is quite similar to our previous version; the only noteworthy difference is that we use the getBeansOfType(Class) method rather than relying on a map being defined, as there is no easy way to define such a map with annotations:
Listing 2: Scanning the context for servlets
[code]
for (Map.Entry<String, HttpServlet> servlet :
context.getBeansOfType (HttpServlet.class).entrySet ())
{
ServletRegistration.Dynamic registration =
servletContext.addServlet (
servlet.getKey (), servlet.getValue ());
// add multipart config if present
if (servlet.getValue ().getClass ().isAnnotationPresent (MultipartConfig.class
...
Post view interrupted. To view full content, click here
|
|
|
|
Background
For a complex project, dependency injection is often the ideal way of managing the relationships between the various components of your application. Taking control of object creation outside of those components allows us to connect them in different ways for various purposes - most importantly, of course, for testing. And the Spring Framework is the most popular implementation of the pattern, providing not just the basic requirements of object instantiation and injection but a variety of extra conveniences: autowiring, automatic transaction management, and so on.
Configuring Servlets with dependency injection, however, can be a bit tricky. The Servlet API was designed before the pattern was commonplace, and attempts to simplify the job of the programmer by managing object creation itself. Unfortunately (at least prior to recent updates to the API, which I'll describe below) this gets in the way of dependency injection. But it doesn't entirely stop you from using it. There are in fact several ways of achieving the same result. I'll show you a few so you can choose your favorite.
Using Spring MVC
Spring MVC is a Model-View-Controller framework included with Spring. Spring provides a DispatcherServlet that can be configured in various ways to find controller methods that implement functions to expose to the web. It is a very useful framework, but not the primary focus of this article, which is geared towards simpler solutions for those who may not want to use an entire MVC framework in their application.
Using an HttpRequestHandler
The approach offered by the Spring framework itself is HttpRequestHandler, an interface which your beans can implement. Spring then provides an HttpServlet implementation that locates a bean from your application context (configured via the name of the servlet specified in web.xml) that forwards the request to your handler bean. Let’s look at some example code.
A simple implementation of HttpRequestHandler might look like this (with imports removed for clarity):
Listing 1: HttpRequestHandler
[code]
package com.example.myapp;
public class MyRequestHandler implements HttpRequestHandler
{
@Override
public void handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.getWriter().println ("hello, world");
}
}
[/code]
In web.xml, we need to declare a servlet of type HttpRequestHandlerServlet, a servlet implementation provided by Spring:
Listing 2: Web.xml
[code]
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>org.springframework.web.context.support.HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
[/code]
We also need to initialize the Spring context, which is usually done with a ContextLoaderListener in web.xml:
Listing 3: ContextLoaderListener in web.xml
[code]
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
[/code]
Finally, in applicationContext.xml you need to declare a bean that has the same name as the servlet and is of the class we just defined:
Listing 4: applicationContext.xml
[code]
<bean id="myServlet" class="com.example.myapp.MyRequestHandler" />
[/code]
Fire it all up and request '/hello' within your application and you'll get the traditional greeting. This approach works, and it has the benefit of being the officially supported way of doing this with Spring, but it does have a few drawbacks. Firstl
...
Post view interrupted. To view full content, click here
|
|
|
|
Introduction:
Seam is a strong component based framework. Seam integrates technologies like JavaScript, JSP, JSTL, Ajax, JPA and JBPM as well. Seam is an application development framework for Java EE that connected the component and other models of JSF and EJB 3.0, which is a strong component dependent framework, providing a streamlined programming model for web-based java and Java EE enterprise applications. Therefore, Seam works with JBoss and Java EE. BY using Seam framework, we can bind our EJB components directly to JSF pages, so we do not need to go through any kind of XML configuration for that.
Creating entity by SEAM
Here we mention the easier way of integration of seam with Java EE. The Seam framework extends and offers the facilities of the annotations defined by EJB 3.0 with a new and latest set of annotations for declarative state management, for this reason we are able to use it quite easily that state validation and declarative context demarcation, eliminating much of the XML required by plain JSF. If we use seam framework, we will find an easy way to create all the entities by some clicks. When we generate the entity by SEAM-generate entity, then we will find many facilities on it. The annotation provides the facilities of preventing the entrance null value by @NotNull, @email etc. If the seam finds any One to Many relation, Many to One within the table structure than it create "@ManyToOne" or @OneToMany(mapped By="divisionId"). The primary key of the entity creates this. Therefore, by this way we can create all the entities, existing in the database.
Listing 1: Creating Entity by Seam
[code]
@Entity
@Name("configDivision")
@Scope(ScopeType.SESSION)
@Table(name="pms.config_division")
Class Name: CongigDivision.java
package org.domain.pms.entities;
import java.io.Serializable;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.validator.Length;
import org.hibernate.validator.NotEmpty;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
@Entity
@Name("configDivision")
@Scope(ScopeType.SESSION)
@Table(name="pms.config_division")
public class ConfigDivision implements Serializable {
@Id@GeneratedValue
@Column(name="DIVISION_ID")
private long divisionId;
@Column(name="DIVISION_NAME")
private String divisionName;
@Column(name="DIVISION_NAME_BEN")
private String divisionNameBen;
@Column(name="ACTIVATION_STATUS")
private String activationStatus;
@OneToMany(mappedBy="divisionId")
private Set<ConfigHoliday> configHolidayCollection;
@OneToMany(mappedBy="divisionId")
private Set<StaffProfile> staffProfileCollection;
@OneToMany(mappedBy="joining")
private Set<StaffProfile> staffProfileCollection2;
@OneToMany(mappedBy="divisionId")
private Set<ConfigWing> configWingCollection;
@OneToMany(mappedBy="divisionId")
private Set<ConfigRank> configRankCollection;
@OneToMany(mappedBy="divisionId")
private Set<ConfigLeaveType> configLeaveTypeCollection;
@OneToMany(mappedBy="divisionId")
private Set<ConfigKeyword> configKeywordCollection;
@OneToMany(mappedBy="divisionId")
private Set<ConfigKeyword> configPayGradeCollection;
private static final long serialVersionUID = 1L;
public ConfigDivision() {
super();
}
public long getDivisionId() {
return this.divisionId;
}
public void setDivisionId(long divisionId) {
this.divisionId = divisionId;
}
public String getDivisionName() {
return this.divisionName;
}
public void setDivisionName(String divisionName) {
this.divisionName = divisionName;
}
public String getDivisionNameBen() {
return this.divisionNameBen;
}
public void setDivisionNameBen(String divisionNameBen) {
this.divisionNameBen = divisionNameBen;
}
public String getActivationStatus() {
return this.activationStatus;
}
public void setActivationStatus(String activationStatus) {
this.activationStatus = activationStatus;
}
public Set<ConfigHoliday> getConfigHolidayCollection() {
return this.configHolidayCollection;
}
public void setConfigHolidayCollection(Set<ConfigHoliday> configHolidayCollection) {
this.configHolidayCollection = configHolidayCollection;
}
public Set<StaffProfile> getStaffProfileCollection() {
return this.staffProfileCollection;
}
public void setStaffProfileCollection(Set<StaffProfile> staffProfileCollection) {
this.staffProfileCollection = staffProfileCollection;
}
public Set<StaffProfile> getStaffProfileCollection2() {
return this.staffProfileCollection2;
}
public void setStaffProfileCollection2(Set<StaffProfile> staffProfileCollection2) {
this.staffProfileCollection2 = staffProfileCollection2;
}
public Set<ConfigWing> getConfigWingCollection() {
return this.configWingCollection;
}
public void setConfigWingCollection(Set<ConfigWing> configWingCollection) {
this.configWingCollection = configWingCollection;
}
public Set<ConfigRank> getConfigRankCollection() {
return this.configRankCollection;
}
public void setConfigRankCollection(Set<ConfigRank> configRankCollection) {
this.configRankCollection = configRankCollection;
}
public Set<ConfigLeaveType> getConfigLeaveTypeCollection() {
return this.configLeaveTypeCollection;
}
public void setConfigLeaveTypeCollection(Set<ConfigLeaveType> configLeaveTypeCollection) {
this.configLeaveTypeCollection = configLeaveTypeCollection;
}
public Set<ConfigKeyword> getConfigKeywordCollection() {
return this.configKeywordCollection;
}
public void setConfigKeywordCollection(Set<ConfigKeyword> configKeywordCollection) {
this.configKeywordCollection = configKeywordCollection;
}
public Set<ConfigKeyword> getConfigPayGradeCollection() {
return configPayGradeCollection;
}
public void setConfigPayGradeCollection(
Set<ConfigKeyword> configPayGradeCollection) {
this.configPayGradeCollection = configPayGradeCollection;
}
[/code]
Here we follow the MVC pattern to make or build any application. The entities act like the model of the pattern. Now we discuss the controller of seam framework. We can use JPA (Java persistence API) to make the entities. SEAM is a very well define and very user-friendly framework. Therefore, we can build our application and enterprise application by the help of SEAM.
Controller or Action Class
In seam framework, the programming model is declarative. Seam introduces modest and declarative application state management for 'POJO' components. Seam components are statefull, stateless and contextual; with a well prove define context management. However, we can define what will be the state of action class. The performance problem occurs when all the classes define statefull. However, this time memory requires killing the useless objects. Seam components may take advantage of SVN or VSS that is subversion of control, a generalization of dependency injection and some other way, which applies, to statefull components as well as stateless services. In seam framework, the Action class controls all the work and makes association, which is needed. When any action occurs, the action class determined which performance needs to take place.
Listing 2: ConfigDivisionAction.java
[code]
package org.domain.pms.session;
import static org.jboss.seam.ScopeType.SESSION;
import static javax.persistence.PersistenceContextType.EXTENDED;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.domain.pms.entities.AuditTrail;
import org.domain.pms.entities.ConfigDivision;
import org.domain.pms.entities.LoginInfo;
import org.domain.pms.entities.StaffProfile;
import org.domain.pms.util.ConstantValues;
import org.domain.pms.util.DbTable;
import org.jboss.seam.annotations.Destroy;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Out;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.annotations.datamodel.DataModelSelection;
import org.jboss.seam.log.Log;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
@Stateful
@Name("configDivisionAction")
@Scope(SESSION)
public class ConfigDivisionAction implements ConfigDivisionActionLocal {
@In(required=false)
private EntityManager entityManager;
@Logger
private static Log log;
private Set<Integer> keys = new HashSet<Integer>();
public void setKeys(Set<Integer> keys) {
this.keys = keys;
}
public Set<Integer> getKeys() {
return keys;
}
@DataModel
List<ConfigDivision> configDivisionList;
@DataModelSelection("configDivisionList")
@In(required=false) @Out(required=false)
private ConfigDivision configDivision;
@DataModel
List<ConfigDivision> inactiveDivList;
@DataModelSelection("inactiveDivList")
@In(required=false) @Out(required=false)
private ConfigDivision inactiveDiv;
@DataModel
List<AuditTrail> divTrailList;
private AuditTrailAction auditTrailAction;
private AuditTrail auditTrail;
@In Credentials credentials;
@In Identity identity;
// list all existing Divisions
@Factory("configDivisionList")
public void viewAll() {
long divId = LoggedUserInfo.instance().getDivisionId();
Query q = entityManager.createQuery("select div from ConfigDivision div where div.divisionId>2 and div.activationStatus='Active'");
configDivisionList = (List<ConfigDivision>) q.getResultList();
//configDivisionList = (List<ConfigDivision>)em.createQuery("select div from ConfigDivision div").getResultList();
//log.info("the list size is"+ configDivisionList.size());
}
// list all in
...
Post view interrupted. To view full content, click here
|
|
|
| |
|