How to validate URL in Java

A short example to show the use of apache.commons.validator.UrlValidator class to validate an URL in Java.

import org.apache.commons.validator.UrlValidator;
 
public class ValidateUrlExample{
 
	public static void main(String[] args) {
 
	    UrlValidator urlValidator = new UrlValidator();
 
	    // valid URL
	    if (urlValidator.isValid("http://www.ziben.com.br")) {
	       System.out.println("url is valid");
	    } else {
	       System.out.println("url is invalid");
	    }
 
	    // invalid URL
	    if (urlValidator.isValid("http://invalidURL^$&%$&^")) {
	        System.out.println("url is valid");
	    } else {
	        System.out.println("url is invalid");
	    }
 
	}
}

Output

url is valid
url is invalid

Reference

  1. http://commons.apache.org/validator/apidocs/org/apache/commons/validator/UrlValidator.html

Microsoft won’t stop .Net on Android

Oracle’s patent and copyright lawsuit against Google for its use of Java in Android won’t be repeated by Microsoft if .Net is used on the Linux-based mobile operating system instead.

Director of the open source technology centre at Microsoft Tom Hanrahan said the Community Promise allows projects like Mono to fully support its technology.

“The type of action Oracle is taking against Google over Java is not going to happen,” Hanrahan said.

Microsoft’s Community Promise has made the .Net runtime and C# specifications available to Miguel de Icaza and the Mono project developers.

“If a .Net port to Android was through Mono it would fall under that agreement,” he said.

Hanrahan is visiting Australia for Microsoft’s annual Tech.Ed conference.

Novell has already developed MonoTouch for Apple’s iOS-based devices like the iPhone and iPad, and a Mono port to Android, dubbed “MonoDroid”, is on the roadmap, due for a preview release in Q3 this year.

“Mono for Android will have an entirely different set of APIs, at most you would be able to reuse business logic, but any user interface and device specific code will have to be rewritten,” according to the Mono developers.

Oracle’s complaint against Google centres around its development of the Dalvik virtual machine that can run applications written in Java.

Dalvik is not an officially sanctioned Java runtime environment, however Sun did initially praise Google for supporting Java on Android.

Potential conflict between Sun and Google over Dalvik was also predicted back in 2007, but did not eventuate until Oracle acquired Sun.

With Java use in Android under fire, Microsoft is unlikely to disrupt any port of C# to the mobile platform, however, Microsoft’s Community Promise has been criticised by the Free Software Foundation for not going far enough to protect open source implementations from patent litigation, which is at the heart of the Oracle-Google case.

“The Community Promise does not give you any rights to exercise the patented claims. It only says that Microsoft will not sue you over claims in patents that it owns or controls,” according to the Free Software Foundation.

“If Microsoft sells one of those patents, there’s nothing stopping the buyer from suing everyone who uses the software.”

Mono developer Miguel de Icaza is not concerned about legal challenges by Microsoft over .Net implementations and wrote on his blog that Google could switch from Java.

“Google could settle current damages with Oracle, and switch to the better designed, more pleasant to use, and more open .Net platform,” de Icaza wrote.

Rodney Gedda is Editor of TechWorld Australia. Follow Rodney on Twitter at @rodneygedda. Rodney’s e-mail address is rodney_gedda@idg.com.au. Follow TechWorld Australia on Twitter at @Techworld_AU.

References

Automatic Resource Management in Java

Part of Project Coin is the ability to deal with Automatic Resource Management, or simply ARM. The purpose is to make it easier to work with external resources which need to be disposed or closed in case of errors or successful completion of a code block. Consider the following trivial file-copy operation, from the Java Bytestream Tutorial:

FileInputStream in = null;
FileOutputStream out = null;
try {
  in = new FileInputStream("xanadu.txt");
  out = new FileOutputStream("outagain.txt");
  int c;
  while ((c = in.read()) != -1)
    out.write(c);
} finally {
  if (in != null)
    in.close();
  if (out != null)
    out.close();
}

Not only is there a lot of boiler plate, but the documentation for InputStream.close() suggests that it can throw an IOException. (An exception is far more likely on the OutputStream but in any case, there needs to be an outer catch or propagation in order to successfully compile this code.)

