Friday, November 21, 2008

Image Search Engine-iStockphoto



URL: http://www.istockphoto.com

iStockphoto is the internet’s original member-generated image and design community. Find your inspiration on the world's leading royalty-free stock destination. Search for over 3 million photographs, vector illustrations, video footage and Flash files.

Wednesday, November 19, 2008

Use of Java Logging



Note: This program write a .Log file with all debugs


import java.util.logging.*;
import java.io.*;
public class TestLog {
public static Logger logger;
static {
try {
boolean append = true;
FileHandler fh = new FileHandler("TestLog.log", append);
//fh.setFormatter(new XMLFormatter());
fh.setFormatter(new SimpleFormatter());
logger = Logger.getLogger("TestLog");
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
logger.severe("my severe message");
logger.warning("my warning message");
logger.info("my info message");
}
}


OutPut

Nov 19, 2008 3:52:19 PM TestLog main
SEVERE: my severe message
Nov 19, 2008 3:52:19 PM TestLog main
WARNING: my warning message
Nov 19, 2008 3:52:19 PM TestLog main
INFO: my info message

------------------------------------------------------------------------------------------------------------------------------------
if the XMLFormatter is in use then the output is





2005-02-28T21:21:09
1109643669250
0
TestLog
SEVERE
TestLog
main
10
my severe message


2005-02-28T21:21:09
1109643669328
1
TestLog
WARNING
TestLog
main
10
my warning message


2005-02-28T21:21:09
1109643669328
2
TestLog
INFO
TestLog
main
10
my info message


------------------------------------------------------------------------------------------------------------------------------------
to customize the output, you can provide you own formatter

import java.util.logging.*;
import java.io.*;
public class TestLog {
public static Logger logger;
static {
try {
boolean append = true;
FileHandler fh = new FileHandler("TestLog.log", append);
fh.setFormatter(new Formatter() {
public String format(LogRecord rec) {
StringBuffer buf = new StringBuffer(1000);
buf.append(new java.util.Date());
buf.append(' ');
buf.append(rec.getLevel());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
logger = Logger.getLogger("TestLog");
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
logger.severe("my severe message");
logger.warning("my warning message");
logger.info("my info message");
}
}
then the output is
Mon Feb 28 21:30:54 EST 2005 SEVERE my severe message
Mon Feb 28 21:30:54 EST 2005 WARNING my warning message
Mon Feb 28 21:30:54 EST 2005 INFO my info message
------------------------------------------------------------------------------------------------------------------------------------
To limit the log file size and set a rolling pattern
int limit = 1000000; // 1 Mb
int numLogFiles = 3;
FileHandler fh = new FileHandler("TestLog%g.log", limit, numLogFiles);
------------------------------------------------------------------------------------------------------------------------------------
To suppress the logging output to the console

Logger rootLogger = Logger.getLogger("");
Handler[] handlers = rootLogger.getHandlers();
if (handlers[0] instanceof ConsoleHandler) {
rootLogger.removeHandler(handlers[0]);
}

Apachi LOG4J


Inserting log statements into your code is a low-tech method for debugging it. It may also be the only way because debuggers are not always available or applicable. This is often the case for distributed applications.

On the other hand, some people argue that log statements pollute source code and decrease legibility. (We believe that the contrary is true). In the Java language where a preprocessor is not available, log statements increase the size of the code and reduce its speed, even when logging is turned off. Given that a reasonably sized application may contain thousands of log statements, speed is of particular importance.

With log4j it is possible to enable logging at runtime without modifying the application binary. The log4j package is designed so that these statements can remain in shipped code without incurring a heavy performance cost. Logging behavior can be controlled by editing a configuration file, without touching the application binary.

Logging equips the developer with detailed context for application failures. On the other hand, testing provides quality assurance and confidence in the application. Logging and testing should not be confused. They are complementary. When logging is wisely used, it can prove to be an essential tool.

One of the distinctive features of log4j is the notion of inheritance in loggers. Using a logger hierarchy it is possible to control which log statements are output at arbitrarily fine granularity but also great ease. This helps reduce the volume of logged output and minimize the cost of logging.
The target of the log output can be a file, an OutputStream, a java.io.Writer, a remote log4j server, a remote Unix Syslog daemon, or many other output targets.

On an AMD Duron clocked at 800Mhz running JDK 1.3.1, it costs about 5 nanoseconds to determine if a logging statement should be logged or not. Actual logging is also quite fast, ranging from 21 microseconds using the SimpleLayout, 37 microseconds using the TTCCLayout. The performance of the PatternLayout is almost as good as the dedicated layouts, except that it is much more flexible.

Monday, November 17, 2008

Styling form file input


Styling form file input

Due to certain security considerations, it is very difficult to change the style of file input.Here is a good post on how to do it.http://www.quirksmode.org/dom/inputfile.htmlFollowing is quoted from above article:
Step-1 Take a normal < type="file">
Step-2To this same parent element, add a normal <> and an image, which have the correct styles. Position these elements absolutely, so that they occupy the same place as the < type="file">.
Step-3 Set the z-index of the < type="file"> to 2 so that it lies on top of the styled input/image.
Step-4 Finally, set the opacity of the < type="file"> to 0. The < type="file"> now becomes effectively invisible, and the styles input/image shines through, but you can still click on the "Browse" button. If the button is positioned on top of the image, the user appears to click on the image and gets the normal file selection window.(Note that you can't use visibility: hidden, because a truly invisible element is unclickable, too, and we need the < type="file"> to remain clickable)

Step-5 When the user has selected a file, the visible, fake input field should show the correct path to this file, as a normal < type="file"> would. It's simply a matter of copying the new value of the < type="file"> to the fake input field, but we need JavaScript to do this

Adding CLASSPATH in NetBeans


Adding CLASSPATH in NetBeans

1.In the Projects window, right-click the project node and choose Properties.
2.Click Libraries in the left panel of the Project Properties dialog box.
3.Adding library path in the right panel.

Adding JDK Javadoc to NetBeans IDE



Adding JDK Javadoc to NetBeans IDE
1.Download JDK documentation from http://java.sun.com/j2se/1.5.0/download.jsp Unzip the zip file to the JDK directoryIn NetBeans IDE1. Choose Tools > Java Platform Manager from the main window.

2. Select the platform to which you want to add Javadoc in the left panel of the dialog box.
3. In the Javadoc tab, click Add ZIP/Folder and specify the location of the Javadoc files.
4. Click Close.

Apachi ofBiz



Introduction: What is Apache OFBiz?
The Apache Open For Business Project is an open source enterprise automation software project licensed under the Apache License Version 2.0. By open source enterprise automation we mean: Open Source ERP, Open Source CRM, Open Source E-Business / E-Commerce, Open Source SCM, Open Source MRP, Open Source CMMS/EAM, and so on.
Apache OFBiz is a foundation and starting point for enterprise solutions, be they for one organization or one million. OFBiz can certainly be used OOTB (out of the box), but if you're looking for something that works really well for that there are many open source projects that do a great job there. OFBiz is great for creating specialized applications for use OOTB by other organizations. OFBiz is also great for organizations that need more than what an OOTB application can offer in order to grow their operations, but find the deployment and maintenance costs of traditional enterprise systems that can handle such things to be unreasonable or unjustifiable.
Being open source under the Apache 2.0 license and driven by a community Apache OFBiz offers both flexibility by design and by access to code, and a solution where you're not alone but rather can work with many others to get things done.
For answers to your questions you might find the following documents useful: Project Overview, Is Apache OFBiz for Me?, Feature List, and Features Coming Soon
For more technical information, see the Documentation page.
Apache OFBiz offers a great deal of functionality, including:



* advanced e-commerce
* catalog management
* promotion & pricing management
* order management (sales & purchase)
* customer management (part of general party management)
* warehouse management
* fulfillment (auto stock moves, batched pick, pack & ship)
* accounting (invoice, payment & billing accounts, fixed assets)
* manufacturing management
* general work effort management (events, tasks, projects, requests, etc)
* content management (for product content, web sites, general content, blogging, forums, etc)
* a maturing Point Of Sales (POS) module using XUI as rich client interface

* and much more all in an open source package!

Example of ofBiz are given in following Reference Site
Reference:
http://ofbiz.apache.org/

Friday, November 14, 2008

howstuffworks



Explorer Everything With howstuffworks. I am crazy about this site.
Try this....

URL: http://computer.howstuffworks.com/

Try It

Wednesday, November 12, 2008

Apachi Common Validator


URL: http://commons.apache.org/validator/

Download:
http://commons.apache.org/downloads/download_validator.cgi

Documentation:
http://commons.apache.org/validator/apidocs/org/apache/commons/validator/package-summary.html#package_description

Other Tutorial (Good one): http://struts.apache.org/2.0.14/docs/validation.html#Validation-Examples


Commons Validator
A common issue when receiving data either electronically or from user input is verifying the integrity of the data. This work is repetitive and becomes even more complicated when different sets of validation rules need to be applied to the same set of data based on locale. Error messages may also vary by locale. This package addresses some of these issues to speed development and maintenance of validation rules.

JAR Search Engine

URL: http://www.findjar.com/




Field Validation with InputVerify Class

Reference Site: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/InputVerifier.html


Example :

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

// This program demonstrates the use of the Swing InputVerifier class.
// It creates two text fields; the first of the text fields expects the
// string "pass" as input, and will allow focus to advance out of it
// only after that string is typed in by the user.

public class VerifierTest extends JFrame {
public VerifierTest() {
JTextField tf1 = new JTextField ("Type \"pass\" here");
getContentPane().add (tf1, BorderLayout.NORTH);
tf1.setInputVerifier(new PassVerifier());

JTextField tf2 = new JTextField ("TextField2");
getContentPane().add (tf2, BorderLayout.SOUTH);

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

class PassVerifier extends InputVerifier {
public boolean verify(JComponent input) {
JTextField tf = (JTextField) input;
return "pass".equals(tf.getText());
}
}

public static void main(String[] args) {
Frame f = new VerifierTest();
f.pack();
f.setVisible(true);
}
}



Output




Tuesday, November 11, 2008

Cool Icons

Find Cool Icons From http://www.iconlook.com/




Try Now






Set Look n Feel of java Swing

example:

String lookAndFeel = UIManager.getSystemLookAndFeelClassName(); // Set systems default theam
UIManager.setLookAndFeel(lookAndFeel);


to set other theam change the variable name "lookAndFeel" as follow

System ------->lookAndFeel = UIManager.getSystemLookAndFeelClassName();
Motif------------>lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
GTK------------>lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
Metal----------> UIManager.setLookAndFeel(new MetalLookAndFeel());


Reference: http://java.sun.com/docs/books/tutorial/uiswing/lookandfeel/plaf.html#dynamic


Example:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.plaf.metal.*;

public class LookAndFeelDemo implements ActionListener {
private static String labelPrefix = "Number of button clicks: ";
private int numClicks = 0;
final JLabel label = new JLabel(labelPrefix + "0 ");

// Specify the look and feel to use by defining the LOOKANDFEEL constant
// Valid values are: null (use the default), "Metal", "System", "Motif",
// and "GTK"
final static String LOOKANDFEEL = "Metal";

// If you choose the Metal L&F, you can also choose a theme.
// Specify the theme to use by defining the THEME constant
// Valid values are: "DefaultMetal", "Ocean", and "Test"
final static String THEME = "Test";


public Component createComponents() {
JButton button = new JButton("I'm a Swing button!");
button.setMnemonic(KeyEvent.VK_I);
button.addActionListener(this);
label.setLabelFor(button);

JPanel pane = new JPanel(new GridLayout(0, 1));
pane.add(button);
pane.add(label);
pane.setBorder(BorderFactory.createEmptyBorder(
30, //top
30, //left
10, //bottom
30) //right
);

return pane;
}

public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
}

private static void initLookAndFeel() {
String lookAndFeel = null;

if (LOOKANDFEEL != null) {
if (LOOKANDFEEL.equals("Metal")) {
lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
// an alternative way to set the Metal L&F is to replace the
// previous line with:
// lookAndFeel = "javax.swing.plaf.metal.MetalLookAndFeel";

}

else if (LOOKANDFEEL.equals("System")) {
lookAndFeel = UIManager.getSystemLookAndFeelClassName();
}

else if (LOOKANDFEEL.equals("Motif")) {
lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
}

else if (LOOKANDFEEL.equals("GTK")) {
lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
}

else {
System.err.println("Unexpected value of LOOKANDFEEL specified: "
+ LOOKANDFEEL);
lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
}

try {


UIManager.setLookAndFeel(lookAndFeel);

// If L&F = "Metal", set the theme

if (LOOKANDFEEL.equals("Metal")) {
if (THEME.equals("DefaultMetal"))
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
else if (THEME.equals("Ocean"))
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
else
MetalLookAndFeel.setCurrentTheme(new TestTheme());

UIManager.setLookAndFeel(new MetalLookAndFeel());
}




}

catch (ClassNotFoundException e) {
System.err.println("Couldn't find class for specified look and feel:"
+ lookAndFeel);
System.err.println("Did you include the L&F library in the class path?");
System.err.println("Using the default look and feel.");
}

catch (UnsupportedLookAndFeelException e) {
System.err.println("Can't use the specified look and feel ("
+ lookAndFeel
+ ") on this platform.");
System.err.println("Using the default look and feel.");
}

catch (Exception e) {
System.err.println("Couldn't get specified look and feel ("
+ lookAndFeel
+ "), for some reason.");
System.err.println("Using the default look and feel.");
e.printStackTrace();
}
}
}

private static void createAndShowGUI() {
//Set the look and feel.
initLookAndFeel();

//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);

//Create and set up the window.
JFrame frame = new JFrame("SwingApplication");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

LookAndFeelDemo app = new LookAndFeelDemo();
Component contents = app.createComponents();
frame.getContentPane().add(contents, BorderLayout.CENTER);

//Display the window.
frame.pack();
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event dispatch thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}


Use of java's System Class

example:

System.out.println(System.getProperty("os.name"))

o/p= windows xp


Reference site : http://java.sun.com/j2se/1.5.0/docs/api/java/lang/System.html



java.version------------------------------------> Java Runtime Environment version
java.vendor
------------------------------------> Java Runtime Environment vendor
java.vendor.url
------------------------------------>Java vendor URL
java.home
------------------------------------>Java installation directory
java.vm.specification.version
------------------------------------>Java Virtual Machine specification version
java.vm.specification.vendor
------------------------------------>Java Virtual Machine specification vendor
java.vm.specification.name
------------------------------------>Java Virtual Machine specification name
java.vm.version
------------------------------------>Java Virtual Machine implementation version
java.vm.vendor
------------------------------------> Java Virtual Machine implementation vendor
java.vm.name
------------------------------------> Java Virtual Machine implementation name
java.specification.version
------------------------------------> Java Runtime Environment specification version
java.specification.vendor
------------------------------------>Java Runtime Environment specification vendor
java.specification.name
------------------------------------> Java Runtime Environment specification name
java.class.version
------------------------------------> Java class format version number
java.class.path
------------------------------------>Java class path
java.library.path
------------------------------------> List of paths to search when loading libraries
java.io.tmpdir
------------------------------------> Default temp file path
java.compiler
------------------------------------> Name of JIT compiler to use
java.ext.dirs
------------------------------------> Path of extension directory or directories
os.name
------------------------------------> Operating system name
os.arch
------------------------------------> Operating system architecture
os.version
------------------------------------> Operating system version
file.separator
------------------------------------> File separator ("/" on UNIX)
path.separator
------------------------------------> Path separator (":" on UNIX)
line.separator
------------------------------------> Line separator ("\n" on UNIX)
user.name
------------------------------------> User's account name
user.home
------------------------------------> User's home directory
user.dir
------------------------------------>User's current working directory

Find Date range from batch

for ex: input=23
output= [20-30]


String age="23";
float fage = Float.parseFloat(age)/10;
System.out.println("Float age is :"+fage);
int iage=(int)fage;
System.out.println("Value of iage is :"+iage);
int mage=iage*10;
int mmage=(iage+1)*10;
String age1=mage+"-"+mmage;
System.out.println("Changed age is :"+age1);

Wednesday, November 5, 2008

How To install openInstaller in to NetBenas 6.1

To install openInstaller in to NetBeans follow followings steps

1. Start IDE
2. Invoke Tools>Plugins, go to Settings tab
3. Click "Add" button -> dialog shows up
4. Fill "openInstaller" in Name field and https://openinstaller.dev.java.net/nonav/public/downloads/updates.xml in URL field (this is the url that is in the blog entry)
5. Click OK to go back to Plugins dialog
6. Choose Available Plugins tab
7. Find and install "NetbeansSuiteInstallerBuilder" module

Instruction To Create Installer
visit
http://blogs.sun.com/vdblog/entry/netbeans_module_suite_installer_generator


Upload Video on Youtube using java with YouTube API

<%@page import="com.google.gdata.util.AuthenticationException"%>
<%@page import="com.google.gdata.util.ServiceException"%>
<%@page import="com.google.gdata.client.youtube.YouTubeService"%>
<%@page import="com.google.gdata.data.media.mediarss.MediaCategory"%>
<%@page import="com.google.gdata.data.media.mediarss.MediaDescription"%>
<%@page import="com.google.gdata.data.media.mediarss.MediaKeywords"%>
<%@page import="com.google.gdata.data.media.mediarss.MediaTitle"%>
<%@page import="com.google.gdata.data.youtube.FormUploadToken"%>
<%@page import="com.google.gdata.data.youtube.VideoEntry"%>
<%@page import="com.google.gdata.data.youtube.YouTubeMediaGroup"%>
<%@page import="com.google.gdata.data.youtube.YouTubeNamespace"%>
<%@page import="java.net.URL"%>
<%

String token="", formUrl="";
YouTubeService service=null;

if (service == null) {
service = new YouTubeService("ytapi-chintanpatel-iposte-v15d53e7-0", "AI39si4mF_tIDllFf-vW8P9VqHdP_2lKU7mY0qp9F03nDEvKeKy8I6pb9IrxSwJfcnKyr3CSFQbdDarQZe200r90y61v1ouQiQ");
String username = "youtubeusername";//YOUTUBE_USERNAME;
String password = "youtubepassowrd";//YOUTUBE_PASSWORD;
try {
service.setUserCredentials(username, password);
} catch (AuthenticationException ae) {
ae.printStackTrace();
}
}

VideoEntry newEntry = new VideoEntry();
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();

String videoTitle = "Titel of the video";

mg.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Autos"));
mg.setTitle(new MediaTitle());
mg.setPrivate(false);
mg.setKeywords(new MediaKeywords());
mg.getKeywords().addKeyword("videokeyword");
mg.getTitle().setPlainTextContent(videoTitle);
mg.setDescription(new MediaDescription());
mg.getDescription().setPlainTextContent(videoTitle);

URL uploadUrl = new URL("http://gdata.youtube.com/action/GetUploadToken");

try {

FormUploadToken fut = service.getFormUploadToken(uploadUrl, newEntry);

token = fut.getToken();
formUrl = fut.getUrl();

} catch (ServiceException se) {
se.printStackTrace();
}

%>

// Note

Now follow the following steps

step1- Create form tag

step2- create action tag and write following

form name="form1" action="<%=formUrl%>?nexturl=http://www.yoursite.org/iposte/youtube_upload_display.jsp" method="post" enctype="multipart/form-data"

step-3 Create one hidden input field to send token

input type="hidden" name="token" value="<%=token%>"

Chintan Patel
Peer Technology
Rajkot

String functions

string string(object?)

This function returns the string-value of the argument. If the argument is a node-set, then it returns the string-value of the first node in the set. If the argument is omitted, it returns the string-value of the context node.

string concat(string, string, string...)


This function returns a string containing the concatenation of all its arguments.

boolean starts-with(string, string)


This function returns true if the first string starts with the second string. Otherwise it returns false.

boolean contains(string, string)

This function returns true if the first string contains the second string. Otherwise it returns false.

string substring-before(string, string)

This returns that part of the first string that precedes the second string. It returns the empty string if the second string is not a substring of the first string. If the second string appears multiple times in the first string, then this returns the portion of the first string before the first appearance of the second string.

string substring-after(string, string)


This returns that part of the first string that follows the second string. It returns the empty string if the second string is not a substring of the first string. If the second string appears multiple times in the first string, then this returns the portion of the first string after the initial appearance of the second string.

string substring(string, number, number?)


This returns the substring of the first argument beginning at the second argument and continuing for the number of characters specified by the third argument (or until the end of the string if the third argument is omitted.) Unlike Java, the foirst character is at position 1, not 0.

number string-length(string?)


Returns the number of Unicode characters in the string, or the string-value of the context node if the argument is omitted. This may not be the same as the number returned by the length() method in Java’s String class because XSLT counts characters and Java counts UTF-16 code points.

string normalize-space(string?)


This function strips all leading and trailing white-space from its argument, or the string-value of the context node if the argument is omitted, and condenses all other runs of whitespace to a single space. It’s very useful in XML documents where whitespace is used primarily for formatting.

string translate(string, string, string)


This function replaces all characters in the first string that are found in the second string with the corresponding character from the third string.




Chintan Patel
Peer Technology
Rajkot


Replace/remove character in a String

To replace all occurences of a given character

String tmpString = myString.replace( '\'', '*' );
System.out.println( "Original = " + myString );
System.out.println( "Result = " + tmpString );

To replace a character at a specified position :

public static String replaceCharAt(String s, int pos, char c) {
return s.substring(0,pos) + c + s.substring(pos+1);
}


To remove a character :

public static String removeChar(String s, char c) {
String r = "";
for (int i = 0; i < style="font-weight: bold; color: rgb(0, 153, 0);">To remove a character at a specified position:


public static String removeCharAt(String s, int pos) {
return s.substring(0,pos)+s.substring(pos+1);
}

Chintan Patel
Peer Technology
Rajkot