Showing posts with label JSE6. Show all posts
Showing posts with label JSE6. Show all posts

Thursday, October 09, 2014

How do I check if a Class is an instanceof another Class without initializing it?

Illustration: Cathy Wilcox
We had a recent security audit and a question was posed about how to check a Class without doing an instanceof. This turned out to be a great learning experience. There were a couple of issues that needed to be resolved, first we were loading a Class by passing in its name using something similar to the line below: This will load the Class, but from here how do we check that it is an instanceof without instantiating it?
This can be solved by using isAssignableFrom(Class clazz) as shown below. In this case we are checking if SolientGreen is Green. Some of you will find the moral paradox of being "Green" with Soilent Green.
The second issue is a more potential security problem. How do we load the Class without initializing it. If the Class has a static initializer, the code is executed when the class is loaded. Alas, this is handled by using a variation of Class.forName(String name, boolean initialize, ClassLoader loader) which takes a boolean to determine if the class should be initialized, and a ClassLoader if you want to specify a specific loader.

Finally, we can check the Class like this: When this is run, you will not see the message. Very nice indeed!

So here is the remaining code for education and entertainment:
The code for the project can be downloaded from Bitbucket here: assignable

Monday, March 11, 2013

Java 6 File Monitoring Example

I was asked today how you would monitor a file for changes using Java 6. Since Java 7 has added some great File handling features that I use, it was a reminder that not everyone is so lucky to use Java 7. I remembered an example from Geosoft (I remembered it because I liked the name). I went looking and I found their example code FileMonitor.java. It is a simple and elegant solution to monitoring files and directories for changes.

This is by no means a complete example, but does show a simple technique.

Thursday, December 15, 2011

Java Tip of the Day: Using ProcessBuilder to Make System Calls

A few years ago I posted an article on how to execute OS level system calls using the Runtime class. When I wrote that article I was using a methodology which has been around since the 1.0 days of Java. In Java 5 Standard Edition, and subsequently improved in Java 6 and Java 7, is a class called ProcessBuilder. This class is a significant improvement over using the Runtime class. It provides complete flexibilty around the system call in terms of environment including directories, input and output streams, and execution.

Here is the NetBeans 7.1 Apache Maven project: process-builder-example.zip


When I execute it from NetBeans I get something like this:
[exec:exec]
total 24
drwxr-xr-x  12 jyeary  staff   408B Dec 15 08:19 .hg
-rw-r--r--   1 jyeary  staff    52B Dec 15 08:08 .hgignore
-rw-r--r--   1 jyeary  staff   1.7K Dec 15 07:59 nbactions.xml
-rw-r--r--   1 jyeary  staff   2.0K Dec 15 08:19 pom.xml
drwxr-xr-x   4 jyeary  staff   136B Dec 14 23:31 src
drwxr-xr-x   4 jyeary  staff   136B Dec 15 08:35 target
Exit Status : 0

Sunday, June 26, 2011

How to Check JDK Supported Encodings and Locales

A map of the various different languages in EuropeImage via Wikipedia
I was working on an issue with a customer about supported locales.  The JDK comes in two varieties: one is for only western languages including European languages, and the other is multilingual. This includes languages like Thai which have different glyphs. The supported encodings for Java 6 are defined here: Supported Encodings. The issue was a download of the standard JDK download on Windows which does not include charsets.jar for use in an international application.

I figured out the issue by creating a simple web application to check the encodings. I figured I would provide it just in case other folks may be able to use it Otherwise it would just be good simple code gone to waste. Here is a link to the maven project: SupportedLocales.zip


Enhanced by Zemanta

Thursday, June 23, 2011

NetBeans 7.0 Tip: Generating SerialVersionUID for Serializable Objects

If you are doing any work on a class which implements Serializable, you should take the time to generate a unique serialVersionUID for the class. By default, the IDE will add a serialVersionUID which is defined as 1L.This is a rather poor substitute for doing it correctly. The serialVersionUID is extremely important in Web Development (Session scoped beans must be Serializable), and in Java Persistence API (JPA) which needs to be able to serialize entities.

I have covered this plugin in a previous blog post, but there is an updated NetBeans plugin to help you with serialization. The Kenai project is located here: serialVersionUID generator for Netbeans. The actual downloadable nbm for NetBeans 7.0 is located here: eu-easyedu-netbeans-svuid.nbm. It was the first plugin I looked for when I installed NetBeans 7.0.
Enhanced by Zemanta

