Friday, December 17, 2010

How to insert multiple database rows into JTable

If you want to insert rows with data into a JTable by fetching from the database, this is the easyest way to do it.


//Statement is got through mysql connection
sql="select code,name,type from item_table"
ResultSet resultset = 
                statement.executeQuery(sql);

Vector rows=new Vector();


while(resultset.next()){
 Vector one_row=new Vector();
 one_row.add(resultset.getString('code'));
 one_row.add(resultset.getString('name'));
 one_row.add(resultset.getString('type'));

 rows.add(one_row);

}

DefaultTableModel model=new DefaultTableModel();

Iterator i=rows.iterator();
int count=0
while(i.hasNext()){
 model.insertRow(count,(Vector)i.next());
 count++;
}

//Table is the JTable instance
table.setModel(model);

Thursday, November 18, 2010

Apache load balancing for Tomcat Example (with Wamp server apache module (Apache2.2.xx))

This is continued from the previous post in here.

Scenario: You have application running on two tomcat servers. Example is for localhost. Replcae it with relevant IP addresses which the tomcat servers are runing.

1. http://localhost:8080/app/
2. http://localhost:8090/app/

You need to load balance between two tomcat servers through apache server as well as to hide the actualURLs from outside.

Here is the Step by Step instructions.

1. First follow the previous post and configure apache proxy.
2. Let's write a balancer configuration named "mybalancer" with two members who are two tomcat servers. The load should be balanced between those two members (1:1). Add the following segment to httpd.conf file.

<PROXY balancer://mybalancer>
BalancerMember http://localhost:8080
BalancerMember http://localhost:8090
</PROXY>

3. Now change the ProxyPass statement to refer the balancing cluster. For that replace line

ProxyPass /proxydemo/ http://localhost:8080/app/

with

ProxyPass /proxydemo/ balancer://mybalancer


4. Then replace the ProxyPassReverse statement line

ProxyPassReverse /proxydemo/http://localhost:8080/app
with

ProxyPassReverse /proxydemo/ balancer://mybalancer

What you did was to place the load balancer behind the apache server. So the requests come to http://localhost:9090/proxydemo (assuming Apache runs on port 9090,replace with your own port)will be redirected to either of the balancing members. But the actual URL is hidden to outside.

If you want to access one of the resource hosted on tomcat servers such as

http://localhost:8080/app/service.jsp

You can access it through apache load balancer through

http://localhost:9090/proxydemo/app/service.jsp

when someone access the above URL requests will be balanced to one of the members, in this case 1:1. You can shut down one tomcat server and  try the above URL. Then it will work as another server is still working. But if you have shut down both servers it will display as server temporaly not available.

Ths example was assuming there are two tomcat servers running on the same machine (port 8080 and port 8090) and apache server is running on port 9090. You can try this on distributed servers and replace localhost with IP addresses.

Apache proxy configuration for Tomcat Example (with Wamp server apache module (Apache2.2.xx))

Apache Proxy Configuration - To place Tomcat server behind apache server

