Good Sites :
Sun Source Examples :
Java, JDBC, and Arrays - How to send arrays to and from a Oracle database via JDBC
Type : Oracle(JDBC)
Driver : oracle.jdbc.driver.OracleDriver
URL : jdbc:oracle:thin:@sun3500:1521:ORCLT
JDBC Test Code :
//System.out.println("--------------------------------------------------------");
//System.out.println("--------------------------------------------------------");
//System.out.println("\n\n!!! About to try connection !!! \n\n");
//
// try {
//
// String ls_user = null;
//
// DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//
// Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@199.191.94.4:1521:ORCLT","jvogel","cotun");
//
// System.out.println("\n\nConnect succeeded ?! "+"[registeruser:EnterProductCriteriaAction_Preprocess.java]\n");
//
// Statement stmt = conn.createStatement();
//
// ResultSet rset = stmt.executeQuery ("select USER from DUAL");
//
// rset.next();
// ls_user = rset.getString(1);
// System.out.println("ls_user2 : "+ls_user);
//
// System.out.println("ls_user : "+ls_user+"[registeruser:EnterProductCriteriaAction_Preprocess.java]");
//
// conn.close();
//
// } catch (SQLException e) {
//
// e.printStackTrace();
//
// System.out.println(e.toString()+ "[registeruser:EnterProductCriteriaAction_Preprocess.java]");
// }
//
//System.out.println("\n\n!!! After Connection Attempt !!! \n\n");
| long to Long |
long plainLong = 100; Long javaLong = new Long(plainLong); |
| long to String |
String s = "100";
try {
long l = Long.parseLong(s.trim());
System.out.println("long l = " + l);
} catch (NumberFormatException nfe) {
System.out.println("NumberFormatException: " + nfe.getMessage());
}
|
| String to Long |
Long.toString(long l) is used to convert in the other direction, from long to String |
| Get CurrentDateTime |
SimpleDateFormat formatter = new SimpleDateFormat("'_'MMM'-'dd'-'yyyy'_'HH:mm:ss");
currentDate = formatter.format(new Date());
|
| Iterator Example |
Long contractId = 0;
Collection contractIdCollection = null;
try {
int maxContract = contractIdCollection.size();
Iterator iterator = contractIdCollection.iterator();
for (int i = 0; i < maxContract; i++) {
contractDa = (ContractDa)iterator.next();
contractId = contractDa.getId();
}
} catch (Exception exception) {
System.out.println(exception.toString());
}
|
| Exceptional General Exceptions |
Original article : http://www.fawcette.com/javapro/2002_09/online/errors_jstreet_09_13_02/page2.asp Note that several exceptions are unchecked, and as such, behave like errors: NullPointerException, ClassCastException, and IndexOutOfBoundsException are all subclasses of RuntimeException. RuntimeException and all of its children are always unchecked. So what should you do about all these nasty unchecked exceptions? You could catch the exceptions in the method where they might occur, but this is a haphazard solution. Doing so solves one problem, but it leaves the rest of the code open to disruption by other unchecked exceptions. There's a better way, thanks to a nifty little method provided by the ThreadGroup class: public class ApplicationLoader extends ThreadGroup
{
private ApplicationLoader()
{
super("ApplicationLoader");
}
public static void main(String[] args)
{
Runnable appStarter = new Runnable()
{
public void run()
{
//invoke your application
(i.e. MySystem.main(args)}
}
new Thread(new ApplicationLoader(),
appStarter).start();
}
//We overload this method from our parent
//ThreadGroup , which will make sure that it
//gets called when it needs to be. This is
//where the magic occurs.
public void uncaughtException(Thread thread, Throwable exception)
{
//Handle the error/exception. This technique rocks. Think of all those times you perform an operation in your GUI, and an unchecked exception happens. Often, you leave the GUI in an unusual state (dialogs still open, buttons disabled, cursors in the wrong state), but with this technique, you could return the GUI to its natural state, inform the user of an error, and feel good about yourself because you wrote a high-quality application. But this technique isn't just for GUIs. Server applications prone to excessive resource usage can use this technique to free resources at a global level, often preventing the VM from entering an unstable state. Catching errors early and often, and dealing with them smartly, can make the difference between a great programmer and an average one. And by virtue of your having read this far, we know which one you want to be. |
| Performance Profiling |
long startTime = System.currentTimeMillis();
...
long endTime = System.currentTimeMillis();
double theTime = (double) ((endTime - startTime)/1000);
System.out.println("Time -----> : " + theTime);
|
| JavaMail with an attachment |
aToAddress - address to be sent to pSubject - subject of message pMessage - the text message pFileName - the name of the file to be attached.
Be sure to give the absolute path name starting from where the JavaTM Virtual Machine1 (JVM) is running. Message msg = new MimeMessage(session);
msg.setFrom( aDefaultFromAddress );
InternetAddress[] address = {aToAddress};
msg.setRecipients(
Message.RecipientType.TO, address);
msg.setSubject( pSubject );
msg.setSentDate(new java.util.Date());
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(pMessage);
// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();
// attach the file to the message
FileDataSource fds=
new FileDataSource(pFileName);
mbp2.setDataHandler(
new DataHandler(fds));
mbp2.setFileName(pFileName);
// create the Multipart
//and its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
Transport.send(msg);
|
| How to send an HTTP request to a servlet from a normal class without having to use a browser to send the HTTP requests | There are a couple of ways of doing this, and this is one
way to do it. This example servlet is called by a normal class by passing
some request parameters. The servlet puts them in a HashMap
and returns the HashMap back to the class, and the class
prints the HashMap object. You can change this code to fit
your needs, but the basic code is here.
Servlet: import java.util.HashMap;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// getting the parameters
String name = request.getParameter("name");
String age = request.getParameter("age");
//putting them in a hashmap
HashMap hm = new HashMap();
hm.put("name", name);
hm.put("age", age);
//returning them
try {
ObjectOutputStream p = new
ObjectOutputStream(response.getOutputStream());
p.writeObject(hm);
p.flush();
p.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
This is the class that calls the servlet: import java.net.*;
import java.util.*;
import java.io.*;
public class Hello {
public static void main(String args[]) {
ObjectInputStream is;
URL url;
String uri =
"http://Server name:port/HelloServlet";
HashMap hash = new HashMap();
try {
//calling the servlet by passing params
url = new URL(uri +"?&name=MyName&age=25");
// open input stream and read the hashmap
// returned by the servlet
is = new ObjectInputStream(url.openStream());
hash = (HashMap) is.readObject();
// print it out
System.out.println(hash);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
}
|
| What Class called my Method? | What class called my method?
If object String callingClassName = sun.reflect.Reflection.getCallerClass(2).getName();
JDK 1.4+ you could just say "new Thread().getStackTrace()[1].getClassName()", with a warning to check that getStackTrace actually returns an array with some elements, or you could end up throwing ArrayOutOfBoundsException unexpectedly
You can get the name of the class by processing the call stack printed
to a stream by the import java.io.*; public class A { public static void main( String args[] ) { B.methodB(); } } class B { public static void methodB() { StringWriter sw = new StringWriter(); new Throwable().printStackTrace( new PrintWriter( sw ) ); String callStack = sw.toString(); int atPos = callStack.indexOf( "at" ); atPos = callStack.indexOf( "at" , atPos ); int dotPos = callStack.indexOf( "." , atPos ); System.out.println( "name of the class that called this method - " + callStack.substring( atPos + 2 , dotPos ) ); } } |
| String to Date conversion | tried:
DateFormat df=DateFormat.getInstance(); Date myDate=df.parse(d); Where d...date in the string is in (UTC) format. I'm getting the following errors: UnparsedDateException The short code snippet below expects a date in the "yyyy-mm-dd" format and will reformat it to the "mm/dd/yyyy" format.
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateFormatTest
{
public static void main( String[] cmdArgs )
throws Exception
{
SimpleDateFormat sdfInput =
new SimpleDateFormat( "yyyy-MM-dd" );
SimpleDateFormat sdfOutput =
new SimpleDateFormat ( "MM/dd/yyyy" );
String textDate = "2001-01-04";
Date date = sdfInput.parse( textDate );
System.out.println( sdfOutput.format( date ) );
} // main
} // class DateFormatTest
If you prefer, you can replace the last two lines of code with
System.out.println( sdfOutput.format(
sdfInput.parse(textDate)));
|
| Implementing the Singleton pattern in Java | Source : http://developer.java.sun.com/developer/qow/archive/111/
public class Singleton {
private static final Singleton INSTANCE =
new Singleton();
// Private constructor supresses
// default public constructor
private Singleton( ) {
}
public static Singleton getInstance( ) {
return INSTANCE;
}
}
If you want to make it serializable, then change the declaration to: and add this method: private Object readResolve()
throws ObjectStreamException {
return INSTANCE;
}
The |
| java.util.StringTokenizer | The string tokenizer class allows an application to break a string into
tokens
The following is one example of the use of the tokenizer. The code:
prints the following output:
See Also: |
| Factory Pattern Example | http://developerlife.com/lessons/factories/default.htm |
| JVM Shutdown Hooks
By Frank Jennings
|
Original Article : http://www.sys-con.com/java/articlenews.cfm?id=1824 The other day I was trying to terminate this unprecedented application server from my console window by using CTRL-C. The application did get the idea that I didn't want to see any more of it, but I guess it was trying to save the settings, flush streams, close database connection, update log files, write preferences, check data files - all when I was waiting patiently. It was in a dangled state and didn't respond even when I killed the PID. I never felt paranoid with JVM Shutdown hooks until that moment. Do not use Runtime.runFinalizersOnExit, for performing a cleanup operation during improper JVM shutdown, because this will result in finalizing of objects, which is being manipulated by different concurrent threads. This is unsafe and will lead to deadlock. Here is the proper implementation of shutdown hook. We create a shutdown hook, which performs the last minute panic operation, and monitor the cleanup period using a hook timer. Whether our application performs cleanup or not, the hook timer forcibly shuts down the application by invoking Runtime.halt. This is because when the JVM is about to be shut down all the hooks are started randomly without any order.
Improper implementation of shutdown-hook turns me off and I, in turn, turn off the JVM's interaction with the OS signals with the java -Xrs switch. So the application can't perform its cleanup during improper shutdown. Some revenge! |
A generic iterator for tree traversal by Alexander Ananiev (DDJ article) - Generic tree traversal logic can be used with any type of tree-like structure or tree node, letting you focus on the application logic rather than the internals of the tree structure organization. Additional resources include aa0011.txt (listings). Local copy of aa0011.txt.
Unraveling
Java - Sun's Developer Table of Contents
Roedy Green's Java & Internet Glossary
Logging for Java (from IBM DeveloperWorks)
exe4j
- A Java exe maker that
helps you integrate your Java applications into the Windows operating environment.
exe4j helps you with starting your Java applications in a safe way, displaying
native splash screens, detecting or distributing suitable JREs and JDKs, startup
error handling and much more.
sql2java: Object-Relational
Mapping Tool for Java
swiftmq.com -
Free
Open source vendors :
Sybase
EAServer Developer Edition (Free - single user license)
Sun
One Application Server 7, Standard Edition
JBoss.org
- an Open Source, standards-compliant, Enterprise JavaBeans application server
implemented in 100% Pure Java, as is our full product suite
XML
NetBeans Java IDE -
Free
dbPrism
(secondary link)
- PL/SQL XML Cartridge for Java (similar to PL/SQL Cartridge under OAS/iAS
mod_plsql)
DB Prism is a Servlet which emulates Oracle Application Server 3.x / Ias. DB Prism provides Java Stored Procedures, and it is 100% compatible with OWS 3.x. It supports UTF-8 database encoding, Oracle 7, 8, and Oracle Lite. It includes DB Producer for the Cocoon framework so that it can integrate with XML technology from http://xml.apache.org/. It also includes the DB Prism/Cocoon Content Management System (CMS), based on Oracle CMS. Look at the "Files" section for downloading it. Look at the "Links" section for getting the new documentation.
KL Groups' - Components and Tuning Products
(ex. JProbe)
Java and Adobe's PDF File Format
CodeGuide
(Java IDE with "step-back" debugging)
Roedy Green's Java & Internet
Glossary
JCertify - Certification
Testing
JODE
Excelsior's Jet - Use
JET to deploy your Java applications as highly optimized native 32-bit Windows
executables.
The core component of JET is an optimizing Java to native code compiler. JET compiler reads Java class files created in any Java IDE, compiles them using aggressive optimization techniques specially adapted to Java, links with high performance runtime support libraries, and produces a conventional executable file.
Swing ( portable GUI with native-platform
"Look-and-Feel"
Java Report Tools from Inetsoft
JTest - Testing
Tool from ParaSoft
MultiLizer - Mult-Language Support
( also check out Corel's Catalyst )
HyperSonic SQL - Free Java
SQL Database
WebTechniques'
Java Regular Expressions article
ColdJava TagLib (at http://www.servletsuite.com)
|
Copyright © : 1997 - 2005 |