The lexical scope of the try-catch-finally block also requires the variable for FileInputStream in and FileOutputStream out to be declared lexically outside the block itself. (If they were defined inside the try block, then they wouldn’t be available inside the catch or finally blocks.)

To eliminate this boilerplate code, and to tighten the lexical scoping of the resources used inside the block, a new addition has been made to the try block in the Java language. An initial specification of the try-with-resources blocks (or ARM blocks) was made available via an ininitial implementation, which has subsequently made its way into build 105 of JDK 7.

A new interface, java.lang.AutoCloseable, has been added to the proposed API, which defines a single method close() which throws Exception. This has been retro-fitted as a parent of java.io.Closeable, which means that all InputStream and OutputStream automatically take advantage of this behaviour. In addition, FileLock and ImageInputStream have also been fitted with the AutoCloseable interface.

This permits the above example to be written as:

try (
  FileInputStream in = new FileInputStream("xanadu.txt");
  FileOutputStream out = new FileOutputStream("outagain.txt")
) {
  int c;
  while((c=in.read()) != -1 )
    out.write();
}

At the end of the try block, whether by completion normally or otherwise, both the out and in resources will have close() called automatically. Furthermore, unlike our original example, both out.close() and in.close() are guaranteed to be executed. (In the original example, had in.close() thrown an exception, then the subsequent out.close() would not have been executed.)

There are some subtle aspects to this which are worth noting:

  • As it currently stands, a trailing semi-colon is not permitted after the final resource in the resources section.
  • The resources block is separated with () rather than the more usual {}, to separate it from the existing try body. If present, it must contain one or more resource definitions.
  • Each resource definition is of the form type var = expression; you can’t have general statements in the resource block.
  • The resources are implicitly final; that is, they behave as if the final modifier is present. Any attempt to assign to the resource variable is a compile-time error.
  • The resources must be a subtype of AutoCloseable; it is a compile-time error if this is not the case.
  • The order of closure is the reverse order in which the resources are defined. In other words, in the refined example, out.close() is called prior to in.close(). This permits nested streams to be built and then closed from outer-in, which makes more sense than in order (e.g. for flushing buffers before the underlying stream is closed).
  • Each block may generate n+1 exceptions, where n is the number of resources. This can occur if the main body throws an exception, and each resource closure throws an exception as well. In this situation, the body’s exception will be thrown, but the others will be added to the exception’s suppressed exception list. They can be accessed via getSuppressedExceptions().
  • Exception stack traces may now have code prefixed with Suppressed: in these cases; the format of the serialized Throwable is now different as well. (This may impact Java 6 clients invoking remote services on Java 7 runtimes, or vice-versa.)
  • javax.swing and java.sql do not participate in ARM at the current time; classes need to opt-in by inheriting from AutoCloseable to be used by ARM. JDBC 4.1, if part of JDK 7, will support ARM but it’s not clear when this will happen.

The ability to remove boilerplate code from the Java developer’s work-flow is likely to be a minor productivity boost; but although it’s available in JDK 7, it will be sometime before source code can be written to take advantage of that fact. Many libraries will need to be compiled to run against Java 6; and any use of the automatic resource management will only be applicable for code compiled with -target 7 (or similar). Once Java 6 is EOL and Java 8 has been released, then using ARM will become an automatic way of working.

Original article here

What Is Coding Dojo

A Coding Dojo is a meeting where a bunch of coders get together to work on a programming challenge. They are there have fun and to engage in DeliberatePractice in order to improve their skills.

The ParisDojo focuses on coding in front of others, most often something from scratch, in a very short amount of time (1 to 1.5 hours). They use various languages, various tools, various exercise formats. They consider the outcome of an exercise successful when it is completed within allocated time AND audience can repeat the exercise at home by themselves.

Maybe the CodingDojoPrinciples help to understand what the CodingDojo is about.

Read more…

Java: Types of Exception

Exception come is several flavours: RuntimeExceptions, Errors, Checked and Unchecked.