Scenario: You have tomcat server applications (http://localhost:8080/app/, etc)which need to be placed behind a apache server. In this example apache port is 9090. You can have your own ports.

First download WampServer2.0i file and install in your machine.
Start Wamp and start apache service (Click on wamp icon in toolbar and go to apache-Service-Start/Resume Service )
In you wamp installation directory go to it's apache module and open httpd.conf file. (WAMP_HOME\bin\apache\Apache2.2.11\conf\httpd.conf)

1. Here you have to enable following modules.
                                  LoadModule proxy_module modules/mod_proxy.so
                                  LoadModule proxy_http_module modules/mod_proxy_http.so 
                                  LoadModule rewrite_module modules/mod_rewrite.so

Search them in httpd.conf file and uncomment them. (Remove # mark infront of each module entry)
Now restart Apache (Click on wamp icon in toolbar and go to apache-Service-Restart Service )

Veryfy whether modules are enabled
Click on Wamp icon and go to Apache-Apache Modules.
Check whether above modules are marked as enabled (If not by clicking on each module enable them and restart wamp)

Now you have enabled the required modules.

2. Add following line to the httpd.conf file

          ProxyRequests Off

3. Now add theproxy stanza as follows to httpd.conf


    Order deny,allow
    Allow from all


4. Then you have to enable URL rewriting as follows

      RewriteEngine on

5. For each server which need to be placed behind apahe server add a ProxyPass statement as follows. In here  proxydemo is the namespace for the application access.

ProxyPass /proxydemo/ http://localhost:8080/app/ 


6. For each ProxyPass statement add ProxyPassReverse statement to rewrite Location headers information before passing redirect response back to the client.
ProxyPassReverse /proxydemo/ http://localhost:8080/app/ 

7. To avoid 404 errors after URL without ending slash add the following line to httpd.conf
    
     RewriteRule ^/proxydemo$ /proxydemo/ [R]


Now You have done proxypassing.
Here after when you access apachserver proxypass proxydemo by http://localhost:9090/proxydemo , it will redirect to http://localhost:8080/app/ but actual URL is hidden from outside.

Imagine now you have service.jsp file in http://localhost:8080/app/service.jsp . To access this through Proxy the URL for outside will be http://localhost:9090/proxydemo/service.jsp.

Please ask if you got any problems.

In my next post apache load balancing for tomcat server will be discussed with an example.

Thursday, November 11, 2010

Java-Simple way to check command line input to enter a number-Give error message if not a number and ask again to input

If you want to take a commandline input through BufferedReader or Scanner and you want user to enter a number. So in this solution user is asked to enter a number and if it is not a number (throws NumberFormatException) error message is displayed and again asks for user to enter. Until user enters a number this continues. This is simple.

Here is the code with comments explaining the code.

import java.io.*;
class InputNumber{
 public static void main(String args[]){
  boolean success=false;
  String value=null;
  int number_value=0;//number value is stored
  System.out.print("Enter Number:");
              
              //loop continues until user entered a number,success 
              //will assigned true when user entered a number and while
              //loop will terminate
              while (!success){
   try{
      BufferedReader bf=new BufferedReader
         (new InputStreamReader(System.in));
      value=bf.readLine();
      number_value=Integer.parseInt(value);


           success=true;//Come to this point only if the 
                                    // exception is not thrown
     System.out.println("\nSuccess! You Entered a Number: "+number_value);

   }catch(IOException e){


   }catch(NumberFormatException e){//When string did 
                                      //not contained a numer it goes here
    System.out.print("\nWrong value, please enter a number!\nEnter Number :");
    success=false;

   }
  }
 }


}

Friday, October 29, 2010

Run two/more Apache tomcat servers in your machine at the same time

If you have currently configured a single tomcat server and you need to add more tomcat servers, first remove the CATALINA_HOST environmental variable.
The configure more tomcat servers in new ports. (How to change the Tomcat running port)
Now go to Command Line.
Go to the first tomcat server directory through command line and go to bin directory.
Type "startup" and execute Tomcat.
Then your tomcat server will start.
Now go to the next Tomcat server dirctory through cmd and as same as the first one execute it through command line.


Here as we haven't created CATALINA_HOME variable , we can not execute Tomcat straghtly double clicking startup.bat file. So when we execute Tomcat from cmd, it creates required environmental variables at that time and starts tomcat.

How to change Apache Tomcat running port

Go to conf folder of your apache tomcat installation.
Open server.xml file.

Method 1
Search for (Ctl+F) "Connector port" key word there. In the first matching occurence change the port value to the value which you wish.
For better accuracy make sure the current port value in the first matching occurence is equal to the port which the tomcat currently running.
restart tomcat.


Method 2
Find the port which tomcat currently running.
Search for (Ctl+F) the current port in server.xml file and change it to the value you want.
restart tomcat.

Monday, October 11, 2010

AXIS2 Web Service in eclipse through Top Down Approach-java.lang.RuntimeException: Element QName is null

Based on this tutorial, But used my own WSDL file.
I used Top Down approach where to create java codes from the WSDL file. But at “Axis 2 Web Service Skeleton Java Bean Configuration” wizard window I clicked next and there occurred an exception as follows saying Element QName is null.

SOLUTION

Add the following XML element within
tags and inside
tag which has a wsdl:fault (Particular operation should throw an exception). So I had to add,

          

It appears as follows,


         
  
      
      
        
      
      
        
      
     
            
      
    
  
Here the getBalance operation throws an exception, so for the wsdl:binding description the given element need to be added. Otherwise it gives an exception at Top Down Approach with eclipse.

Axis 2 web services in eclipse: Exception java.lang.NoClassDefFoundError: org/apache/http/HttpResponseFactory thrown when Services link clicked

I created the web service using axis2 and deploy through tomcat in eclipse following a Tutorial. Then axis2 homepage get displayed OK. But when the Services link clicked an exception page will get displayed as follows.

type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet.init() for servlet AxisServlet threw exception
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Unknown Source)
root cause
java.lang.NoClassDefFoundError: org/apache/http/HttpResponseFactory
org.apache.axis2.transport.http.SimpleHTTPServer.init(SimpleHTTPServer.java:116)
org.apache.axis2.engine.ListenerManager.init(ListenerManager.java:74)
org.apache.axis2.transport.http.AxisServlet.init(AxisServlet.java:449)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
java.lang.Thread.run(Unknown Source)


SOLUTION


The reason here is that jar file related to class org.apache.http.HttpResponseFactory is missing to the project which is httpcore-x.jar. It is always not the case that eclipse automatically adds all required libraries. So we need to add this lib to the project. We can find httpcore-x.jar from your axis2 libraries (AXIS_HOME/libs). Go to project WebContent/WEB-INF/libs folder add the jar there.


Even you can copy the httpcore-x.jar and add it to tomcat libraries (CATALINA_HOME/lib). So that you do not need to add it all the time you create a new web service.


AXIS2 web service in eclipse: Web Service created, but when executed HTTP Status 404 page get displayed

Web Service project name= SimpleATMService

http://localhost:8080/ATMService/ : HTTP Status 404 page

SOLUTION
Try This URL: http://localhost:8080/ATMService/axis2-web/

Monday, September 6, 2010

Add HTML, JavaScript, or any other codings into blogger posts

First you need to add some HTML content to your blog.
For that go to Design tab---> Edit HTML
Inside the Edit Template add the following code inside it's existing <head></head> tags. You can copy and paste the following code to the end of header codings.

Here is the code that need to be added.








The Edit Template look as follows when code is added.

 Then when you are creating posts and you need to put some codings, you just need to put it inside folowing tags.
Your Code Here