Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Learn Java: Programming Articles, Examples and Tips - Page 393


Previous 1060 Stories (530 Pages, 2 Per Page) Next

Checking that your classpath is valid

Go to all tips in Story by Dr. Kabutz

The Java Specialists' Newsletter [Issue 037] - Checking that your classpath is valid

Author: Sydney Redelinghuys (with Dr. Heinz M. Kabutz in the peanut gallery)

JDK version:

Category: Software Engineering

You can subscribe from our home page: http://www.javaspecialists.co.za (which also hosts all previous issues, available free of charge Smile

Welcome to the 37th edition of "The Java(tm) Specialists' Newsletter", sent to 2103 Java experts in 62 countries. This week, my friend Sydney Redelinghuys has stepped in and provided the ideas for this newsletter, as well as most of the writing. Sydney was the brain behind the SoftHashMap newsletter that also made it onto DevX . I consider Sydney to be the 2nd best Java programmer that I know (position #1 is already given to Paul), [SR: So what position is given to HK] [HK: Position # 0 of course! ;-] but I marvel at the designs Sydney comes up with, I don't know anyone with such a knack for cool designs. Sydney found a copy of the Design Patterns book in the home economics section of his university (I will refrain from making comments regarding his university based on that last comment Wink)).

How do you go from being an OO beginner to an OO guru? Simple answer: Experience! But what if you can't wait 10 years to get that experience? Simple answer: Design Patterns! How can you learn Design Patterns from someone who has used them in the real world? Simple answer: Ask about my new course "Design Patterns - The Timeless Way of Coding".

Enough of my jabbering, let's see what Sydney, the one-legged Java Guru has to say ...


Checking Your Classpath Validity

The classpath - like most programmers, I really struggled with it in the beginning. I first cut my teeth on Java in middle of 1996 when I was a student doing some vacation work, as part of an experiment of using JDK 1.0 to solve the world's problems. As you might imagine, I caused more problems than I solved. I must've been the most underpaid Java programmer of all time - in today's South African currency terms, I only got US$ 272 for 2 months work (and that was with a 100% bonus)! Enough reminiscing, back to class paths. It is not that class paths are difficult to understand, it is just that it is too easy to get them wrong and not easy enough to locate errors, especially if you are used to case-insensitive NT paths. The classpath problem is so part of the Java culture that even The Onion reports on it! [HK: A must-read magazine for TJSN subscribers]

Even after I got more experienced it still seemed to eek its way into builds. In those days (before Ant and what not) we used to write huge batch files to check that all the required jars were available, I believe the company in question still does it Wink [HK: Actually, we had a chap who had an MCSE in WinNT 3.51 who was a real whizz at batch files. This, perhaps, was to our disadvantage.]

These days I am involved with Websphere, a product aimed at the Java professional who thinks he knows how Java works. This product will make even the seasoned Java expert quiver at his knees when he gets a MarshallException at run-time due to linkage errors often caused by an incorrect classpath. Note: in Websphere the classpath can be specified on at least three levels (container, server and node levels).

My first attempt at solving the marshall exception was to add another dynamic layer like any true geek developer. [HK: Sydney is truly the master of adding dynamic layers. That first Java program that he wrote for US$ 272 over 2 months took US$ 13500 of real professional Java programmers' time to debug.] Java does tend to make it too easy to do this with reflection, dynamic class loaders, dynamic proxies, soft references and all other kinds of weird & wonderful constructs this newsletter likes to comment on.

So, my first solution was to load the class files dynamically (via Class.forName(...)) and then to simply try catching the ClassNotFoundException:


try {
  Class my_class = Class.forName("ClassName");
} catch(ClassNotFoundException cnfe) {
  cnfe.printStackTrace();
}

Of course this worked, so now I could see the exception other application servers probably would have provided me with originally.

This really bugged me. I had to write compilers at varsity and I always thought I was doing the world a favour by doing compile time type checking etc. It surely is better to find a bug at compile time than at run-time, especially if your build-deploy cycle spirals into an affair that can take hours. [HK: With the batch files that we had originally the build cycle took so long that we could only do a weekly build!] [SR: I think the most time consuming part of that process was actually Source Safe]

Ant (or other similar build-tools) could solve some of these problems, unfortunately some of our components have to be deployed manually due to our IDE keeping information hidden. [HK: Isn't your IDE written in Java - perhaps you could use reflection to find the information dynamically and ... ] [SR: No such luck it is actually written in SmallTalk.]

So I asked myself: "Why does Sun keep the classpath hidden at runtime?" I decided to start digging in the jdk api's.

To load classes, the default class loader needs access to the classpath. The default class loader is very easy to get hold of, via the java.lang.ClassLoader.getSystemClassLoader static method. Unfortunately, the interface of java.lang.ClassLoader does not contain any methods that appear to be useful to us.

Just before I decided to start digging in the Sun source code, I noticed that java.security.SecureClassLoader extended java.lang.ClassLoader and java.net.URLClassLoader extended java.security.SecureClassLoader. By doing a quick experiment, I discovered that the System class loader (in the SUN VM) is indeed an instance of java.net.URLClassLoader. [HK: *evil grin*]

At this point I got all excited. Why? Because URLClassLoader contains a method getURLs() which returns the current classpath. So by writing the following small class, I can validate the classpath (i.e. make sure all the jars exist).

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

public class ClassPathInfo {
  private final ClassLoader classLoader;

  public ClassPathInfo(ClassLoader classLoader) {
    this.classLoader = classLoader;
  }

  public ClassPathInfo() {
    this(ClassLoader.getSystemClassLoader());
  }

  /**
   * validates classpath, throws an LinkageError if invalid
   * classpath was specified
   */
  public void validateClassPath() {
    try {
      URL[] urls = ((URLClassLoader)classLoader).getURLs();
      for(int i=0; itry {
          urls[i].openStream();
        } catch(IllegalArgumentException iae) {
          throw new LinkageError(
            "malformed class path url:
 "+urls[i]);
        } catch(IOException ioe) {
          throw new LinkageError(
            "invalid class path url:
 "+urls[i]);
        }
      }
    } catch(ClassCastException e) {
      throw new IllegalArgumentException(
        "The current VM's System classloader is not a "
        + "subclass of java.net.URLClassLoader");
    }
  }

  public static void main(String[] args) {
    ClassPathInfo info = new ClassPathInfo();
    info.validateClassPath();
  }
}

Now it is possible to add batch or script files to replace java and javac. I was planning to leave this as an exercise for the reader but Heinz would have none of that [HK: Incidentally, someone sent me the "exercise to the reader" parts of the CircularArrayList, if any of you are interested]. It turned out to be more difficult than it initially seemed, as it is tricky to make sure that ClassPathInfo is in the classpath.

Firstly if you are a Unix user I shall leave this as an exercise for the reader. [HK: awww, come-on Syd] If you are using Windows you need to copy the following three batch files with ClassPathInfo.class to somewhere on your PATH. You also need to change the STRICTHOME enviroment variable in checkcp.bat to the directory these files were copied into.

checkcp.bat

@echo off 
rem Set STRICTHOME to the directory you're deploying this file to.
set STRICTHOME=C:strictjava

if ""=="%3" (
  set STRICTCP="%CLASSPATH%;%STRICTHOME%"
) else (
  if -classpath==%1 (
    set STRICTCP="%2;%STRICTHOME%"
  )else (
    echo If more than three parameters are specified,
    echo the first has to be -classpath.
    set ERRORLEVEL=1
    goto end
  )
)

java -classpath %STRICTCP% ClassPathInfo
set STRICTHOME=
set STRICTCP=

:end

strictjavac.bat

@echo off
call checkcp %1 %2 %3
if not %errorlevel%==0 goto END
javac %1 %2 %3 %4 %5 %6 %7 %8 %9
:END

strictjava.bat

@echo off
call checkcp %1 %2 %3
if not %errorlevel%==0 goto END
java %1 %2 %3 %4 %5 %6 %7 %8 %9
:END

Please note that if you supply the classpath to these batch files, you will have to put it in quotes (i.e. strictjava -classpath "c:subjar1.jar;c:sub2jar2.jar" MyClass).

Regards

Sydney Redelinghuys (aka hopalong)


Copyright 2000-2004 Maximum Solutions, South Africa

Reprint Rights. Copyright subsists in all the material included in this email, but you may freely share the entire email with anyone you feel may be interested, and you may reprint excerpts both online and offline provided that you acknowledge the source as follows: This material from The Java(tm) Specialists' Newsletter by Maximum Solutions (South Africa). Please contact Maximum Solutions for more information.

Java and Sun are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Maximum Solutions is independent of Sun Microsystems, Inc.

8136 bytes more | comments? | Printer Friendly Page  Send to a Friend | Score: 5
Posted by jalex on Saturday, August 13, 2005 (00:00:00) (2889 reads)

More about JNLP - Java Network Launching Protocol...

Go to all tips in Networking

More about JNLP - Java Network Launching Protocol...

The Java Network Launching Protocol is a new Java protocol to allow remote applications to be downloaded and run on a client machine. All necessary class files, images, etc, can be downloaded, and do not need to be present on the client machine beforehand. This chapter looks at JNLP and compares it to Jini, and shows how the two can be used together to get the advantages of both

The concept of applets was one of the initial boosts for Java's success. However, while Java has gone from strength to strength, applets have fallen by the wayside. This is partly because the sandbox model is so tight that there is little you can do with them, but also because the Java runtime engines in the different browsers were inconsistent and often buggy, frequently causing the browser to crash.

THE JNLP is another approach to this type of problem, where remote code is sent to a browser for execution. Instead of running within the browser though, the code is run in a manner similar to CGI scripts by passing it to a Java runtime engine that runs as a separate application. There are plenty of mechanisms within JNLP to ensure safety in a variety of sandbox (or freer) models, and also to ensure that resources required are present (such as a late enough version of the Java runtime).

A JNLP application is described by a JNLP file, which is an XML do*****ent. Typically, this do*****ent will be downloaded by a Web browser. The browser itself will not know what to do with this file, so it will pass it to a "JNLP helper" to deal with. This is a standard browser technique, and allows a browser to call a Postscript viewer such as ghostscript to handle Postscript files, Adobe acrobat to handle PDF files, and so on. The JNLP helper will read the list of resources required and download them if necessary. It will also check that all constraints such as version of the Java runtime are satisfied. Once this is all done, the helper will start the Java application running.

A minimal JNLP file can be

File Classifier Application This states the codebase from where all resources will be drawn, the jar file containing the classes and the main class of an application (rather than an applet). This is enough for the helper to run the application.

3. Jini and JNLP Comparison

On the face of it, Jini and JNLP appear to occupy similar spaces in that they both allow code to be migrated to a client machine and to execute there. The following table summarises some of the differences and similarities

Jini JNLP
downloads a service downloads an application
a client must be running to request a service a browser must be running which calls a helper to start the application
each service looks after itself, independently of any clients each JNLP file specifies all required parts of an application; if any part changes, the JNLP file must be updated
the client may need to know the location of a lookup service, but not of any service the user of a JNLP application must know the URL of the JNLP file
no generic client generic JNLP helper
4. Combining Jini and JNLP

The whole book (Jan Newmarch's Guide to Jini Technologies) and chapter "Java Network Launching Protocol" you can read here.



comments? | Printer Friendly Page  Send to a Friend | Score: 4.5
Posted by Anonymous on Wednesday, August 10, 2005 (00:00:00) (4000 reads)

Previous 1060 Stories (530 Pages, 2 Per Page) Next

530| 529| 528| 527| 526| 525| 524| 523| 522| 521| 520| 519| 518| 517| 516| 515| 514| 513| 512| 511| 510| 509| 508| 507| 506| 505| 504| 503| 502| 501| 500| 499| 498| 497| 496| 495| 494| 493| 492| 491| 490| 489| 488| 487| 486| 485| 484| 483| 482| 481| 480| 479| 478| 477| 476| 475| 474| 473| 472| 471| 470| 469| 468| 467| 466| 465| 464| 463| 462| 461| 460| 459| 458| 457| 456| 455| 454| 453| 452| 451| 450| 449| 448| 447| 446| 445| 444| 443| 442| 441| 440| 439| 438| 437| 436| 435| 434| 433| 432| 431| 430| 429| 428| 427| 426| 425| 424| 423| 422| 421| 420| 419| 418| 417| 416| 415| 414| 413| 412| 411| 410| 409| 408| 407| 406| 405| 404| 403| 402| 401| 400| 399| 398| 397| 396| 395| 394|
393
| 392| 391| 390| 389| 388| 387| 386| 385| 384| 383| 382| 381| 380| 379| 378| 377| 376| 375| 374| 373| 372| 371| 370| 369| 368| 367| 366| 365| 364| 363| 362| 361| 360| 359| 358| 357| 356| 355| 354| 353| 352| 351| 350| 349| 348| 347| 346| 345| 344| 343| 342| 341| 340| 339| 338| 337| 336| 335| 334| 333| 332| 331| 330| 329| 328| 327| 326| 325| 324| 323| 322| 321| 320| 319| 318| 317| 316| 315| 314| 313| 312| 311| 310| 309| 308| 307| 306| 305| 304| 303| 302| 301| 300| 299| 298| 297| 296| 295| 294| 293| 292| 291| 290| 289| 288| 287| 286| 285| 284| 283| 282| 281| 280| 279| 278| 277| 276| 275| 274| 273| 272| 271| 270| 269| 268| 267| 266| 265| 264| 263| 262| 261| 260| 259| 258| 257| 256| 255| 254| 253| 252| 251| 250| 249| 248| 247| 246| 245| 244| 243| 242| 241| 240| 239| 238| 237| 236| 235| 234| 233| 232| 231| 230| 229| 228| 227| 226| 225| 224| 223| 222| 221| 220| 219| 218| 217| 216| 215| 214| 213| 212| 211| 210| 209| 208| 207| 206| 205| 204| 203| 202| 201| 200| 199| 198| 197| 196| 195| 194| 193| 192| 191| 190| 189| 188| 187| 186| 185| 184| 183| 182| 181| 180| 179| 178| 177| 176| 175| 174| 173| 172| 171| 170| 169| 168| 167| 166| 165| 164| 163| 162| 161| 160| 159| 158| 157| 156| 155| 154| 153| 152| 151| 150| 149| 148| 147| 146| 145| 144| 143| 142| 141| 140| 139| 138| 137| 136| 135| 134| 133| 132| 131| 130| 129| 128| 127| 126| 125| 124| 123| 122| 121| 120| 119| 118| 117| 116| 115| 114| 113| 112| 111| 110| 109| 108| 107| 106| 105| 104| 103| 102| 101| 100| 99| 98| 97| 96| 95| 94| 93| 92| 91| 90| 89| 88| 87| 86| 85| 84| 83| 82| 81| 80| 79| 78| 77| 76| 75| 74| 73| 72| 71| 70| 69| 68| 67| 66| 65| 64| 63| 62| 61| 60| 59| 58| 57| 56| 55| 54| 53| 52| 51| 50| 49| 48| 47| 46| 45| 44| 43| 42| 41| 40| 39| 38| 37| 36| 35| 34| 33| 32| 31| 30| 29| 28| 27| 26| 25| 24| 23| 22| 21| 20| 19| 18| 17| 16| 15| 14| 13| 12| 11| 10| 9| 8| 7| 6| 5| 4| 3| 2| 1|


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy