Sunday, December 6, 2009

Hibernate 3.0: Sql Dialect must be explicitly set:(configuration error in hibernate 3.0)

You may have used hibernate 2.x and in case you are getting error (Hibernate Dialect must be explicitly set, jdbc connection parameters must be specified, etc) by using the same code to initialize SessionFactory as you did before then there's a simple fix for that error.

  • Create a hibernate.cfg.xml file and place it in root of the classpath and to initialize SessionFactory use the following code.


    AnnotationConfiguration ac= new AnnotationConfiguration().
    setProperties(System.getProperties());
    ac.configure();
    //static final instance of SessionFactory
    sessionFactory=ac.buildSessionFactory();


    or the following code which is the same but uses method chaining:-



    //static final instance of SessionFactory
    sessionFactory=new AnnotationConfiguration().
    setProperties(System.getProperties()).
    configure().
    buildSessionFactory();


this will solve your Dialect or other errors related to configuration you might be facing.

Sunday, August 16, 2009

Dual core processors: The main logic

The dual core and quad core processors have become very popular nowadays but the main reason behind their success is the power management.

There are two basic concepts that one must know, they are :-

Overclocking the processor :-

Let's say that ideally a normal single core processor takes x units of power to give x units of performance. But users generally tend to increase the performance by overclocking the processor ie essentially increasing the clock frequency of the processor. If a user follows the process of overclocking the processor, then the performance increase is about 12-13 percent but the power increase required for that would be about 70 percent.

Under-clocking the processor :-

Now the interesting concept is what if we under-clock the processor that is decrease the clock frequency of the processor?

In this case we could get about 80 percent of the performance at roughly half the power. For example we would get .8x units of performance at .5x units of power.

Now this is the concept that is utilized by the dual core processors and instead of using a single processor we combine the two processors and operate each one of them at half of it's power and so for the same power taken by the normal single core processor we get about 70 percent increase in performance. The aforementioned reason is the core reason behind the success of dual core processors.

Another major factor in dual core processors is as they operate at lower clock rates it helps in reducing the speed mismatch between the processor and the memory and this is a relevant factor because with processor clock rates increasing at very faster speeds the corresponding increase in clock rates of cache memory is not their, therefore a processor's clock cycles are not utilized properly and are wasted in memory read/write cycles.

Hence the concept of under-clocking helps also in reducing the speed mismatch b/w the memory and the processor.

Tuesday, July 21, 2009

Using Timer class in java swing

The first thing that you should know is that Timer class is available both in java.util and javax.swing packages and they both are different from each other.

I will be discussing code example about the Timer class in javax.Swing package which you can use to make a countdown timer, JprogressBar or do other operations.

Below is the code example and then the explanation follows:-


import java.awt.event.*;
import javax.swing.Timer;
/**
*
* @author morph
*/
public class timer_Example extends javax.swing.JFrame implements ActionListener {
Timer timer=null;
javax.swing.JLabel label=null;
static int counter=0;
/** Creates new form timer_Example */

public timer_Example(){
//your code goes here
label=new javax.swing.JLabel("The time is 0 seconds");
this.getContentPane().add(label);
this.pack();
timer=new Timer(1000,this);/*create a timer that generates an event after 1 second and pass it the frame object which handles the action event by implementing the ActionListener interface*/
timer.start();
}

public void actionPerformed(ActionEvent e){
if(counter==100)
{
timer.stop();
}
javax.swing.SwingUtilities.invokeLater(new updateCount());
}

public class updateCount implements Runnable{
public void run(){
counter=counter+1;//update the counter value
label.setText("the time is "+counter+" seconds");
//your JProgressBar code can go here
//or any other code that you may like
}
}
public static void main(String args[]) {

timer_Example form=new timer_Example();
form.setVisible(true);
form.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
}


}



