Friday, December 9, 2011

Using Eclipse with Java7 on Windows 7

I tried using below Eclipse Build with Java SE 7

Eclipse Platform
Version: 3.7.1
Build id: M20110909-1335

It throws error if you try running with Java 7 sdk or jre.

I was able to run by invoking below jar file.

 C:\Program Files\Glassfish\jdk7\bin>java -jar D:\eclipse-jee-indigo-SR1-win32\plugins\org.eclipse.equinox.launcher_1.2.0.v20110502.jar


Check this wiki for those who want to run Java 7 on eclipse :

http://wiki.eclipse.org/JDT/Eclipse_Java_7_Support_%28BETA%29

Thursday, September 1, 2011

Free Online Java Training Using Alice and Greenfoot

 
"It is a great opportunity to find out the fun of programming and creating your own animation or whatever you want to create," said Isabella, a 10th grade student who participated in the summer workshop.
 

Alice and Greenfoot are two award-winning educational software tools designed to teach Java programming and problem solving. No programming experience is required to benefit from the recordings of the Java Summer Workshop 2011, which was organized by the Oracle Technology Network and Oracle Academy.

Monday, July 4, 2011

Java : read from xml


Check this API : javax.xml.parsers  below :
http://download.oracle.com/javase/6/docs/api/




