Thursday, June 30, 2011

How to Implement Stack

package org.best.example;

import java.util.*;
 import java.awt.*;
 import java.awt.event.*;
 import javax.swing.*;

 public class StackTest extends JFrame
 {

     public StackTest()
     {
         super( "Stacks" );

         Container c = getContentPane();

         final JLabel status = new JLabel();
         final Stack s = new Stack();

         c.setLayout( new FlowLayout() );
         c.add( new JLabel( "Enter a string" ) );
         final JTextField input = new JTextField( 10 );
         c.add( input );

         JButton pushBtn = new JButton( "Push" );
         pushBtn.addActionListener( new ActionListener()
         {
             public void actionPerformed( ActionEvent e )
             {
                 status.setText( "Pushed: " + s.push( input.getText() ) );
             }
         } );
         c.add( pushBtn );

         JButton popBtn = new JButton( "Pop" );
         popBtn.addActionListener( new ActionListener()
         {
             public void actionPerformed( ActionEvent e )
             {
                 try
                 {
                     status.setText( "Popped: " + s.pop() );
                 }
                 catch ( EmptyStackException exception )
                 {
                     status.setText( exception.toString() );
                 }
             }
         } );
         c.add( popBtn );

         JButton peekBtn = new JButton( "Peek" );
         peekBtn.addActionListener( new ActionListener()
         {
             public void actionPerformed( ActionEvent e )
             {
                 try
                 {
                     status.setText( "Top: " + s.peek() );
                 }
                 catch ( EmptyStackException exception )
                 {
                     status.setText( exception.toString() );
                 }
             }
         } );
         c.add( peekBtn );

         JButton emptyBtn = new JButton( "Is Empty?" );
         emptyBtn.addActionListener( new ActionListener()
         {
             public void actionPerformed( ActionEvent e )
             {
                 status.setText( s.empty() ? "Stack is empty" : "Stack is not empty" );
             }
         } );
         c.add( emptyBtn );

         JButton searchBtn = new JButton( "Search" );
         searchBtn.addActionListener( new ActionListener()
         {
             public void actionPerformed( ActionEvent e )
             {
                 String searchKey = input.getText();
                 int result = s.search( searchKey );

                 if ( result == -1 )
                     status.setText( searchKey + " not found" );
                 else
                     status.setText( searchKey + " found at element " + result );
             }
        } );
        c.add( searchBtn );

         JButton displayBtn = new JButton( "Display" );
         displayBtn.addActionListener( new ActionListener()
         {
             public void actionPerformed( ActionEvent e )
             {
                 Enumeration enum = s.elements();
                 StringBuffer buf = new StringBuffer();

                 while ( enum.hasMoreElements() )
                     buf.append( enum.nextElement() ).append( " " );

                 JOptionPane.showMessageDialog( null, buf.toString(), "Display", JOptionPane.PLAIN_MESSAGE );
             }
         } );
         c.add( displayBtn );
         c.add( status );

         setSize( 675, 100 );
         show();
     }

     public static void main( String args[] )
     {
         StackTest app = new StackTest();

         app.addWindowListener( new WindowAdapter()
         {
             public void windowClosing( WindowEvent e )
             {
                 System.exit( 0 );
             }
         } );
     }
 }

Java BuzzWords - 9


High Performance

While the performance of interpreted bytecodes is usually more than adequate, there are situations where higher performance is required. The bytecodes can be translated on the fly (at runtime) into machine code for the particular CPU the application is running on. For those accustomed to the normal design of a compiler and dynamic loader, this is somewhat like putting the final machine code generator in the dynamic loader.

The bytecode format was designed with generating machine codes in mind, so the actual process of generating machine code is generally simple. Efficient code is produced: the compiler does automatic register allocation and some optimization when it produces the bytecodes.
In interpreted code we're getting about 300,000 method calls per second on an Sun Microsystems SPARCStation 10. The performance of bytecodes converted to machine code is almost indistinguishable from native C or C++.

Wednesday, June 29, 2011

How to List All Available Unicode to Character Set Converters

package org.best.example;


public static void main(String args[])
    {
     Map map = Charset.availableCharsets();
     Iterator it = map.keySet().iterator();
         while (it.hasNext()) {
         // Get charset name
         String charsetName = (String)it.next();
         System.out.println("Charset Name "+charsetName);
       
         // Get charset
         Charset charset = Charset.forName(charsetName);
         System.out.println("Charset "+charset);
     }
}




Java BuzzWords - 8


Interpreted