Type codes used in describing Exceptions
Letter Type Parent Class Checked?
(declare throws?)
Use
R Runtime java.lang.RuntimeException N Error that can occur in almost any code e.g. NullPointerException.
E Error java.lang.Error N Serious error you really should not try to catch, e.g. OutOfMemoryError.
C Checked java.lang.Exception Y Likely exceptional condition that can only occur in specific places in the code e.g. EOFException.

Collectively, RuntimeException, Error and Exception are derived from Throwable. RuntimeException is derived from Exception, which is derived from Throwable. Error is derived directly from Throwable. If you catch RuntimeException you will catch all manner of run time Exceptions (type R).
If you catch Error you will catch all manner of errors (type E).
If you catch Exception you will catch all manner of checked Exceptions and run time Exceptions (type R+C).
If you catch Throwable, you will catch everything, (Type R+E+C );
If the Exception is checked, you must either fob it off on the caller, with the throws clause or catch it yourself. Unchecked Exceptions are ones like running out of RAM that, in general you can’t do much about, or that are not associated with specific problematic code, or that are very common such as IllegalArgumentException or NullPointerException. You don’t have to catch unchecked Exceptions or explicitly fob them off on the caller with throws. The classification of an Exception is not an exact science. It is a little bit like the arbitrary assignment of gender in French or German to objects. You just have to look it up. There is a major clue, Error Exceptions end in the string “Error” while checked Exceptions and RuntimeExceptions end in the string “Exception”.