==============XMLReader.java==================

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader {

 public static void main(String argv[]) {

  try {
  File file = new File("MyXMLFile.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
  System.out.println("Root element " + doc.getDocumentElement().getNodeName());
  NodeList nodeLst = doc.getElementsByTagName("employee");
  System.out.println("Information of all employees");

  for (int s = 0; s < nodeLst.getLength(); s++) {

    Node fstNode = nodeLst.item(s);
   
    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
 
           Element fstElmnt = (Element) fstNode;
      NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
      Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
      NodeList fstNm = fstNmElmnt.getChildNodes();
      System.out.println("First Name : "  + ((Node) fstNm.item(0)).getNodeValue());
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
      System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
    }

  }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}

=====================END=====================

============MyXMLFile.xml=================
<?xml version="1.0"?>
<company>
    <employee>
        <firstname>Sriram</firstname>
        <lastname>Sreedhar</lastname>
    </employee>
    <employee>
        <firstname>Harini</firstname>
        <lastname>Sriram</lastname>
    </employee>
    <employee>
        <firstname>firstname</firstname>
        <lastname>lastname</lastname>
    </employee>
</company>








========================================

Oracle datasource in Glassfish

Glassfish does not ship with oracle jdbc drivers. The oracle driver needs to be added manually.  The driver can be found either in a JDeveloper or oracle client or database installation in {install_path}/jdbc/lib, or from oracle's site:

http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/htdocs/jdbc_10201.html

Glassfish needs at least ojdbc14.jar to work properly. Older drivers do not work. Put the ojdbc14.jar in {glassfish}/lib directory and restart glassfish:

asadmin stop-domain domain1
asadmin start-domain domain1

Now you need to navigate to the administrator application:
http://localhost:4848/
 
Open the 'Resources' -> 'JDBC' -> 'Connection Pools' and select 'New.
Fill in the Connection Pool 'Name'.
Select 'Resource Type' : 'javax.sql.ConnectionPoolDataSource'.
Select 'Database Vendor' : 'Oracle'.
Select 'Next'.

At the next page go down at the additional Properties.
Select all the properties and select 'Delete Properties'.
Select 'Add Property', fill 'Name' : 'user' and 'Value' : {db_user}
Select 'Add Property', fill 'Name' : 'password' and 'Value' : {db_user_pass}
Select 'Add Property', fill 'Name' : 'url' and 'Value' :
jdbc:oracle:thin:@[host][:port]:SID
or
jdbc:oracle:thin:@//[host][:port]/SID
Select 'Finish'.

Navigate to Connection Pools and select the pool you just created.
Click Ping to test that it is working. If it is not, it is probably because you have mistyped the connection credentials. Go to 'Additional Properties' tab of the connection pool detail page and correct any errors. Try ping again.

Open the 'Resources' -> 'JDBC' -> 'JDBC Resources' and select 'New.
Fill the JNDI Name like 'jdbc/myconnnection'.
Select from 'Pool Name' combo box the pool we already created.
And select 'OK'.

The Connection Pool is ready!

Have taken this article from
http://mariosgaee.blogspot.com/2009/12/oracle-connection-pool-in-glassfish.html

Configuring Web Application Server Glassfish :

Download Glassfish from : https://glassfish.dev.java.net/

untar the glassfish in install path eg : /install_home

run the glassfish-x.x-unix.sh (mine was I think 3.1)

To Start a domain:

$ ./asadmin start-domain domain1
Waiting for domain1 to start .......
Successfully started the domain : domain1
domain  Location: /ubuntu/glassfish_install/glassfish/domains/domain1
Log File: /ubuntu/glassfish_install/glassfish/domains/domain1/logs/server.log
Admin Port: 4848
Command start-domain executed successfully.

To Stop Domain :

$ ./asadmin stop-domain domain1
Waiting for the domain to stop ...
Command stop-domain executed successfully.


To Deploy a Application :

$ ./asadmin deploy /ubuntu/ebooks/hello.war
Application deployed with name hello.
Command deploy executed successfully.


I Configured Http instance port to (9090) , default is 8080:

I use below to check application deployed.
http://127.0.0.1:9090/hello


Admin server console (make sure you have atleast one domain running to access admin server):


http://localhost:4848





This is how the installation screen details will look like :

CREATING DOMAIN
_______________
Executing command :/ubuntu/glassfish_install/glassfish/bin/asadmin --user admin --passwordfile /tmp/asadminTmp2258577312851916948.tmp create-domain --savelogin --checkports=false --adminport 4848 --instanceport 9090 --domainproperties=jms.port=7676:domain.jmxPort=8686:orb.listener.port=3700:http.ssl.port=8181:orb.ssl.port=3820:orb.mutualauth.port=3920 domain1
/ubuntu/glassfish_install/glassfish/bin/asadmin --user admin --passwordfile /tmp/asadminTmp6210518625018142589.tmp create-domain --savelogin --checkports=false --adminport 4848 --instanceport 9090 --domainproperties=jms.port=7676:domain.jmxPort=8686:orb.listener.port=3700:http.ssl.port=8181:orb.ssl.port=3820:orb.mutualauth.port=3920
=============================
domain1Using port 4848 for Admin.
Using port 9090 for HTTP Instance.
==================================
Using port 7676 for JMS.
Using port 3700 for IIOP.
Using port 8181 for HTTP_SSL.
Using port 3820 for IIOP_SSL.
Using port 3920 for IIOP_MUTUALAUTH.
Using port 8686 for JMX_ADMIN.
Using default port 6666 for OSGI_SHELL.
Using default port 9009 for JAVA_DEBUGGER.
Distinguished Name of the self-signed X.509 Server Certificate is:
[CN=ubuntu,OU=GlassFish,O=Oracle Corporation,L=Santa Clara,ST=California,C=US]
Distinguished Name of the self-signed X.509 Server Certificate is:
[CN=ubuntu-instance,OU=GlassFish,O=Oracle Corporation,L=Santa Clara,ST=California,C=US]
No domain initializers found, bypassing customization step
Domain domain1 created.
Domain domain1 admin port is 4848.
Domain domain1 admin user is "admin".
Login information relevant to admin user name [admin]
for this domain [domain1] stored at
[/home/sriram/.asadminpass] successfully.
Make sure that this file remains protected.
Information stored in this file will be used by
asadmin commands to manage this domain.
Command create-domain executed successfully.
























Tuesday, June 21, 2011

Program to find Prime Numbers till 100

What is a Prime Number ?
If it is bigger than one and has no divisors other than 1 and itself.


==========================primenumbers.java=======================
public class primenumbers {
   
    /**
    * Calculating Prime Numbers
    *
    */
    public static void main(String[] args) {

    int num1, num2, modulo = 0;
    int maxPrimeNumber = 100;

    for (num1 = 1; num1 < maxPrimeNumber; num1++) {

    label:for (num2 = 2; num2 < num1; num2++) {

    modulo = num1 % num2;

    if (modulo == 0)
    break label;
    }

    if (num1 == num2)
    System.out.print(num1 + " : ");
    }

    }

    }
====================================================


Output:
2 : 3 : 5 : 7 : 11 : 13 : 17 : 19 : 23 : 29 : 31 : 37 : 41 : 43 : 47 : 53 : 59 : 61 : 67 : 71 : 73 : 79 : 83 : 89 : 97 :


Monday, June 20, 2011

Java Cast assigning Double to Init.

Whats is as Cast ?
A cast is an explicit conversion.

In the below program we convert values from double to int.

===conversiontypes.java======
public class converisontypes {
    public static void main (String[] args) {
        double  x,y;
        x=20;
        y=10;
        int z;
       
       
        z = (int) (x/y);
       
        System.out.println("The Value of Z is " +z);
       
       
       
       
    }

}
========================
result: 

The Value of Z is 2


Thursday, June 16, 2011

Change of Variables inside different Block

Here in below program Block1 initializes   z values as 20 and Block2 initializes z values as 30.

public class Scopevariable {
public static void main(String[] args) {
    int x,y;
    x=10;
    y=20;
    if(x==10){
        int z=20;
        System.out.println("The Value of z inside Block 1 is " +z );
    }
    if(x==10){
        int z=30;
        System.out.println("The value of z inside Block 2 is " +z );
    }
}
   
}

Tuesday, June 14, 2011

Integers and values they support.


Java defines four integer types: byte, short, int, and long, which are shown here:

Type Width in Bits Range

byte 8 –128 to 127
short 16 –32,768 to 32,767
int 32 –2,147,483,648 to 2,147,483,647
long 64 –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

As the table shows, all of the integer types are signed positive and negative values.
Java does not support unsigned (positive-only) integers.
Many other computer languages support both signed and unsigned integers.
However, Java’s designers felt that unsigned integers were unnecessary.


for loop with iteration example

public class appleprice {
    public static void main(String[] args) {
        int apple,cost,price;
        cost=10;
       
        /* using { after for statement will use block and execute iterations if you remove block it wont show iterations */

        for (apple=1; apple <10; apple++) {
            price = cost * apple;
            System.out.println("price of  " + apple + "   apple is  " +price);
        }
           
           
    }

}

Sunday, June 12, 2011

A Sample Java Program and description :

class Example{
public static void main(String...args){
S.o.p("HOW");
}
}

[S.o.p = System.out.println]



class Example {
This line uses the keyword class to declare that a new class is being defined.
The class is Java’s basic unit of encapsulation.

public static void main (String args[]) {
The method is public because it be accessible to the JVM to begin execution of the program.

It is Static because it be available for execution without an object instance. you may know that you need an object instance to invoke any method. So you cannot begin execution of a class without its object if the main method was not static.

It returns only a void because, once the main method execution is over, the program terminates. So there can be no data that can be returned by the Main method

The last parameter is String args[]. This is used to signify that the user may opt to enter parameters to the java program at command line. We can use both String[] args or String args[]. The Java compiler would accept both forms.








Javas Magic "The Bytecode"

                                  Java Program (eg class files)
                                                       |
                                                       |
JVM (Java Virtual Machine) part for JRE (Java Runtime Environment)
                                                       |
                                                       |
 JVM converts the Java Program to Bytecodes and talks to the machine    

Bytecodes are the machine language of the Java virtual machine. When a JVM loads a class file, it gets one stream of bytecodes for each method in the class


*Java Bytecode is Highly optimised for speed of execution.


$javac testfile.java

This will create a testfile.class which will have java bytecode version of the program.

To actually run the program 

You run,
$java testfile (class file name).






 Also read for more info:

http://www.javaworld.com/javaworld/jw-09-1996/jw-09-bytecodes.html




JAVA FAQ's

1) How Java Relates to C and C++

Java is directly related to both C and C++. Java inherits its syntax from C. Its object model is adapted from C++.


Second, Java’s designers did not “reinvent the wheel.” Instead, they further refined an already highly successful programming paradigm. The modern age of programming began with C. It moved to C++, and now to Java.

This makes it easy for a C/C++ programmer to learn Java and, conversely, for a Java programmer to learn C/C++.


2) What are  Java Applets
An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed by a Java-compatible Web browser. Furthermore, an applet is downloaded on demand.

3) Java Security :

Java confines a Java program to the Java execution environment and not allowing it access to other parts of the computer.

Frankly, the ability to download applets with confidence that no harm will be done to the client computer is the single most important aspect of Java.

4)   To address the issues of portability and security, why was it necessary to create a new computer language such as Java; couldn’t a language like C++ be adapted? In other words, couldn’t a C++ compiler that outputs bytecode be created?

While it would be possible for a C++ compiler to generate bytecode rather than
executable code, C++ has features that discourage its use for the creation of applets—the most important feature being C++’s support for pointers. A pointer is the address of some object stored in memory. Using a pointer, it would be possible to access resources outside the program itself, resulting in a security breach. Java does not support pointers,thus eliminating this problem.