Java bytecodes are translated on the fly to native machine instructions (interpreted) and not stored anywhere. And since linking is a more incremental and lightweight process, the development process can be much more rapid and exploratory.As a part of the bytecode stream, more compile-time information is carried over and available at runtime. This is what the linker's type checks are based on. It also makes programs more amenable to debugging.

Tuesday, June 28, 2011

How to Locate Time Server

package org.best.example;

import java.io.*;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.util.regex.*;


public class TimeServer {

    // We can't use the normal daytime port (unless we're running as root,
    // which is unlikely), so we use this one instead
    private static int PORT = 8013;

    // The port we'll actually use
    private static int port = PORT;

    // Charset and encoder for US-ASCII
    private static Charset charset = Charset.forName("US-ASCII");
    private static CharsetEncoder encoder = charset.newEncoder();

    // Direct byte buffer for writing
    private static ByteBuffer dbuf = ByteBuffer.allocateDirect(1024);


    // Open and bind the server-socket channel
    //
    private static ServerSocketChannel setup() throws IOException {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    InetSocketAddress isa
        = new InetSocketAddress(InetAddress.getLocalHost(), port);
    ssc.socket().bind(isa);
    return ssc;
    }

    // Service the next request to come in on the given channel
    //
    private static void serve(ServerSocketChannel ssc) throws IOException {
    SocketChannel sc = ssc.accept();
    try {
        String now = new Date().toString();
        sc.write(encoder.encode(CharBuffer.wrap(now + "
")));
        System.out.println(sc.socket().getInetAddress() + " : " + now);
        sc.close();
    } finally {
        // Make sure we close the channel (and hence the socket)
        sc.close();
    }
    }

    public static void main(String[] args) throws IOException {
    if (args.length > 1) {
        System.err.println("Usage: java TimeServer [port]");
        return;
    }

    // If the first argument is a string of digits then we take that
    // to be the port number
    if ((args.length == 1) && Pattern.matches("[0-9]+", args[0]))
        port = Integer.parseInt(args[0]);

    ServerSocketChannel ssc = setup();
    for (;;)
        serve(ssc);

    }

}

Java BuzzWords - 7


Portable

Being architecture neutral is a big chunk of being portable, but there's more to it than that. Unlike C and C++, there are no "implementation dependent" aspects of the specification. The sizes of the primitive data types are specified, as is the behavior of arithmetic on them. For example, "int" always means a signed two's complement 32 bit integer, and "float" always means a 32-bit IEEE 754 floating point number. Making these choices is feasible in this day and age because essentially all interesting CPUs share these characteristics.

The libraries that are a part of the system define portable interfaces. For example, there is an abstract Window class and implementations of it for Unix, Windows NT/95, and the Macintosh.The Java system itself is quite portable. The compiler is written in Java and the runtime is written in ANSI C with a clean portability boundary. The portability boundary is essentially a POSIX subset.

Monday, June 27, 2011

Java BuzzWords - 6


Architecture Neutral

Java was designed to support applications on networks. In general, networks are composed of a variety of systems with a variety of CPU and operating system architectures. To enable a Java application to execute anywhere on the network, the compiler generates an architecture-neutral object file format--the compiled code is executable on many processors, given the presence of the Java runtime system.

This is useful not only for networks but also for single system software distribution. In the present personal computer market, application writers have to produce versions of their application that are compatible with the IBM PC and with the Apple Macintosh. With the PC market (through Windows/NT) diversifying into many CPU architectures, and Apple moving off the 680x0 toward the PowerPC, production of software that runs on all platforms becomes nearly impossible. With Java, the same version of the application runs on all platforms.

The Java compiler does this by generating bytecode instructions which have nothing to do with a particular computer architecture. Rather, they are designed to be both easy to interpret on any machine and easily translated into native machine code on the fly.

How to Fade a Image in Applet

package org.best.example;

import java.applet.*;
 import java.awt.*;
 import java.awt.image.*;
 import java.net.*;

 public class FadeImage extends Applet {
   Image   img, faded;
   int level, sign;
   MediaTracker tracker;
   AlphaFilter f;
   FilteredImageSource fis;

   public void init() {
     level = 0;
     sign =  15;
     tracker = new MediaTracker(this);
     try {
       img = getImage(new URL(getDocumentBase(), "gumby.gif"));
       tracker.addImage(img,0);
       tracker.waitForID(0);
       }
     catch (Exception e) {
       e.printStackTrace();
       }
     f = new AlphaFilter();
     f.setLevel(level);
     fis = new FilteredImageSource(img.getSource(), f) ;

     FadeThread ft = new FadeThread();
     ft.delayedFading(this, 20);
     ft.start();
     }

   public void paint(Graphics g) {
     if (faded != null) {
        g.drawImage(faded,0,0,this);
        }
     }

   public void fadeIt() {
     Graphics g = this.getGraphics();
     level += sign;
     if (level < 0) {
        level=0;
        sign = sign * -1;
        }
     if (level > 255) {
        level=255;
        sign =  sign * -1;
      try {
        Thread.sleep(1000);
        }
      catch (Exception e) {}
        }
     f.setLevel(level);
     if (faded != null) faded.flush();
     faded = this.createImage(fis);
     tracker.addImage(faded,0);
     try {
       tracker.waitForID(0);
       }
     catch (Exception ex) {
       ex.printStackTrace();
       }
     repaint();
     }

   class FadeThread extends Thread {
     FadeImage fadeApplet;
     int delay;

     public void delayedFading(FadeImage f, int delay) {
       this.fadeApplet = f;
       this.delay = delay;
       }

     public void run() {
       while (true) {
         try {
           sleep(delay);
           fadeApplet.fadeIt();
           }
         catch (Exception e) {
           e.printStackTrace();
           }
         }
       }
     }

    class AlphaFilter extends RGBImageFilter {
      private int level;

      public AlphaFilter() {
        canFilterIndexColorModel = true;
        }

      public void setLevel(int lev) {
        level = lev;
        }

      public int filterRGB(int x, int y, int rgb) {
        int a = level * 0x01000000;
        return (rgb &   0x00ffffff) | a;
        }
      }
 }

Sunday, June 26, 2011

Java BuzzWords - 5


Secure

Java is intended for use in networked/distributed environments. Toward that end, a lot of emphasis has been placed on security. Java enables the construction of virus-free, tamper-free systems. The authentication techniques are based on public-key encryption.There is a strong interplay between "robust" and "secure." For example, the changes to the semantics of pointers make it impossible for applications to forge access to data structures or to access private data in objects that they do not have access to. This closes the door on most activities of viruses.

How to Draw a Pie Chart in Applet

package org.best.example;

import java.util.*;
 import java.awt.*;
 import java.applet.Applet;

 public class Graph extends Applet {
  int    depth, radius;

 public void init() {
   float value;
   String at = getParameter("width");
   radius = (at != null) ?  Integer.valueOf(at).intValue() : 100;
   at = getParameter("depth");
   depth = (at != null) ? Integer.valueOf(at).intValue() : 20;
   at = getParameter("values");
   PieChartCanvas c = new PieChartCanvas(radius, depth);
   setLayout(new BorderLayout());

   // Create Hashtable to map color name (String) to Color type
   Hashtable colors = new Hashtable();
   colors.put("green", Color.green);
   colors.put("red", Color.red);
   colors.put("blue", Color.blue);
   colors.put("yellow", Color.yellow);
   colors.put("magenta", Color.magenta);
   colors.put("cyan", Color.cyan);
   colors.put("orange", Color.orange);
   colors.put("pink", Color.pink);
   colors.put("white", Color.white);
   colors.put("black", Color.black);

   // "value-color,value-color,..."
   StringTokenizer t = new StringTokenizer(at, ",");
   String s;
   int i;
   while (t.hasMoreTokens()) {
     s = t.nextToken();
     i = s.indexOf('-');
     value = Float.valueOf(s.substring(0, i)).floatValue();
     c.addSlice(value, (Color)colors.get(s.substring(i + 1)));
    }

   resize(c.getMinimumSize().width, c.getMinimumSize().height);
   add("Center", c);
   }
 }

 class PieChartCanvas extends Canvas {

   final double aspectFudge = 2.5;
   int radius, depth, called = 1, numSlices = 0;
   float total = 0, value[] = new float[10];
   Color color[] = new Color[10];
   Graphics offGraphics;
   Image gfxBuff;

   public PieChartCanvas(int radius, int depth) {
     this.value = value;
     this.color = color;
     this.radius = radius;
     this.depth = depth;
     }

   public void paint(Graphics g) {
     int startAngle;
     float angle;
     Dimension d = getSize();

     if(gfxBuff == null) {
       gfxBuff = createImage(d.width, d.height);
       offGraphics = gfxBuff.getGraphics();
       offGraphics.setColor(getBackground());
       offGraphics.fillRect(0, 0, d.width, d.height);
       }

     // do the 3d effect
     for(int x = depth; x >= 1; x--) {
       startAngle = -45;
       for(int i = 0; i < numSlices; i++) {
         offGraphics.setColor(color[i].darker());
         angle = Math.round(360 * (value[i] / total));
         offGraphics.fillArc(0, x, radius, (int)(radius / aspectFudge),
             startAngle, (int)angle);
             startAngle += angle;
         }
     }

     // draw the pie slice
     startAngle = -45;
     for(int i = 0; i < numSlices; i++) {
       offGraphics.setColor(color[i]);
       angle = Math.round(360 * (value[i] / total));
       offGraphics.fillArc(0, 0, radius, (int)(radius / aspectFudge),
          startAngle, (int)angle);
          startAngle += angle;
       }
     g.drawImage(gfxBuff, 0, 0, null);
     }

   public void addSlice(float value, Color color) {
     this.value[numSlices] = value;
     this.color[numSlices++] = color;
     total += value;
     }

   public Dimension getPreferredSize() {
     return getMinimumSize();
     }

   public Dimension getMinimumSize() {
     return new Dimension(radius, (int)((radius / aspectFudge) + depth));
     }
   }

 <APPLET CODE=Graph.class WIDTH=150 HEIGHT=150>
   <PARAM NAME="depth"  VALUE="30">
   <PARAM NAME="width"  VALUE="120">
   <PARAM NAME="values" VALUE="1-red,2-green,3-blue">
 </APPLET>

Saturday, June 25, 2011

How to Rotate Banner


package org.best.example;

import java.applet.Applet;
import java.applet.AppletContext;
import java.awt.*;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.StringTokenizer;
import java.util.Vector;

public class BhuBanner extends Applet
    implements Runnable {

    Thread A;
    int B;
    int C;
    int D;
    int E;
    int F;
    int G;
    int H;
    int I;
    int J;
    int K;
    int L;
    int M;
    int N;
    int O;
    int P;
    int Q;
    int R;
    int S;
    int T;
    int U;
    Font V;
    String W;
    String X;
    String Y;
    String Z;
    FontMetrics a;
    Color b;
    Color c;
    Color d;
    Image e;
    Graphics f;
    char g[];
    Vector h;
    Vector i;
    Vector j;
    int k;
    int l;
    int m;
    int n;
    int o;
    int p;
    int q;
    boolean r;
    final int s = 0;
    final int t = 1;
    int u;
    int v[];

    public void init() {
        B = 0;
        h = new Vector(10, 10);
        i = new Vector(10, 10);
        j = new Vector(10, 10);
        B();
        W = (String)h.elementAt(0);
        setBackground(b);
        E = size().width;
        F = size().height;
        v = new int[Q];
        V = new Font(Y, S, I);
        a = getFontMetrics(V);
        J = a.getHeight();
        H = a.stringWidth(W);
        G = (F - a.getHeight()) / 2 + a.getAscent();
        e = createImage(E, F);
        f = e.getGraphics();
        f.setFont(V);
        g = W.toCharArray();
        L = g.length;
        K = (E - H) / 2;
        P = K;
        k = b.getRed();
        l = b.getGreen();
        m = b.getBlue();
        d = c;
        n = c.getRed();
        p = c.getGreen();
        o = c.getBlue();
        for(int i1 = 0; i1 < Q; i1++) {
            String s1 = (String)j.elementAt(i1);
            if(s1.equalsIgnoreCase("DROP"))
                v[i1] = 1;
            else
            if(s1.equalsIgnoreCase("SCROLL"))
                v[i1] = 0;
            else
                v[i1] = 0;
        }

        u = v[0];
    }

    public void B() {
        W = getParameter("TextToDisplay");
        if(W == null)
            W = "String not defined;";
        Q = D(W, h);
        W = getParameter("URLtoDisplay");
        if(W == null)
            W = "";
        D(W, i);
        W = getParameter("Effect");
        if(W == null)
            W = "DROP;SCROLL;DROP";
        D(W, j);
        X = getParameter("FontSize");
        if(X == null)
            I = 24;
        else
            I = Integer.parseInt(X);
        Y = getParameter("FontName");
        if(Y == null)
            Y = "TimesRoman";
        String s1 = getParameter("FontStyle");
        if(s1 == null)
            S = 1;
        else
        if(s1.equalsIgnoreCase("PLAIN"))
            S = 0;
        else
        if(s1.equalsIgnoreCase("BOLD"))
            S = 1;
        else
        if(s1.equalsIgnoreCase("ITALIC"))
            S = 2;
        else
        if(s1.equalsIgnoreCase("BOLDandITALIC"))
            S = 3;
        else
            S = 1;
        Z = getParameter("target");
        if(Z == null)
            Z = "_blank";
        String s2 = getParameter("speed");
        if(s2 == null)
            O = 5;
        else
            O = Integer.parseInt(s2);
        String s3 = getParameter("xStep");
        if(s3 == null)
            T = 20;
        else
            T = Integer.parseInt(s3);
        String s4 = getParameter("yStep");
        if(s4 == null)
            U = 10;
        else
            U = Integer.parseInt(s4);
        String s5 = getParameter("Delay");
        if(s5 == null)
            R = 3000;
        else
            R = Integer.parseInt(s5);
        String s6 = getParameter("bgCOLOR");
        if(s6 == null)
            b = Color.white;
        else
        if((b = C(s6)) == null)
            b = Color.white;
        String s7 = getParameter("textCOLOR");
        if(s7 == null)
            c = Color.black;
        else
        if((c = C(s7)) == null)
            c = Color.black;
        String s8 = getParameter("Author");
        if(s8 == null || !s8.equals("www")) {
            c = Color.black;
            b = Color.black;
        }
        String s9 = getParameter("Email");
        if(s9 == null || !s9.equals("x@xxx")) {
            c = Color.black;
            b = Color.black;
        }
    }

    public int D(String s1, Vector vector) {
        StringTokenizer stringtokenizer = new StringTokenizer(s1, ";", false);
        int i1;
        for(i1 = 0; stringtokenizer.hasMoreTokens(); i1++) {
            String s2 = stringtokenizer.nextToken().trim();
            vector.addElement(s2);
        }

        return i1;
    }

    public Color C(String s1) {
        int i1;
        int j1;
        int k1;
        try {
            i1 = Integer.parseInt(s1.substring(0, s1.indexOf(",")).trim());
            j1 = Integer.parseInt(s1.substring(s1.indexOf(",") + 1, s1.lastIndexOf(",")).trim());
            k1 = Integer.parseInt(s1.substring(s1.lastIndexOf(",") + 1).trim());
        }
        catch(NumberFormatException numberformatexception) {
            System.out.println("can't convert to integer, Switching to default colors" + numberformatexception);
            return null;
        }
        try {
            return new Color(i1, j1, k1);
        }
        catch(IllegalArgumentException illegalargumentexception) {
            System.out.println("can't create new color, Switching to default colors" + illegalargumentexception);
        }
        return null;
    }

    public void start() {
        if(A == null) {
            A = new Thread(this);
            A.start();
        }
    }

    public void stop() {
        if(A != null) {
            A.stop();
            A = null;
        }
    }

    public void destroy() {
        f.dispose();
    }

    public void run() {
        do {
            d = c;
            r = true;
            switch(u) {
            default:
                break;

            case 1: // '\001'
                M = 0;
                for(N = 0; M < L; N++) {
                    if(g[N] == ' ') {
                        M++;
                        N++;
                    }
                    P = K + a.charsWidth(g, 0, M);
                    D = -J;
                    C = P;
                    for(; G - D > U; D += U) {
                        repaint();
                        try {
                            Thread.sleep(O);
                        }
                        catch(InterruptedException interruptedexception) { }
                    }

                    D = G;
                    repaint();
                    try {
                        Thread.sleep(O);
                    }
                    catch(InterruptedException interruptedexception1) { }
                    M++;
                }

                for(int i1 = 0; i1 <= 100; i1 += q) {
                    r = false;
                    A(i1);
                    repaint();
                    try {
                        Thread.sleep(200L);
                    }
                    catch(InterruptedException interruptedexception2) { }
                }

                break;

            case 0: // '\0'
                M = 0;
                for(N = 0; M < L; N++) {
                    if(g[N] == ' ') {
                        M++;
                        N++;
                    }
                    P = K + a.charsWidth(g, 0, M);
                    C = E;
                    D = G;
                    for(; C - P > T; C -= T) {
                        repaint();
                        try {
                            Thread.sleep(O);
                        }
                        catch(InterruptedException interruptedexception3) { }
                    }

                    C = P;
                    repaint();
                    try {
                        Thread.sleep(O);
                    }
                    catch(InterruptedException interruptedexception4) { }
                    M++;
                }

                for(int j1 = 0; j1 <= 100; j1 += q) {
                    r = false;
                    A(j1);
                    repaint();
                    try {
                        Thread.sleep(200L);
                    }
                    catch(InterruptedException interruptedexception5) { }
                }

                break;
            }
            B++;
            if(B > Q - 1)
                B = 0;
            W = (String)h.elementAt(B);
            H = a.stringWidth(W);
            g = W.toCharArray();
            L = g.length;
            K = (E - H) / 2;
            u = v[B];
        } while(true);
    }

    public void A(int i1) {
        int j1 = ((k - n) * i1) / 100 + n;
        int k1 = ((l - p) * i1) / 100 + p;
        int l1 = ((m - o) * i1) / 100 + o;
        d = new Color(j1, k1, l1);
    }

    public void paint(Graphics g1) {
        f.setColor(b);
        f.fillRect(0, 0, E, F);
        f.setColor(d);
        if(r) {
            f.drawChars(g, 0, M, K, G);
            f.drawChars(g, N, 1, C, D);
        } else {
            f.drawString(W, K, G);
        }
        g1.drawImage(e, 0, 0, this);
    }

    public void update(Graphics g1) {
        paint(g1);
    }

    public boolean mouseDown(Event event, int i1, int j1) {
        try {
            getAppletContext().showDocument(new URL((String)i.elementAt(B)), Z);
        }
        catch(MalformedURLException malformedurlexception) {
            System.out.println("Wrong URL");
        }
        return true;
    }

    public BhuBanner() {
        q = 5;
        r = true;
    }
}

Java BuzzWords - 4


Robust

Java is intended for writing programs that must be reliable in a variety of ways. Java puts a lot of emphasis on early checking for possible problems, later dynamic (runtime) checking, and eliminating situations that are error prone.

One of the advantages of a strongly typed language (like C++) is that it allows extensive compile-time checking so bugs can be found early. Unfortunately, C++ inherits a number of loopholes in compile-time checking from C, which is relatively lax (particularly method/procedure declarations). In Java, we require declarations and do not support C-style implicit declarations.The linker understands the type system and repeats many of the type checks done by the compiler to guard against version mismatch problems.

The single biggest difference between Java and C/C++ is that Java has a pointer model that eliminates the possibility of overwriting memory and corrupting data. Instead of pointer arithmetic, Java has true arrays. This allows subscript checking to be performed. In addition, it is not possible to turn an arbitrary integer into a pointer by casting.While Java doesn't make the QA problem go away, it does make it significantly easier.

Very dynamic languages like Lisp, TCL and Smalltalk are often used for prototyping. One of the reasons for their success at this is that they are very robust: you don't have to worry about freeing or corrupting memory. Java programmers can be relatively fearless about dealing with memory because they don't have to worry about it getting corrupted. Because there are no pointers in Java, programs can't accidentally overwrite the end of a memory buffer. Java programs also cannot gain unauthorized access to memory, which could happen in C or C++.

One reason that dynamic languages are good for prototyping is that they don't require you to pin down decisions too early. Java uses another approach to solve this dilemma; Java forces you to make choices explicitly because it has static typing, which the compiler enforces. Along with these choices comes a lot of assistance: you can write method invocations and if you get something wrong, you are informed about it at compile time. You don't have to worry about method invocation error.

Friday, June 24, 2011

How to Use StringTokenizer in Java

The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical analyzer) or scanner. StringTokenizer implements the Enumeration interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using StringTokenizer.
To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example, ",;:" sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage return.
The StringTokenizer constructors are shown here:
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)

In all versions, str is the string that will be tokenized. In the first version, the default delimiters are used. In the second and third versions, delimiters is a string that specifies the delimiters. In the third version, if delimAsToken is true, then the delimiters are also returned as tokens when the string is parsed. Otherwise, the delimiters are not returned. 
Delimiters are not returned as tokens by the first two forms. Once you have created a StringTokenizer object, the nextToken( ) method is used to extract consecutive tokens. The hasMoreTokens( ) method returns true while there are more tokens to be extracted. Since StringTokenizer implements Enumeration, the hasMoreElements( ) and nextElement( ) methods are also implemented, and they act the same as hasMoreTokens( ) and nextToken( ), respectively.
Here is an example that creates a StringTokenizer to parse "key=value" pairs. Consecutive sets of "key=value" pairs are separated by a semicolon.

package org.best.example;

import java.util.StringTokenizer;
class STDemo {
static String in = "title=Java-Samples;" +
"author=Emiley J;" +
"publisher=java-samples.com;" +
"copyright=2007;";
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer(in, "=;");
while(st.hasMoreTokens()) {
String key = st.nextToken();
String val = st.nextToken();
System.out.println(key + "\t" + val);
}
}
}

