Monday, March 30, 2009

How To Disable Autorun

If your pen drive is affected by any virus/worm/malware then it is suggested to disable the autorun function in your computer.

Here are the steps to disable the autorun.

1.Go to start ->Run

Type gpedit.msc

press Enter

2.In that go to Administrative Templates->System->Turn off autoplay

3.Now set it to Enabled if you want to turn off the autorun feature.

The default value will not configured

4.There is one more option in it

We have to select between All drives/ CD-ROM drives

Select CD-ROM drive if you want to disable autorun only for CDS or select all drives if you want to turn off autorun for all drives including your pen drives or flash drives

5 ways to speed up your PC

By following a few simple guidelines, you can maintain your computer and keep it running smoothly. This article discusses how to use the tools available in Windows XP Service Pack 2 (SP2) and Windows Vista to more efficiently maintain your computer and safeguard your privacy when you're online.

Free up disk space
By freeing disk space, you can improve the performance of your computer. The Disk Cleanup tool helps you free up space on your hard disk. The utility identifies files that you can safely delete, and then enables you to choose whether you want to delete some or all of the identified files.
Use Disk Cleanup to:

• Remove temporary Internet files.
• Remove downloaded program files (such as Microsoft ActiveX controls and Java applets).
• Empty the Recycle Bin.
• Remove Windows temporary files.
• Remove optional Windows components that you don't use.
• Remove installed programs that you no longer use.

Tip: Typically, temporary Internet files take the most amount of space because the browser caches each page you visit for faster access later.

To use Disk Cleanup

1. Click Start, point to All Programs, point to Accessories, point to System Tools, and then click Disk Cleanup. If several drives are available, you might be prompted to specify which drive you want to clean.
2. In the Disk Cleanup for dialog box, scroll through the content of the Files to delete list.
3. Clear the check boxes for files that you don't want to delete, and then click OK.
4. When prompted to confirm that you want to delete the specified files, click Yes.

After a few minutes, the process completes and the Disk Cleanup dialog box closes, leaving your computer cleaner and performing better.

Speed up access to data
Disk fragmentation slows the overall performance of your system. When files are fragmented, the computer must search the hard disk when the file is opened to piece it back together. The response time can be significantly longer.

Disk Defragmenter is a Windows utility that consolidates fragmented files and folders on your computer's hard disk so that each occupies a single space on the disk. With your files stored neatly end-to-end, without fragmentation, reading and writing to the disk speeds up.

When to run Disk Defragmenter
In addition to running Disk Defragmenter at regular intervals—monthly is optimal—there are other times you should run it too, such as when:

• You add a large number of files.
• Your free disk space totals 15 percent or less.
• You install new programs or a new version of Windows.

To use Disk Defragmenter:
1.Click Start, point to All Programs, point to Accessories, point to System Tools, and then click Disk Defragmenter.
2.In the Disk Defragmenter dialog box, click the drives that you want to defragment, and then click the Analyze button. After the disk is analyzed, a dialog box appears, letting you know whether you should defragment the analyzed drives.

Tip: You should analyze a volume before defragmenting it to get an estimate of how long the defragmentation process will take.

3.To defragment the selected drive or drives, click the Defragment button. Note: In Windows Vista, there is no graphical user interface to demonstrate the progress—but your hard drive is still being defragmented.
After the defragmentation is complete, Disk Defragmenter displays the results.
4.To display detailed information about the defragmented disk or partition, click View Report.
5.To close the View Report dialog box, click Close.
6.To close the Disk Defragmenter utility, click the Close button on the title bar of the window.

Detect and repair disk errors

In addition to running Disk Cleanup and Disk Defragmenter to optimize the performance of your computer, you can check the integrity of the files stored on your hard disk by running the Error Checking utility.

As you use your hard drive, it can develop bad sectors. Bad sectors slow down hard disk performance and sometimes make data writing (such as file saving) difficult, or even impossible. The Error Checking utility scans the hard drive for bad sectors, and scans for file system errors to see whether certain files or folders are misplaced.

If you use your computer daily, you should run this utility once a week to help prevent data loss.

To run the Error Checking utility:

1.Close all open files.
2.Click Start, and then click My Computer.
3.In the My Computer window, right-click the hard disk you want to search for bad sectors, and then click Properties.
4.In the Properties dialog box, click the Tools tab.
5.Click the Check Now button.
6.In the Check Disk dialog box, select the Scan for and attempt recovery of bad sectors check box, and then click Start.
7.If bad sectors are found, choose to fix them.

Tip: Only select the "Automatically fix file system errors" check box if you think that your disk contains bad sectors.

Protect your computer against spyware