Friday, September 11, 2009

Using JTabbedPane on Swing Application Framework (JSR-296)

I was trying to figure out how to set the selected tab for a multi-tab JTabbedPane on my Swing Application Framework application. I thought that a quick Google search would have a simple answer. This was not the case. I found a post on a forum where a number of other people were wondering how to do it. So here is a summary of how I did it.

On the Frameview, I added a method as show below:

public void setSelectedTab (Integer tabIndex) {
tabPanel.setSelectedIndex(tabIndex);
}


The tabPanel in my case is the JTabbedPane instance.

In the SingleFrameApplication, I modified the startup() method to display the tab I want.

Note: You must set it after a call to show() the FrameView

@Override
protected void startup() {
FrameViewImpl frameView = new FrameViewImpl(this);
show(frameView);
//This must be done after the GUI is displayed
frameView.setSelectedTab(0);
}

Sunday, August 31, 2008

Sun™ Certified Java™ Programmer Boot Camp

The Greenville Java Users Group (GreenJUG) is conducting an ten (10) week boot camp to prepare its members for the CX-310-065 exam. It is a great opportunity to get a better understanding of Java™ and a obtain a valuable industry certification.

The code examples, books, and notes can be found on the Blue Lotus Software Sun™ Certified Java™ Programmer (SCJP) Boot Camp site. All of the code is Open Source Apache 2 licensed. The schedule for classes and final exam preparation are on the GreenJUG site.

Saturday, June 28, 2008

Java RandomAccessFile Example

Here is another example of how to use a common file handling mechanism in Java. RandomAccessFile is very powerful tool to open a file and find specific items in it. It also allows you to update, delete, or append data to the file. Developers become accustomed to using File for a number of operations, but I contend that using RandomAccessFile is more powerful and flexible.

In the code example and Netbeans project that follow, I create a file and append data to it. I print the data out, and then add the class name to the beginning of the file, append the existing data, and print it back out again.

I originally came across my work on it when I was learning Java many years ago. I re-examined it, tweaked it, and converted it to a Netbeans project.

1 /*
  2  * 
  3  * Blue Lotus Software, LLC
  4  * 
  5  * Copyright 2008. All Rights Reserved.
  6  * 
  7  * $Id$
  8  * 
  9  */
 10 /*
 11  * Copyright (C) 2008 Blue Lotus Software. All Rights Reserved.
 12  *
 13  * THIS SOFTWARE IS PROVIDED "AS IS," WITHOUT A WARRANTY OF ANY KIND.
 14  * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 15  * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 16  * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. 
 17  * BLUE LOTUS SOFTWARE, LLC AND ITS LICENSORS SHALL NOT BE LIABLE 
 18  * FOR ANY DAMAGES OR LIABILITIES
 19  * SUFFERED BY LICENSEE AS A RESULT OF  OR RELATING TO USE, MODIFICATION
 20  * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL
 21  * BLUE LOTUS SOFTWARE, LLC OR ITS LICENSORS BE LIABLE FOR ANY LOST 
 22  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, 
 23  * CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED 
 24  * AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE 
 25  * OF OR INABILITY TO USE SOFTWARE, EVEN IF BLUE LOTUS SOFTWARE, LLC 
 26  * HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 27  *
 28  * You acknowledge that Software is not designed, licensed or intended
 29  * for use in the design, construction, operation or maintenance of any
 30  * nuclear facility.
 31  */
 32 package com.bluelotussoftware.j2se.examples;
 33
 34 import java.io.FileNotFoundException;
 35 import java.io.IOException;
 36 import java.io.RandomAccessFile;
 37 import java.util.logging.Level;
 38 import java.util.logging.Logger;
 39
 40 /**
 41  *
 42  * @author John Yeary
 43  * @version 1.0
 44  */
 45 public class RandomAccessFileExample {
 46
 47     private static final String CLASSNAME = RandomAccessFileExample.class.getName();
 48     private static Logger logger = Logger.getLogger(CLASSNAME);
 49
 50     /**
 51      * @param args the command line arguments
 52      */
 53     public static void main(String[] args) {
 54
 55         if (args.length < 1) {
 56             System.err.print("You must provide at least a file name with path!");
 57             logger.log(Level.WARNING, "You must provide at least a file name with path");
 58             System.exit(0);
 59         }
 60
 61         RandomAccessFile raf = null;
 62
 63         try {
 64             raf = new RandomAccessFile(args[0], "rw");
 65         } catch (FileNotFoundException e) {
 66             logger.log(Level.SEVERE, null, e);
 67             // Error, set return to 1, and exit 
 68             System.exit(1);
 69         }
 70
 71         for (int i = 1; i < args.length; i++) {
 72             try {
 73                 raf.seek(raf.length());
 74                 raf.writeBytes(args[i] + "\n");
 75             } catch (IOException e) {
 76                 logger.log(Level.SEVERE, null, e);
 77             }
 78         }
 79
 80         try {
 81             raf.close();
 82         } catch (IOException e) {
 83             logger.log(Level.SEVERE, null, e);
 84         }
 85
 86         RandomAccessFileExample.readRAF(args[0]);
 87
 88         try {
 89             raf = new RandomAccessFile(args[0], "rw");
 90
 91             /* If you call seek() before you read, it will not work
 92              * as expected. The read operation will move the cursor
 93              * to the end of the read method.
 94              */
 95             //raf.seek(0); 
 96
 97             byte[] b = new byte[(int) raf.length()];
 98             raf.read(b);
 99
100             /* Here we place the seek() method to append to
101              * start writing at the beginning of the file.
102              */
103             raf.seek(0);
104             raf.writeBytes(CLASSNAME + "\n");
105
106             // Append the original content of the file.
107             raf.write(b);
108             raf.close();
109         } catch (IOException ex) {
110             logger.log(Level.SEVERE, null, ex);
111         }
112         RandomAccessFileExample.readRAF(args[0]);
113     }
114
115     public static void readRAF(String fileName) {
116         try {
117             RandomAccessFile raf = new RandomAccessFile(fileName, "r");
118             String line = null;
119             while ((line = raf.readLine()) != null) {
120                 System.out.println(line);
121                 logger.log(Level.INFO, line);
122             }
123         } catch (FileNotFoundException ex) {
124             logger.log(Level.SEVERE, null, ex);
125         } catch (IOException ex) {
126             logger.log(Level.SEVERE, null, ex);
127         }
128     }
129 }

