Java Introspection

What JavaBeans know about them selves.

In another article I already wrote about JavaBeans and briefly mentioned Introspection. In this post I include a more advanced example of Introspection. The example below uses the Introspector class which provides a standard way for tools to learn about the properties, events, and methods supported by a target JavaBean.
For each of those three kinds of information, the Introspector will separately analyze the bean’s class and superclasses looking for either explicit or implicit information and use that information to build a BeanInfo object that comprehensively describes the target bean:

try {
    BeanInfo bi = Introspector.getBeanInfo(MyBean.class);
    PropertyDescriptor[] pds = bi.getPropertyDescriptors();
    for (int i=0; i<pds.length; i++) {
        // Get property name
        String propName = pds[i].getName();
    }
    // class, prop1, prop2, PROP3
} catch (java.beans.IntrospectionException e) {
}

public class MyBean {
    // Property prop1
    public String getProp1() {
        return null;
    }
    public void setProp1(String s) {
    }

    // Property prop2
    public int getProp2() {
        return 0;
    }
    public void setProp2(int i) {
    }

    // Property PROP
    public byte[] getPROP3() {
        return null;
    }
    public void setPROP3(byte[] bytes) {
    }
}

Apache Axis, real time remote SOAP API’s

Introduction

I wrote about SOA elsewhere in this site. It’s Service Oriented Architecture based on well described services which can be accessed trough the http protocol. This is essential to prevent routers which block all kinds of ports not to prevent our Service Oriented Architecture.

Apache Axis

Axis is yet another fine Apache project which enables us to make services available in a truely amazing easy way! Apache Axis is above all very easy to use since it’s built in in most IDE’s. Eclipse is one of them and creating a Service with Eclipse is really a piece of cake. It’s really as easy as right-clicking a JavaBean and selecting “Generate Web Application”. Eclipse will then take over and go ahead generating the service. Next to the Service it will also generate:

  • A WSDL file.
  • A (JSP based client) to test your service.
  • API Documentation (for the Consumers of your Service).
Creating a Client

In Eclipse this is even more easy. Right click the WSDL and select “Generate Web-Service Client. Eclipse goes to work and produces a skeleton of Java Classes and interfaces which you need to get the client working!

What type of Programs are worth generating services for?

It depends. Do you want to do SOA? Then your service should be as elementary as possible. (Atomic). A generic service could be anything, Database lookups, Conversions and more functions which can be useful for public users.

 

Testing in Java

Introduction

In the Java Programming language we use a discipline for testing called Test Driven Development (TDD). It’s the way we Develop Java Applications. Before we actually start writing code we first create a JUnit test case. This is just our functional code but enhanced with assertions that makes sure that the code will work as expected.

JUnit
JUnit

This may seem overkill but actually it’s a big timesaver because it’s automated. Once we  know what our class should do we start coding it as a Test Case. In order to enable this, we add the Junit Jar in our Classpath and start coding.

Real world advantages

Everyone who ever did Application Support will understand the advantages. When something is wrong and you’re job is to figure out what it is you definitely profit from knowing which parts of the Application are definitely good and can be excluded from testing manually. Also deployment is much easier and more professional when you can deliver the project together with a professional looking test report.

Building Projects

After the Java development is done we extract the functional code and start working on the build script. This can either be done with Apache Ant or Apache Maven. The latter has the advantage of being dependancy aware, which is a big advantage because it will automatically download the required dependancies during the building process.