Spyware collects personal information without letting you know and without asking for permission. From the Web sites you visit to usernames and passwords, spyware can put you and your confidential information at risk. In addition to privacy concerns, spyware can hamper your computer's performance.

Learn all about ReadyBoost

If you're using Windows Vista, you can use ReadyBoost to speed up your system. A new concept in adding memory to a system, it allows you to use non-volatile flash memory—like a USB flash drive or a memory card—to improve performance without having to add additional memory.

How To Block USB Devices

To this what can be done is that the USB can be blocked and then stopping the use of USB drives. Here is a simple registry hack to do so, try it with care.

1. Go to Start –> Run, type Regedit.
2. Go to HKEY_LOCAL_MACHINE\System\CurrentControlset\Services\USBStor
3. In the right pane, look for value Start and have value as 0000000(3)
4. Double click on that and change that value to 4.

You might be required to restart the PC, and then you are done with it, USB is now blocked.

In case if you want to get the USB unblocked, just change the value again to 3.
See, its so easy. Isn’t it

How To Format USB Drive with NTFS File System

The advantage of NTFS file system is more security options and fast. Normally USB drive capacity is very small enough that NTFS is not recommended. But, nowadays USB drives are coming with larger capacity also. So we can format USB drive with NTFS to have more security options.

NTFS enabled USB Drives are write-able only on one PC and becomes read only on all other PCs. Hence, we can read and write on our own PC and transfer files to elsewhere without any fear of virus.

In XP, only FAT and FAT32 file systems are available in format options, use the below steps to format in NTFS File System.

1). Insert USB drive in your PC
2). Goto Device Manager (Start>Run>devmgmt.msc)
3). Select Disk Drives and expand
4). Right Click on USB drive and select Properties
5). Goto policies tab and select Optimize for performance and press OK
6). Open My Computer, Click on USB Drive and select Format Opton

Now you can have NTFS option there.

How To Disable Autorun

If your pen drive is affected by any virus/worm/malware then it is suggested to disable the autorun function in your computer.

Here are the steps to disable the autorun.

1.Go to start ->Run

Type gpedit.msc

press Enter

2.In that go to Administrative Templates->System->Turn off autoplay

3.Now set it to Enabled if you want to turn off the autorun feature.

The default value will not configured

4.There is one more option in it

We have to select between All drives/ CD-ROM drives

Select CD-ROM drive if you want to disable autorun only for CDS or select all drives if you want to turn off autorun for all drives including your pen drives or flash drives

How To Use Pen Drive as RAM

Follow these steps :-

1. Insert the Pen Drive (1GB atleast) in the USB port
try to prefer 4GB.
2. Let the PC do what it wants to do to detect it..
3. After it finished his work, you have to act smart,

" Here goes the real thing "

4. Right Click on My Computer -> Properties
5. Advanced -> Performance Settings
6. Advanced -> Change
7. Select the Pen Drive
8. Click on Custom Size

" Check the value of space available "

9. Enter the same in the Initial and the Max columns

" You just used the space of the PenDrive as a Virtual Memory "

Restart...
" VOILA !!! Your PC is fast and furious "

Monday, March 23, 2009

How to check if a Java String is an integer?

Use static method Integer.parseInt() and catch the exception that is thrown when the number cannot be parsed.


String s = "123";
boolean isValidInteger = false;
try
{
int i = Integer.parseInt(s);

// s is a valid integer

isValidInteger = true;
}
catch (NumberFormatException ex)
{
// s is not an integer
}

How do a check that a string contains a valid date?

Use the parse() method of the SimpleDateFormat class, it will throw an exception if the string does not contain a valid date. Use setLenient(false) to force strict parsing.

DateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
dateFormat.setLenient(false);
try
{
Date d = dateFormat.parse("01/05/06");

// string contains valid date
}
catch (ParseException ex)
{
// string contains invalid date
}

try
{
Date d = dateFormat.parse("99/88/06");

// string contains valid date
}
catch (ParseException ex)
{
// string contains invalid date
}

How do I display my Swing application in full screen mode?

The GraphicsDevice class has a method setFullScreenWindow() that allows you to specify the window to display in full screen mode on that device.


JFrame frame = new JFrame();

GraphicsEnvironment environment =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices =
environment.getScreenDevices();

// we will assume the screen of interest is the 1st one

GraphicDevice device = devices[0];
if (device.isFullScreenSupported())
{

// make frame undecorated and not resizeable

frame.setUndecorated(true);
frame.setResizable(false);

// go into full screen mode

device.setFullScreenWindow(frame);
frame.validate();
}

How to maximize a JFrame?

A frame can be maximized using the Jframe method setExtendedState() as shown in the example below.

frame.setExtendedState(
frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);

How do I use regular expressions to decode text containing html escape code?

String s = "Some html escape codes ABC";
StringBuffer stringBuffer = new StringBuffer();
String re = "(?:&#(\\d+);)";
Pattern pattern = Pattern.compile(re);
Matcher matcher = pattern.matcher(args[0]);
while (matcher.find())
{
char c = (char) Integer.parseInt(matcher.group(1));
matcher.appendReplacement(stringBuffer, Character.toString(c));
}
matcher.appendTail(stringBuffer);
String result = stringBuffer.toString();

How to check if a String is an integer using a regular expression?

String s = "321";
boolean isNumber = s.matches("-?\\d+");

How do I replace all occurences of a string regardless of case?

Use the CASE_INSENSITIVE flag in your regex. It can be embedded in the regex string using (?i).

String s = "aBcXYZABCdefAbc";
String replaced = s.replaceAll("(?i)abc", "123");

How do I display an image in a JButton with the text centered below the image?

Use the JButton classes setVerticalTextPosition() and setHorizontalTextPosition() methods to control the text positioning.


JButton button = new JButton("Press Me", icon);

// Text below image

button.setVerticalTextPosition(SwingConstants.BOTTOM);

// And centred

button.setHorizontalTextPosition(SwingConstants.CENTER);

How do I display a JList with icons and text?

You can achieve that by creating a custom ListCellRenderer. Easiest is to subclass DefaultListCellRenderer and override the getListCellRendererComponent() method to add the appropriate icon.

That just leaves how to determine which icon to use for a given list item value. One solution to this is to provide the renderer with a set of mappings containing what icon to use for which value.


import java.awt.Component;
import java.util.HashMap;
import java.util.Map;

import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.plaf.basic.BasicIconFactory;
import javax.swing.plaf.metal.MetalIconFactory;

public class IconListRenderer
extends DefaultListCellRenderer {

private Map icons = null;

public IconListRenderer(Map icons) {
this.icons = icons;
}

@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {

// Get the renderer component from parent class

JLabel label =
(JLabel) super.getListCellRendererComponent(list,
value, index, isSelected, cellHasFocus);

// Get icon to use for the list item value

Icon icon = icons.get(value);

// Set icon to display for value

label.setIcon(icon);
return label;
}

public static void main(String[] args) {

// setup mappings for which icon to use for each value

Map icons = new HashMap();
icons.put("details",
MetalIconFactory.getFileChooserDetailViewIcon());
icons.put("folder",
MetalIconFactory.getTreeFolderIcon());
icons.put("computer",
MetalIconFactory.getTreeComputerIcon());

JFrame frame = new JFrame("Icon List");
frame.setDefaultCloseOperation(
JFrame.DISPOSE_ON_CLOSE);

// create a list with some test data

JList list = new JList(
new Object[] {
"details", "computer", "folder", "computer"});

// create a cell renderer to add the appropriate icon

list.setCellRenderer(new IconListRenderer(icons));
frame.add(list);
frame.pack();
frame.setVisible(true);
}

}

How do I display a JComboBox with icons and text?





You can achieve that by creating a custom ListCellRenderer. Easiest is to subclass DefaultListCellRenderer and override the getListCellRendererComponent() method to add the appropriate icon.

That just leaves how to determine which icon to use for a given combo item value. One solution to this is to provide the renderer with a set of mappings containing what icon to use for which value.

import java.awt.Component;
import java.util.HashMap;
import java.util.Map;

import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.plaf.metal.MetalIconFactory;