UPDATED 12/29/2009
The Netbeans project is here: RandomAccessFile.zip

Here is an example of how to delete a String value from the file.

public static void deleteRAF(String value, String fileName) {
        try {
            RandomAccessFile raf = new RandomAccessFile(fileName, "rw");
            long position = 0;
            String line = null;
            while ((line = raf.readLine()) != null) {
                System.out.println("line::line.length()::position::getFilePointer()");
                System.out.println(line + "::" + line.length() + "::" + position + "::" + raf.getFilePointer());
                logger.log(Level.INFO, line);

                if (line.equals(value)) {
                    //Create a byte[] to contain the remainder of the file.
                    byte[] remainingBytes = new byte[(int) (raf.length() - raf.getFilePointer())];
                    System.out.println("Remaining byte information::" + new String(remainingBytes));
                    raf.read(remainingBytes);
                    //Truncate the file to the position of where we deleted the information.
                    raf.getChannel().truncate(position);
                    System.out.println("Moving to beginning of line..." + position);
                    raf.seek(position);
                    raf.write(remainingBytes);
                    return;
                }
                position += raf.getFilePointer();
            }
        } catch (FileNotFoundException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }

Friday, June 27, 2008

Putting the Current Directory in the CLASSPATH

Someone from our users group posed a good question. Should you put the current directory in the CLASSPATH? Does it represent any security issues like on UNIX?

Here is the answer...depends, but it is generally a bad idea. Here is an example. I created a class called TestCase. It calls another class called ClassA in a jar file called ExampleJar.jar. I put another class called ClassA in the current directory and set the CLASSPATH as a passed parameter

java -classpath .:./lib/ExampleJar.jar TestCase
Here are the classes:


1 public class TestCase {
2
3 public TestCase() {
4 }
5
6 public static void main(String[] args) {
7 ClassA a = new ClassA();
8 a.print();
9 }
10 }


1 public class ClassA {
2
3 public void print() {
4 System.out.println("I am ClassA in a jar.");
5 }
6 }


1 public class ClassA {
2
3 // Bad apple!!!
4 public void print() {
5 System.out.println("I am ClassA in the wild...");
6 }
7 }


The question becomes which one of the ClassA files gets called? The legitimate one, or the bad apple?

[sundev:Desktop:root]#java -classpath .:lib/ExampleJar.jar TestCase
I am ClassA in the wild...
If I reverse the order to java -classpath lib/ExampleJar.jar:. TestCase

I get the expected result:

[sundev:Desktop:root]#java -classpath lib/ExampleJar.jar:. TestCase
I am ClassA in a jar.
The Classloader finds the first instance of the class which matches the appropriate signature and loads it. Subsequent classes of the same name and signature are not loaded.

Why does it matter?

The inclusion of the current directory into the CLASSPATH represents a potential security risk, also it may produce unexpected results from similarly named classes. The second item may be a bit more contrived in general terms, i.e. com.abc.ClassA and com.cba.ClassA are called ClassA, but are in different packages. This will not represent a problem.

The security issue can be real. A lot of programs that do installs on Windows specifically, add the CLASSPATH variable to the Windows environment and put the . (period) first. I checked my installation and found it to be the case. I would not knowingly put it there myself. Also I checked a couple of tutorials which suggest that you should do it for convenience. That piece is quickly forgotten 200 pages ago.

ADDENDUM:

Java 6 SE (J6SE) has added some additional enhancements around classpath. You can use the * (asterisk) wildcard to include all files in the classpath:

java -cp "*"; TestCase (Windows)
java -cp '*' TestCase (Unix/OS X)

Mark Reinhold has a blog entry entitled Class-Path Wildcards in Mustang which details it.

Friday, February 01, 2008

Java Generics and Collections

The Java Generics book provides an in-depth analysis of the new Generics and Collections APIs in Java 5 and 6. The book provides a level of detail on this new technology that can not be found elsewhere. This book is generally not for a novice programmer due to the level of architectural details and theory. It provides a seasoned programmer with a comprehensive examination of why and how the Generics and Collections APIs were modified, as well as, the design decisions and impact. The book provides the programmer with the information they need to make informed decisions on which type of Collection to use, and the associated pitfalls based on design decisions.

The only issue I found with the book was that it did not provide enough concrete examples. The code was provided generally in code snippets which do not provide enough detail.

The book is a definite choice for the advanced Java programmer and architect. If you are serious about learning these new technologies: this is the book to get.

Sunday, October 21, 2007

Murach's Java SE 6

There have been a number of books and tutorials written about Java. The gold standard for me has always been "Learning Java" by Patrick Niemeyer and Johnathan Knudsen (O'Reilly & Associates). I have had a number of new programmers, enthusiasts, and members of the JUG tell me it is information overload. The book does contain a lot of information in its 828 page heft. As a result, I have been looking for a book just for beginners. I have found it.

I just completed reviewing Murach's Java SE 6. It is a very good resource for learning Java. This book does an excellent job of providing a firm basis for understanding the technology. The book is clearly and concisely written. The book is divided into 5 major sections which cover the essential Java skills to advanced topics on data access programming using XML and JDBC.

The teaching style is very clever. It typically takes the form of a page of information with facing page with examples. I found this to be very important in getting sometimes difficult points across. I typically take the "Show me the code" philosophy, and this style works for me.

The other technique that used is to convey a purpose for learning Java. This is done by using the various topics as building blocks to create an application. The final result is a completed application at the end of the book. It encompasses the lessons learned, and gives the new programmer a sense of accomplishment with a completed functional application at the end of the book. I love it.

I have found that people learn better with functional code examples. This book is replete with them. One of my greatest annoyances is to have code samples which do not work. This clouds the ability to learn because it forces the beginning programmer to question their abilities. The shroud of uncertainty should not be because the gold standard code is incorrect. I am pleased to note that I tried a number of code examples and they all worked.

My favorite section is Data access programming with Java. Chapter 20 covers working with XML. This is a must for any programmer. XML is the new black, and anything that can help you learn this important technology is a must. In chapter 20, the topic of StAX is covered. This is the best simplified example of using StAX I have seen. After reading the information, and performing the examples, I felt I had a better understanding of this technology.

I only have a few minor negative points to mention: the title is a little misleading. The majority of the information in the book really details Java SE 5 enhancements with two notable exceptions: StAX and an introduction to Derby (Java DB). The water is chummed in Chapter 1 where he mentions that C# runs faster than Java. This is a point that needs to be proven. Java 6 SE is almost as fast as C/C++ on bare metal. I have not heard anything like this for C#. I will forgive this remark though since the rest of the book is so well written.

My overall impression is that the book is an outstanding resource for new and seasoned programmers. This is a great book to add to the reference shelf.

The publisher has a number of code samples, student workbooks, and tutorials:

Student and Trainer Resources (Publisher)

Popular Posts