Java BuzzWords - 3


Network-Savvy

Java has an extensive library of routines for coping easily with TCP/IP protocols like HTTP and FTP. This makes creating network connections much easier than in C or C++. Java applications can open and access objects across the net via URLs with the same ease that programmers are used to when accessing a local file system.

Thursday, June 23, 2011

Java BuzzWords - 2


Object-Oriented

This is, unfortunately, one of the most overused buzzwords in the industry. But object-oriented design is very powerful because it facilitates the clean definition of interfaces and makes it possible to provide reusable "software ICs."

Simply stated, object-oriented design is a technique that focuses design on the data (=objects) and on the interfaces to it. To make an analogy with carpentry, an "object-oriented" carpenter would be mostly concerned with the chair he was building, and secondarily with the tools used to make it; a "non-object-oriented" carpenter would think primarily of his tools. Object-oriented design is also the mechanism for defining how modules "plug and play."

The object-oriented facilities of Java are essentially those of C++, with extensions from Objective C for more dynamic method resolution.

How to Do Hashing String with SHA-256

It will use SHA-256 hashing algorithm to generate a hash value for a password “123456″.

package org.best.example;
 
import java.security.MessageDigest;
 
public class SHAHashingExample 
{
    public static void main(String[] args)throws Exception
    {
     String password = "123456";
 
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(password.getBytes());
 
        byte byteData[] = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < byteData.length; i++) {
         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Hex format : " + sb.toString());
 
        //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
     for (int i=0;i<byteData.length;i++) {
      String hex=Integer.toHexString(0xff & byteData[i]);
          if(hex.length()==1) hexString.append('0');
          hexString.append(hex);
     }
     System.out.println("Hex format : " + hexString.toString());
    }
}
Output
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
Hex format : 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92