public class IconListRenderer
extends DefaultListCellRenderer {

private Map icons = null;

public IconListRenderer(Map icons) {
this.icons = icons;
}

@Override
public Component getListCellRendererComponent(
JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {

// Get the renderer component from parent class

JLabel label =
(JLabel) super.getListCellRendererComponent(list,
value, index, isSelected, cellHasFocus);

// Get icon to use for the list item value

Icon icon = icons.get(value);

// Set icon to display for value

label.setIcon(icon);
return label;
}

/**
* @param args
*/
public static void main(String[] args) {

// setup mappings for which icon to use for each value

Map icons = new HashMap();
icons.put("details",
MetalIconFactory.getFileChooserDetailViewIcon());
icons.put("folder",
MetalIconFactory.getTreeFolderIcon());
icons.put("computer",
MetalIconFactory.getTreeComputerIcon());

JFrame frame = new JFrame("Icon List");
frame.setDefaultCloseOperation(
JFrame.DISPOSE_ON_CLOSE);

// create a list with some test data

JComboBox combo = new JComboBox(
new Object[] {
"details", "computer", "folder", "computer"});

// create a cell renderer to add the appropriate icon

combo.setRenderer(new IconListRenderer(icons));
frame.add(combo);
frame.pack();
frame.setVisible(true);
}

}



How do I get the ip address of the machine a Java application is running on?

Use the InetAddress class.


InetAddress address = InetAddress.getLocalHost();
byte[] ip = address.getAddress();

// to get a string representation use
// the getHostAddress() method

String ipString = address.getHostAddress();

// for a string representation in
// form hostname/literal IP address
// use the toString() method

String hostAndIp = address.toString();

How do I get the hostname of the machine the application is running on?

Use the getHostName() method of the InetAddress class

InetAddress address = InetAddress.getLocalHost();
String hostname = address.getHostName();

How do I convert an ip address into an array of bytes?

Use the getAddress() method in the InetAddress class.

InetAddress address =
InetAddress.getByName("192.168.1.1");
byte[] bytes = address.getAddress();
for (byte b : bytes)
{
System.out.println(b & 0xFF);
}

How do I determine the location a component in a JScrollPane is currently scrolled to?

The JViewport of the JScrollPane provides a method to return the location of top left point showing in the scroll pane.

JViewport viewport = myScrollPane.getViewport();
Point scrolledTo = viewport.getViewPosition();

How do I add scroll bars to my JList?

You need to add your JList (or any component) to a JScrollPane. Easiest way to do this is to pass your component to the JScrollPane’s constructor. You then add the JScrollPane to your component hierarchy (instead of adding your JList).


JScrollPane scrollPne = new JScrollPane(mylist);
panel.add(scrollPane);

How to change the width of scroll bars in a JScrollPane?

You need to set the preferred size of the JScrollBar components.

scrollpane.getVerticalScrollBar().setPreferredSize(
new Dimension(width, Integer.MAX_VALUE));
scrollpane.getHorizontalScrollBar().setPreferredSize(
new Dimension(Integer.MAX_VALUE, width));

Thursday, March 19, 2009

How do I execute a block of code after a specified time has elapsed?

The java.util.Timer class can be used to schedule code to be execute in the future. The TimerTask class is used to encapsulate the code to be executed.


int delay = 5000; //msecs
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
// put the code you want to run here
// It will get executed in 5000 msecs
}
}, delay);

How do I execute a piece of code at a specified time?

The java.util.Timer class can be used to schedule code to be executed in the future. The TimerTask class is used to encapsulate the code to be executed.

Date whenToExecute = getTimeToExecuteCode();
Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
// put the code you want to run here
}
}, whenToExecute);

How to execute code at regular interval?

The java.util.Timer class can be used to schedule code to be executed repeated at a fixed interval. The TimerTask class is used to encapsulate the code to be executed.


Timer timer = new Timer();
timer.schedule(new TimerTask()
{
public void run()
{
// put the code you want to run here
}
}, initialDelay, interval);

How do I send a POST request using Java?

// Create query string

String queryString = "param1=" +
URLEncoder.encode(param1Value, "UTF-8");
queryString += "¶m2=" +
URLEncoder.encode(param2Value, "UTF-8");

// Make connection

URL url = new URL("http://www.objects.com.au/");
URLConnection urlConnection = url.openConnection();
urlConnection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(
urlConnection.getOutputStream());

// Write query string to request body

out.write(queryString);
out.flush();

// Read the response

BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
System.out.println(line);
}
out.close();
in.close();

How do I extract the query string from a POST request?

You need to build it manually from the ServletRequest.

StringBuilder sb = new StringBuilder("?");
for (Enumeration e = request.getParameterNames();
e.hasMoreElements();)
{
String param = (String) e.nextElement();
sb.append(param)
.append("=")
.append(request.getParameter(param))
.append("&");
}
String queryString = sb.toString().
substring(0, sb.length() - 1);

How do I scale or resize a BufferedImage?

There are two main ways to scale an image.

The first is to ‘paint’ a scaled version of the image to a new image of the required size.


// Create new (blank) image of required (scaled) size

BufferedImage scaledImage = new BufferedImage(
width, height, BufferedImage.TYPE_INT_RGB);

// Paint scaled version of image to new image

Graphics2D graphics2D = scaledImage.createGraphics();
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
graphics2D.drawImage(image, 0, 0, width, height, null);

// clean up

graphics2D.dispose();



The second is to use an AffineTransform