In the building scripts (whichever we use, the Junit tests are all included and executed during building. With every build a nice looking test report is generated which shows us if everything is still working as expected.

Continuous Integration

For big projects which are continuously updated there is Continuous integration. The project is buid over and over again. This is done by a Web Application which resides on a Servlet Container or Web Application Server. The Web Application is usually Apache Jenkins. It’s widely used in the larger Open Source projects. You can see Jenkins in action at https://builds.apache.org/. Open the link and choose a project. You can also choose to monitor the projects life.

Conclusion

Java Junit testing makes it easier for Java Developers to produce high quality and stable code. It also saves time and efforts.

 

 

What are JavaBeans?

ejwagenaar.com logo

What are JavaBeans?

According to Wikipedia:

JavaBeans are classes that encapsulate many objects into a single object (the bean). They are serializable, have a zero-argument constructor, and allow access to properties using getter and setter methods. The name “Bean” was given to encompass this standard, which aims to create reusable software components for Java.

According to Evert:

A JavaBean is a normal class with a few properties:

  • Javabeans have a zero argument Constructor. They cannot be instantiated with Data. The data is always added after the instantiation.
  • JavaBeans implement the Serializable interface which make them serializable.
  • All class-members are private.
  • To access data inside the class you need to create so-called ‘Accessor methods’ these are the getters and setters. You can only change the values of the class members by calling setProperty(). The same thing is true to get read the private class-members. This is done by the getters. getProperty().
  • Accessor Methods have a naming convention as follows: Lowecas get or set, followed by the property name (capitalized) so if the bean has a property called id, it’s accessor-methods become getId() and setId().
  • JavaBeans can be serialized.
  • Javabeans know things about theirselves. This is called Introspection.
So what are they used for?

JavaBeans are typically used as data-carriers, for example a JavaBean can be used to represent a Database Table Row, which makes sense in a DAO (Data Access  Object). This is indeed one of the most common applications of JavaBeans.

Utilities
Example of Introspection.

As I already mentioned, JavaBeans can look inside themselves, for example to get the class name:

// Get the fully-qualified name of a class
Class cls = java.lang.String.class;
String name = cls.getName();        // java.lang.String

// Get the fully-qualified name of a inner class
cls = java.util.Map.Entry.class;
name = cls.getName();               // java.util.Map$Entry

// Get the unqualified name of a class
cls = java.util.Map.Entry.class;
name = cls.getName();
if (name.lastIndexOf('.') > 0) {
    name = name.substring(name.lastIndexOf('.')+1);  // Map$Entry
}
// The $ can be converted to a .
name = name.replace('$', '.');      // Map.Entry


// Get the name of a primitive type
name = int.class.getName();         // int

// Get the name of an array
name = boolean[].class.getName();   // [Z
name = byte[].class.getName();      // [B
name = char[].class.getName();      // [C
name = short[].class.getName();     // [S
name = int[].class.getName();       // [I
name = long[].class.getName();      // [J
name = float[].class.getName();     // [F
name = double[].class.getName();    // [D
name = String[].class.getName();    // [Ljava.lang.String;
name = int[][].class.getName();     // [[I

// Get the name of void
cls = Void.TYPE;
name = cls.getName();               // void

A more complex example of Introspection can be found here.

The java.net.URL

ejwagenaar.com logo

 

Introduction

Above everything the Java Programming language was designed to

be a Networking Language by Sun Microsystems early nineties Sun’s slogan was “The Network is the Computer”.

Actually John Gage wasn’t completely right. Although it has become true for some systems   Computers are still the Computer, weather they are smartphones, smart watches, PC’s, Macs, iPads, Android tablets or Virtual Machines are still the real computers. Although they have become more and more connected and serve the API’s which  are accessed trough the networks.

Public API’s are becoming more and more available and are used as services which indeed make the Network. The coming of SOA slowly is making things better.

Time to see how you can connect to a (web) service using the java.net API.

Opening and reading from a url

In java.net the Opbject which represents an url is the URL object. You can instantiate it as follows:

URL url = new URL("http://www.ejwagenaar.com");

The next step is to open a connection:

HTTPUrlConnection con = url.openConnection();

Now we are ready to read from the connection. This is similar to reading from a file:

 

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine())
          != null) 
          System.out.println(inputLine);
        in.close();
    }
}

This prints the html of my homepage to the console. If you want to write it to disk, follow the instructions on writing to a file.

As you can see, the methods for java.io are consistent everywhere, which makes the Java programming language easy to learn.

i/o streams should always be closed!!!

Conclusion

This article demonstrates how to make a http connection and read a full HTML page from an HTTP connection using only plain Java objects. In another article we will post something to the http server.

 

The Java Math Class

ejwagenaar.com logo

 

Introduction

Java.Math does exactly what it’s name implies. Mathematics. There’s something special is going on with the math class. It’s methods are all static. In other words they don’t have to be initialized. You can call them all in the static way, e.g. without the ‘new’ keyword. So to compute the sqare of a value we say:

Math.square(value);

Other examples of simple calculations:

Math.round(number to round);
Math.ceil(Number to Ceil);

Etcetera…..

Math also introduces special numbers like the BigDecimal.

// Create via a string
BigDecimal bd1 = new BigDecimal("123456789.0123456890");