Wednesday, June 22, 2011

How to Do Java SHA Hashing

SHA-2 is believe the most secure hashing algorithm as this article is written, here are few examples for the SHA implementation. The possible MessageDigest algorithm are SHA-1, SHA-256, SHA-384, and SHA-512, you can check the reference for the detail.It will use SHA-256 hashing algorithm to generate a checksum for file “c:\\loging.log”.

package org.best.example;
 
import java.io.FileInputStream;
import java.security.MessageDigest;
 
public class SHACheckSumExample 
{
    public static void main(String[] args)throws Exception
    {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        FileInputStream fis = new FileInputStream("c:\\loging.log");
 
        byte[] dataBytes = new byte[1024];
 
        int nread = 0; 
        while ((nread = fis.read(dataBytes)) != -1) {
          md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();
 
        //convert the byte to hex format method 1
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
          sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
 
        System.out.println("Hex format : " + sb.toString());
 
       //convert the byte to hex format method 2
        StringBuffer hexString = new StringBuffer();
     for (int i=0;i<mdbytes.length;i++) {
       hexString.append(Integer.toHexString(0xFF & mdbytes[i]));
     }
 
     System.out.println("Hex format : " + hexString.toString());
    }
}
 
Output
 
Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4
Hex format : 21a57f2fe765e1ae4a8bf15d73fc1bf2a533f547f2343d12a499d9c0592044d4 

Java BuzzWords - 1


Simple

We wanted to build a system that could be programmed easily without a lot of esoteric training and which leveraged today's standard practice. Most programmers working these days use C, and most programmers doing object-oriented programming use C++. So even though we found that C++ was unsuitable, we designed Java as closely to C++ as possible in order to make the system more comprehensible.

Java omits many rarely used, poorly understood, confusing features of C++ that in our experience bring more grief than benefit. These omitted features primarily consist of operator overloading (although the Java language does have method overloading), multiple inheritance, and extensive automatic coercions.

We added automatic garbage collection, thereby simplifying the task of Java programming but making the system somewhat more complicated. A common source of complexity in many C and C++ applications is storage management: the allocation and freeing of memory. By virtue of having automatic garbage collection (periodic freeing of memory not being referenced) the Java language not only makes the programming task easier, it also dramatically cuts down on bugs.
Another aspect of being simple is being small. One of the goals of Java is to enable the construction of software that can run stand-alone in small machines. The Java interpreter and standard libraries have a small footprint. A small size is important for use in embedded systems and so Java can be easily downloaded over the net.

Tuesday, June 21, 2011

How to LinkedList in Java

In this example, you will see the use of java.util.LinkedList class. We will be creating an object of link list class and performing various operation like adding and removing object.
This class extends AbstractSequentialList and implements List, Cloneable, Serializable. It permits all elements including null. LinkedList class provides methods get, insert and remove an element at the beginning and end of the list.
In this example six methods of LinkedList class is demonstrated.
add(Object o): Appends the specified element to the end of this list. It returns a boolean value.
size(): Returns the number of elements in this list.
addFirst(Object o): Inserts the given element at the beginning of this list. addLast(Object o): Inserts the given element at the last of this list.
add(int index,Object o): Insert the specified element at the specified position in this list. It throws IndexOutOfBoundsException if index is out of range.
remove(int index): Remove the element at the specified position in this list. It returns the element that was removed from the list. It throws IndexOutOfBoundsException if index is out of range. 


import java.util.*;

public class LinkedListDemo{
 public static void main(String[] args){
  LinkedList link=new LinkedList();
  link.add("a");
  link.add("b");
  link.add(new Integer(10));
  System.out.println("The contents of array is" + link);
  System.out.println("The size of an linkedlist is" + link.size());
  
  link.addFirst(new Integer(20));
  System.out.println("The contents of array is" + link);
  System.out.println("The size of an linkedlist is" + link.size());

  link.addLast("c");
  System.out.println("The contents of array is" + link);
  System.out.println("The size of an linkedlist is" + link.size());

  link.add(2,"j");
  System.out.println("The contents of array is" + link);
  System.out.println("The size of an linkedlist is" + link.size());

  link.add(1,"t");
  System.out.println("The contents of array is" + link);
  System.out.println("The size of an linkedlist is" + link.size());

  link.remove(3);
  System.out.println("The contents of array is" + link);
  System.out.println("The size of an linkedlist is" + link.size());
 }
}

Java BuzzWords


Java

Java: A simple, object-oriented, network-savvy, interpreted, robust, secure, architecture neutral, portable, high-performance, multithreaded, dynamic language,Distributed.
One way to characterize a system is with a set of buzzwords. We use a standard set of them in describing Java. Here's an explanation of what we mean by those buzzwords and the problems we were trying to solve.

Monday, June 20, 2011

How to get the file creation date in Java

There are no official way to get the file creation date in Java. However, you can use the following workaround to get the file creation date in Windows platform.

package org.best.example.file;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
 
public class GetFileCreationDateExample
{
    public static void main(String[] args)
    { 
 
     try{
 
      Process proc = 
         Runtime.getRuntime().exec("cmd /c dir c:\\logfile.log /tc");
 
      BufferedReader br = 
         new BufferedReader(
            new InputStreamReader(proc.getInputStream()));
 
      String data ="";
 
      //it's quite stupid but work
      for(int i=0; i<6; i++){
       data = br.readLine();
      }
 
      System.out.println("Extracted value : " + data);
 
      //split by space
      StringTokenizer st = new StringTokenizer(data);
      String date = st.nextToken();//Get date
      String time = st.nextToken();//Get time
 
      System.out.println("Creation Date  : " + date);
      System.out.println("Creation Time  : " + time);
 
     }catch(IOException e){
 
      e.printStackTrace();
 
     }
 
    }
}

What is Difference between Application Server & Web Server


Difference between an application server and a Web server

Taking a big step back, a Web server serves pages for viewing in a Web browser, while an application server provides methods that client applications can call. A little more precisely, you can say that:
A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols. 

An example

As an example, consider an online store that provides real-time pricing and availability information. Most likely, the site will provide a form with which you can choose a product. When you submit your query, the site performs a lookup and returns the results embedded within an HTML page. The site may implement this functionality in numerous ways. I'll show you one scenario that doesn't use an application server and another that does. Seeing how these scenarios differ will help you to see the application server's function.

Scenario 1: Web server without an application server

In the first scenario, a Web server alone provides the online store's functionality. The Web server takes your request, then passes it to a server-side program able to handle the request. The server-side program looks up the pricing information from a database or a flat file. Once retrieved, the server-side program uses the information to formulate the HTML response, then the Web server sends it back to your Web browser.
To summarize, a Web server simply processes HTTP requests by responding with HTML pages.

Scenario 2: Web server with an application server

Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a script. However, you can now put the business logic for the pricing lookup onto an application server. With that change, instead of the script knowing how to look up the data and formulate a response, the script can simply call the application server's lookup service. The script can then use the service's result when the script generates its HTML response.
In this scenario, the application server serves the business logic for looking up a product's pricing information. That functionality doesn't say anything about display or how the client must use the information. Instead, the client and application server send data back and forth. When a client calls the application server's lookup service, the service simply looks up the information and returns it to the client.
By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far more reusable between applications. A second client, such as a cash register, could also call the same service as a clerk checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not reusable because the information is embedded within the HTML page. To summarize, in Scenario 2's model, the Web server handles HTTP requests by replying with an HTML page while the application server serves application logic by processing pricing and availability requests.

Caveats

Recently, XML Web services have blurred the line between application servers and Web servers. By passing an XML payload to a Web server, the Web server can now process the data and respond much as application servers have in the past.
Additionally, most application servers also contain a Web server, meaning you can consider a Web server a subset of an application server. While application servers contain Web server functionality, developers rarely deploy application servers in that capacity. Instead, when needed, they often deploy standalone Web servers in tandem with application servers. Such a separation of functionality aids performance (simple Web requests won't impact application server performance), deployment configuration (dedicated Web servers, clustering, and so on), and allows for best-of-breed product selection.