Dynamic Loading using Java Reflection and Properties.

What is Java Reflection and Properties

In this article I will be explaining how you load classes dynamically using a properties file and Java Reflections. The Properties file are basically a collection of key-value pairs. It is the most commonly used mechanism for storing applications configuration data and settings. Reflection is a feature available in Java used by developers for examining and modifying the run-time behavior of applications running in the JVM.

MyBirds example

Let us start with a very simple problem statement: I should be able to load characters of a particular bird when I specify it’s name. For e.g: When i specify duck, the calling the sound() function should print “quack”;

This is a situation where you need to load a class dynamically based on some data provided by the client or external source. You also want the flexibility to configure classes in a simple properties file and these classes are having similar behavior.

To implement this we will need the following components:

  • mybirds.properties – The properties file where you can map keys to your class
  • MyBird.java – An interface which all the classes specified in the properties file will have to implement.
  • Duck.java, Eagle.java – The classes that implements the interface MyBird.
  • MyBirdFactory.java – The factory class that dynamically creates classes

Let us look at the code for each of these. Let us start with mybirds.properties.

#BIRD-TYPE=IMPLEMENTATION-CLASS
duck=com.foo.Duck
eagle=com.foo.Eagle

package com.foo;

public interface MyBird {
    public String sound();
}

Now let us see Duck.java and Eagle.java.

packagecom.foo;

public class Duck implements MyBird {
    public String sound() {
        return "Quack";
    }
}
package com.foo;

public class Eagle implements MyBird {
    public String sound() {
        return "Scream";
    }
}

MyBirdFactory.java is the class responsible for creating the desirable instance based on the birdType input passed to it.