// Create via a long
BigDecimal bd2 = BigDecimal.valueOf(123L);

bd1 = bd1.add(bd2);
bd1 = bd1.multiply(bd2);
bd1 = bd1.subtract(bd2);
bd1 = bd1.divide(bd2, BigDecimal.ROUND_UP);
bd1 = bd1.negate();

As you see the BigDecimal is an exception. It’s an encapsulated class, similar to Integer, Boolean or Char.

Some more examples:

// Create via a string
BigInteger bi1 = new BigInteger("1234567890123456890");

// Create via a long
BigInteger bi2 = BigInteger.valueOf(123L);

bi1 = bi1.add(bi2);
bi1 = bi1.multiply(bi2);
bi1 = bi1.subtract(bi2);
bi1 = bi1.divide(bi2);
bi1 = bi1.negate();
int exponent = 2;
bi1 = bi1.pow(exponent);
// Get a byte array
byte[] bytes = new byte[]{(byte)0x12, (byte)0x0F, (byte)0xF0};

// Create a BigInteger using the byte array
BigInteger bi = new BigInteger(bytes);

// Format to binary
String s = bi.toString(2);      // 100100000111111110000

// Format to octal
s = bi.toString(8);             // 4407760

// Format to decimal
s = bi.toString();              // 1183728

// Format to hexadecimal
s = bi.toString(16);            // 120ff0
if (s.length() % 2 != 0) {
    // Pad with 0
    s = "0"+s;
}


// Parse binary string
bi = new BigInteger("100100000111111110000", 2);

// Parse octal string
bi = new BigInteger("4407760", 8);

// Parse decimal string
bi = new BigInteger("1183728");

// Parse hexadecimal string
bi = new BigInteger("120ff0", 16);

// Get byte array
bytes = bi.toByteArray();

 

Traversing all files under a Directory with java.util.File

ejwagenaar.com logo

Today I had this requirement.

I have a large collection of HTML on my local SSD. I downloaded a complete site with the wget command in order to do this  I used the command below:

wget --mirror --convert-links --adjust-extension --page-requisites 
--no-parent http://www.yoursite.org

This downloads the full website to your current directory, including scripts, CSS-files, graphics and videos. Then I needed to access all HTML files to clean them. I wanted to use Java so had to write a recursive function. After some attempts I got the following code. After the weekend I hope to be finished with the project and put the results online.

// Process all files and directories under dir
public static void visitAllDirsAndFiles(File dir) {
    process(dir);

    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
         //Recursive call:
           visitAllDirsAndFiles(new File(dir, 
           children[i]));
        }
    }
}

// Process only directories under dir
public static void visitAllDirs(File dir) {
    if (dir.isDirectory()) {
        process(dir);

        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            visitAllDirs(new File(dir, children[i]));
        }
    }
}

// Process only files under dir
public static void visitAllFiles(File dir) {
    if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i=0; i<children.length; i++) {
            visitAllFiles(new File(dir, children[i]));
        }
    } else {
        process(dir);
    }
}

In my case I only need some parts of the HTML code, which I want to transfer to MySQL. (The project I’m working on is a webscraping project).

I hope to be able to show you more details after the weekend. So stay tuned!

Windows 10 Pro Activation keys

Windows 10 Pro Activation Keys

I found these on the web when dowloading Win 10 Pro.

  • Windows 10 Pro: W269N-WFGWX-YVC9B-4J6C9-T83GX
  • Windows 10 Education: NW6C2-QMPVW-D7KKK-3GKT6-VCFB2
  • Windows 10 Enterprise: NPPR9-FWDCX-D2C8J-H872K-2YT43
Windows 10 EditionProduct Key
Windows 10 HomeTX9XD-98N7V-6WMQ6-BX7FG-H8Q99
Windows 10 Home Single Language7HNRX-D7KGG-3K4RQ-4WPJ4-YTDFH
Windows 10 Home Country Specific (CN)PVMJN-6DFY6-9CCP6-7BKTT-D3WVR
Windows 10 Home N3KHY7-WNT83-DGQKR-F7HPR-844BM
Windows 10 ProfessionalW269N-WFGWX-YVC9B-4J6C9-T83GXVK7JG-NPHTM-C97JM-9MPGT-3V66T8N67H-M3CY9-QT7C4-2TR7M-TXYCV
Windows 10 Professional NMH37W-N47XK-V7XM9-C7227-GCQG92B87N-8KFHP-DKV6R-Y2C8J-PKCKT
Windows 10 EnterpriseNPPR9-FWDCX-D2C8J-H872K-2YT43XGVPP-NMH47-7TTHJ-W3FW7-8HV2CCKFK9-QNGF2-D34FM-99QX3-8XC4K
Windows 10 Enterprise NDPH2V-TTNVB-4X9Q3-TJR4H-KHJW4WGGHN-J84D6-QYCPR-T7PJ7-X766F
Windows 10 Enterprise SFWN7H-PF93Q-4GGP8-M8RF3-MDWWW
Windows 10 EducationNW6C2-QMPVW-D7KKK-3GKT6-VCFB2YNMGQ-8RYV3-4PGQ3-C8XTP-7CFBY
Windows 10 Education N2WH4N-8QGBV-H22JP-CT43Q-MDWWJ84NGF-MHBT6-FXBX8-QWJK7-DRR8H
Windows 10 Enterprise 2015 LTSBWNMTR-4C88C-JK8YV-HQ7T2-76DF9
Windows 10 Enterprise 2015 LTSB N2F77B-TNFGY-69QQF-B8YKP-D69TJ
Windows 10 CoreKTNPV-KTRK4-3RRR8-39X6W-W44T3
Windows 10 Core Single LanguageBT79Q-G7N6G-PGBYW-4YWX6-6F4BTJPYNJ-XTFCR-372YJ-YJJ4Q-G83YBJPYNH-XTFCR-372YJ-YJJ3Q-G83YBR3BYW-CBNWT-F3JTP-FM942-BTDXY (CN)
ESD ISO6P99N-YF42M-TPGBG-9VMJP-YKHCF

Java Architecture in Eclipse

ejwagenaar.com logo

Using Ecipse for Reversed Engineering

Eclipse is one of the most popular IDE’s. In this article we will use Eclipse to investigate an existing class from the java.text package. The class we will investigate is the DateFormat.

DateForma is an abstract class for date/time formatting subclasses which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting (i.e., date -> text), parsing (text -> date), and normalization. The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.
DateFormat provides many class methods for obtaining default date/time formatters based on the default or a given locale and a number of formatting styles. The formatting styles include FULL, LONG, MEDIUM, and SHORT. More detail and examples of using these styles are provided in the method descriptions.

DateFormat helps you to format and parse dates for any locale. Your code can be completely independent of the locale conventions for months, days of the week, or even the calendar format: lunar vs. solar. Browsing the JavaDoc is always fun. But even more fun is firing up your IDE and have a look. So let’s do so!

Eclipse with DateFormat Chosen.
Eclipse with DateFormat Chosen.

With DateFormat chosen in the TypeHierachy I can see it inherits directly from an Abstract class named Format. (You recognize the Abstract Class by the small A in it’s upper-right corner. As you can see DateFormat is Abstract itself.

Now zoom in on the DateFormat to get the full type hierarchy:

As you can see, SimpleDateFormat inherits from DateFormat, which in turn Inherits from Format, which (like any other Object) inherits from Object.

Conclusion

Eclipse is an excellent tool to study existing Java Classes and their hyrarchie in comparison with other classes. You can also use this to investigate (chains of) method calls by selecting a method and choose ‘Call hierarchy’. Try this yourself and enjoy it!

 

Useful Java Snippets (4)

ejwagenaar.com logo

Hello all of you Java geeks!

Welcome back to a new episode of this fine Java snippet series! In former episodes we looked at the  java.util package. We covered the Collections Framework as well as utilities to convert between Collections, Arrays and back to Collections again. We also covered Locales to make your Applications International.

Time to move on to another part of the java.util area. Today I choose  the java.util.prefs also known as the Java Preferences API.

This package allows applications to store and retrieve user and system preference and configuration data. This data is stored persistently in an implementation-dependent backing store. There are two separate trees of preference nodes, one for user preferences and one for system preferences.

The Java Preferences API provides a systematic way to handle program preference configurations, e.g. to save user settings, remember the last value of a field etc.

Preferences are key / values pairs where the key is an arbitrary name for the preference. The value can be a boolean, string, int of another primitive type. Preferences are received and saved by get and put methods while the get methods also supply a default value in case the preferences is not yet set.

Format

Preferences in Java are readable text documents, either the Properties format or XML variants thereof. You don’t have to worry to much about that yet. Eclipse or your preferred IDE can help you with this and you only use accessor methods (getters and setters) to work with them.

Your Java Runtime Environment (JRE) has it’s own set of preferences.

1. Listing your JRE Preferences

// Get all system properties
Properties props = System.getProperties();

// Enumerate all system properties
Enumeration enum = props.propertyNames();
for (; enum.hasMoreElements(); ) {
    // Get property name
    String propName = (String)enum.nextElement();

    // Get property value
    String propValue = (String)props.get(propName);
}
  1. Getting and setting values in preferences:

A preference node holds only string values. However, the Preferences class has convenience methods that will convert a number of basic Java types to and from strings. For example, Preferences.putByteArray() converts a byte array into a string and then saves the string value. Preferences.getByteArray() converts the string back into an array of bytes.
The types for which there are conversion methods are boolean, int, long, float, double, and byte[]. For all other types, serialization can be used to convert an arbitrary Java type into a byte array (see Serializing an Object).

// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

// Preference key name
final String PREF_NAME = "name_of_preference";

// Save
prefs.put(PREF_NAME, "a string"); // String
prefs.putBoolean(PREF_NAME, true); // boolean
prefs.putInt(PREF_NAME, 123); // int
prefs.putLong(PREF_NAME, 123L); // long
prefs.putFloat(PREF_NAME, 12.3F); // float
prefs.putDouble(PREF_NAME, 12.3); // double
byte[] bytes = new byte[1024];
prefs.putByteArray(PREF_NAME, bytes); // byte[]

// Retrieve
String s = prefs.get(PREF_NAME, "a string"); // String
boolean b = prefs.getBoolean(PREF_NAME, true); // boolean
int i = prefs.getInt(PREF_NAME, 123); // int
long l = prefs.getLong(PREF_NAME, 123L); // long
float f = prefs.getFloat(PREF_NAME, 12.3F); // float
double d = prefs.getDouble(PREF_NAME, 12.3); // double
bytes = prefs.getByteArray(PREF_NAME, bytes); // byte[]
  1. Serializing an Object:

The types for which there are conversion methods are boolean, int, long, float, double, and byte[]. For all other types, serialization can be used to convert an arbitrary Java type into a byte array and can be serialized as follows:

Note: The Object to be Serialized must implement java.io.Serializable.

This example serializes a javax.swing.JButton object.

Object obj = new javax.swing.JButton("push me");

try {
    // Serialize to a file
    ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
    out.writeObject(object);
    out.close();

    // Serialize to a byte array
    ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
    out = new ObjectOutputStream(bos) ;
    out.writeObject(object);
    out.close();

    // Get the bytes of the serialized object
    byte[] buf = bos.toByteArray();
} catch (IOException e) {
}

Off course now we serialized our JButton we also need to bring it back to the original JButton Object. This is called Deserialization. You do it as follows:

try {
    // Deserialize from a file
    File file = new File("filename.ser");
    ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
    // Deserialize the object
    javax.swing.JButton button = (javax.swing.JButton) in.readObject();
    in.close();

    // Get some byte array data
    byte[] bytes = getBytesFromFile(file);
    // see Reading a File into a Byte Array for the implementation of this method

    // Deserialize from a byte array
    in = new ObjectInputStream(new ByteArrayInputStream(bytes));
    button = (javax.swing.JButton) in.readObject();
    in.close();
} catch (ClassNotFoundException e) {
} catch (IOException e) {
}
  1. Saving and Retrieving a Preference Value

Preference values are persistent key/value pairs. The key must be a string. Preference values are stored in a preference node, which behaves much like a Map object. In order to get or set a preference value, the preference node containing that preference must first be retrieved.
By convention, a preference node is associated with a Java package. For example, if a class called com.mycompany.Foo needs to save some preferences, it would save them in the preference node associated with the package com.mycompany.

There are two types of preference nodes: a system type and a user type. A system node is shared by all users of a system. Any changes made to a system node are immediately visible to all users of the system. A user node is a node whose values are accessible only by the user using the application.

A preference node can be retrieved using a Class object or by a string. See Retrieving a Preference Node for an example.

This example retrieves the user preference node using a Class object and saves and retrieves a preference in the node.

// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

// Preference key name
final String PREF_NAME = "name_of_preference";

// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);

// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"

Enough for today chaps! Hope you can ingest this all. I need to do some coding myself.