Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Thursday, February 28, 2008

How To Make http To https Request

What the Diff b/w http & https?
How to make http to https request where I am not using application server?

HTTP stands for HyperText Transport Protocol, which is just a fancy way of saying it's a protocol (a language, in a manner of speaking) for information to be passed back and forth between web servers and clients.

You really don't need to know what it all stands for; the important thing is the letter S which makes the difference between HTTP and HTTPS. The S (big surprise) stands for "Secure". You probably didn't need me to tell you that, because you already knew it had something to do with security.

If you visit a website or webpage, and look at the address in the web browser, it will likely begin with the following: http://. This means that the website is talking to your browser using the regular 'unsecure' language. In other words, it is possible for someone to "eavesdrop" on your computer's conversation with the website. If you fill out a form on the website, someone might see the information you send to that site. But if the web address begins with https://, that basically means your computer is talking to the website in a secure code that no one can eavesdrop on.

You understand why this is so important, right? If a website ever asks you to enter your credit card information, you should automatically look to see if the web address begins with https://. If it doesn't, there's no way you're going to enter sensitive information like a credit card number

Add the following code in "Init" method

// register for the BeginRequest event application.BeginRequest += new EventHandler(OnBeginRequest); application.EndRequest += new EventHandler(OnEndRequest);

Add the following method to implement "BeginRequest" event
//BeginRequest implementation public void OnBeginRequest(Object
sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; string HttpUrl = app.Request.Url.ToString(); if (HttpUrl.StartsWith("http:"))
//Redirection done only if URL starts with http: { HttpUrl = HttpUrl.Replace("http:", "https:"); app.Response.Redirect(HttpUrl.ToString(), true);
//Redirecting (http 302) to the same URL but with https app.Response.End();
//We don't want to any further so end } }

Add the following method to implement "BeginRequest" event
//BeginRequest implementation public void OnBeginRequest(Object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; string HttpUrl = app.Request.Url.ToString(); if (HttpUrl.StartsWith("http:")) //Redirection done only if URL starts with http: { HttpUrl = HttpUrl.Replace("http:", "https:"); app.Response.Redirect(HttpUrl.ToString(), true);
//Redirecting (http 302) to the same URL but with https app.Response.End();
//We don't want to any further so end } }

Add the following method to implement "OnEndRequest" event
//This is for scenario where SSL is forced on the site public void OnEndRequest(Object sender, EventArgs e) { HttpApplication app = (HttpApplication)sender; if (app.Response.StatusCode == 403 && app.Response.SubStatusCode == 4) { string HttpUrl = app.Request.Url.ToString(); if (HttpUrl.StartsWith("http:")) { HttpUrl = HttpUrl.Replace("http:", "https:"); app.Response.Redirect(HttpUrl.ToString(), true); app.Response.End(); } }

Make sure you have the following in your web.config inside configuration tag

User With Password Never Expires on MS-Adam

I am able to create users on MS-ADAM Ldap, but the problem is I am not able to set UserAccountControl attribute to "Password NeverExpires". Due to this I am not able to login with the created userid unless I goto ldap console and choose "Reset Password". How to write a code snippet that creates users & sets the UserAccountControl to Password Never Expires.

Here is my program for MS-ADAM user creation :

Here is the code to create user with password never expires on MS-ADAM :

import javax.naming.*;
import javax.naming.ldap.LdapContext;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.directory.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
/** * Sample JNDI client ADD application to demonstrate how to create
a new user entry in MS-ADAM with user account never expires */ public
class LDAPCreateUser { public static void main(String[] args) throws
UnsupportedEncodingException { Hashtable env = new Hashtable(); env.put (Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
env.put
(Context.PROVIDER_URL, "ldap://esnth001:636/dc=ldapbasedn,dc=com");
env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PROTOCOL, "ssl"); env.put (Context.SECURITY_PRINCIPAL, "cn=adminuser,dc=ldapbasedn,dc=com");
env.put(Context.SECURITY_CREDENTIALS, "adminpwd");
try { // Create the initial context // DirContext ctx = new
InitialDirContext(env);
LdapContext ctx = new InitialLdapContext(env,null);
// The distinguished name of the new entry String dn = "cn="+args[0]
+",OU=People,OU=Vap73Nagesh";
// Create attributes to be associated with the new entry Attributes
attrs = new BasicAttributes(true);
// Objectclass -- required in MUST list Attribute oc = new
BasicAttribute("objectclass");
// required by 'top' oc.add("top");
oc.add("person");
oc.add("organizationalPerson");
oc.add("user");
attrs.put(oc);
System.out.println(args[0]);
// Other mandatory attributes -- required in MUST list attrs.put ("uid", args[0]); attrs.put("sn", "SomeSN"); // required by 'person' attrs.put("givenName","SomeGN"); attrs.put("cn", args[0]); // required by 'person' // Optional attributes -- but they must be
defined in schema attrs.put("mail","usermail@mydomain.com");
//this 2 props are needed for user creation without password
expiration in MS-ADAM. attrs.put("msDS-UserAccountDisabled", "FALSE"); attrs.put("msDS-UserDontExpirePassword", "TRUE"); attrs.put("ou", "people"); // Create the context Context result = ctx.createSubcontext(dn,
attrs);
System.out.println("Created account for: " + dn);
//set password is a ldap modfy operation //and we'll update the
userAccountControl //enabling the acount and force the user to update
ther password //the first time they login ModificationItem[] mods =
new ModificationItem[1];
//Replace the "unicdodePwd" attribute with a new value //Password
must be both Unicode and a quoted string String newQuotedPassword
= "\""+args[0]+"\"";
byte[] newUnicodePassword = newQuotedPassword.getBytes("UTF-16LE");
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new
BasicAttribute("userPassword", newUnicodePassword));
// Perform the update ctx.modifyAttributes(dn, mods); System.out.println("Set password & updated userccountControl"); // Close the contexts when we're done result.close(); ctx.close(); }catch(NamingException e){ e.printStackTrace(); } } }

Sample Code On Use XML in Java to Write Save Documents

An explanation on how to use xml in java to write and save documents.

This java program will help you to read xml value from xml file.

Also you have to download two jar file:
1 xerces_1_0_3.jar
2 xmlparserv2.jar

and set class path for above jar files after compile the below java file
================start=============================
import java.io.File;
import org.w3c.dom.Document;
import org.w3c.dom.*;
import java.util.*;
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 arg[])
{
Vector vcrs = null;
try {
vcrs = null ;
vcrs = new Vector() ;

DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse (new File("interest.xml"));
// normalize text representation
doc.getDocumentElement ().normalize ();

NodeList listOfPersons = doc.getElementsByTagName("interest_master");
int totalPersons = listOfPersons.getLength();
for(int s=0; s

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

Element firstPersonElement = (Element)firstPersonNode;
//-------
NodeList firstNameList = firstPersonElement.getElementsByTagName("interest_id");
Element firstNameElement = (Element)firstNameList.item(0);
NodeList textFNList = firstNameElement.getChildNodes(); System.out.println("First Name : " + ((Node)textFNList.item(0)).getNodeValue().trim());
String id=((Node)textFNList.item(0)).getNodeValue().trim();
vcrs.add(id);
//-------
NodeList lastNameList = firstPersonElement.getElementsByTagName("interest_name");
Element lastNameElement = (Element)lastNameList.item(0);
NodeList textLNList = lastNameElement.getChildNodes(); System.out.println("Last Name : " + ((Node)textLNList.item(0)).getNodeValue().trim());
String name=((Node)textFNList.item(0)).getNodeValue().trim();
vcrs.add(name);
//----
//------

}//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);
System.out.println("size of the vector is " + vcrs.size()) ;
}

}//end of class ===========================end==================

Below is xml file from which we will read value.
========================start================




1
Economics


2
Sports



3
Medical


4
Music


5
Mytest


======================end==================

Sample Code On Random Sentence Generator