Specific Exceptions
Exception Name Type Package Notes
AbstractMethodError E java.lang  
AccessControlException R java.security This is an exception that is thrown whenever a reference is made to a non-existent ACL (Access Control
List). notes.
AccessException C java.rmi Thrown by certain methods of the java.rmi.Naming class.
AclNotFoundException C java.security.acl Thrown whenever a reference is made to a non-existent ACL (Access Control List).
ActivateFailedException C java.rmi.activation thrown by the RMI runtime when activation fails during a remote call to an activatable object.
ActivationException C java.rmi.activation  
AlreadyBoundException C javax.naming  
ApplicationException C org.omg.CORBA.portable Used for reporting application level exceptions between ORBs and stubs
ArithmeticException R java.lang Most commonly a divide by zero. notes.
ArrayIndexOutOfBoundsException R java.lang Can be handled more generically with IndexOutOfBoundsException. notes.
ArrayStoreException R java.lang Thrown to indicate that an attempt has been made to store the wrong type of object into an array of
objects. notes.
AttributeInUseException C javax.naming.directory  
AttributeModificationException C javax.naming.directory  
AuthenticationException C javax.naming  
AuthenticationNotSupportedException C javax.naming  
AWTError E java.awt  
AWTError E java/awt  
AWTException C java.awt  
BadLocationException C javax.swing.text This exception is to report bad locations within a document model.
BatchUpdateException C java.sql  
BindException C java.net Signals that an error occurred while attempting to bind a socket to a local address and port
CannotProceedException C javax.naming  
CannotRedoException R javax.swing.undo  
CannotUndoException R javax.swing.undo  
CertificateEncodingException C java.security.cert  
CertificateException C java.security.cert  
CertificateExpiredException C java.security.cert  
CertificateNotYetValidException C java.security.cert  
CertificateParsingException C java.security.cert  
ChangedCharSetException C javax.swing.text  
CharConversionException C java.io  
ClassCastException R java.lang notes.
ClassCircularityError E java.lang  
ClassFormatError E java.lang notes.
ClassNotFoundException C java.lang notes.
CloneNotSupportedException C java.lang  
CMMException R java.awt.color  
CommunicationException C javax.naming  
ConcurrentModificationException R java.util This exception may be thrown by methods that have detected concurrent modification of a backing object
when such modification is not permissible, e. g. two threads modifying a HashMap
simultaneously. notes.
ConfigurationException C javax.naming  
ConnectException C java.rmi  
ConnectIOException C java.rmi  
ContextNotEmptyException C javax.naming  
CRLException C java.security.cert CRL (Certificate Revocation List) Exception.
DataFormatException C java.util.zip  
DigestException C java.security  
EmptyStackException R java.util Thrown by methods in the Stack class to indicate that the stack is empty. Does not refer to the system
stack.
EOFException C java.io notes.
Error E java.lang Catches any serious error such as OutOfMemoryError that you unlikely can
recover from.
Exception C java.lang generic. Catches any specify Exception plus general Runtime exceptions, but not Errors.
ExceptionInInitializerError E java.lang notes.
ExceptionInInitializerError E java.lang  
ExpandVetoException C javax.swing.tree  
ExportException C java.rmi.server  
FileNotFoundException C java.io  
FontFormatException C java.awt  
GeneralSecurityException C java.security  
IllegalAccessError E java.lang notes.
IllegalAccessException C java.lang Thrown when an application tries to load in a class, but the currently executing method does not have
access to the definition of the specified class, because the class is not public and in another
package.
IllegalArgumentException R java.lang Most common exception to reject a bad parameter to a method.
IllegalComponentStateException R java.awt  
IllegalMonitorStateException R java.lang  
IllegalPathStateException R java.awt.geom  
IllegalStateException R java.lang Signals that a method has been invoked at an illegal or inappropriate time.
IllegalThreadStateException R java.lang  
ImagingOpException R java.awt.image  
IncompatibleClassChangeError E java.lang notes.
IndexOutOfBoundsException R java.lang Similar to ArrayIndexOutOfBoundsException for ArrayList.
IndirectionException R org.omg.CORBA.portable  
InstantiationError E java.lang  
InstantiationException C java.lang  
InsufficientResourcesException C javax.naming  
InternalError E java.lang  
InterruptedException C java.lang Thrown when a thread is waiting, sleeping, or otherwise paused for a long time and another thread
interrupts it using the interrupt method in class Thread.
InterruptedIOException C java.io  
InterruptedNamingException C javax.naming  
IntrospectionException C java.beans  
InvalidAlgorithmParameterException C java.security This is a GeneralSecurityException. See IllegalArgumentException.
InvalidAttributeIdentifierException C javax.naming.directory  
InvalidAttributesException C javax.naming.directory  
InvalidAttributeValueException C javax.naming.directory  
InvalidClassException C java.io notes.
InvalidDnDOperationException R java.awt.dnd  
InvalidKeyException C java.security  
InvalidKeySpecException C java.security.spec  
InvalidMidiDataException C javax.sound.midi  
InvalidNameException C javax.naming  
InvalidObjectException C java.io  
InvalidParameterException R java.security  
InvalidParameterSpecException C java.security.spec  
InvalidSearchControlsException C javax.naming.directory  
InvalidSearchFilterException C javax.naming.directory  
InvalidTransactionException C javax.transaction  
InvocationTargetException C java.lang.reflect  
IOException C java.io  
JarException C java.util.jar  
KeyException C java.security  
KeyManagementException C java.security  
KeyStoreException C java.security  
LastOwnerException C java.security.acl  
LdapReferralException C javax.naming.ldap  
LimitExceededException C javax.naming  
LineUnavailableException C javax.sound.sampled  
LinkageError E java.lang  
LinkException C javax.naming  
LinkLoopException C javax.naming  
MalformedLinkException C javax.naming  
MalformedURLException C java.net  
MarshalException C java.rmi  
MidiUnavailableException C javax.sound.midi  
MimeTypeParseException C java.awt.datatransfer  
MissingResourceException R java.util  
NameAlreadyBoundException C javax.naming  
NameNotFoundException C javax.naming  
NamingException C javax.naming  
NamingSecurityException C javax.naming  
NegativeArraySizeException R java.lang  
NoClassDefFoundError E java.lang notes.
NoInitialContextException C javax.naming  
NoninvertibleTransformException C java.awt.geom  
NoPermissionException C javax.naming  
NoRouteToHostException C java.net  
NoSuchAlgorithmException C java.security  
NoSuchAttributeException C javax.naming.directory  
NoSuchElementException R java.util  
NoSuchFieldError E java.lang  
NoSuchFieldException C java.lang  
NoSuchMethodError E java.lang notes.
NoSuchMethodException C java.lang  
NoSuchObjectException C java.rmi  
NoSuchProviderException C java.security notes.
NotActiveException C java.io Thrown when serialization or deserialization is not active
NotBoundException C java.rmi  
NotContextException C javax.naming  
NotOwnerException C java.security.acl  
NotSerializableException C java.io notes.
NullPointerException R java.lang Actually a null reference exception. notes.
NumberFormatException R java.lang Commonly thrown when a String is converted to internal binary numeric format. notes.
ObjectStreamException C java.io  
OperationNotSupportedException C javax.naming  
OptionalDataException C java.io Unexpected data appeared in an ObjectInputStream trying to read an Object. Occurs when the stream
contains primitive data instead of the object that is expected by readObject. The EOF flag in the exception
is true indicating that no more primitive data is available. The count field contains the number of bytes
available to read.
OutOfMemoryError E java.lang By the time this happens it is almost too late. gc has already done what it could. Possibly some
process has just started gobbling RAM, or perhaps the problem you are trying to solve is just too big for
the size of the allotted virtual ram. You can control that with the java.exe command line switches.
ParseException C java.text  
PartialResultException C javax.naming  
PolicyError E org.omg.CORBA  
PrinterAbortException C java.awt.print  
PrinterException C java.awt.print  
PrinterIOException C java.awt.print  
PrivilegedActionException C java.security  
ProfileDataException R java.awt.color  
PropertyVetoException C java.beans  
ProtocolException C java.net  
ProviderException R java.security  
RasterFormatException R java.awt.image  
ReferralException C javax.naming  
RemarshalException C org.omg.CORBA.portable  
RemoteException C java.rmi  
RMISecurityException C java.rmi  
RuntimeException R java.lang Error that can occur in almost any code e.g. NullPointerException. Use this
when to catch general errors when no specific exception is being thrown.
SchemaViolationException C javax.naming.directory  
SecurityException R java.lang  
ServerCloneException C java.rmi.server  
ServerError E java.rmi  
ServerException C java.rmi  
ServerNotActiveException C java.rmi.server  
ServerRuntimeException C java.rmi  
ServiceUnavailableException C javax.naming  
SignatureException C java.security  
SizeLimitExceededException C javax.naming  
SkeletonMismatchException C java.rmi.server  
SkeletonNotFoundException C java.rmi.server  
SocketException C java.net  
SocketSecurityException C java.rmi.server  
SQLException C java.sql  
StackOverflowError E java.lang notes.
StreamCorruptedException C java.io ObjectStream data are scrambled. notes.
StringIndexOutOfBoundsException R java.lang Can be handled more generically with IndexOutOfBoundsException. notes.
StubNotFoundException C java.rmi  
SyncFailedException C java.io  
SystemException R org.omg.CORBA  
TimeLimitExceededException C javax.naming  
TooManyListenersException C java.util  
TransactionRequiredException C javax.transaction  
TransactionRolledbackException C javax.transaction  
UndeclaredThrowableException R java.lang.reflect  
UnexpectedException R java.rmi  
UnknownError E java.lang  
UnknownException R org.omg.CORBA.portable  
UnknownGroupException C java.rmi.activation  
UnknownHostException C java.rmi  
UnknownHostException C java.net  
UnknownObjectException C java.rmi.activation  
UnknownServiceException C java.net  
UnknownUserException C org.omg.CORBA  
UnmarshalException C java.rmi notes.
UnrecoverableKeyException C java.security  
UnsatisfiedLinkError E java.lang notes.
UnsupportedAudioFileException C javax.sound.sampled  
UnsupportedClassVersionError E java.lang notes.
UnsupportedDataTypeException C java.io undocumented. notes.
UnsupportedEncodingException C java.io  
UnsupportedFlavorException C java.awt.datatransfer  
UnsupportedLookAndFeelException C javax.swing  
UnsupportedOperationException R java.lang Use for code not yet implemented, or that you deliberately did not implement.
UserException C org.omg.CORBA  
UTFDataFormatException C java.io  
VerifyError E java.lang notes.
VirtualMachineError E java.lang  
WriteAbortedException C java.io  
ZipException C java.util.zip notes.