BufferedImage scaledImage = new BufferedImage(
width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = scaledImage.createGraphics();
AffineTransform xform = AffineTransform.getScaleInstance(scale, scale);
graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics2D.drawImage(image, xform, null);
graphics2D.dispose();

How do I write a BufferedImage to an output stream?

The ImageIO class provides utility classes for both read and writing images. To write your image to an output stream you would can use the write method telling it what format you want to write the image in, eg. JPEG, PNG.


ImageIO.write(image, "PNG", out);

How do I convert a Java Image to a png byte array?

The ImageIO class can be used to write an image as a JPEG encoded stream.If you write that stream to a ByteArrayOutputStream then you will end up with a byte array that contains the JPEG encoded image.


ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, "PNG", out);
byte[] imageBytes = out.toByteArray();

How do I paint a tiled image, for example as a background of a panel?

The TexturePaint class can be used to achieve that.

public void paintComponent(Graphics g)
{
if(paint == null)
{
try
{
// Create TexturePaint instance the first time

int height = image.getHeight(this);
int width = image.getWidth(this);
bi = (BufferedImage) createImage(width, height);
Graphics2D biG2d = (Graphics2D) bi.getGraphics();
biG2d.drawImage(image, 0, 0, Color.black, this);
paint = new TexturePaint(bi,
new Rectangle(0,0,width,height));
}
catch (Exception ex)
{
ex.printStackTrace();
}
}

// Now actually do the painting

How do I read an image from a byte array in Java?

Create a ByteArrayInputStream from your byte array and then use ImageIO class to read image from that stream.

InputStream in = new ByteArrayInputStream(bytearray);
BufferedImage image = ImageIO.read(in);

How do I read a text file line by line into a List?

The readLine() method of java.io.BufferedReader class reads the next line from a text file. When it reaches the end of the file it will return null.


List lines = new ArrayList();
BufferedReader in = new BufferedReader(new FileReader(filename));
String line = null;
while (null!=(line=in.readLine()))
{
lines.add(line);
}
in.close();

// lines will now contain the contents of the file

How do I read the contents of a file into a byte array?

Use the File classes length() method to determine the size of the file and thus the required size for the byte array. You can then use the readFully() method in DataOutputStream to read the file into the byte array.


File file = new File("myfile.dat");

// determine amount of bytes needed

byte[] content = new byte[(int)file.length()];

// Create input stream to read file

DataInputStream in = new DataInputStream(
new FileInputStream(file)));

// Read contents of file into byte array

in.readFully(content);
in.close();

How to format a number to a certain number of significant figures, as opposed to decimal places?

That’s a job for the BigDecimal class

public static String formatToSignificant(double value,
int significant)
{
MathContext mathContext = new MathContext(significant,
RoundingMode.DOWN);
BigDecimal bigDecimal = new BigDecimal(value,
mathContext);
return bigDecimal.toPlainString();
}

How do I convert a String to an enum?

Use the static valueOf() method

enum Colour
{
red, green, blue
}

Colour red = Colour.valueOf("red");

Rounding strategy used by DecimalFormat?

Decimal format uses BigDecimal .ROUND_HALF_EVEN and this cannot be changed.

If you need an alternate rounding strategy then you need to use BigDecimal to do your formatting.

double d = 123.45;
BigDecimal bd = new BigDecimal(d);
bd.setScale(1, BigDecimal.ROUND_HALF_UP);
String formatted = bd.toString();

How do I get the date of first day of the current week?

Use the Calendar class to set the day of the week to the first day of the week.

Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK,
cal.getActualMinimum(Calendar.DAY_OF_WEEK));
Date firstDayOfTheWeek = cal.getTime();

How can I iterate through all dates in a range?

The following custom iterator allows iteration through a date range.

import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;

public class DateIterator
implements Iterator, Iterable
{

private Calendar start = Calendar.getInstance();
private Calendar end = Calendar.getInstance();
private Calendar current = Calendar.getInstance();

public DateIterator(Date start, Date end)
{
this.start.setTime(start);
this.end.setTime(end);
this.current.setTime(start);
}

public boolean hasNext()
{
return !current.after(end);
}

public Date next()
{
current.add(Calendar.DATE, 1);
return current.getTime();
}

public void remove()
{
throw new UnsupportedOperationException(
"Cannot remove");
}

public Iterator iterator()
{
return this;
}

public static void main(String[] args)
{
Date d1 = new Date();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 20);
Date d2 = cal.getTime();

Iterator i = new DateIterator(d1, d2);
while(i.hasNext())
{
Date date = i.next();
System.out.println(date);
}
}
}

How do I format a Date as a String?

Either use the format() method of the SimpleDateFormat class, or the (static) format() method of the String class.



DateFormat dateFormat = new SimpleDateFormat("hhmmddMMyy");

Date today = new Date();

String formatted = dateFormat.format(today);