/*
* Just run the below CODE
*/
import java.util.*;
import java.lang.*;
class RandomSentence
{
public static void main (String args[])
{
Random randomNumber = new Random();//random number generator
//variables hold words to be chosen by program
String article1 = "A";
String article2 = "The";
String article3 = "a";
String article4 = "the";
String noun1 = "man";
String noun2 = "doctor";
String noun3 = "nurse";
String noun4 = "firefighter" ;
String noun5 = "cat";
String noun6 = "mouse";
String noun7 = "goat";
String nounA = "rock";
String nounB = "rules";
String nounC = "wall";
String nounD = "stick";
String nounE = "ditch";
String nounF = "bicycle";
String verb1 = "tested";
String verb2 = "recited";
String verb3 = "disregarded" ;
String verb4 = "leaped";
String verb5 = "cracked";
String verb6 = "followed";
String verb7 = "broke";
//sets up variable for final sentence
String finalSentence = " ";
//displays title of program
System.out.println ("\n Random sentence generator \n\n" );
// sets up loop to generate number of sentences desired
for (int i = 1; i <=10; i++)
{
switch (1 + randomNumber. nextInt(2) )//generates numbers 1-2 {
case 1:
finalSentence = article1 + " ";
break;
case 2:
finalSentence = article2 + " ";
}
switch (1 + randomNumber. nextInt(7) )//generates numbers 1-7 {
case 1:
finalSentence += noun1 + " ";
break;
case 2:
finalSentence += noun2 + " ";
break;
case 3:
finalSentence += noun3 + " ";
break;
case 4:
finalSentence += noun4 + " ";
break;
case 5:
finalSentence += noun5 + " ";
break;
case 6:
finalSentence += noun6 + " ";
break;
case 7:
finalSentence += noun7 + " ";
}
switch (1 + randomNumber. nextInt(7) )//generates numbers 1-7 {
case 1:
finalSentence += verb1 + " ";
break;
case 2:
finalSentence += verb2 + " ";
break;
case 3:
finalSentence += verb3 + " ";
break;
case 4:
finalSentence += verb4 + " ";
break;
case 5:
finalSentence += verb5 + " ";
break;
case 6:
finalSentence += verb6 + " ";
break;
case 7:
finalSentence += verb7 + " ";
}
switch (1 + randomNumber. nextInt(2) )//generates numbers 1-3 {
case 1:
finalSentence += article3 + " ";
break;
case 2:
finalSentence += article4 + " ";
}
switch (1 + randomNumber. nextInt(6) )//generates numbers 1-6 {
case 1:
finalSentence += nounA + ".";
break;
case 2:
finalSentence += nounB + ".";
break;
case 3:
finalSentence += nounC + ".";
break;
case 4:
finalSentence += nounD + ".";
break;
case 5:
finalSentence += nounE + ".";
break;
case 6:
finalSentence += nounF + ".";
}
System.out.println( i + ".\t" + finalSentence) ;//prints sentence number, and formatted sentence output
}//end for
}//end main
}//end class


/**

*/

Sample Code On How To Send Email Using Java Mail

Can someone please help with the following code
If (a===b)
//then send email using java mail API

How do I code above?

Look thru java mail API's there are methods like
public void sendMail() etc.

You need to follow a few steps as given below:

//Create an instance of properties
Properties props = new Properties();
//Setup mail server
Authenticator auth = new PopupAuthenticator();
//Set the Servername and hostname of email Server
props.put(
ConfigHelper.getProperty(HOST_NAME),
ConfigHelper.getProperty(SERVER_NAME));
props.put("mail.smtp.auth", "true");

//Get session
Session session = Session.getInstance(props, auth);
//Create Message instance for email content
Message msg = new MimeMessage(session);
//senders mail id
Address loggerId = new InternetAddress(sender, sender);
//Set the from email id
msg.setFrom(loggerId);
multipleEmailsSplit(receiver, msg, Message.RecipientType.TO);
if ((receiverCC != null) && !receiverCC.equals("null")) {
multipleEmailsSplit(receiverCC, msg, Message.RecipientType.CC);
}
if ((receiverBCC != null) && !receiverBCC.equals("null")) {
multipleEmailsSplit(receiverBCC, msg, Message.RecipientType.BCC);
}
msg.setSubject(subject);
MimeBodyPart mbp = new MimeBodyPart();
mbp.setContent(emailContent, "text/html");
// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
//attach files to e-mail
for (int i = 0; i <>
String file = (String) fileList.get(i);
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
mp.addBodyPart(mbp2);
}
// add the Multipart to the message
msg.setContent(mp);
//Send the mail
Transport.send(msg);

or

- Create the mail session object (or get/lookup the session from your app server using JNDI)
- Compose message, set/add recipient(s)
- Send using Transport's static send method

Properties props = new Properties();
props.put("mail.smtp.host", "mailserver.com");
Session s = Session.getInstance(props,null);

InternetAddress from = new InternetAddress("mail@...");
InternetAddress to = new InternetAddress(recepeint@...");

MimeMessage message = new MimeMessage(s);
message.setFrom(from);
message.addRecipient(Message.RecipientType.TO, to);

message.setSubject("Your subject");
message.setText("Your text");
Transport.send(message);

If you lookup up the session using JNDI you configure mail server (smtp host) in your app server configuration

Keeping a Standard Coding Template

One old trick I had when learning to program was keeping a standard coding template. In it, I had a common list of import declarations so I would be covered for virtually all my needs. Then, use an IDE such as NetBeans, JBuilder, JCreator, or Eclipse that can autocomplete methods for you. For example, a beginner might want to copy and paste this template for basic console/command-line apps:

/*
* basic template
*/
import java.io.*;
import java.util.*;
// add more imports here when desired

public class BasicProgram {
public BasicProgram() {
}

public static void main(String[] args) {
BasicProgram program = new BasicProgram();
program.method1();
}

public void method1() {
System.out.println("Hello, Universe!");
}
}

Tip: The java.lang package is imported by default in all Java programs.

Sample Code On How to Upload a File and How to Store it?

A quick and dirty Java Sockets API program:

// imports java.net.Socket, java.io.*

void uploadFile(String hostAddr, int port, String fileName) throws
FileNotFoundException, IOException {
byte[] buf = new byte[1000];
int len = -1;

// connect to host at hostAddr, port
Socket sock = new Socket(hostAddr, port);

FileInputStream in = new FileInputStream(fileName);
OutputStream out = sock.getOutputStream();

while ( ( len = in.read(buf) ) != -1 ) {
out.write(buf, 0, len);
out.flush(); // manually flush output stream for sockets
}
out.close();
sock.close();
in.close();
}

Sample Code On Example Uses Of Calendar Class

Write a java program that can find your age if the current year is 2007.

This example uses the Calendar class to compute a person's age.

// Create a calendar object with the date of birth
Calendar dateOfBirth = new GregorianCalendar(1972, Calendar.JANUARY, 27);

// Create a calendar object with today's date
Calendar today = Calendar.getInstance();

// Get age based on year
int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);

// Add the tentative age to the date of birth to get this year's birthday
dateOfBirth.add(Calendar.YEAR, age);

// If this year's birthday has not happened yet, subtract one from age

if (today.before(dateOfBirth)) {
age--;
}

Sample Code On How to Get the Start Date of the Week in Java

import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
/*
* Created on Feb 20, 2006
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
/**
* @author pu00125
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class Cal {
public static void main(String ss[]){

GregorianCalendar calendar = new GregorianCalendar();
String[] months = new String[] { "NOV", "DEC", "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT" };

for(int i=0;i<12;i++){>

calendar.set(2006,i,1);
System.out.println("startDay of Month " + calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("max Days: " + calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
}

java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMdd");
//String date = formatter.format(GregorianCalendar.getTime());
// return formattedDate.toUpperCase();

/*System.out.println("DAY_OF_WEEK_IN_MONTH: "+ calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("MONTH: " + calendar.get(GregorianCalendar.MONTH));*/
System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
//System.out.println("First Day: " + calendar.getLeastMaximum()calendar.getFirstDayOfWeek());

}
}

How to Make a Java Class Immutable

Making a class immutable

Immutability must be familiar to every one when we talk about String & StringBuffer classes in java. Strings are considered immutable because the values contained in the reference variable cannot be changed. Whereas String Buffer is considered mutable because the value in a string buffer can be changed (i.e. mutable).