The code is pretty basic but this code can be used to perform various tasks. In the code we initialize the counter to 0 and then create the timer object by calling its constructor and passing it 2 arguments the time in milliseconds after which the timer shall generate an event (timer generates an ActionEvent) and second parameter is an event handler for the action event which in this case is the form object itself.

The actionPerformed function just simply checks whether the count has reached 100 or not and if it has it stops the timer. Otherwise it creates a new runnable object of a nested class updateCount which updates the count value and displays the count value through the JLabel. Here you can do other things like updating the JProgressBar or any other event that you may wish to implement. I have used SwingUtilities.invokeLater() function because it is always recommended that you should place the call to some other class on an event queue and not directly call the class.

I have used a similar concept to develop a simple application in java that performs various operations like Shutdown, Hibernate, Standby, lock etc but in that case the counter is countdown counter. You can also create beautiful application launcher windows with changing backgrounds and updating progress bar with it.

Sunday, June 28, 2009

Java Servlets:Introduction,Compiling,Deploying and Running

What is a servlet ?

Servlet:a short introduction:-
A servlet handles the requests from the server, that require servlet to add something or do some operations in response to the client request so that a dynamic page can be generated, rather than the same old monotonous static html pages.

The servlet API's are generally provided along with Containers like tomcat, JBoss etc and you have to import the servlet-api.jar for compiling your servlet .java files. A java servlet does not have a main method so it is the container that controls the execution of servlet methods. The container initializes the servlet by calling it's init method, after which it's service method is called which determines that which of the servlet's method is to be called depending upon the client request and after a servlet's job is done it purges it's resources by calling it's destroy method.
The container also provides support for JSP.

The servlet class that you will implement let it's name be MyServlet , will generally extend the HttpServlet class that extends the GenericServlet class so the class hierarchy will be as shown in the following figure.












The servlet class that you will implement will most likely implement either of the following two methods:-

  1. public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{ //code here}:-

    If the client uses the http Get query, then this will be the method that will be invoked by the container to handle the Get request. It takes reference to two objects HttpServletRequest and HttpServletResponse object, these objects are created by the container and their reference is passed to this method. A client will use a Get http request, If the amount of data to be sent is less, the data sent using get request is visible in the browser navigation bar, so you would not want to display sensitive information like user password, for that you will want to use the Http Post request .

  2. public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException{ // code here }

    If the client uses the http post request then this will be the method called by the container by looking at the client request. It is used when the amount of data to be sent is more, like filling up the html form and sending it to the server to process it and also when sensitive information like user password is to sent.
An example servlet :-

The example servlet(infoServlet) will be the most basic servlet, It will take the parameter user-name and password, perform some fake authentication (authentication won't actually be done) and display a welcome message to the user along with the current date and time.

The servlet code is given below and the explanation follows:-

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class infoServlet extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException
{
response.setContentType("text/html");
PrintWriter output=response.getWriter();
String name=request.getParameter("text_field");
String password=request.getParameter("password_field");
Date now = new Date();
//No authentication will be done
output.println("<html>"+"<head>"+"<title>"+
"Welcome page"+"</title>"+"</head>"+
"<body>"+"Welcome "+name+"<br/>"+
"The time is"+now+"</body>"+"</html>");
}
}



In this servlet we have implemented the doPost method as the client will be sending the sensitive information in a post request.

The method setContentType("content_type"); tells about the response mime type to the client browser so that it can display the page received properly.
Then we obtain a printwriter object reference by invoking the getWriter() method on the response object, which is used to generate the dynamic response page for the client.

The getParameter("field_name") gets the parameter value entered by the user in the form.

Now save the java file as infoServlet.java .

Compiling the servlet:-

To compile the servlet follow these steps:-
  • Open the command prompt and navigate to the directory where the infoServlet java file is saved.
  • Now to compile the servlet execute the following command.

    javac -classpath "C:/Program files/Tomcat6.0/lib/servlet_api.jar" infoServlet.java


    Here replace the classpath (the path between the quotes) with the path to your servlet_api.jar file provided by the container that you are using.
Deploying the servlet:-

I am here using the tomcat container, the deploying part may vary depending upon the container that you use.
  • Create a directory under the tomcat6.0/webapps directory, name it proj1 then under the proj1 directory create a directory WEB-INF , then create a directory classes under the WEB-INF directory.
  • Copy the generated class file into the classes directory.
Deployment Descriptor (DD):-

Now you would have to create the deployment descriptor ie the web.xml file that tells the container about information such as where the servlet class file is placed, what is the deployment name that you are using, what will be the name by which client will call the servlet and obviously various other parameters.

The deployment descriptor is given in the following code-box, copy the contents and save it as web.xml

<?xml version="1.0"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>infoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/submit</url-pattern>
</servlet-mapping>
</web-app>


Explanation:-

One should not worry about the webapp tag just copy and paste it.

The <servlet> tag:- It defines the properties relating to your servlet. In this case we map the deployment name ie the name specified by <servlet-name> tag , to the path to actual class file i.e the name specified by the <servlet-class&gt tag; i.e the infoservlet, notice here that we do not specify the name as infoServlet.java as it is the java class file.

The <servlet-mapping > tag :-It is used to map the name by which the client will access the servlet to the deployment name. Here the <url-pattern> specifies the name by which the client accesses the servlet.

  • Deploying (Contd .....) : Copy the web.xml file and save it under the WEB-INF directory.

  • Now we would have to create the simple html form in which user will enter the details and when he clicks on the submit button the post request will be send to the server. The container will then invoke the servlet to do its operation and servlet will generate the response which will be converted to http repsonse by the container and send back to the client. Simple isn't it. The code for the form is given below, copy and paste the code and save it as form.html under the proj1 directory.

    <html>
    <head>
    <title> A temporary page </title>
    </head>
    <body>
    <h1>
    Fill up the following form
    </h1>
    <form id="2314" method="post" action="submit">
    <center>
    Enter your name <input name="text_field" type="text" value=""/><br/><br/>
    Enter your password <input name="password_field" type="password" value="" /> <br/><br/>
    <br/>
    <input type="submit" value="submit form">
    </center>
    </form>
    </body>
    </html>


    The html code is pretty simple and you should note only 2 things :-

    1. The form is using the post method so a post query is generated when the user clicks on the submit button.

    2. The input field name property is used by the servlet to access the parameter values entered by the user.

Running the servlet:-

Phew! everything is done now just the working of application is to be seen.
  • Start the apache tomcat service. Note in case you have problems launching it just go to its binary directory i.e the bin directory and launch it from there, it will be launched in a command prompt.
  • Open the browser and access the html form and type http://localhost:8080/proj1/form.html in your browser navigation bar.
  • Fill up the details and click on the submit button and voila! you will see the response generated by the servlet which will be the user-name and the date that you entered in the form.
Note:If you have any problems do post a comment and i will post the solution.

Sunday, June 7, 2009

Changing window manager in ubuntu

The problem that you might face when you install ubuntu is it's default window manager GNOME is quite heavy on resources and tends to be buggy (for my pc configuration at least) so to cope up with resource crunch you can shift to a light window manager like fluxbox, XFCE etc as they tend to provide better performance than GNOME or KDE but are a little un-user friendly.

To change the window manager follow these steps:-

1) Install MENU:- The precondition for changing to any new window manager is to install the program MENU that manages the application menus so that you can launch the applications without the need of Gnome or KDE launchers.

To install MENU
  • Open terminal i.e Application->Accesories->Terminal or press ALT+F2 and choose run in terminal

  • Then type the following command in the terminal :-

    sudo apt-get install menu
    you will be asked for your password, enter it and the package menu will be installed.
2) Install the window manager :- The next step is to install the window manager itself. I would be explaining about how to install the FLUXBOX window manager.