String formatted2 =

String.format("%<tH%<tM%<tS%tY%<tm%<td", today);


How do I add a specified number of hours to a Java Date?

The Calendar class can be used to do a variety of date arithmetic

Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, numberOfHours);
date = cal.getTime();

How to fill a String with a character using Java?

The fill() method in the Arrays class is useful for creating string filled with a certain character.

// create a buffer of 9 characters

char[] fill = new char[9];

// Fill the buffer with all '0's

Arrays.fill(fill, '0');

// Create string using the buffer

String zeroes = new String(fill);

// zeroes string now contains "000000000"

How to convert a number into words using Java?

The following example shows how recusion can be used to convert any number from 0 to 99 into words. eg. NumberToWords.numberToWords(34) returns “Thirty Four”.

public class NumberToWords {

private static final String[] ONES = {
"Zero", "One", "Two", "Three", "Four", "Five",
"Six", "Seven", "Eight", "Nine" };
private static final String[] TEENS = {
"Ten", "Eleven", "Twelve", "Thirteen", null, "Fifteen",
null, null, "Eighteen", null };
private static final String[] TENS = {
null, null, "Twenty", "Thirty", "Forty", "Fifty",
"Sixty", "Seventy", "Eighty", "Ninety" };

public static String numberToWords(int number) {
if (number<10)>
return ONES[number];
} else if (number<20)>
int n = number - 10;
String words = TEENS[n];
return words==null ? ONES[n]+"teen" : TEENS[n];
} else {
int n = number % 10;
return TENS[number/10] +
(n==0 ? "" : (" " + numberToWords(n)));
}
}

public static void main(String[] args) {
for (int i=0; i<100;>
System.out.println(i+" "+numberToWords(i));
}
}
}

How to convert an array to a String?

The Arrays class has a set of helper toString methods for converting an array to a string representation.

String representation = Arrays.toString(array);

This will work for all array types. For Objects it uses the toString() method of the type to convert array elements.

If you needmore control how the array is represented then you will need to implement the conversion yourself using a loop.

Wednesday, March 18, 2009

How To Self Sign Applet




Download PDF


1. Create your code for the applet as usual.

It is not necessary to set any permissions or use security managers in
the code.

2. Install JDK 1.3
Path for use of the following commands: [jdk 1.3 path]\bin\
(commands are keytool, jar, jarsigner)
Password for the keystore is any password. Only Sun knows why...
perhaps ;-)

3. Generate key
Command= keytool -genkey -keyalg rsa -alias tstkey

Enter keystore password: *******
What is your first and last name?
[Unknown]: Your Name
What is the name of your organizational unit?
[Unknown]: YourUnit
What is the name of your organization?
[Unknown]: YourOrg
What is the name of your City or Locality?
[Unknown]: YourCity
What is the name of your State or Province?
[Unknown]: YS
What is the two-letter country code for this unit?
[Unknown]: US
Is CN=Your Name, OU=YourUnit, O=YourOrg, L=YourCity, ST=YS, C=US
correct?
[no]: yes

(wait...)

Enter key password for tstkey
(RETURN if same as keystore password):

(press [enter])

4. Export key
Command= keytool -export -alias tstkey -file tstcert.crt

Enter keystore password: *******
Certificate stored in file tstcert.crt

5. Create JAR
Command= jar cvf tst.jar tst.class
Add all classes used in your project by typing the classnames in the
same line.

added manifest
adding: tst.class(in = 849) (out= 536)(deflated 36%)

6. Verify JAR:
Command=jar tvf tst.jar

Thu Jul 27 12:58:28 GMT+02:00 2000 META-INF/
68 Thu Jul 27 12:58:28 GMT+02:00 2000 META-INF/MANIFEST.MF
849 Thu Jul 27 12:49:04 GMT+02:00 2000 tst.class

7. Sign JAR
Command= jarsigner tst.jar tstkey
Enter Passphrase for keystore: *******

8. Verifiy Signing
Command= jarsigner -verify -verbose -certs tst.jar

130 Thu Jul 27 13:04:12 GMT+02:00 2000 META-INF/MANIFEST.MF
183 Thu Jul 27 13:04:12 GMT+02:00 2000 META-INF/TSTKEY.SF
920 Thu Jul 27 13:04:12 GMT+02:00 2000 META-INF/TSTKEY.RSA
Thu Jul 27 12:58:28 GMT+02:00 2000 META-INF/
smk 849 Thu Jul 27 12:49:04 GMT+02:00 2000 tst.class

X.509, CN=Your Name, OU=YourUnit, O=YourOrg, L=YourCity, ST=YS, C=US
(tstkey)