package com.foo;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Locale;
import java.util.ResourceBundle;
publicclassMyBirdFactory {
    private static final String MY_BIRDS_CONFIGURATION = "mybirds";
    private static Hashtable<String, String> myBirdsMappings = new Hashtable<String, String>();
    static {
        try {
            loadMyBirdsrMappings();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static MyBird getMyBird(String birdType) {
        String className = myBirdsMappings.get(birdType);
        MyBird bird = null;
        try {
            if( className!=null) {
                Class cls = Class.forName(className);
                bird = (MyBird)cls.newInstance();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bird;
    }
    private static void loadMyBirdsrMappings() {
        ResourceBundle rb = ResourceBundle.getBundle(MY_BIRDS_CONFIGURATION, Locale.getDefault());
        for (Enumeration e = rb.getKeys(); e.hasMoreElements();) {
            String key = (String) e.nextElement();
            myBirdsMappings.put(key, rb.getString(key));
        }
    }
}

We can write TestCode.java to test the code.

package com.foo;

public class TestCode {

    public static void main(String[] args) {
        if(args.length <=0)
            System.out.println("Please provide input. E.G: duck eagle duck ...");
        else {
            for(String name:args){
                MyBird bird = MyBirdFactory.getMyBird( name );
                if(bird == null){
                    System.out.println("Couldn't find your bird. Please make sure it's entered in mybirds.properties");
                } else {
                    System.out.println("The sound of the bird"  + name + " is " + bird.sound() );
                }
            }
        }
    }
}

Check out the output when you run the code.

C:\Janeve\MyBirds>java -classpath ./ com.foo.TestCode duck duck eagle duck eagle eagle

The sound of the bird duck is Quack
The sound of the bird duck is Quack
The sound of the bird eagle is Scream
The sound of the bird duck is Quack
The sound of the bird eagle is Scream
The sound of the bird eagle is Scream
C:\Janeve\MyBirds>

Source : http://www.janeve.me/articles/dynamic-loading-using-java-reflection-and-properties

 

Advertisements

The Java™ Tutorials : The Really Big Index

A list of all content pages in the The Java™ Tutorials

Trail: Getting Started

The Java Technology Phenomenon

About the Java Technology
What Can Java Technology Do?
How Will Java Technology Change My Life?

The “Hello World!” Application

“Hello World!” for the NetBeans IDE
“Hello World!” for Microsoft Windows
“Hello World!” for Solaris OS and Linux

A Closer Look at the “Hello World!” Application

Questions and Exercises: Getting Started

Common Problems (and Their Solutions)

Trail: Learning the Java Language

Object-Oriented Programming Concepts

What Is an Object?
What Is a Class?
What Is Inheritance?
What Is an Interface?
What Is a Package?
Questions and Exercises: Object-Oriented Programming Concepts

Language Basics

Variables
    Primitive Data Types
    Arrays
    Summary of Variables
    Questions and Exercises: Variables
Operators
    Assignment, Arithmetic, and Unary Operators
    Equality, Relational, and Conditional Operators
    Bitwise and Bit Shift Operators
    Summary of Operators
    Questions and Exercises: Operators
Expressions, Statements, and Blocks
Questions and Exercises: Expressions, Statements, and Blocks
Control Flow Statements
    The if-then and if-then-else Statements
    The switch Statement
    The while and do-while Statements
    The for Statement
    Branching Statements
    Summary of Control Flow Statements
    Questions and Exercises: Control Flow Statements

Classes and Objects

Classes
    Declaring Classes
    Declaring Member Variables
    Defining Methods
    Providing Constructors for Your Classes
    Passing Information to a Method or a Constructor
Objects
    Creating Objects
    Using Objects
More on Classes
    Returning a Value from a Method
    Using the this Keyword
    Controlling Access to Members of a Class
    Understanding Instance and Class Members
    Initializing Fields
    Summary of Creating and Using Classes and Objects
    Questions and Exercises: Classes
    Questions and Exercises: Objects
Nested Classes
    Inner Class Example
    Summary of Nested Classes
    Questions and Exercises: Nested Classes
Enum Types
Questions and Exercises: Enum Types
Annotations
Questions and Exercises: Annotations

Interfaces and Inheritance

Interfaces
    Defining an Interface
    Implementing an Interface
    Using an Interface as a Type
    Rewriting Interfaces
    Summary of Interfaces
    Questions and Exercises: Interfaces
Inheritance
    Overriding and Hiding Methods
    Polymorphism
    Hiding Fields
    Using the Keyword super
    Object as a Superclass
    Writing Final Classes and Methods
    Abstract Methods and Classes
    Summary of Inheritance
    Questions and Exercises: Inheritance

Numbers and Strings

Numbers
    The Numbers Classes
    Formatting Numeric Print Output
    Beyond Basic Arithmetic
    Summary of Numbers
    Questions and Exercises: Numbers
Characters
Strings
    Converting Between Numbers and Strings
    Manipulating Characters in a String
    Comparing Strings and Portions of Strings
    The StringBuilder Class
    Summary of Characters and Strings
Autoboxing and Unboxing
Questions and Exercises: Characters and Strings

Generics (Updated)

Why Use Generics?
Generic Types
    Raw Types
Generic Methods
Bounded Type Parameters
    Generic Methods and Bounded Type Parameters
Generics, Inheritance, and Subtypes
Type Inference
Wildcards
    Upper Bounded Wildcards
    Unbounded Wildcards
    Lower Bounded Wildcards
    Wildcards and Subtyping
    Wildcard Capture and Helper Methods
    Guidelines for Wildcard Use
Type Erasure
    Erasure of Generic Types
    Erasure of Generic Methods
    Effects of Type Erasure and Bridge Methods
    Non-Reifiable Types
Restrictions on Generics
Questions and Exercises: Generics

Packages

Creating and Using Packages
    Creating a Package
    Naming a Package
    Using Package Members
    Managing Source and Class Files
    Summary of Creating and Using Packages
    Questions and Exercises: Creating and Using Packages

Trail: Essential Classes

Exceptions

What Is an Exception?
The Catch or Specify Requirement
Catching and Handling Exceptions
    The try Block
    The catch Blocks
    The finally Block
    The try-with-resources Statement
    Putting It All Together
Specifying the Exceptions Thrown by a Method
How to Throw Exceptions
    Chained Exceptions
    Creating Exception Classes
Unchecked Exceptions — The Controversy
Advantages of Exceptions
Summary
Questions and Exercises

Basic I/O

I/O Streams
    Byte Streams
    Character Streams
    Buffered Streams
    Scanning and Formatting
        Scanning
        Formatting
    I/O from the Command Line
    Data Streams
    Object Streams
File I/O (Featuring NIO.2)
    What Is a Path? (And Other File System Facts)
    The Path Class
        Path Operations
    File Operations
    Checking a File or Directory
    Deleting a File or Directory
    Copying a File or Directory
    Moving a File or Directory
    Managing Metadata (File and File Store Attributes)
    Reading, Writing, and Creating Files
    Random Access Files
    Creating and Reading Directories
    Links, Symbolic or Otherwise
    Walking the File Tree
    Finding Files
    Watching a Directory for Changes
    Other Useful Methods
    Legacy File I/O Code
Summary
Questions and Exercises: Basic I/O

Concurrency

Processes and Threads
Thread Objects
    Defining and Starting a Thread
    Pausing Execution with Sleep
    Interrupts
    Joins
    The SimpleThreads Example
Synchronization
    Thread Interference
    Memory Consistency Errors
    Synchronized Methods
    Intrinsic Locks and Synchronization
    Atomic Access
Liveness
    Deadlock
    Starvation and Livelock
Guarded Blocks
Immutable Objects
    A Synchronized Class Example
    A Strategy for Defining Immutable Objects
High Level Concurrency Objects
    Lock Objects
    Executors
        Executor Interfaces
        Thread Pools
        Fork/Join
    Concurrent Collections
    Atomic Variables
    Concurrent Random Numbers
For Further Reading
Questions and Exercises: Concurrency

The Platform Environment

Configuration Utilities
    Properties
    Command-Line Arguments
    Environment Variables
    Other Configuration Utilities
System Utilities
    Command-Line I/O Objects
    System Properties
    The Security Manager
    Miscellaneous Methods in System
PATH and CLASSPATH
Questions and Exercises: The Platform Environment

Regular Expressions

Introduction
Test Harness
String Literals
Character Classes
Predefined Character Classes
Quantifiers
Capturing Groups
Boundary Matchers
Methods of the Pattern Class
Methods of the Matcher Class
Methods of the PatternSyntaxException Class
Unicode Support
Additional Resources
Questions and Exercises: Regular Expressions

Trail: Deployment

Java Applets

Getting Started With Applets
    Defining an Applet Subclass
    Methods for Milestones
    Life Cycle of an Applet
    Applet’s Execution Environment
    Developing an Applet
    Deploying an Applet
        Deploying With the Applet Tag
Doing More With Applets
    Finding and Loading Data Files
    Defining and Using Applet Parameters
    Displaying Short Status Strings
    Displaying Documents in the Browser
    Invoking JavaScript Code From an Applet
    Invoking Applet Methods From JavaScript Code
    Handling Initialization Status With Event Handlers
    Manipulating DOM of Applet’s Web Page
    Displaying a Customized Loading Progress Indicator
    Writing Diagnostics to Standard Output and Error Streams
    Developing Draggable Applets
    Communicating With Other Applets
    Working With a Server-Side Application
        Network Client Applet Example
    What Applets Can and Cannot Do
Solving Common Applet Problems
Questions and Exercises: Applets

Java Web Start

Developing a Java Web Start Application
    Retrieving Resources
Deploying a Java Web Start Application
    Setting Up a Web Server
Displaying a Customized Loading Progress Indicator
Running a Java Web Start Application
Java Web Start and Security
Common Java Web Start Problems
Questions and Exercises: Java Web Start

Doing More With Java Rich Internet Applications

Setting Trusted Arguments and Secure Properties
    System Properties
JNLP API
    Accessing the Client Using JNLP API
Cookies
    Accessing Cookies
Customizing the Loading Experience
Security in Rich Internet Applications
Questions and Exercises: Doing More With Rich Internet Applications

Deployment In-Depth

Deployment Toolkit
    Deploying an Applet
        Customizing the Loading Screen
        Embedding JNLP File in Applet Tag
    Deploying a Java Web Start Application
        Changing the Launch Button
        Deploying Without Codebase
    Checking the Client JRE Software Version
Java Network Launch Protocol
    Structure of the JNLP File
Deployment Best Practices
    Reducing the Download Time
    Avoiding Unnecessary Update Checks
    Signing JAR Files Only When Necessary
    Ensuring the Presence of the JRE Software
    Questions and Exercises: Deployment In-Depth

Packaging Programs in JAR Files

Using JAR Files: The Basics
    Creating a JAR File
    Viewing the Contents of a JAR File
    Extracting the Contents of a JAR File
    Updating a JAR File
    Running JAR-Packaged Software
Working with Manifest Files: The Basics
    Understanding the Default Manifest
    Modifying a Manifest File
    Setting an Application’s Entry Point
    Adding Classes to the JAR File’s Classpath
    Setting Package Version Information
    Sealing Packages within a JAR File
Signing and Verifying JAR Files
    Understanding Signing and Verification
    Signing JAR Files
    Verifying Signed JAR Files
Using JAR-related APIs
    The JarClassLoader Class
    The JarRunner Class
    Questions and Exercises: JAR

Trail: Creating a GUI With JFC/Swing

Getting Started with Swing

About the JFC and Swing
Compiling and Running Swing Programs

Learning Swing with the NetBeans IDE

Setting up the CelsiusConverter Project
NetBeans IDE Basics
Creating the CelsiusConverter GUI
Adjusting the CelsiusConverter GUI
Adding the Application Logic
Questions and Exercises: Learning Swing with the NetBeans IDE

Using Swing Components

Using Top-Level Containers
The JComponent Class
Using Text Components
    Text Component Features
    The Text Component API
How to Use Various Components
    How to Make Applets
    How to Use Buttons, Check Boxes, and Radio Buttons
    How to Use the ButtonGroup Component
    How to Use Color Choosers
    How to Use Combo Boxes
    How to Make Dialogs
    How to Use Editor Panes and Text Panes
    How to Use File Choosers
    How to Use Formatted Text Fields
    How to Make Frames (Main Windows)
    How to Use Internal Frames
    How to Use Labels
    How to Use Layered Panes
    How to Use Lists
    How to Use Menus
    How to Use Panels
    How to Use Password Fields
    How to Use Progress Bars
    How to Use Root Panes
    How to Use Scroll Panes
    How to Use Separators
    How to Use Sliders
    How to Use Spinners
    How to Use Split Panes
    How to Use Tabbed Panes
    How to Use Tables
    How to Use Text Areas
    How to Use Text Fields
    How to Use Tool Bars
    How to Use Tool Tips
    How to Use Trees
How to Use HTML in Swing Components
How to Use Models
How to Use Icons
How to Use Borders
Solving Common Component Problems
Questions and Exercises: Using Swing Components

Concurrency in Swing

Initial Threads
The Event Dispatch Thread
Worker Threads and SwingWorker
    Simple Background Tasks
    Tasks that Have Interim Results
    Canceling Background Tasks
    Bound Properties and Status Methods
    Questions and Exercises: Concurrency in Swing

Using Other Swing Features

How to Integrate with the Desktop Class
How to Create Translucent and Shaped Windows
How to Decorate Components with the JLayer Class
How to Use Actions
How to Use Swing Timers
How to Support Assistive Technologies
How to Use the Focus Subsystem
How to Use Key Bindings
How to Use Modality in Dialogs
How to Print Tables
How to Print Text
How to Create a Splash Screen
How to Use the System Tray
Solving Common Problems Using Other Swing Features

Laying Out Components Within a Container

A Visual Guide to Layout Managers
Using Layout Managers
How Layout Management Works
How to Use Various Layout Managers
How to Use BorderLayout
How to Use BoxLayout
How to Use CardLayout
How to Use FlowLayout
How to Use GridBagLayout
How to Use GridLayout
How to Use GroupLayout
    A GroupLayout Example
How to Use SpringLayout
Creating a Custom Layout Manager
Doing Without a Layout Manager (Absolute Positioning)
Solving Common Layout Problems
Questions and Exercises: Laying Out Components within a Container

Modifying the Look and Feel

How to Set the Look and Feel
The Synth Look and Feel
    A Synth Example
Nimbus Look and Feel
    Changing the Look of Nimbus
    Resizing a Component
    Changing the Color Theme
    For More Information

Drag and Drop and Data Transfer

Introduction to DnD
Default DnD Support
    Demo – BasicDnD
TransferHandler Class
    Export Methods
    Import Methods
TransferSupport Class
Setting the Drop Mode
    Demo – DropDemo
Choosing the Drop Action
    Demo – ChooseDropAction
Showing the Drop Location
Location Sensitive Drop
    Demo – LocationSensitiveDemo
Empty Table Drop
Drop Location Rendering
Top-Level Drop
Adding Cut, Copy and Paste (CCP)
CCP in a Text Component
CCP in a non-Text Component
Using and Creating a DataFlavor
Putting it All Together – DnD and CCP
Further Information
Solving Common Data Transfer Problems

Writing Event Listeners

Introduction to Event Listeners
General Information about Writing Event Listeners
Listeners Supported by Swing Components
Implementing Listeners for Commonly Handled Events
    How to Write an Action Listener
    How to Write a Caret Listener
    How to Write a Change Listener
    How to Write a Component Listener
    How to Write a Container Listener
    How to Write a Document Listener
    How to Write a Focus Listener
    How to Write an Internal Frame Listener
    How to Write an Item Listener
    How to Write a Key Listener
    How to Write a List Data Listener
    How to Write a List Selection Listener
    How to Write a Mouse Listener
    How to Write a Mouse-Motion Listener
    How to Write a Mouse-Wheel Listener
    How to Write a Property Change Listener
    How to Write a Table Model Listener
    How to Write a Tree Expansion Listener
    How to Write a Tree Model Listener
    How to Write a Tree Selection Listener
    How to Write a Tree-Will-Expand Listener
    How to Write an Undoable Edit Listener
    How to Write Window Listeners
Listener API Table
Solving Common Event-Handling Problems
Questions and Exercises: Writing Event Listeners

Performing Custom Painting

Creating the Demo Application (Step 1)
Creating the Demo Application (Step 2)
Creating the Demo Application (Step 3)
Refining the Design
A Closer Look at the Paint Mechanism
Summary
Solving Common Painting Problems
Questions and Exercises: Performing Custom Painting

Trail: Collections

Introduction to CollectionsInterfaces

The Collection Interface
The Set Interface
The List Interface
The Queue Interface
The Deque Interface
The Map Interface
Object Ordering
The SortedSet Interface
The SortedMap Interface
Summary of Interfaces
Questions and Exercises: Interfaces

Implementations

Set Implementations
List Implementations
Map Implementations
Queue Implementations
Deque Implementations
Wrapper Implementations
Convenience Implementations
Summary of Implementations
Questions and Exercises: Implementations

AlgorithmsCustom Collection ImplementationsInteroperability

Compatibility
API Design

Trail: Internationalization

Introduction

A Quick Example
    Before Internationalization
    After Internationalization
    Running the Sample Program
    Internationalizing the Sample Program
Checklist

Setting the Locale

Creating a Locale
BCP 47 Extensions
Identifying Available Locales
The Scope of a Locale
Locale-Sensitive Services SPI

Isolating Locale-Specific Data

About the ResourceBundle Class
Preparing to Use a ResourceBundle
Backing a ResourceBundle with Properties Files
Using a ListResourceBundle
Customizing Resource Bundle Loading

Formatting

Numbers and Currencies
    Using Predefined Formats
    Customizing Formats
Dates and Times
    Using Predefined Formats
    Customizing Formats
    Changing Date Format Symbols
Messages
    Dealing with Compound Messages
    Handling Plurals

Working with Text

Checking Character Properties
Comparing Strings
    Performing Locale-Independent Comparisons
    Customizing Collation Rules
    Improving Collation Performance
Unicode
    Terminology
    Supplementary Characters as Surrogates
    Character and String APIs
    Sample Usage
    Design Considerations
    More Information
Detecting Text Boundaries
    About the BreakIterator Class
    Character Boundaries
    Word Boundaries
    Sentence Boundaries
    Line Boundaries
Converting Latin Digits to Other Unicode Digits
Converting Non-Unicode Text
    Byte Encodings and Strings
    Character and Byte Streams
Normalizing Text
Working with Bidirectional Text with the JTextComponent Class

Internationalization of Network Resources

Internationalized Domain Name

Trail: 2D Graphics

Overview of the Java 2D API Concepts

Coordinates
Java 2D Rendering
Geometric Primitives
Text
Images
Printing

Getting Started with GraphicsWorking with Geometry

Drawing Geometric Primitives
Drawing Arbitrary Shapes
Stroking and Filling Graphics Primitives

Working with Text APIs

Font Concepts
Text Layout Concepts
Physical and Logical Fonts
Measuring Text
Advanced Text Display
    Displaying Antialiased Text by Using Rendering Hints
    Using Text Attributes to Style Text
    Drawing Multiple Lines of Text
    Working with Bidirectional Text

Working with Images

Reading/Loading an Image
Drawing an Image
Creating and Drawing to an Image
Writing/Saving an Image

Printing

A Basic Printing Program
Using Print Setup Dialogs
Printing a Multiple Page Document
Working with Print Services and Attributes
Printing the Contents of a User Interface
Printing Support in Swing Components

Advanced Topics in Java2D

Transforming Shapes, Text, and Images
Clipping the Drawing Region
Compositing Graphics
Controlling Rendering Quality
Constructing Complex Shapes from Geometry Primitives
Supporting User Interaction

Trail: Sound

Overview of the Sampled Package
Accessing Audio System Resources
Playing Back Audio
Capturing Audio
Processing Audio with Controls
Using Files and Format Converters
Overview of the MIDI Package
Accessing MIDI System Resources
Transmitting and Receiving MIDI Messages
Introduction to Sequencers
Using Sequencer Methods
Using Advanced Sequencer Features
Synthesizing Sound
Introduction to the Service Provider Interfaces
Providing Sampled-Audio Services
Providing MIDI Services

Trail: JavaBeans(TM)

Quick Start

Creating a Project
A Button is a Bean
Wiring the Application
Using a Third-Party Bean

Writing JavaBeans Components

Properties
Methods
Events
Using a BeanInfo

Advanced JavaBeans Topics

Bean Persistence
Long Term Persistence
Bean Customization

Trail: JDBC(TM) Database Access

JDBC Introduction

JDBC Architecture
A Relational Database Overview

JDBC Basics

Getting Started
Processing SQL Statements with JDBC
Establishing a Connection
Connecting with DataSource Objects
Handling SQLExceptions
Setting Up Tables
Retrieving and Modifying Values from Result Sets
Using Prepared Statements
Using Transactions
Using RowSet Objects
Using JdbcRowSet Objects
Using CachedRowSetObjects
Using JoinRowSet Objects
Using FilteredRowSet Objects
Using WebRowSet Objects
Using Advanced Data Types
Using Large Objects
Using SQLXML Objects
Using Array Objects
Using DISTINCT Data Type
Using Structured Objects
Using Customized Type Mappings
Using Datalink Objects
Using RowId Objects
Using Stored Procedures
Using JDBC with GUI API

Trail: Java Management Extensions (JMX)

Overview of the JMX Technology

Why Use the JMX Technology?
Architecture of the JMX Technology
Monitoring and Management of the Java Virtual Machine

Introducing MBeans

Standard MBeans
MXBeans

NotificationsRemote Management

Exposing a Resource for Remote Management By JConsole
Creating a Custom JMX Client

Trail: Java API for XML Processing (JAXP)

Introduction to JAXP

Overview of the Packages
Simple API for XML APIs
Document Object Model APIs
Extensible Stylesheet Language Transformations APIs
Streaming API for XML APIs
Finding the JAXP Sample Programs
Where Do You Go From Here?

Simple API for XML

When to Use SAX
Parsing an XML File Using SAX
Implementing SAX Validation
Handling Lexical Events
Using the DTDHandler and EntityResolver
Further Information

Document Object Model

When to Use DOM
Reading XML Data into a DOM
Validating with XML Schema
Further Information

Extensible Stylesheet Language Transformations

Introducing XSL, XSLT, and XPath
How XPath Works
Writing Out a DOM as an XML File
Generating XML from an Arbitrary Data Structure
Transforming XML Data with XSLT

Streaming API for XML

Why StAX?
StAX API
Using StAX
Oracle’s Streaming XML Parser Implementation
Example Code
Further Information

Trail: RMI

An Overview of RMI Applications
Writing an RMI Server
    Designing a Remote Interface
    Implementing a Remote Interface
Creating a Client Program
Compiling and Running the Example
    Compiling the Example Programs
    Running the Example Programs

Trail: Security Features in Java SE

Security Features OverviewQuick Tour of Controlling Applets

Observe Applet Restrictions
Set up a Policy File to Grant the Required Permission
    Start Policy Tool
    Grant the Required Permission
    Save the Policy File
See the Policy File Effects

Quick Tour of Controlling Applications

Observe Application Freedom
See How to Restrict Applications
Set up the Policy File to Grant the Required Permissions
    Open the Policy File
    Grant the Required Permissions
    Save the Policy File
See the Policy File Effects

API and Tools Use for Secure Code and File ExchangesSigning Code and Granting It Permissions

Steps for the Code Signer
    Download and Try the Sample Application
    Create a JAR File Containing the Class File
    Generate Keys
    Sign the JAR File
    Export the Public Key Certificate
Steps for the Code Receiver
    Observe the Restricted Application
    Import the Certificate as a Trusted Certificate
    Set Up a Policy File to Grant the Required Permission
        Start Policy Tool
        Specify the Keystore
        Add a Policy Entry with a SignedBy Alias
        Save the Policy File
    See the Policy File Effects

Exchanging Files

Steps for the Contract Sender
    Create a JAR File Containing the Contract
    Generate Keys
    Sign the JAR File
    Export the Public Key Certificate
Steps for the Contract Receiver
    Import the Certificate as a Trusted Certificate
    Verify the JAR File Signature

Generating and Verifying Signatures

Generating a Digital Signature
    Prepare Initial Program Structure
    Generate Public and Private Keys
    Sign the Data
    Save the Signature and the Public Key in Files
    Compile and Run the Program
Verifying a Digital Signature
    Prepare Initial Program Structure
    Input and Convert the Encoded Public Key Bytes
    Input the Signature Bytes
    Verify the Signature
    Compile and Run the Program
Weaknesses and Alternatives

Implementing Your Own Permission

ExampleGame
The HighScore Class
The HighScorePermission Class
A Sample Policy File
Putting It All Together
    Steps for the HighScore Developer (Chris)
    Steps for the ExampleGame Developer (Terry)
    Steps for a User Running ExampleGame (Kim)

Trail: The Extension Mechanism

Creating and Using Extensions

Installed Extensions
Download Extensions
Understanding Extension Class Loading

Making Extensions Secure

Setting Privileges for Extensions
Sealing Packages in Extensions

Trail: The Reflection API

Classes

Retrieving Class Objects
Examining Class Modifiers and Types
Discovering Class Members
Troubleshooting

Members

Fields
    Obtaining Field Types
    Retrieving and Parsing Field Modifiers
    Getting and Setting Field Values
    Troubleshooting
Methods
    Obtaining Method Type Information
    Retrieving and Parsing Method Modifiers
    Invoking Methods
    Troubleshooting
Constructors
    Finding Constructors
    Retrieving and Parsing Constructor Modifiers
    Creating New Class Instances
    Troubleshooting

Arrays and Enumerated Types

Arrays
    Identifying Array Types
    Creating New Arrays
    Getting and Setting Arrays and Their Components
    Troubleshooting
Enumerated Types
    Examining Enums
    Getting and Setting Fields with Enum Types
    Troubleshooting

Trail: Custom Networking

Overview of Networking

What You May Already Know About Networking in Java
Networking Basics

Working with URLs

What Is a URL?
Creating a URL
Parsing a URL
Reading Directly from a URL
Connecting to a URL
Reading from and Writing to a URLConnection

All About Sockets

What Is a Socket?
Reading from and Writing to a Socket
Writing the Server Side of a Socket

All About Datagrams

What Is a Datagram?
Writing a Datagram Client and Server
Broadcasting to Multiple Recipients

Programmatic Access to Network Parameters

What Is a Network Interface?
Retrieving Network Interfaces
Listing Network Interface Addresses
Network Interface Parameters

Working With Cookies

HTTP State Management With Cookies
CookieHandler Callback Mechanism
Default CookieManager
Custom CookieManager

Trail: Bonus

Generics

Introduction
Defining Simple Generics
Generics and Subtyping
Wildcards
Generic Methods
Interoperating with Legacy Code
The Fine Print
Class Literals as Runtime-Type Tokens
More Fun with Wildcards
Converting Legacy Code to Use Generics
Acknowledgements

Full-Screen Exclusive Mode API

Full-Screen Exclusive Mode
Display Mode
Passive vs. Active Rendering
Double Buffering and Page Flipping
BufferStrategy and BufferCapabilities
Examples

Preparation for Java Programmer Language Certification

Programmer Level I Exam
Programmer Level II Exam
Java SE 7 Upgrade Exam

Trail: Java Naming and Directory Interface

Naming and Directory Concepts

Directory Concepts

Overview of JNDI

Naming Package
Directory and LDAP Packages
Event and Service Provider Packages

Software Setup

LDAP Setup
Java Application Setup

Naming and Directory Operations

Naming Exceptions
Lookup an Object
List the Context
Add, Replace or Remove a Binding
Rename
Create and Destroy Subcontexts
Attribute Names
Read Attributes
Modify Attributes
Add, Replace Bindings with Attributes
Search
    Basic Search
    Filters
    Scope
    Result Count
    Time Limit
Trouble Shooting Tips

Advanced Topics for LDAP Users

LDAP v3
JNDI as an LDAP API
    How LDAP Operations Map to JNDI APIs
    How LDAP Error Codes Map to JNDI Exceptions
Security
    Modes of Authenticating to LDAP
    Authentication Mechanisms
    Anonymous
    Simple
    SASL
    Digest-MD5
    SSL and Custom Sockets
More LDAP Operations
    LDAP Compare
    Search Results
     LDAP Unsolicited Notifications
Connection Management
    Creation
     Closing
    Pooling
    Configuration
Frequently Asked Questions

Java Objects in the Directory

Storing and Reading Objects
Serializable Objects

New features in JDK 5.0 and JDK 6

Retrieving Distinguished Name
Standard LDAP Controls
Paged Results Control
Sort Control
Manage Referral Control
Manipulating LdapName (Distinguished Name)
Manipulating Relative Distringuished Name (RDN)
Setting Timeout for Ldap Operations

Trail: Sockets Direct Protocol

Understanding the Sockets Direct Protocol

Overview
Creating an SDP Configuration File
Enabling the SDP Protocol
Debugging SDP
Technical Issues with SDP
Solaris and Linux Support
Supported Java APIs
For More Information

Trail: Java Architecture for XML Binding

Introduction to JAXB

JAXB Architecture
Representing XML Content
Binding XML Schemas
Customizing Generated Classes and Java Program Elements
JAXB Examples
Basic Examples
Customizing JAXB Bindings
Java-to-Schema Examples
For More Information
Source : http://docs.oracle.com/javase/tutorial/reallybigindex.html

ScheduledExecutorService java.util.concurrent Tutorial

The java.util.concurrent.ScheduledExecutorService is anExecutorService which can schedule tasks to run after a delay, or to execute repeatedly. Tasks are executed asynchronously by a worker thread, and not by the thread handing the task to the ScheduledExecutorService.

ScheduledExecutorService Implementations

Since ScheduledExecutorService is an interface, you will have to use its implementation in the java.util.concurrent package, in order to use it.ScheduledExecutorService as the following implementation:

  • ScheduledThreadPoolExecutor

Creating a ScheduledExecutorService

How you create an ScheduledExecutorService depends on the implementation you use. However, you can use the Executors factory class to create ScheduledExecutorService instances too. Here is an example:

ScheduledExecutorService scheduledExecutorService =

        Executors.newScheduledThreadPool(5);

ScheduledExecutorService Usage

Once you have created a ScheduledExecutorService you use it by calling one of its methods:

  • schedule (Callable task, long delay, TimeUnit timeunit)
  • schedule (Runnable task, long delay, TimeUnit timeunit)
  • scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)
  • scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)

I will briefly cover each of these methods below.

schedule (Callable task, long delay, TimeUnit timeunit)

This method schedules the given Callable for execution after the given delay.

The method returns a ScheduledFuture which you can use to either cancel the task before it has started executing, or obtain the result once it is executed.

Here is an example:

ScheduledExecutorService scheduledExecutorService =
        Executors.newScheduledThreadPool(5);

ScheduledFuture scheduledFuture =
    scheduledExecutorService.schedule(new Callable() {
        public Object call() throws Exception {
            System.out.println("Executed!");
            return "Called!";
        }
    },
    5,
    TimeUnit.SECONDS);

System.out.println("result = " + scheduledFuture.get());

scheduledExecutorService.shutdown();

This example outputs:

Executed!
result = Called!

schedule (Runnable task, long delay, TimeUnit timeunit)

This method works like the method version taking a Callable as parameter, except a Runnable cannot return a value, so the ScheduledFuture.get()method returns null when the task is finished.

scheduleAtFixedRate (Runnable, long initialDelay, long period, TimeUnit timeunit)

This method schedules a task to be executed periodically. The task is executed the first time after the initialDelay, and then recurringly every time theperiod expires.

If any execution of the given task throws an exception, the task is no longer executed. If no exceptions are thrown, the task will continue to be executed until the ScheduledExecutorService is shut down.

If a task takes longer to execute than the period between its scheduled executions, the next execution will start after the current execution finishes. The scheduled task will not be executed by more than one thread at a time.

scheduleWithFixedDelay (Runnable, long initialDelay, long period, TimeUnit timeunit)

This method works very much like scheduleAtFixedRate() except that theperiod is interpreted differently.

In the scheduleAtFixedRate() method the period is interpreted as a delay between the start of the previous execution, until the start of the next execution.

In this method, however, the period is interpreted as the delay between the endof the previous execution, until the start of the next. The delay is thus between finished executions, not between the beginning of executions.

 

Source : http://tutorials.jenkov.com/java-util-concurrent/scheduledexecutorservice.html

Java Heap Space: What is it?

java-memory

Are you new to Java and Java EE? Looking for a simple high level overview of the Java Heap Space or just to improve your Java Heap knowledge? This post is for you.

 Background
 When learning Java for the first time, a lot of focus is often spent on the Java language itself, Object-oriented programming principles, design patterns, compilation etc. and not so much on the Java VM itself such as the Java Heap memory management, garbage collection, performance tuning which are often considered “advanced” topics.
A beginner Java or Java EE programmer ends up creating his first program or Web application. Java Heap memory problems are then often observed such asOutOfMemoryError which can be quite challenging for Java beginners or even intermediates to troubleshoot.
Sounds familiar?
Java Heap Space – Overview & life cycle
Proper knowledge of the Java VM Heap Space is critical; including for Java beginner so my recommendation to you is to learn these principles at the same time you learn the Java language technicalities.
Your Java VM is basically the foundation of your Java program which provides you with dynamic memory management services, garbage collection, Threads, IO and native operations and more.
The Java Heap Space is the memory “container” of you runtime Java program which provides to your Java program the proper memory spaces it needs (Java Heap, Native Heap) and managed by the JVM itself.
Your Java program life cycle typically looks like this:
  • Java program coding (via Eclipse IDE etc.) e.g. HelloWorld.java
  • Java program compilation (Java compiler or third party build tools such as Apache Ant, Apache Maven..) e.g. HelloWord.class
  • Java program start-up and runtime execution e.g. via your HelloWorld.main() method

 

The Java Heap space is mainly applicable and important for the third step: runtime execution. For the HotSpot VM, the Java Heap Space is split in 3 silos:
  • Java Heap for short & long lived objects (YoungGen & OldGen spaces)
  • PermGen space
  • Native Heap
Now let’s dissect your HelloWorld.class program so you can better understand.
  • At start-up, your JVM will load and cache some of your static program and JDK libraries to the Native Heap, including native libraries, Mapped Files such as your program Jar file(s), Threads such as the main start-up Thread of your program etc.
  • Your JVM will then store the “static” data of your HelloWorld.class Java program to the PermGen space (Class metadata, descriptors..)
  • Once your program is started, the JVM will then manage and dynamically allocate the memory of your Java program to the Java Heap (YoungGen & OldGen). This is why it is so important that you understand how much memory your Java program needs to you can properly fine-tuned the capacity of your Java Heap controlled via –Xms & -Xmx JVM parameters. Profiling, Heap Dump analysis allow you to determine your Java program memory footprint
  • Finally, the JVM has to also dynamically release the memory from the Java Heap Space that your program no longer need; this is called the garbage collection process. This process can be easily monitored via the JVM verbose GC or a monitoring tool of your choice such as JConsole
Sounds complex? The good news is that the JVM maturity has improved significantly over the last 10 years and provides you with out-of-the-box tools allowing you to understand your Java program Java Heap allocation monitor it and fine-tuned.
Src : http://javaeesupportpatterns.blogspot.in/2012/02/java-heap-space-what-is-it.html

Java : Local variables inside a loop and performance

Overview

Sometimes a question comes up about how much work allocating a new local variable takes.  My feeling has always been that the code becomes optimised to the point where this cost is static i.e. done once, not each time the code is run.

Recently Ishwor Gurung suggested considering moving some local variables outside a loop. I suspected it wouldn’t make a difference but I had never tested to see if this was the case.

The test.

This is the test I ran

public static void main(String… args) {
for (int i = 0; i < 10; i++) {
testInsideLoop();
testOutsideLoop();
}
}

private static void testInsideLoop() {
long start = System.nanoTime();
int[] counters = new int[144];
int runs = 200 * 1000;
for (int i = 0; i < runs; i++) {
int x = i % 12;
int y = i / 12 % 12;
int times = x * y;
counters[times]++;
}
long time = System.nanoTime() – start;
System.out.printf(“Inside: Average loop time %.1f ns%n”, (double) time / runs);
}

private static void testOutsideLoop() {
long start = System.nanoTime();
int[] counters = new int[144];
int runs = 200 * 1000, x, y, times;
for (int i = 0; i < runs; i++) {
x = i % 12;
y = i / 12 % 12;
times = x * y;
counters[times]++;
}
long time = System.nanoTime() – start;
System.out.printf(“Outside: Average loop time %.1f ns%n”, (double) time / runs);
}

and the output ended with

Inside: Average loop time 3.6 ns
Outside: Average loop time 3.6 ns
Inside: Average loop time 3.6 ns
Outside: Average loop time 3.6 ns

Increasing the time the test takes to 100 million iterations made little difference to the results.

Inside: Average loop time 3.8 ns
Outside: Average loop time 3.8 ns
Inside: Average loop time 3.8 ns
Outside: Average loop time 3.8 ns

Replacing the modulus and multiplication with >>, &, + I got

int x = i & 15;
int y = (i >> 4) & 15;
int times = x + y;

prints

Inside: Average loop time 1.2 ns
Outside: Average loop time 1.2 ns
Inside: Average loop time 1.2 ns
Outside: Average loop time 1.2 ns

While modulus is relatively expensive the resolution of the test is to 0.1 ns or less than 1/3 of a clock cycle. This would show any difference between the two tests to an accuracy of this.

Using Caliper

As @maaartinus comments, Caliper is a micro-benchmarking library so I was interested in how much slower it might be that doing the code by hand.

public static void main(String… args) {
Runner.main(LoopBenchmark.class, args);
}

public static class LoopBenchmark extends SimpleBenchmark {
public void timeInsideLoop(int reps) {
int[] counters = new int[144];
for (int i = 0; i < reps; i++) {
int x = i % 12;
int y = i / 12 % 12;
int times = x * y;
counters[times]++;
}
}

public void timeOutsideLoop(int reps) {
int[] counters = new int[144];
int x, y, times;
for (int i = 0; i < reps; i++) {
x = i % 12;
y = i / 12 % 12;
times = x * y;
counters[times]++;
}
}
}

The first thing to note is the code is shorter as it doesn’t include timing and printing boiler plate code.  Running this I get on the same machine as the first test.

0% Scenario{vm=java, trial=0, benchmark=InsideLoop} 4.23 ns; σ=0.01 ns @ 3 trials
50% Scenario{vm=java, trial=0, benchmark=OutsideLoop} 4.23 ns; σ=0.01 ns @ 3 trials

benchmark   ns linear runtime
InsideLoop 4.23 ==============================
OutsideLoop 4.23 =============================

vm: java
trial: 0

Replacing the modulus with shift and and

0% Scenario{vm=java, trial=0, benchmark=InsideLoop} 1.27 ns; σ=0.01 ns @ 3 trials
50% Scenario{vm=java, trial=0, benchmark=OutsideLoop} 1.27 ns; σ=0.00 ns @ 3 trials

benchmark   ns linear runtime
InsideLoop 1.27 =============================
OutsideLoop 1.27 ==============================

vm: java
trial: 0

This is consistent with the first result and only about 0.4 – 0.6 ns slower for one test. (about two clock cycles), and next to no difference for the shift, and, plus test.  This may be due to the way calliper samples the data but doesn’t change the outcome.

It is worth nothing that when running real programs, you typically get longer times than a micro-benchmark as the program will be doing more things so the caching and branch predictions is not as ideal.  A small over estimate of the time taken may be closer to what you can expect to see in a real program.

Conclusion

This indicated to me that in this case it made no difference.  I still suspect the cost of allocating local variables is don’t once when the code is compiled by the JIT and there is no per-iteration cost to consider.

 

Source: http://vanillajava.blogspot.ru/2012/12/local-variables-inside-loop-and.html

Why String is immutable or final in Java?

Though there could be many possible answer for this question and only designer of String class can answer this , I think below two does make sense

1)Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. “Test” has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

String A = “Test”
String B = “Test”

Now String B called “Test”.toUpperCase() which change the same object into “TEST” , so A will also be “TEST” which is not desirable.

2)String has been widely used as parameter for many java classes e.g. for opening network connection you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

In case if String is not immutable , this would lead serious security threat , I mean some one can access to any file for which he has authorization and then can change the file name either deliberately or accidentally and gain access of those file. This is some time asked as Why Char array is better than String for Storing password in Java in interviews as well.

3)Since String is immutable it can safely shared between many threads ,which is very important for multi threaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don’t need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.  This one is also suggested by  Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects.
Had String been mutable, a request to load “java.io.Writer” could have been changed to load “mil.vogoon.DiskErasingWriter”

I believe there could be some more very convincing reasons also , Please post those reasons as comments and I will include those on this post.

I think above reason holds good for another java interview questions “Why String is final in Java”  also to be immutable you have to be final so that your subclass doesn’t break immutability.  what do you guys think ?

Source : http://javarevisited.blogspot.com/2010/10/why-string-is-immutable-in-java.html#ixzz2IlmuOgOu