Pages

Monday, December 26, 2011

Read Propserties File

import java.io.*;
import java.util.*;

public class ReadProp{
  String str, key;
  public static void main(String[] args) {
  ReadProp r = new ReadProp();
  }
  public ReadProp(){
     
  try{
  int check = 0;
  while(check == 0){
  check = 1;
 BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
  System.out.print("Enter file name which has properties extension :");
 // str = bf.readLine();
  str = "C:\\Documents and Settings\\subhani.s\\My Documents\\NetBeansProjects\\December\\src\\properties\\myjdbc";
  File f = new File(str + ".properties");
  if(f.exists()){
  Properties pro = new Properties();
  FileInputStream in = new FileInputStream(f);
  pro.load(in);
  System.out.println("All key are given: " + pro.keySet());
  System.out.print("Enter Key : ");
 key = bf.readLine();
  String p = pro.getProperty(key);
  System.out.println(key + " : " + p);
  }
  else{
  check = 0;
  System.out.println("File not found!");
  }
  }
  }
  catch(IOException e){
  System.out.println(e.getMessage());
  }
  }
}

Create Properties File

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;

public class javaPro {
  
    public static void main( String[] args )
    {
        Properties prop = new Properties();

        try {
            //set the properties value
            prop.setProperty("host_name", "localhost");
            prop.setProperty("user_id", "as400");
            prop.setProperty("bpassword", "samplecode");

            //save properties to project root folder
            prop.store(new FileOutputStream("src/properties/myjdbc.properties"), null);

        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

Thursday, December 22, 2011

XML

XML

DTD
XML DOM
XSLT
XPATH

XQUERY
XLINK

XPOINTER
SCHEMA
XSL-FO

SVG

Wednesday, December 21, 2011

xml write

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml;

/**
 *
 * @author Subhani.s
 */
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class WriteXMLFile {

    public static void main(String argv[]) {

      try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("company");
        doc.appendChild(rootElement);

        // staff elements
        Element staff = doc.createElement("Staff");
        rootElement.appendChild(staff);

        // set attribute to staff element
        Attr attr = doc.createAttribute("id");
        attr.setValue("1");
        staff.setAttributeNode(attr);

        // shorten way
        // staff.setAttribute("id", "1");

        // firstname elements
        Element firstname = doc.createElement("firstname");
        firstname.appendChild(doc.createTextNode("yong"));
        staff.appendChild(firstname);

        // lastname elements
        Element lastname = doc.createElement("lastname");
        lastname.appendChild(doc.createTextNode("mook kim"));
        staff.appendChild(lastname);

        // nickname elements
        Element nickname = doc.createElement("nickname");
        nickname.appendChild(doc.createTextNode("mkyong"));
        staff.appendChild(nickname);

        // salary elements
        Element salary = doc.createElement("salary");
        salary.appendChild(doc.createTextNode("100000"));
        staff.appendChild(salary);

        // write the content into xml file
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(new File("C:\\file.xml"));

        // Output to console for testing
        // StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);

        System.out.println("File saved!");

      } catch (ParserConfigurationException pce) {
        pce.printStackTrace();
      } catch (TransformerException tfe) {
        tfe.printStackTrace();
      }
    }
}

xml read

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xml;

/**
 *
 * @author Subhani.s
 */
import java.io.File;
import org.w3c.dom.*;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class ReadAndPrintXMLFile{

    public static void main (String argv []){
    try {

            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File("book.xml"));

            // normalize text representation
            doc.getDocumentElement ().normalize ();
            System.out.println ("Root element of the doc is " +    doc.getDocumentElement().getNodeName());


            NodeList listOfPersons = doc.getElementsByTagName("person");
            int totalPersons = listOfPersons.getLength();
            System.out.println("Total no of people : " + totalPersons);

            for(int s=0; s

                Node firstPersonNode = listOfPersons.item(s);
                if(firstPersonNode.getNodeType() == Node.ELEMENT_NODE){


                    Element firstPersonElement = (Element)firstPersonNode;

                    //-------
                    NodeList firstNameList = firstPersonElement.getElementsByTagName("first");
                    Element firstNameElement = (Element)firstNameList.item(0);

                    NodeList textFNList = firstNameElement.getChildNodes();
                    System.out.println("First Name : " +
                           ((Node)textFNList.item(0)).getNodeValue().trim());

                    //-------
                    NodeList lastNameList = firstPersonElement.getElementsByTagName("last");
                    Element lastNameElement = (Element)lastNameList.item(0);

                    NodeList textLNList = lastNameElement.getChildNodes();
                    System.out.println("Last Name : " +
                           ((Node)textLNList.item(0)).getNodeValue().trim());

                    //----
                    NodeList ageList = firstPersonElement.getElementsByTagName("age");
                    Element ageElement = (Element)ageList.item(0);

                    NodeList textAgeList = ageElement.getChildNodes();
                    System.out.println("Age : " +
                           ((Node)textAgeList.item(0)).getNodeValue().trim());

                    //------


                }//end of if clause


            }//end of for loop with s var


        }catch (SAXParseException err) {
        System.out.println ("** Parsing error" + ", line "
             + err.getLineNumber () + ", uri " + err.getSystemId ());
        System.out.println(" " + err.getMessage ());

        }catch (SAXException e) {
        Exception x = e.getException ();
        ((x == null) ? e : x).printStackTrace ();

        }catch (Throwable t) {
        t.printStackTrace ();
        }
        //System.exit (0);

    }//end of main


}

Monday, December 19, 2011

TimerBasedAnimation

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class TimerBasedAnimation extends JPanel implements ActionListener
{
  private Ellipse2D.Float ellipse = new Ellipse2D.Float();

  private double esize;

  private double maxSize = 0;

  private boolean initialize = true;

  Timer timer;

  ActionListener updateProBar;

  public TimerBasedAnimation()
  {
    setXY(20 * Math.random(), 200, 200);

    timer = new Timer(20, this);
    timer.setInitialDelay(190);
    timer.start();
  }

  public void setXY(double size, int w, int h)
  {
    esize = size;
    ellipse.setFrame(10, 10, size, size);
  }

  public void reset(int w, int h)
  {
    maxSize = w / 10;
    setXY(maxSize * Math.random(), w, h);
  }

  public void step(int w, int h)
  {
    esize++;
    if (esize > maxSize)
    {
      setXY(1, w, h);
    } else {
      ellipse.setFrame(ellipse.getX(), ellipse.getY(), esize, esize);
    }
  }

  public void render(int w, int h, Graphics2D g2)
  {
    g2.setColor(Color.BLUE);
    g2.draw(ellipse);
  }

  public void paint(Graphics g)
  {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;

    RenderingHints rh = new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

    rh.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    g2.setRenderingHints(rh);
    Dimension size = getSize();

    if (initialize)
    {
      reset(size.width, size.height);
      initialize = false;
    }
    this.step(size.width, size.height);
    render(size.width, size.height, g2);
  }

  public void actionPerformed(ActionEvent e)
  {
    repaint();
  }

  public static void main(String[] args)
  {
    JFrame frame = new JFrame("TimerBasedAnimation");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new TimerBasedAnimation());
    frame.setSize(350, 250);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

Friday, December 16, 2011

Feature
Struts 1
Struts 2
Action classes
Struts1 extends the abstract base class by its action class. The problem with struts1 is that it uses the abstract classes rather than interfaces. While in Struts 2, an Action class implements an Action interface, along with other interfaces use optional and custom services. Struts 2 provides a base ActionSupport class that implements commonly used interfaces. Although an Action interface is not necessary, any POJO object along with an execute signature can be used as an Struts 2 Action object.
Threading Model
Struts 1 Actions are singletons therefore they must be thread-safe because only one instance of a class handles all the requests for that Action. The singleton strategy restricts to Struts 1 Actions and requires extra care to make the action resources thread safe or synchronized while developing an application. Struts 2 doesn't have thread-safety issues as Action objects are instantiated for each request. A servlet container generates many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.
Servlet Dependency
Actions are dependent on the servlet API because HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked therefore Struts1. Container does not treat the Struts 2 Actions as a couple. Servlet contexts are typically represented as simple Maps that allow Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. While other architectural elements directly reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse.
Testability
Struts1 application has a major problem while testing the application because the execute method exposes the Servlet API. Struts TestCase provides a set of mock object for Struts 1. To test the Struts 2 Actions instantiate the Action, set the properties, and invoking methods. Dependency Injection also makes testing easier.
Harvesting Input
Struts 1 recieves an input by creating an ActionForm object. Like the action classes, all ActionForms class must extend a ActionForm base class. Other JavaBeans classes cannot be used as ActionForms, while developers create redundant classes to receive the input. DynaBeans is the best alternative to create the conventional ActionForm classes. Struts 2 requires Action properties as input properties that eliminates the need of a second input object. These Input properties may be rich object types, since they may have their own properties. Developer can access the Action properties from the web page using the taglibs. Struts 2 also supports the ActionForm pattern, POJO form objects and POJO Actions as well.
Expression Language
Struts1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into views
Struts 1 binds objects into the page context by using the standard JSP mechanism. Struts 2 uses a ValueStack technology to make the values accessible to the taglibs without coupling the view to the object to which it is rendering. The ValueStack strategy enables us to reuse views across a range of types, having same property name but different property types.
Type Conversion
Struts 1 ActionForm properties are almost in the form of Strings. Commons-Beanutils are used by used by Struts 1 for type conversion. Converters are per-class, which are not configurable per instance. Struts 2 uses OGNL for type conversion and converters to convert Basic and common object types and primitives as well.
Validation
Struts 1 uses manual validation that is done via a validate method on the ActionForm, or by using an extension to the Commons Validator. Classes can have different validation contexts for the same class, while chaining to validations on sub-objects is not allowed. Struts 2 allows manual validation that is done by using the validate method and the XWork Validation framework. The Xwork Validation Framework allows chaining of validations into sub-properties using the validations defined for the properties class type and the validation context.
Control Of Action Execution
Each module in Struts 1 has a separate Request Processors (lifecycles), while all the Actions in the module must share the same lifecycle. In Struts 2 different lifecycles are created on a per Action basis via Interceptor Stacks. Custom stacks are created and used with different Actions, as required.s

Thursday, December 15, 2011

FileRead

/**
 *
 * @author Subhani.s
 */
import java.io.*;
public class FileRead
{
    public static void main(String args[]) throws FileNotFoundException, IOException
    {
        File f = new File("D:\\a.txt");
        FileReader fr = new FileReader(f);
   //     FileInputStream fin = new FileInputStream(f);
     //   DataInputStream din = new DataInputStream(fin);
       BufferedReader br = new BufferedReader(fr);
     //   BufferedReader br = new BufferedReader(new InputStreamReader(din));
        String s;
        while((s = br.readLine()) !=null)
        {
            System.out.println(s);
        }
      //  din.close();
       
    }
   
}

Number into primes

import java.io.*;
/**
 *
 * @author subhani.s
 */
public class primeex {

    public static void main(String args[])
    {
        new primeex();
    }
   
    int j;
    public void myPrime(int k)
    {
     for (j=2; j
       {
            int l = k%j;
            if(l==0)
            {
                if(j==k)
                {
                    System.out.println("prime");

                }
                else
                    k--;
            }
        }
        if(j==k)
        {
             System.out.println("prime number");
        }
    }
    public primeex()
    {
        try
        {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String str = br.readLine();
            Integer x = Integer.valueOf(str);
            myPrime(x);
            int q;
            q=x-j;
            System.out.println("num: "+ q +"+"+ j);
        }
        catch(Exception e)
        {

        }
    }
}

PrimeNumber


import java.io.*;
public class primenumbers
{
    public static void main(String args[]) throws IOException
    {
         int i;
  BufferedReader bf = new BufferedReader(
  new InputStreamReader(System.in));
  System.out.println("Enter number:");
  int num = Integer.parseInt(bf.readLine());
  System.out.println("Prime number: ");
  for (i=1; i < num; i++ ){
  int j;
  for (j=2; j  int n = i%j;
  if (n==0){
  break;
  }
  }
  if(i == j){
  System.out.print("  "+i);
  }
  }
 
 
       

    }
   
}

String reverse

public class ReverseStringTest {
  public static void main(String[] args) {
    String str = "SubhanI";
    System.out.println(ReverseString.reverseIt(str));
  }
}

class ReverseString {
  public static String reverseIt(String source) {
    int i, len = source.length();
    StringBuffer dest = new StringBuffer(len);

    for (i = (len - 1); i >= 0; i--)
      dest.append(source.charAt(i));
    return dest.toString();
  }
}

FreeSpace

import java.io.IOException;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Subhani.s
 */
public class freespace
{
    public static void main(String args[]) throws IOException
    {
      //1.  Runtime.getRuntime().exec("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
    System.out.println( "Free Memory: "+   Runtime.getRuntime().freeMemory());
    System.out.println( "Total Memory: "+ Runtime.getRuntime().totalMemory());
    System.out.print( "Used Memory: ");
    System.out.println (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory());
   
    }
   
}

Monday, December 5, 2011

Annotations

Annotations provide data about a program that is not part of the program itself. They have no direct effect on the operation of the code they annotate.
Annotations have a number of uses, among them:
  • Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
  • Compiler-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.
  • Runtime processing — Some annotations are available to be examined at runtime.
Annotations can be applied to a program's declarations of classes, fields, methods, and other program elements.
The annotation appears first, often (by convention) on its own line, and may include elements with named or unnamed values:
@Author(
   name = "Benjamin Franklin",
   date = "3/27/2003"
)
class MyClass() { }
or
@SuppressWarnings(value = "unchecked")
void myMethod() { }
If there is just one element named "value," then the name may be omitted, as in:
@SuppressWarnings("unchecked")
void myMethod() { }
Also, if an annotation has no elements, the parentheses may be omitted, as in:
@Override
void mySuperMethod() { }

Friday, November 25, 2011

Singleton class

/**
*
* @author Subhani.s
*/
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() {}

/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}


}

Thursday, August 25, 2011

xml interview questions

1. What is the difference between SAX parser and DOM parser?
DOM spec defines an object-oriented hieararchy.
The DOM parser creates an internal tree based on the hierarchy of the XML data.
Tree stays in memory until released. The DOM parser is more memory intensive. DOM Parser’s advantage is that it is simple. Pairs nicely with XSLT.
SAX spec defines an event based approach, calling handler functions whenever certain text nodes or processing instructions are found. These events include the start and end of the document, finding a text node, finding child elements, and hitting a malformed element. SAX development is more challenging. SAX can parse gigabytes worth of XML without hitting resource barriers. It’s also faster and more complex. Better for huge XML docs. Best suited for sequential-scan applications.
2. What is the difference between Schema and DTD?
Schema might outphase DTD. XML shemas are in XML. XML Schema has a lot of built-in data types including xs:string,xs:decimal,xs:integer,xs:boolean,xs:date,xs:time. XML schemas can be edited with Schema files, parsed with XML parser, manipulated with XML DOM, and transformed with XSLT.
The building blocks of DTD include elements, attributes, entities, PCDATA, and CDATA.
3. How do you parse/validate the XML document?
By using a SAXParser, DOMParser, or XSDValidator.
4. What is XML Namespace?
Defining a namespace to avoid confusion involves using a prefix and adding an xmlns attribute to the tag to give the prefix a qualified name associated with the namespace. All child elements with the same prefix are associated with the namespace defined in the start tag of an element.
5. What is Xpath?
XPath is a language for addressing parts of an XML document, designed to be used by both XSLT and XPointer.
6. What is XML template?
* A style sheets describes transformation rules
* A transformation rule: a pattern + a template
* Pattern: a configuration in the source tree
* Template: a structure to be instantiated in the result tree
* When a pattern is matched in the source tree, the corresponding pattern is generated in the result tree
7. How would you produce PDF output using XSL’s?
FOP it. =)
-transform xml into xsl-fo doc using xslt, or DOM or SAX
-process xsl-fo using a Formatter to convert xsl-fo into a pdf.
8. What are the steps to transform XML into HTML using XSL?
An XSLT processor may output the result tree as a sequence of bytes.The xsl:output element allows stylesheet authors to specify how they wish the result tree to be output. If an XSLT processor outputs the result tree, it should do so as specified by the xsl:output element; however, it is not required to do so.The method attribute on xsl:output identifies the overall method that should be used for outputting the result tree.
The html output method outputs the result tree as HTML; for example,

9. What is XSL?
In addition to XSLT, XSL includes an XML vocabulary for specifying formatting. XSL specifies the styling of an XML document by using XSLT to describe how the document is transformed into another XML document that uses the formatting vocabulary.
10. What is XSLT?
A language for transforming XML documents into other XML documents. XSLT is designed for use as part of XSL, which is a stylesheet language for XML.

Monday, July 25, 2011

JavaScript_Timer

<script type="text/javascript">

var alertTimerId = 0;

function alertTimerClickHandler ( )
{
if ( document.getElementById("alertTimerButton").value == "Click me and wait!" )
{
// Start the timer
document.getElementById("alertTimerButton").value = "Click me to stop the timer!";
alertTimerId = setTimeout ( "showAlert()", 6000);
}
else
{
document.getElementById("alertTimerButton").value = "Click me and wait!";
clearTimeout ( alertTimerId );
}
}

function showAlert ( )
{
alert ( "Too late! You didn't stop the timer." );
document.getElementById("alertTimerButton").value = "Click me and wait!";
}

</script>
<body onload="alertTimerClickHandler()">
<input type="button" name="clickMe" id="alertTimerButton" value="Click me and wait!"

onclick="alertTimerClickHandler()"/>

</body>