s = signature was verified
m = entry is listed in manifest
k = at least one certificate was found in keystore
i = at least one certificate was found in identity scope

jar verified.

9. Create HTML-File for use of the Applet by the Sun Plugin 1.3
(recommended to use HTML Converter Version 1.3)

10. Now Applet Signed and ready to work

Monday, March 16, 2009

How to Refresh iFrame

function reload() {
fr = document.getElementById(”iframe1″);
fr.src = fr.src;
}

How To Add Border To HTML Select Tag

HTML <select> tag (aka DropDownList) do not suport BORDER style. But you can add border with a trick… by adding a SPAN/DIV tag around it with required style.

Here is the code:



<span style="border:solid 2px red">

<select style="border:solid 2px red">

<option>asdf</option>

<option>asdf</option>

<option>asdf</option>

</select></span>

JDBC Connection URLs for 22 Databases

Microsoft SQL Server JDBC connection URL

jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=northwind
com.microsoft.jdbc.sqlserver.SQLServerDriver
msbase.jar;mssqlserver.jar;msutil.jar


Microsoft SQL Server 2005 JDBC connection URL

jdbc:sqlserver://serverName\instance:port[;user=value][;password=value][;property=value]
com.microsoft.sqlserver.jdbc.SQLServerDriver

sqljdbc.jar
download SQL Server 2005 driver



Microsoft SQL Server (JTurbo) JDBC connection URL

jdbc:JTurbo://:/
com.ashna.jturbo.driver.Driver


Microsoft SQL Server (Sprinta) JDBC connection URL

jdbc:inetdae7::?database=
com.inet.tds.TdsDrive
download


Cloudscape JDBC connection URL

jdbc:cloudscape:MyDataBase
COM.cloudscape.core.JDBCDriver



Cloudscape RMI JDBC connection URL

jdbc:rmi://hostname:portnumber/jdbc:cloudscape:MyDatabase
RmiJdbc.RJDriver


Hypersonic SQL (server) JDBC connection URL

jdbc:hsqldb:hsql://localhost
org.hsqldb.jdbcDriver
hsqldb.jar
download (SourceForge)



Hypersonic SQL (in-process) JDBC connection URL

jdbc:hsqldb:file:/opt/db/testdb
org.hsqldb.jdbcDriver
hsqldb.jar

Hypersonic SQL (in-memory) JDBC connection URL

jdbc:hsqldb:mem:aname
org.hsqldb.jdbcDriver
hsqldb.jar

H2 Database (embedded)

jdbc:h2:test

H2 Database (Client Server)

jdbc:h2:tcp://localhost:9092/test


H2 Database (Client Server, Clustered)

jdbc:h2:tcp://localhost:9092,backuphost.com:9092/test



H2 Database (In Memory)