The fluxbox window manager provides tab options, styles menu from which you can change the theme and wallpapers, configuration menu for configuring window display (including transparency,icons etc), wsm (text browser) and by default comes with 4 workspaces that you can toggle between, more workspace windows can be added. The thing that i like about it is that it's very fast.

To install fluxbox execute the following command:-

sudo apt-get install fluxbox

3) Changing the window manager
:- Now all you have to do is logout from ubuntu and then from the options on the login screen choose select session, choose Fluxbox and choose the window manager for current session only so that you can try it out before choosing to make it default.

The following is the snapshot of fluxbox:-

Saturday, May 30, 2009

Intel's Nehalem architecture: What's new ?

Intel's Nehalem architecture is utilized in their i7 Core processors for desktops and Nehalem based Xeon processors for servers and the following features tell you about what's new in them and why you should purchase one of these.

  • High performance: The processors perform better than the amd's phenom and intel's core 2 extreme processors available in the market. The extra performance boost is always welcomed by gamers. When performance was tested on the game World of Conflict the phenom processor gave 136 fps, Core 2 extreme processors gave 220 fps whereas the nehalem architecture based processors gave out 250 fps.

  • Enhanced Hyper Threading: Hyper threading technology (HTT) is a term used by intel which simply means simultaneous multi-threading which causes the operating system to interact with a single processor as if you had dual processors. So it doubles the number of threads that can be handled by the processor at one time. Thus if you have a Nehalem based quad core processor it can handle 8 threads going by the same logic.

  • Turbo boost : Dynamic performance Control :-
    This is similar to Overclocking in the standard processors but unlike the standard processors where you had to manually overclock or under-clock the processor to suit your performance requirements, in this case it is handled automatically by the processor depending upon the system load. So if the load is higher it can automatically increase the clock rate i.e basically increasing the frequency and when the load decreases it automatically lowers it's clock rate.

  • QPI(Quick path interconnect):- This technology is similar to amd's hyper transport technology but it is much faster than it. What the QPI does is it gets rid of the FSB(Front Side Bus) in the standard processors. The Xeon and i7 core processors provide 25.6 GB/s per link that is twice that of 1600MHZ FSB (which according to me is very fast :-) ) .

    The QPI architecture provides separate integrated memory controllers for each core so that instead of the memory and I/O requests sharing a bus and waiting for many cycles, the QPI and the memory bus are separate. QPI also provides separate channels for writing and reading, so these tasks can be performed in parallel.

  • 3 Level Cache :- The dual core processors came with a 2 level cache whereas in the nehalem architecture it is expanded to 3 levels of cache. Each processor has it's own L1 and L2 levels of cache and all the processors share the L3 Level cache which is about 8MB in size. The L3 level cache contains copies of the contents of L1 and L2 caches which leads to better performance.

  • DDR-3: Higher speed memory :-
    The Nehalem architecture also supports faster (so logically more expensive) RAM: The DDR3 RAM is 2wice as fast compared to the DDR-2 RAM and also maintains the same ratio when it comes to the prefetch buffer. The prefetch buffer is used to buffer the instructions for the processor when it is performing some operation and logically larger prefetch buffer size leads to better performance.

  • Lower power consumption:- The Intelligent Power Node Manager for Xeon servers will automatically adjust the power for the optimum power to performance ratio (this was already mentioned when the turbo boost feature was explained). This leads to better power management and hence lower power consumption.


Hope this was informational enough and now that you know of the benefits of the nehalem architecture you would be in a better position to know whether or not you want to buy one of these.

Sunday, May 17, 2009

Google Search Operators

In this article i provide you with a presentation file that explains Advanced and basic google search operators. The most obvious question is why i need to know about them?

The answer is the following benefits that it provides:
  • The advanced search operators and basic operators reduce your search time by a large extent and if you work for an organization you would know how often you have to search for resources on the net and most of us use google search engine.
  • It also provides you with certain kinds of information you would be not able to access in a normal search query.
  • It also weeds out duplicate results and unwanted results.
That being said here's the presentation that explains those operators download it here .