However I always thought how to make our user defined classes as immutable though I am unaware as to why any one would need this.

The reason perhaps might be clear once we have a look at the code.

Now in order to make a class immutable we must restrict changing the state of the class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Above do not provide any method where we modify the instance variables.

Still done? No. How if some body creates a sub class from our up till now immutable class? Yes here lies the problem. The new subclass can contain methods, which over ride our base class (immutable class) methods. Here he can change the variable values.

Hence make the methods in the class also final. Or a better approach. Make the immutable class itself final. Hence cannot make any sub classes, so no question of over ridding.

The following code gives a way to make the class immutable.

/*
Code Developed By Ashish Agarwal
This code demonstrates the way to make a class immutable
*/

// The immutable class which is made final
final class MyImmutableClass
{
// instance var are made private & final to restrict the access

private final int count;
private final double value;

// Constructor where we can provide the constant value
public MyImmutableClass(int paramCount,double paramValue)
{
count = paramCount;
value = paramValue;
}

// provide only methods which return the instance var
// & not change the values

public int getCount()
{
return count;
}

public double getValue()
{
return value;
}
}

// class TestImmutable
public class TestImmutable
{
public static void main(String[] args)
{
MyImmutableClass obj1 = new MyImmutableClass(3,5);

System.out.println(obj1.getCount());
System.out.println(obj1.getValue());

// there is no way to change the values of count & value-
// no method to call besides getXX, no subclassing, no public access to var -> Immutable
}
}

The possible use of immutable classes would be a class containing a price list represented for a set of products.
Otherwise also this represents a good design.

Simple Program for Reading Writing Content From File

Program for reading content from file:

import java.io.*;
public class MyFirstFilereadingApp
{
// Main method
public static void main (String args[])
{
// Stream to read file
FileInputStream fin;
try
{
// Open an input stream
fin = new FileInputStream ("c:\\myfile1.txt");
// Read a line of text
System.out.println( new DataInputStream(fin).readLine() );
// Close our input stream
fin.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to read fr! om file");
System.exit(-1);
}
}
}

Program for writing content from file:

import java.io.*;
public class MyFirstFileWritingApp
{
// Main method
public static void main (String args[])
{
// Stream to write file
FileOutputStream fout;
try
{
// Open an output stream
fout = new FileOutputStream ("c:\\myfile1.txt");
// Print a line of text
new PrintStream(fout).println ("hello world!");
// Close our output stream
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
}

Code for Java-Mail

I am sending the code for Java-Mail.

sendmail.java
---------------

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import javax.activation.*;
import javax.swing.text.*;
import javax.swing.*;
import java.io.*;
import java.awt.*;

public class SendMail{
public SendMail(){ }
private class SMTPAuthenticator extends javax.mail.Authenticator{
public PasswordAuthentication getPasswordAuthentication(){
String username = "Muni";
String password = "Raj";
return new PasswordAuthentication(username, password);
}
}
public void postMail() throws MessagingException {

boolean debug = false;
String recipients[] = {"java.muni@rediffmail.com"};
String recipientsCC[] = {"likhis_007@yahoo.com"};

String subject = "Mail";
String message = "This is body for the message";
String from = "pop_muni@yahoo.com";
Properties props = new Properties();
props.put("mail.smtp.host","208.220.245.70");//mail.yahoo.com/68.142.225.208
props.put("mail.smtp.auth","true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for(int i = 0; i < recipients.length; i++){
addressTo[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, addressTo);

//recipientsCC[]
InternetAddress[] addressCC = new InternetAddress[recipientsCC.length];
for(int j = 0; j < recipientsCC.length; j++){
addressCC[j] = new InternetAddress(recipientsCC[j]);
}
msg.setRecipients(Message.RecipientType.CC, addressCC);

// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
msg.setSubject(subject);
msg.setContent(message,"text/html");
Transport.send(msg);
System.out.println("Mail Successfully Sent");

}//End of postMail()

}//End of Class

Sample Code On Simple Date Validation

import java.util.Date;
import java.text.ParseException;
import java.text.DateFormat;

public class validateDate
{
public static void main(String args[])
{
String dt = "04/31/2005"; //Invalid Date
//String dt = "02/29/2004"; //Valid Date
try
{
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
df.setLenient(false); // this is important!
Date dt2 = df.parse(dt);
System.out.println("Date is ok = " + dt2);
}
catch (ParseException e)
{
System.out.println("Invalid date " + dt);
}
catch (IllegalArgumentException e)
{
System.out.println("Invalid date " + dt);
}
}
}//End of validateDate

Sample Code On Cows and Bulls Game

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

class prog5 extends JFrame implements ActionListener
{


private String s;
private boolean q1=false,q2;
private int a=0,b,cows=0,bulls;
private int w=0;
private int q[]=new int [4];
private int e[]=new int [4];
private static final String NEWLINE =
System.getProperty("line.separator");
private JMenuBar menuBar;
private JMenu fileMenu;
private JMenu helpMenu;
private JLabel won;
private JLabel lost;
private JTextArea textArea;
private JScrollPane scrollPane;
private JTextField inputLine;
private JButton guess;
private JButton resign;
private JButton clear;
private Container con;
private int i=0;
private int wonCount;
private int lostCount;
private int number;
private int chances;
public static void main(String args[])
{
prog5 a = new prog5();
a.setVisible(true);
}

public void actionPerformed(ActionEvent event)
{
if(event.getSource() instanceof JButton)
{
JButton eventButton = (JButton) event.getSource();
if(eventButton.getText() == "Guess")
// if(inputLine.getText()!=null)

// b=Integer.parseInt(s);)
guess();
else if(eventButton.getText() == "Clear")
clearTextArea();
else if(eventButton.getText() == "Resign")
resign();
}
if(event.getSource() instanceof JTextField)
{
// if(inputLine.getText()!=null)
guess();
}
if(event.getSource() instanceof JMenuItem)
{
String command = event.getActionCommand();

if (command == "New Game")
resign();
else if(command == "Exit")
System.exit(0);
else if(command == "Instructions")
{
Instructions a = new Instructions();
a.setVisible(true);
}
else if(command == "Clear stats.")
clearStats();
else if(command == "About")
JOptionPane.showMessageDialog(null, "You are playing Cows and bull
game Designed by Dheeraj Kota.");

}
}

private void clearStats()
{
int choice=JOptionPane.showConfirmDialog(this,"Are you sure you want
to clear stats.");
if(choice == JOptionPane.YES_OPTION)
{
wonCount=0;
lostCount=0;
won.setText("Won : " + wonCount);
lost.setText("Lost : " + lostCount);
}
}

private void guess()


{
if(i ==0)
{
do
{
q1=true;
a=(int)(Math.floor(Math.random()*9000)+1000);
s=Integer.toString(a);
for(int i=0;i<4;i++)
{
e[i]=Integer.parseInt(s.substring(i,i+1));
}
for(int i=0;i<4;i++)
for(int k=i+1;k<4;k++)
{


if(e[i]==e[k])
{
q2=false;
//continue;
q1=q1&q2;
}
else
{
q2=true;
q1=q1&q2;
}

}
}while(!q1);
}

if(i<10)

{
cows=0;
bulls=0;
s=inputLine.getText();

b=Integer.parseInt(s);
w=0;
while(w<4)
{

q[w]=Integer.parseInt(s.substring(w,w+1));
w++;
}
for(int y=0;y<4;y++)
for(int t=0;t<4;t++)
{
if(e[y]==q[t] && y==t)
{

cows=cows+1;

}
if(e[y]==q[t] && y!=t)
{

bulls=bulls+1;
}



}


textArea.append(s+"\t"+"cows"+cows+"\t"+"Bulls"+bulls+"\t"+"Try"+(i+1)+NEWLINE);
i++;

if(cows==4)
{
textArea.append("U Won");
wonCount++;
won.setText("Won : " + wonCount);
i=0;

}
}

if(cows!=4 && i>9)
{
textArea.append(NEWLINE+a);
//System.out.println(a);
textArea.append(NEWLINE+"Sorry u lost"+NEWLINE);
lostCount++;
lost.setText("Lost : " + lostCount);
i=0;
}
}
private void clearTextArea()
{
inputLine.setText("");
textArea.setText("");
textArea.append("Try to guess the number." + NEWLINE);
textArea.append("You have " + (10-i) + " chances left."+NEWLINE);
}


private void resign()
{
textArea.append("You resigned." + NEWLINE);
textArea.append("The number was : " + a + NEWLINE);
textArea.append(NEWLINE);
textArea.append("Try to guess another number." + NEWLINE);

inputLine.setText("");

//number = randomNumber();
i = 0;
lostCount++;
lost.setText("Lost : " + lostCount);
}



public prog5()
{
setSize(426,600);
setLocation(100,100);
setTitle("Cows and Bulls Game");

setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);

con = getContentPane();
con.setLayout(null);

menuBar = new JMenuBar();
createFileMenu();
createHelpMenu();
setJMenuBar(menuBar);

createWonLabels();
createLostLabels();

createTextArea();
createInputLine();
createButtons();

lostCount=0;
wonCount=0;
chances=5;


textArea.append("Try to guess a secret number." + NEWLINE);
textArea.append(NEWLINE);
}


private void createButtons()
{
guess = new JButton("Guess");
guess.setBounds(10,482,100,40);
con.add(guess);
guess.addActionListener(this);

resign = new JButton("Resign");
resign.setBounds(160,482,100,40);
con.add(resign);
resign.addActionListener(this);


clear = new JButton("Clear");
clear.setBounds(310,482,100,40);
con.add(clear);
clear.addActionListener(this);

}

private void createInputLine()
{
inputLine = new JTextField();
inputLine.setBounds(10,432,400,40);
con.add(inputLine);
inputLine.addActionListener(this);
}


private void createTextArea()
{
textArea = new JTextArea();
textArea.setBounds(10,122,400,300);
textArea.setBorder(BorderFactory.createLineBorder(Color.red));
textArea.setEditable(false);
scrollPane = new JScrollPane(textArea);
scrollPane.setBounds(10,122,400,300);
con.add(scrollPane);
}


private void createLostLabels()
{

lost = new JLabel("Lost : 0");
lost.setBounds(304,10,100,102);

con.add(lost);
}


private void createWonLabels()
{

won = new JLabel("Won : 0");
won.setBounds(102,10,100,102);

con.add(won);
}

private void createFileMenu()
{
fileMenu = new JMenu("File");

JMenuItem item;

item = new JMenuItem("New Game");
item.addActionListener(this);
fileMenu.add(item);

item = new JMenuItem("Clear stats.");
item.addActionListener(this);
fileMenu.add(item);

fileMenu.addSeparator();

item = new JMenuItem("Exit");
item.addActionListener(this);
fileMenu.add(item);

menuBar.add(fileMenu);
}

private void createHelpMenu()
{
helpMenu = new JMenu("Help");

JMenuItem item;

item = new JMenuItem("Instructions");
item.addActionListener(this);
helpMenu.add(item);

helpMenu.addSeparator();

item = new JMenuItem("About");
item.addActionListener(this);
helpMenu.add(item);

menuBar.add(helpMenu);
}
}

class Instructions extends JFrame implements ActionListener
{

private static final String NEWLINE =
System.getProperty("line.separator");
JTextArea textArea;
JButton ok = new JButton("Ok");

Instructions()
{
setTitle("Instructions");
setLocation(200,200);
setSize(450,270);

Container con = getContentPane();
con.setLayout(null);
setResizable(false);

textArea = new JTextArea();
textArea.setBounds(10,10,420,165);
textArea.setEditable(false);
textArea.setBorder(
BorderFactory.createTitledBorder("Instructions"));
con.add(textArea);

setDefaultCloseOperation(DISPOSE_ON_CLOSE);

textArea.append("1. The program will think a 4 digit random number
with out repitition." + NEWLINE);
textArea.append(NEWLINE);
textArea.append("2. You have ten chances to get that number." +
NEWLINE);
textArea.append(NEWLINE);
textArea.append("3. The program will say there is a bull if any
digit of u'r guessed number"+NEWLINE+"equals the digit in the random number
generated in a different place" + NEWLINE + " Cow if the digit is at
the same place. " + NEWLINE);
textArea.append(NEWLINE);
textArea.append("4. You can start a new game at any time if you wish
to." + NEWLINE);
textArea.append(NEWLINE);

ok = new JButton("Ok");
ok.setBounds(160,185,100,40);
con.add(ok);
ok.addActionListener(this);
}

public void actionPerformed(ActionEvent event)
{
dispose();
}
}

Sample Code On BasicDateFormatting.java

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* Created on Feb 21, 2003
*/
public class BasicDateFormatting
{
public static void main(String[] args) throws Exception
{
// get today's date
Date today = Calendar.getInstance().getTime();
// create a short version date formatter
DateFormat shortFormatter
= SimpleDateFormat.getDateInstance( SimpleDateFormat.SHORT );
// create a long version date formatter
DateFormat longFormatter
= SimpleDateFormat.getDateInstance( SimpleDateFormat.LONG );
// create date time formatter, medium for day, long for time
DateFormat mediumFormatter
= SimpleDateFormat.getDateTimeInstance( SimpleDateFormat.MEDIUM,
SimpleDateFormat.LONG );
// use the formatters to output the dates
System.out.println( shortFormatter.format( today ) );
System.out.println( longFormatter.format( today ) );
System.out.println( mediumFormatter.format( today ) );
// convert form date -> text, and text -> date
String dateAsText = shortFormatter.format( today );
Date textAsDate = shortFormatter.parse( dateAsText );
System.out.println( textAsDate );
}
}


Sample Code On TTSTest.java

import java.io.File;
import java.util.Locale;
import javax.speech.Central;
import javax.speech.Engine;
import javax.speech.synthesis.Synthesizer;
import javax.speech.synthesis.SynthesizerModeDesc;
import javax.speech.synthesis.SynthesizerProperties;
import javax.speech.synthesis.Voice;

/**
* Created on Dec 6, 2002
* Simple program showing how to use TTS in JSAPI.
*/
public class TTSTest {
public static void main(String[] argv) {
try {
String synthesizerName = System.getProperty
("synthesizerName",
"Unlimited domain FreeTTS Speech Synthesizer from Sun Labs");
// Create a new SynthesizerModeDesc that will match the TTS
// Synthesizer.
SynthesizerModeDesc desc = new SynthesizerModeDesc
(synthesizerName,
null,
Locale.US,
Boolean.FALSE, // running?
null); // voice
Synthesizer synthesizer = Central.createSynthesizer(desc);
if (synthesizer == null) {
String message = "Can't find synthesizer.\n" +
"Make sure that there is a \"speech.properties\" file " +
"at either of these locations: \n";
message += "user.home : " +
System.getProperty("user.home") + "\n";
message += "java.home/lib: " + System.getProperty("java.home")
+ File.separator + "lib\n";
System.err.println(message);
System.exit(1);
}
// create the voice
String voiceName = System.getProperty("voiceName", "kevin16");
Voice voice = new Voice
(voiceName, Voice.GENDER_DONT_CARE, Voice.AGE_DONT_CARE, null);
// get it ready to speak
synthesizer.allocate();
synthesizer.resume();
synthesizer.getSynthesizerProperties().setVoice(voice);
// speak the "Hello World" string
synthesizer.speakPlainText("Hello World", null);
// wait till speaking is done
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
// clean up
synthesizer.deallocate();
}
catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
}

Sample Code On Process Execution

import java.io.IOException;

/**
* Created on Feb 21, 2003
*/
// To start a process(Spawn a process within the jvm)
public class ProcessExec
{
public static void main( String[] argv )
{
String command = "c:\\winnt\\explorer.exe";
try
{
Process process = Runtime.getRuntime().exec( command );
}
catch ( IOException ioex )
{
ioex.printStackTrace();
}
}
}

Sample Code On Read Contents Of URL

import java.io.*;
import java.net.*;

/**
* Created on Feb 20, 2003
*/
public class ReadContentsOfURL{
public static void main(String[] args) throws Exception
{
// create a URL object and open a stream to it
URL httpUrl = new URL("http://www.weather.com/weather/local/94539?lswe=94539");
InputStream istream = httpUrl.openStream();
// convert stream to a BufferedReader
InputStreamReader ir = new InputStreamReader(istream);
BufferedReader reader = new BufferedReader( ir );
// then read the contents of the URL through a BufferedReader
StringBuffer buf = new StringBuffer();
int nextChar;
while( (nextChar = reader.read()) != -1 )
{
buf.append( (char)nextChar );
}
// close the reader
reader.close();
System.out.println( buf );
}
}

Sample Code On XMLParserUtils

import javax.xml.parsers.*;
import org.w3c.dom.*;

/**
* Created on Nov 21, 2002
* Used for parsing elements & attributes
*/

public class XMLParserUtils {

/**
This method is used to get the value of the element.
The element should have only one text node, and no child elements.
Eg: xxx
@params n = 'value' node
@return value = 'xxx' in the value element
*/
public static String getElementValue(Node n) {
String retVal = null;
Node textNode = n.getFirstChild();
if((textNode != null) && (textNode.getNodeType() == Node.TEXT_NODE)) {
retVal = textNode.getNodeValue();
}
return retVal;
}

/**
This method is used to get the value of the attribute in an element.
Eg: xxx
@params n = 'value' node
@params attr = attribute name, 'id' in the above example
@return value = "abc" the attribute value of id in the value element
*/

public static String getAttributeValue(Node n, String attr) {
String retVal = null;
if(n.getNodeType() == Node.ELEMENT_NODE) {
retVal = ((Element)n).getAttribute(attr);
}
return retVal;
}
}

Sample Code On Bin.java

import java.awt.*;
import java.awt.event.*;

/*
RUN THIS PROGRAM AND ENTER 2 VALUES(+ve or -ve), then CLICK ON
THE OPERATOR BUTTON...SEE THE RESULT in binary(exactly the
way it is stored in memory).
*/
class BinApp extends Frame {
TextField T1, T2;
Label Result, Error;
Button bAND, bOR, bXOR, bRShift, bLShift,bRRShift;

BinApp(){
Panel P = new Panel();
Panel P_edit = new Panel();
Panel P_btn = new Panel();
Panel P_result = new Panel();
add(P, "Center");
P.setLayout(new GridLayout(3, 0));
P.add(P_edit);
T1 = new TextField(20);
T2 = new TextField(20);
P_edit.add(T1);
P_edit.add(T2);
P.add(P_btn);
bAND = new Button("&");
bOR = new Button("|");
bXOR = new Button("^");
bRShift = new Button(">>");
bLShift = new Button("<<");
bRRShift = new Button(">>>");
P_btn.setLayout(new GridLayout(3, 0));
P_btn.add(bAND);
P_btn.add(bOR );
P_btn.add(bXOR);
P_btn.add(bRShift);
P_btn.add(bLShift);
P_btn.add(bRRShift);
P.add(P_result);
Result = new Label(" ");
Error = new Label("");
P_result.setLayout(new GridLayout(2, 0));
P_result.add(Result);
P_result.add(Error);
ButtonHandler handler = new ButtonHandler();
bAND.addActionListener(handler);
bOR.addActionListener(handler);
bXOR.addActionListener(handler);
bRShift.addActionListener(handler);
bLShift.addActionListener(handler);
bRRShift.addActionListener(handler);
Error.setForeground(Color.red);
}

class ButtonHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
Error.setText("");
String s = e.getActionCommand();
int n1 = getInt(T1.getText());
int n2 = getInt(T2.getText());
if (s=="&")
Result.setText(printBin(n1&n2));
else if (s=="|")
Result.setText(printBin(n1|n2));
else if (s=="^")
Result.setText(printBin(n1^n2));
else if (s==">>")
Result.setText(printBin(n1>>n2));
else if (s=="<<")
Result.setText(printBin(n1< else if (s==">>>")
Result.setText(printBin(n1>>>n2));
}
}
int getInt(String s)
{
int n1 = 0;
try
{
n1 = Integer.parseInt(s);
}
catch(Exception e)
{
Error.setText("Illegal integer #: " + s);
}
return n1;
}
String printBin(int x)
{
String result = "";

int filter = 0x40000000;
try
{
if ((x & 0x80000000) == 0x80000000)//This is sign bit
result = result + "1";
else
result = result + "0";
for (int i=0; i < 31; i++)
{
if ((filter & x) == filter)
result = result + "1";
else
result = result + "0";
filter = filter >> 1;
}
}
catch(Exception e)
{
System.out.println("ERROR");
}
return result;
}
}

public class Bin extends Frame {
public static void main(String[] arg) {
BinApp a = new BinApp();
a.setSize(250,200);
a.setVisible(true);
}
}

Sample Code On ASCII_code

public class ASCII_code{
public static void main(String argv[]){ System.out.println("Value\tChar\tValue\tChar\tValue\tChar\tValue\tChar\tValue\tChar\t");
int c=1;
while (c < 256)
{
for (int col = 0; col < 5 && c < 256; col++, c++)
System.out.print(c + "\t" + (char)c + "\t");
System.out.println();
}
}
}

Sample Code On Prime

import java.util.*;
import java.lang.Math;
public class Prime {
public static void main(String[] args)
{
for (int i = 1; i < 1500; i++)
if (isPrime(i))
System.out.println(i);
}
public static boolean isPrime(int n)
{
for (int i = 2; i <= Math.sqrt(n); i++)
{
if (n % i == 0)
return false;
}
return true;
}
}

Sample Code On Factorial

Factorial.java
import java.util.*;
import java.lang.*;
public class Factorial {
public static void main(String[] args)
{
if (args.length == 0)
System.out.println("Example: java Factorial 10");
try
{
for (int i=0; i < args.length; i++)
{
System.out.print("Fact of Param # " + (i+1) + ": " + Fact(args[i]));
}
}
catch(Exception E)
{
System.out.println(E.getMessage());
}
}
public static long Fact(String f) throws Exception
{
int f1 = Integer.parseInt(f);
long Result = 1;
if (f1 < 0)
throw new Exception("I can not calculate this!");
if (f1 > 20)
throw new Exception("that is a big ####");
try
{
for (int j=1; j <= f1; j++)
Result *= j;
}
catch(Exception e)
{
System.out.println(e.getMessage());
throw e;
}
return Result;
}
}

A Serializable JButton

package com.dwave.gui;

import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.Action;
import java.awt.Font;
import com.javaworld.BrowserControl;

/**
* A Serializable JButton which uses the Lucida Sans font by
* default because fonts on linux are wierd
*/
public class DButton extends JButton implements java.io.Serializable {
private static final long serialVersionUID = -757087513022738653L;
/**
* Construct a button
*/
public DButton() {
super();
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font("Lucida Sans", 1, 10));
}

/**
* Construct a button with an icon
* @param icon an icon
*/
public DButton(Icon icon) {
super(icon);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font("Lucida Sans", 1, 10));
}
/**
* Construct a button with text
* @param text some text
*/
public DButton(String text) {
super(text);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font("Lucida Sans", 1, 10));
}
/**
* Construct a button with an action.


*
* IMPORTANT: Only works with jdk1.3+
* @param a an action
*/
public DButton(Action a) {
super(a);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font("Lucida Sans", 1, 10));
}
/**
* Construct a button with text and an icon
* @param text some text
* @param icon an icon
*/
public DButton(String text, Icon icon) {
super(text, icon);
if(!BrowserControl.isWindowsPlatform())
this.setFont(new java.awt.Font("Lucida Sans", 1, 10));
}
}

A Java Calculator

calculator.java

import java.awt.*;
import java.lang.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.datatransfer.*;

public class calculator extends Applet
{
public void init()
{
calf calWindow = new calf("Java Calculator");
calWindow.setSize(200, 250);
calWindow.setVisible(true);
calWindow.setResizable(false);
}
}

class calf extends Frame implements WindowListener, ActionListener, KeyListener
{
String command, copy, arg, chg, txt;
double result;
String number = "123456789.0";
String operator = "/*-+=";
CopyPaste cp;

Menu Menu1;
MenuBar Menubar1;
MenuItem menuitem1, menuitem2, menuitem3;
TextField entrytext;
Button numbut []; //Number buttons
Button combut []; //Command buttons
Panel companel, numpanel;

public static void main(String[] arguments)
{
calf calWindow = new calf("Java Calculator");
calWindow.setSize(200, 250);
calWindow.setVisible(true);
}

public calf(String title)
{
super(title);
addWindowListener(this);
addKeyListener(this);

cp = new CopyPaste();
//cp.clip = getToolkit().getSystemClipboard();

setBackground(Color.blue);
setLayout(new GridLayout(1, 1));
Menubar1 = new MenuBar();
Menu1 = new Menu("Edit");
menuitem1 = new MenuItem("&Copy");
Menu1.add(menuitem1);
menuitem1.addActionListener(this);
menuitem2 = new MenuItem("&Paste");
Menu1.add(menuitem2);
menuitem2.addActionListener(this);
menuitem3 = new MenuItem("&Exit");
Menu1.add(menuitem3);
menuitem3.addActionListener(this);
Menubar1.add(Menu1);
setMenuBar(Menubar1);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints constraints = new GridBagConstraints();
setLayout(gridbag);
constraints.weighty = 1;
constraints.weightx = 1;
//constraints.fill = GridBagConstraints.BOTH;
Font bigFont = new Font("Courier",Font.BOLD, 14);
entrytext = new TextField(20);
constraints.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(entrytext,constraints);
add(entrytext);
entrytext.setFont(bigFont);
entrytext.setEditable(false);
entrytext.setForeground(Color.black);
entrytext.setBackground(Color.white);
entrytext.addKeyListener(this);
entrytext.requestFocus();

constraints.weighty = 1;
constraints.weightx = 1;
companel = new Panel();

constraints.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(companel,constraints);
/*
Command GridLayout
---------------------
| Back | CE | C |
---------------------
*/

companel.setLayout(new GridLayout(1,3,5,5));

// Create the buttons
Font comsFont = new Font("Arial",Font.BOLD, 12);
String[] coms = { "Back","CE","C"
};
combut = new Button[3];
for (int i=0; i<=2; i++)
{
combut[i] = new Button(coms[i]);
companel.add(combut[i]);
combut[i].addActionListener(this);
combut[i].setFont(comsFont);
combut[i].addKeyListener(this);

}
add(companel);
companel.addKeyListener(this);

constraints.weighty = 4;
constraints.weightx = 1;
numpanel = new Panel();
constraints.gridwidth = GridBagConstraints.REMAINDER;
gridbag.setConstraints(numpanel,constraints);
/*
Number GridLayout
---------------------
| 7 | 8 | 9 | / |sqr|
---------------------
| 4 | 5 | 6 | * | % |
---------------------
| 1 | 2 | 3 | - |1/x|
---------------------
| 0 |+/-| . | + | = |
---------------------
*/
numpanel.setLayout(new GridLayout(4,5,3,3));
// Create the buttons
String[] nums = { "7","8","9","/","sqrt",
"4","5","6","*","%",
"1","2","3","-","1/x",
"0","+/-",".","+","="
};
numbut = new Button[20];
for (int i=0; i<=19; i++)
{
numbut[i] = new Button(nums[i]);
numpanel.add(numbut[i]);
numbut[i].addActionListener(this);
numbut[i].addKeyListener(this);
if(operator.indexOf(nums[i]) > -1)
{
numbut[i].setForeground(Color.red);
}
else
{
numbut[i].setForeground(Color.blue);
}

}
add(numpanel);
numpanel.addKeyListener(this);

//initialize global variables.
command = "+";
copy = "";
chg = "N";
txt = "";
arg = "";
result = 0;
}

public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand() == "&Exit")
{
setVisible(false);
System.exit(0);
}
else if (e.getActionCommand() == "&Copy")
{
String txt = entrytext.getText();
if (txt != null)
{
cp.doCopy(txt);
}
}
else if (e.getActionCommand() == "&Paste")
{
cp.doPaste();
if (cp.ctxt != null)
{
entrytext.setText(cp.ctxt);
}
}
else if (e.getActionCommand() == "Back") back_space();
else if (e.getActionCommand() == "CE") entrytext.setText("");
else if (e.getActionCommand() == "C")
{
result = 0;
command = "+";
entrytext.setText("");
}
else
{
arg = e.getActionCommand();
txt = entrytext.getText();
if(number.indexOf(arg) > -1)
{
if (chg == "Y") txt = "";
txt = txt + arg;
entrytext.setText(txt);
chg = "N";
}
else check_entry();
}
}

public void keyPressed(KeyEvent k){}
public void keyReleased(KeyEvent k)
{
int ikey = k.getKeyCode();
if (ikey == 127) entrytext.setText("");
}
public void keyTyped(KeyEvent k)
{
int ikey = k.getKeyChar();
if (ikey == 8) back_space();
else if (ikey == 10)
{
arg = "=";
txt = entrytext.getText();
display_ans();
}
else
{
txt = entrytext.getText();
char ckey = (char) ikey;
arg = String.valueOf(ckey);
if(number.indexOf(arg) > -1)
{
if (chg == "Y") txt = "";
txt = txt + arg;
entrytext.setText(txt);
chg = "N";
}
else check_entry();
}
}

public void back_space()
{
txt = entrytext.getText();
int l = txt.length();
if (l > 0)
{
txt = txt.substring(0,l-1);
entrytext.setText(txt);
}
}
public void display_ans()
{
entrytext.setText(compute_tot(txt,command));
chg = "Y";
command = "+";
result = 0;
}
public void check_entry()
{
if(arg.equals("=")) display_ans();
else if(arg.equals("%"))
{
entrytext.setText(compute_tot(txt,arg));
chg = "Y";
}
else if(operator.indexOf(arg) > -1)
{
entrytext.setText(compute_tot(txt,command));
command = arg;
chg = "Y";
}
else if(arg == "sqrt")
{
entrytext.setText(compute_tot(txt,arg));
chg = "Y";
command = "";
}
else if(arg == "+/-")
{
Double tnum = Double.valueOf(txt);
double num = tnum.doubleValue();
num = num * -1;
entrytext.setText(String.valueOf(num));
chg = "Y";
}
else if(arg == "1/x")
{
entrytext.setText(compute_tot(txt,arg));
chg = "Y";
}
}
String compute_tot(String t, String c)
{
Double tnum = Double.valueOf(t);
double num = tnum.doubleValue();

if (c.equals("+")) result = result + num;
else if (c.equals("-")) result = result - num;
else if (c.equals("*")) result = result * num;
else if (c.equals("/")) result = result / num;
else if (c.equals("%")) result = num / 100;
else if (c.equals("+/-")) result = num * -1;
else if (c.equals("1/x")) result = 1.000 / num;
else if (c.equals("sqrt")) result = Math.sqrt(num);
return String.valueOf(result);
}

public void windowClosing(WindowEvent we)
{
setVisible(false);
System.exit(0);
}
public void windowClosed(WindowEvent we) {}
public void windowDeiconified(WindowEvent we) {}
public void windowIconified(WindowEvent we) {}
public void windowOpened(WindowEvent we) {}
public void windowActivated(WindowEvent we) {}
public void windowDeactivated(WindowEvent we) {}
}

class CopyPaste implements ClipboardOwner
{

Clipboard clip;
String ctxt;

CopyPaste()
{
clip = new Clipboard("clip");
ctxt = null;
}

void doCopy(String txt)
{
StringSelection trans = new StringSelection(txt);
clip.setContents(trans, this);
}

void doPaste()
{
ctxt = null;
Transferable toPaste = clip.getContents(this);
if (toPaste != null)
{
try
{
ctxt = (String)toPaste.getTransferData(
DataFlavor.stringFlavor);
}
catch (Exception e)
{
System.out.println("Error -- " + e.toString());
}
}

}

public void lostOwnership(Clipboard clip,
Transferable contents) {
}
}

The example draws several moving wadges on a circle

/* The example draws several moving wadges on a circle. These wedges move with different speeds */
import java.applet.*;
import java.awt.*;
import java.util.*;

public class DrawMultWedges extends Applet {
Wedges t [] = new Wedges [6];
Graphics g;

public void init ()
{
g = getGraphics ();

for (int i = 0; i < t.length; i++)
{
if ( i < t.length / 2)
t [i] = new Wedges (g, 10, 10 + i * 100, 100, 100, 100 * (i + 1));
else
t [i] = new Wedges (g, 110, 10 + (i - 3) * 100, 100, 100, 100 * (i + 1));
t [i].start ();
}
}

public void paint (Graphics g)
{
}
}

class Wedges implements Runnable {
int x, y, width, height, interval;
Graphics g;
volatile boolean isSet = true;
Thread t;

public Wedges (Graphics g, int x, int y, int width, int height, int interval)
{
this.g = g;
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.interval = interval;

t = new Thread (this);
}

public void start ()
{
t.start ();
}

public void run ()
{
int i = 0;

if (g == null)
{
System.out.println ("The reference to Graphics is " + g);
return;
}
g.drawArc (x, y, width, height, 0, 360); // draw a circle
while (isSet)
{
g.setColor (Color.white);
g.fillArc (x, y, width, height, i - 45, 45); // erase a wedge
g.setColor (Color.black);
g.drawArc (x, y, width, height, i - 45, 45); // draw a circle sector
g.fillArc (x, y, width, height, i, 45); // draw a wedge
if (i != 315)
i += 45;
else
i = 0;
System.out.println (i);
try
{
Thread.sleep (interval);
} catch (InterruptedException ie)
{
System.out.println (ie.getMessage ());
}
}
g.dispose ();
}

}

Demonstrate Boolean Values

//demonstrate boolean values.
class BoolTest {
public static void main(String args[]) {
boolean b;
b=false;
System.out.println("b is "+b);
b=true;
System.out.println("b is "+b);
//a boolean value can control the if statement
if(b) System.out.println("this is xecuted");//i.e. if b is true
b=false;
if (b)System.out.println("this is not xecuted");
//outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " +(10>9));
}
}

The output generated by the program is :
b is false
b is true
this is xecuted
10 > 9 is true
Normal Termination
Output completed (4 sec consumed).

Few things to note in the above example :
When a boolean value is outputted by println () , true or false is displayed .

The value of a boolean variable is sufficient , by itself , to control the if statement .

The outcome of a relational operator is a boolean value .

This is why the expression 10 > 9 displays the value true .

StackDemo shows how to use the linear set of objects

//--- class StackDemo shows how to use the linear set of objects ---//
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;

public class StackDemo extends Applet {
//--- Instance variables ---//
Frame f;

//--- Instance methods ---//
public void init ()
{
f = new StackFrame ("Stack"); // instanciate a frame object
f.setSize (200, 150);
f.setResizable (false);
f.show ();
}

public void start ()
{
f.setVisible (true);
repaint ();
}

public void stop ()
{
f.setVisible (false);
}

public void paint (Graphics g)
{
g.drawString ("Ancestor object for the frame", 0, 30);
}
}// end of class StackDemo

//--- class StackFrame ---//
class StackFrame extends Frame {

StackPanel p;
Stack stk;
MessageBox mb;

//--- Constructor ---//
public StackFrame (String title)
{
super (title);

//--- The object to handle action events ---//
ActionListener al = new ActionHandler ();

//--- Instanciate a panel object and add it into the frame ---//
p = new StackPanel (al);
add(BorderLayout.CENTER, p);

//--- Instanciate a message box class ---//
mb = new MessageBox (this, "Stack Message", al);

//--- Instanciate stack class ---//
stk = new Stack ();

//--- anonimous inner class for handling window events ---//
addWindowListener (new WindowAdapter (){
public void windowClosing (WindowEvent e)
{
e.getWindow ().dispose ();
}
});
}

//--- Inner private class StackPanel ---//
private class StackPanel extends Panel {
//--- Instance variables ---//
Label lblTitle;
TextField tfStack;
Button btnPush, btnPop, btnPeek;

//--- Constructor ---//
public StackPanel (ActionListener al)
{
super ();

lblTitle = new Label ("Stack element");
tfStack = new TextField (25);
btnPush = new Button ("Push");
btnPop = new Button ("Pop ");
btnPeek = new Button ("Peek");

add (lblTitle);
add (tfStack);
add (btnPush);
add (btnPop);
add (btnPeek);

btnPush.addActionListener (al);
btnPop.addActionListener (al);
btnPeek.addActionListener (al);

setBackground (Color.green);
}
}// end of class StackPanel

//--- Inner class MessageBox ---//
private class MessageBox extends Dialog {
Label lbl; // text to show in the dialog box
Button btnOK; // botton OK

//--- Constructor ---//
public MessageBox (Frame parent, String title, ActionListener al)
{
super (parent, title, true); //call the ancestor constructor and make the dialog box modal
setSize (100, 150);
setBackground (Color.red);

//--- Change the layout and add components into the container ---//
setLayout (new FlowLayout ());
add ( lbl = new Label ());
add ( btnOK = new Button ("OK"));

btnOK.addActionListener (al);
}

//--- Methods ---//
public void showBox (String s)
{
lbl.setText (s);
show ();
}
}// end class MessageBox

//--- Inner class ActionHandler ---//
private class ActionHandler implements ActionListener {
public void actionPerformed (ActionEvent e)
{
Object source = e.getSource ();
String s = p.tfStack.getText ();

if (source == p.btnPush)
{
//--- If the tfStack is not empty than pust its content into the stack ---//
if (!s.equals (""))
stk.push (s);

p.tfStack.setText ("");
System.out.println ("Push");
p.tfStack.requestFocus ();
}

else if (source == p.btnPop)
{
//--- If the stack is not empty, pop the element of the stack ---//
if (!stk.empty ())
p.tfStack.setText ((String) stk.pop ());
else
{
p.tfStack.setText ("");
mb.showBox ("Stack is empty");
}

System.out.println ("Pop");
p.tfStack.requestFocus ();
}

else if (source == p.btnPeek)
{
//--- If the stack is not empty, pop the element of the stack ---//
if (!stk.empty ())
p.tfStack.setText ((String) stk.peek ());
else
{
p.tfStack.setText ("");
mb.showBox ("Stack is empty");
}

System.out.println ("Peek");
p.tfStack.requestFocus ();
}

else if (source == mb.btnOK)
{
mb.dispose ();
}
}
}// end of class ActionHandler
}// end of class StackFrame

Hide Password From Command Line

import java.io.*;

/**
* Created on Feb 21, 2003
*/
public class HidePasswordFromCommandLine extends Thread {
boolean stopThread= false;
boolean hideInput= false;
boolean shortMomentGone= false;
public void run() {
try {
sleep(500);
} catch (InterruptedException e) {}
shortMomentGone= true;
while (!stopThread) {
if (hideInput) {
System.out.print("\b*");
}
try {
sleep(1);
} catch (InterruptedException e) {}
}
}
public static void main(String[] arguments) {
String name= "";
String password= "";
HidePasswordFromCommandLine hideThread= new HidePasswordFromCommandLine();
hideThread.start();
BufferedReader in= new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Name: ");
// Wait for the username and clear the keyboard buffer (if neccessarry)
do {
name= in.readLine();
}
while (hideThread.shortMomentGone == false);
// Now the hide thread should begin to overwrite any input with "*"
hideThread.hideInput= true;
// Read the password
System.out.println("\nPassword:");
System.out.print(" ");
password = in.readLine();
hideThread.stopThread= true;
}
catch (Exception e) {}
System.out.print("\b \b");
// JUST FOR TESTING - PLEASE DELETE!
System.out.println("\n\nLogin= " + name);
System.out.println("Password= " + password);
}
}

Input through Keyboard

/*The following program is written in a very simple form to show the keyboard input from the programmer which
returns the corresponding value conditioned by the if-statement in the method min(int, int) */

import java.io.*;

public class KeyBoardInput {

public static int min( int a, int b) {

if (a <= b)
return a;
else
return b;
}

public static void main(String[] args) throws IOException {

int x;
int y;

String sb;
String ks;

BufferedReader bk = new BufferedReader (
new InputStreamReader(System.in));

System.out.println ("Enter x ");

sb = bk.readLine();
x = Integer.parseInt(sb);

System.out.println("Enter y");

ks = bk.readLine();
y = Integer.parseInt(ks);

bk.close();

System.out.print("The returned value is = ");
System.out.println(Math.min(x * 5, y + 20));
}
}

Assertion in Java

Assertion facility is added in J2SE 1.4. In order to support this facility J2SE 1.4 added the keyword assert to the language, and AssertionError class. An assertion checks a boolean-typed expression that must be true during program runtime execution. The assertion facility can be enabled or disable at runtime.

Declaring Assertion

Assertion statements have two forms as given below

assert expression;

assert expression1 : expression2;

The first form is simple form of assertion, while second form takes another expression. In both of the form boolean expression represents condition that must be evaluate to true runtime.

If the condition evaluates to false and assertions are enabled, AssertionError will be thrown at runtime.

Some examples that use simple assertion form are as follows.

assert value > 5 ;

assert accontBalance > 0;

assert isStatusEnabled();

The expression that has to be asserted runtime must be boolean value. In third example isStatusEnabled() must return boolean value. If condition evaluates to true, execution continues normally, otherwise the AssertionError is thrown.

Following program uses simple form of assertion

//AssertionDemo.java

Class AssertionDemo{

Public static void main(String args[]){

System.out.println( withdrawMoney(1000,500) );

System.out.println( withdrawMoney(1000,2000) );

}

public double withdrawMoney(double balance , double amount){

assert balance >= amount;

return balance – amount;

}

}

In above given example, main method calls withdrawMoney method with balance and amount as arguments. The withdrawMoney method has a assert statement that checks whether the balance is grater than or equal to amount to be withdrawn. In first call the method will execute without any exception, but in second call it AssertionError is thrown if the assertion is enabled at runtime.

Enable/Disable Assertions

By default assertion are not enabled, but compiler complains if assert is used as an identifier or label. The following command will compile AssertionDemo with assertion enabled.

javac –source 1.4 AssertionDemo.java

The resulting AssertionDemo class file will contain assertion code.

By default assertion are disabled in Java runtime environment. The argument –eanbleassertion or –ea will enables assertion, while –disableassertion or –da will disable assertions at runtime.

The following command will run AssertionDemo with assertion enabled.

Java –ea AssertionDemo

or

Java –enableassertion AssertionDemo

Second form of Assertion

The second form of assertion takes another expression as an argument.

The syntax is,

assert expression1 : expression2;

where expression1 is the condition and must evaluate to true at runtime.

This statement is equivalent to

assert expression1 : throw new AssertionError(expression2);

Note: AssertionError is unchecked exception, because it is inherited from Error class.

Here, expression2 must evaluate to some value.

By default AssertionError doesn’t provide useful message so this form can be helpful to display some informative message to the user.

String in Java

Handling character strings in Java is supported through two final classes: String and StringBuffer. The String class implements immutable character strings, which are read-only once the string has been created and initialized, whereas the StringBuffer class implements dynamic character strings. All string literals in Java programs, are implemented as instances of String class. Strings in Java are 16-bit Unicode.

Note : In JDK 1.5+ you can use StringBuilder, which works exactly like StringBuffer, but it is faster and not thread-safe

The easiest way of creating a String object is using a string literal:

String str1 = "I cant be changed once created!";

A string literal is a reference to a String object. Since a string literal is a reference, it can be manipulated like any other String reference. i.e. it can be used to invoke methods of String class.

For example,

Int myLength = “Hello world”.length();

The Java language provides special support for the string concatenation operator ( + ), which has been overloaded for Strings objects. String concatenation is implemented through the StringBuffer class and its append method.

For example,

String finalString = “Hello” + “World”

Would be executed as

String finalString = new StringBuffer().append(“Hello”).append(“World”).toString();

The Java compiler optimizes handling of string literals. Only one String object is shared by all string having same character sequence. Such strings are said to be interned, meaning that they share a unique String object. The String class maintains a private pool where such strings are interned.

For example,

String str1=”Hello”;

String str2=”Hello”;

If(str1 == str2)

System.out.println(“Equal”);

Would print Equal when run.

Since the String objects are immutable. Any operation performed on one String reference will never have any effect on other references denoting the same object.

Constructors

String class provides various types of constructors to create String objects. Some of them are,

String()

Creates a new String object whose content is empty i.e. “”.

String(String s)

Creates a new String object whose content is same as the String object passed as an argument.

Note: Constructor creates a new string means it does not intern the String. Interned String object reference can be obtained by using intern() method of the String class

String also provides constructors that take byte and char array as argument and returns String object.

String equality

String class overrides the equals() method of the Object class. It compares the content of the two string object and returns the boolean value accordingly.

For example,

String str1=”Hello”;

String str2=”Hello”;

String str3=new String(”Hello”) //Using constructor.

If(str1 == str2)

System.out.println(“Equal 1”);

Else

System.out.println(“Not Equal 1”);

If(str1 == str3)

System.out.println(“Equal 2”);

Else

System.out.println(“I am constructed using constructor, hence

not interned”);

If( str1.equals(str3) )

System.out.println(“Equal 3”);

Else

System.out.println(“Not Equal 3”);

The output would be,

Equal 1

Not Equal 2

Equal 3

Note that == compares the references not the actual contents of the String object; Where as equals method compares actual contents of two String objects.

String class also provides another method equalsIgnoreCase() which ignores the case of contents while comparing.

Apart from these methods String class also provides compareTo methods.

int compareTo(String str2)

This method compares two Strings and returns an int value. It returns value 0, if this string is equal to the string argument a value less than 0, if this string is less than the string argument

a value greater than 0, if this string is greater than the string argument

int compareTo(Object object)

This method behaves exactly like the first method if the argument object is actually a String object; otherwise, it throws a ClassCastException.

String Manipulations

Reading characters from String:

char charAt(index i)

Returns char at specified index. An index ranges from 0 to length() -1.

Searching characters in String

String class provides indexOf method which searches for the specified character inside the string object. This method has been overloaded. If the search is successful, then it returns the index of the char otherwise -1 is returned.

int indexOf(int c)

Returns the index of first occurrence of the argument char.

int indexOf(int c, int fromIndex)

Finds the index of the first occurrence of the argument character in a string, starting at the index specified in the second argument.

int indexOf(String str)

Finds the start index of the first occurrence of the substring argument in a String.

int indexOf(String str, int fromIndex)

Finds the start index of the first occurrence of the substring argument in a String, starting at the index specified in the second argument.

The String class also provides methods to search for a character or string in backward direction. These methods are given below.

int lastIndexOf(int ch)

int lastIndexOf(int ch, int fromIndex)

int lastIndexOf(String str)

int lastIndexOf(String str, int fromIndex)

Replacing characters in String

The replace method of String can be used to replace all occurrences of the specified character with given character.

String replace(char oldChar, int newchar)

Getting substrings

String class provides substring method to extract specified portion of the given String. This method has been overloaded.

String substring(int startIndex)

String substring(int startIndex, int endIndex)

Note: A new String object containing the substring is created and returned. The original String won’t be affected.

If the index value is not valid, a StringIndexOutOfBoundsException is thrown.

Conversions

String class provides set of static overloaded valueOf method to convert primitives and object into strings.

static String valueOf(Object obj)

static String valueOf(char[] character)

static String valueOf(boolean b)

static String valueOf(char c)

static String valueOf(int i)

static String valueOf(long l)

static String valueOf(float f)

static String valueOf(double d)

Manipulating Character Case

String class provides following methods to manipulate character case in String.

String toUpperCase()

String toUpperCase(Locale locale)

String toLowerCase()

String toLowerCase(Locale locale)

Note : Original String object is returned if none of the characters changed, otherwise new String object is constructed and returned.

Miscellaneous methods

String trim()

This method removes white space from the front and the end of a String.

int length()

Returns length of the String.

String intern()

This method returns interned String object, if already present in the String pool. Otherwise this String is added into the pool, and then interned reference is returned.