jdbc:h2:{ {.|mem:}[name] | [file:]fileName | {tcp|ssl}:[//]server[:port][,server2[:port]]/name }[;key=value...]


Informix JDBC connection URL

jdbc:informix-sqli://hostname:portnumber/MyDatabase:INFORMIXSERVER=MyServerName
com.informix.jdbc.IfxDriver


MySQL JDBC connection URL

jdbc:mysql:///test
jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]...
com.mysql.jdbc.Driver

Oracle JDBC connection URL

jdbc:oracle:thin:@localhost:1521:MyDatabase
oracle.jdbc.driver.OracleDriver
classes12.zip

PostgresSQL JDBC connection URL

jdbc:postgresql:template1
org.postgresql.Driver

DB2 JDBC connection URL

jdbc:db2:test
com.ibm.db2.jdbc.app.DB2Driver

TimesTen in-memory database JDBC connection URL

jdbc:timesten:direct:test
com.timesten.jdbc.TimesTenDriver


DB2/400 (native) JDBC connection URL

jdbc:db2://systemname
com.ibm.db2.jdbc.app.DB2Driver

DB2/400 (toolbox) JDBC connection URL

jdbc:as400://systemname
com.ibm.as400.access.AS400JDBCDriver


Derby JDBC connection URL

jdbc:derby:/test;create=true
org.apache.derby.jdbc.EmbeddedDriver

Sybase JDBC connection URL

jdbc:sybase:Tds:localhost:2048/MyDatabase
com.sybase.jdbc2.jdbc.SybDriver
jconn2.jar
download



Mckoi SQL JDBC connection URL

jdbc:mckoi:local://C:/mckoi1.0.3/db.conf
com.mckoi.JDBCDriver


SAP DB JDBC connection URL

jdbc:sapdb://localhost/TST
com.sap.dbtech.jdbc.DriverSapDB


JSQL JDBC connection URL

jdbc:JSQLConnect://localhost/test
com.jnetdirect.jsql.JSQLDriver

JTurbo JDBC connection URL

jdbc:JTurbo://localhost:1433/test
com.newatlanta.jturbo.driver.Driver

jTDS JDBC connection URL

jdbc:jtds:sqlserver://localhost/test
net.sourceforge.jtds.jdbc.Driver


Interbase (Java driver) JDBC connection URL

jdbc:firebirdsql:localhost/3050:/firebird/test.gdb
org.firebirdsql.jdbc.FBDriver


Interbase (Interclient driver) JDBC connection URL

jdbc:interbase://localhost:3060/C:/firebird/test.gdb
interbase.interclient.Driver


PointBase JDBC connection URL

jdbc:pointbase:embedded:sample
com.pointbase.jdbc.jdbcUniversalDriver

Ingres JDBC connection URL

ca.edbc.jdbc.EdbcDriver
jdbc:edbc://localhost:II7/database


Mimer SQL JDBC connection URL

jdbc:mimer:multi1
com.mimer.jdbc.Driver

Database Connection With My SQL



Download JDBC Driver

import java.*;
import java.sql.Connection;
import java.sql.DriverManager;

public class MySQLDatabaseConnectionTest{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost/";
String dbName = "DatabaseName";
String driver = "com.mysql.jdbc.Driver";
String userName = "UserName";
String password = "Password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Database Connection With Sybase






Download JDBC Driver

import java.*;
import java.sql.Connection;
import java.sql.DriverManager;
public class SybaseConnectionTest{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:sybase:Tds:localhost:2638/";
String dbName = "Databasename";
String driver = "com.sybase.jdbc2.jdbc.SybDriver";
String userName = "username";
String password = "password";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Database Connection With Microsoft SQL Server 2005




Download JDBC Driver





With SQLEXPRESS (Using Microsoft JDBC Driver)

Note: You can also use JTDS JDBC Driver for more information visit
http://jtds.sourceforge.net/


import java.*;
public class Connect{
private java.sql.Connection con = null;

public Connect(){}

private String getConnectionUrl(){
return "jdbc:sqlserver://win-xp\\sqlexpress;database=test;user=sa;password=admin104";
}

private java.sql.Connection getConnection(){
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = java.sql.DriverManager.getConnection(getConnectionUrl());
if(con!=null) System.out.println("Connection Successful!");
}catch(Exception e){
e.printStackTrace();
System.out.println("Error Trace in getConnection() : " + e.getMessage());
}
return con;
}

/*
Display the driver properties, database details
*/

public void displayDbProperties(){
java.sql.DatabaseMetaData dm = null;
java.sql.ResultSet rs = null;
try{
con= this.getConnection();
if(con!=null){
dm = con.getMetaData();
System.out.println("Driver Information");
System.out.println("\tDriver Name: "+ dm.getDriverName());
System.out.println("\tDriver Version: "+ dm.getDriverVersion ());
System.out.println("\nDatabase Information ");
System.out.println("\tDatabase Name: "+ dm.getDatabaseProductName());
System.out.println("\tDatabase Version: "+ dm.getDatabaseProductVersion());
System.out.println("Avalilable Catalogs ");
rs = dm.getCatalogs();
while(rs.next()){
System.out.println("\tcatalog: "+ rs.getString(1));
}
rs.close();
rs = null;
closeConnection();
}else System.out.println("Error: No active Connection");
}catch(Exception e){
e.printStackTrace();
}
dm=null;
}

private void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
Connect myDbTest = new Connect();
myDbTest.displayDbProperties();
}
}


WithOut SQLEXPRESS (Using Microsoft JDBC Driver)




import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class test {

public static void main(String args[]) throws ClassNotFoundException, SQLException{

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection conn = DriverManager.getConnection("jdbc:sqlserver://win-xp;database=Databasename;user=sa;password=111111");
System.out.println(conn);
}

}

Database Connection With Oracle 10 g




Download JDBC Driver


Connection con=null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:Databasename", "username", "password" );
Statement s=con.createStatement();

Saturday, March 14, 2009

How To Using shift operator for faster division and multiplication


Send File to Browser using JSP

String filename = "companySecret.txt";
String filepath = "C:\\";
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + '"');
java.io.FileInputStream fileInputStream = new java.io.FileInputStream(filepath + filename);
int i;
while ((i=fileInputStream.read()) != -1)
{
out.write(i);
}
fileInputStream.close(); out.close();

Determining OS Name

if (System.getProperty("os.name").startsWith("Mac"))

{

// do something mac specific System.out.println("hello!");

}