Showing posts with label SE6. Show all posts
Showing posts with label SE6. Show all posts

Monday, December 31, 2012

Java: Store/Load properties file in both XML and TEXT format.

Most of the time we created the properties file and modifying it in text editors like Notepad++ and notpad etc. We also can create and modifies the properties files from Java program as well. You will see in the following example XmlTextPropsReaderWriter.java how to do it.

The most common properties files are Log4j.properties that is used to configure Log4J system logging, and jdbc.properties which also used to control your program JDBC API connectivity parameters, and finally no web application working with internationalization (I18N) doesn’t have a resource bundle in form of properties file.

Let's see how to read and create properties file from java program in both formats (XML and TEXT).

Java API’s java.util.Properties class provides utility store() methods to store properties in either text or xml format. store() can be used to store property in text properties file and storeToXML() method can be used for creating a property file in XML format. On the other hand the load() reads a text format properties file while loadFromXML() reads XML format properties file.

The following example is streamlined using new JDK7 feature and NIO.2 capabilities.

Program source:

Running the above program produces the following output:

value1
value3

The created properties file text (users.properties) format is:

And the created properties file XML (user.xml) format is:

Note that: xml file created is governed by the following properties.dtd specification file:

Although most of us even me by default using the normal text format of the properties file and statically defined. Then the questions that may raise here are:

1- When to use the XML format?
2- When we can benefit from creating it dynamically?

for the first question, there are many areas that you can benefit from the xml format especially when you working with the same configuration file from many systems, and working with different languages to specific devices and need one configuration understood by all languages, readable, easy to secure, and retrieving data using xPath API is doable, all of these benefits leads to xml properties format.

The second part is, whenever you want to create a dynamic configuration, then you have the solution now.


Friday, March 9, 2012

Webservice: Part 3- Create, compile and publish WS using JDK only (No App. Server)

In Part 1 i have introduced the web services, and how to create, implement and publish WS then show the resulting WSDL.

After that in Part 2 i have implemented a Java Requester for the Web Service created in part 1.

In this part i will implement a multithreading version of the Endpoint Publisher to accept concurrent requests.

Multithreading the Endpoint Publisher

In the examples so far, the Endpoint publisher has been single-threaded and, therefore, capable of handling only one client request at a time: the published service completes the processing of one request before beginning the processing of another request. If the processing of the current request hangs, then no subsequent request can be processed unless and until the hung request is processed to completion.

In production mode, the Endpoint publisher would need to handle concurrent requests so that several pending requests could be processed at the same time. If the underlying computer system is, for example, a symmetric multiprocessor (SMP), then separate CPUs could process different requests concurrently.

On a single-CPU machine, the concurrency would occur through time sharing; that is, each request would get a share of the available CPU cycles so that several requests would be in some stage of processing at any given time. In Java, concurrency is achieved through multithreading. At issue, then, is how to make the Endpoint publisher multithreaded. The JWS framework supports Endpoint multithreading without forcing the programmer to work with difficult, error-prone constructs such as the synchronized block or the wait and notify method invocations.

An Endpoint object has an Executor property defined with the standard get/set methods. An Executor is an object that executes Runnable tasks; for example, standard Java Thread instances. (The Runnable interface declares only one method whose declaration is public void run().) An Executor object is a nice alternative to Thread instances, as the Executor provides high-level constructs for submitting and managing tasks that are to be executed concurrently.

The first step to making the Endpoint publisher multithreaded is thus to create an Executor class such as the following very basic one:

The class MyThreadPool creates a pool of 10 threads, using a fixed-size queue to store the threads that are created under the hood. If the pooled threads are all in use, then the next task in line must wait until one of the busy threads becomes available.

All of these management details are handled automatically. The MyThreadPool class overrides a few of the available methods to give the flavor.

A MyThreadPool object can be used to make a multithreaded Endpoint publisher. Here is the revised publisher, which now consists of several methods to divide the work:

Once the ThreadPoolWorker has been coded, all that remains is to set the Endpoint publisher's executor property to an instance of the worker class. The details of thread management do not intrude at all into the publisher.

The multithreaded Endpoint publisher is suited for lightweight production, but this publisher is not a service container in the true sense; that is, a software application that readily can deploy many web services at the same port.

A web container such as Tomcat, which is the reference implementation, is better suited to publish multiple web services.

References:
Java Web Services: Up and Running, 1st Edition

Webservice: Part 2- Create, compile and publish WS using JDK only (No App. Server)

In part 1 i gives an introduction to web services,then created, implemented and published a WS, after that show the resulting WSDL.

In this part i will show you how to implement a Java Requester of the Web Service created in part 1.

A Java Requester of the Web Service

Example 1. Java client for the Java web service

The Java client uses the same URL with a query string, but the Java client explicitly creates an XML qualified name, which has the syntax namespace URI:local name.

A URI is a Uniform Resource Identifier and differs from the more common URL in that a URL specifies a location, whereas a URI need not specify a location. In short, a URI need not be a URL. For now, it is enough to underscore that the Java class java.xml.namespace.QName represents an XML-qualified name.

In this example, the namespace URI is provided in the WSDL, and the local name is the SIB class name TimeServerImpl with the word Service appended. The local name occurs in the service section, the last section of the WSDL document.

Once the URL and QName objects have been constructed and the Service.create method has been invoked, the statement of interest:

Executes. Recall that, in the WSDL document, the portType section describes, in the style of an interface, the operations included in the web service. The getPort method returns a reference to a Java object that can invoke the portType operations.

The port object reference is of type eg.com.tm.ws.ts.TimeServer, which is the SEI type. The Java client invokes the two web service methods; and the Java libraries generate and process the SOAP messages exchanged transparently to enable the successful method invocations.

In part 3 i will show you how to implement WS created in part 1 to accept concurrent requests.

Webservice: Part 1- Create, compile and publish WS using JDK only (No App. Server)

This is 3 parts series as the following:
  1. Part1: introduction to web services, create, implement and publish WS then show the resulting WSDL.
  2. Part2: A Java Requester of the Web Service created in part 1.
  3. Part3: Multithreading the Endpoint Publisher version for the same service created in part 1.
What Are Web Services?

Although the term web service has various, imprecise, and evolving meanings, a glance at some features typical of web services will be enough to get us into coding a web service and a client, also known as a consumer or requester. As the name suggests, a web service is a kind of webified application, that is, an application typically delivered over HTTP (Hyper Text Transport Protocol).

A web service is thus a distributed application whose components can be deployed and executed on distinct devices. For instance, a stock-picking web service might consist of several code components, each hosted on a separate business-grade server, and the web service might be consumed on PCs, handhelds, and other devices.

Web services can be divided roughly into two groups, SOAP-based and REST-style. The distinction is not sharp because, as a code example later illustrates, a SOAP-based service delivered over HTTP is a special case of a REST-style service. SOAP originally stood for Simple Object Access Protocol but, by serendipity, now may stand for Service Oriented Architecture (SOA) Protocol.

Deconstructing SOA is nontrivial but one point is indisputable: whatever SOA may be, web services play a central role in the SOA approach to software design and development. (This is written with tongue only partly in cheek. SOAP is officially no longer an acronym, and SOAP and SOA can live apart from one another.)

ADF: Creating and Using an ADF Declarative Component

This tutorial shows you how to create ADF declarative component metadata, add ADF Faces components that make up the composite component, and use the declarative component on a JSF page.

In this post ADF: About JSF fragments, ADF regions, declarative components …, i wrote about different declarative component in ADF faces.

You will use wizards to quickly create applications and projects, and a declarative component definition consisting of an attribute, a facet and a method.

The declarative component you will create is panel box containing one label, list of input text, and button. The metadata for the declarative component definition will allow page authors to set the label for a panel box, attach a method to the button to print the input lists after modification, and use built in controllerContext to view page viewId as default value.

To create the declarative component layout, you will use design tools such as the visual editor, Component Palette, and the Property Inspector. Then you will deploy the project to an ADF Library JAR file. For an application to consume the declarative component, you will use the Resource Palette to add the deployed JAR, and then add the deployed JAR to the project that contains JSF pages.

To make use of the declarative component, you will add it to a simple JSF page, edit the pre-defined attributes, create a method and attach it to the declarative component. When you run the application, the page will look similar to this:



Saturday, February 11, 2012

Java: Copy jar files programmatically into another destination

Copying a jar file programmatically involves the following steps:
  1. Create a JarOutputStream based on the destination jar file.
  2.  Loop through all entries in the source jar file, and get the InputStream from each entry.
  3. Create a new jar entry with the same name as the source jar entry, and put the new entry to the JarOutputStream.
  4. Now we have InputStream, OutputStream, and the new jar entry in place, we are ready to transfer the bits, by reading bytes from InputStream into a buffer and writing buffer content to OutputStream.
  5. Close the InputStream, flush the JarOutputStream, and close the jar entry. This completes the copying of one jar entry.
  6. After the loop ends, all entries are copied from source jar file to destination jar file. Finally, close the JarOutputStream.
package test;
import java.io.*;
import java.util.Enumeration;
import java.util.jar.*;

//java -cp . test.CopyZip xxx/lib/sac-1.3.jar /tmp

public class CopyZip {
   public static void main(String[] args) throws Exception {
       File sourceFileOrDir = new File(args[0]);
       File destDir = new File(args[1]);
       if (sourceFileOrDir.isFile()) {
           copyJarFile(new JarFile(sourceFileOrDir), destDir);
       } else if (sourceFileOrDir.isDirectory()) {
           File[] files = sourceFileOrDir.listFiles(new FilenameFilter() {
               public boolean accept(File dir, String name) {
                   return name.endsWith(".jar");
               }
           });
           for (File f : files) {
               copyJarFile(new JarFile(f), destDir);
           }
       }
   }

   public static void copyJarFile(JarFile jarFile, File destDir) throws IOException {
       String fileName = jarFile.getName();
       String fileNameLastPart = fileName.substring(fileName.lastIndexOf(File.separator));
       File destFile = new File(destDir, fileNameLastPart);

       JarOutputStream jos = new JarOutputStream(new FileOutputStream(destFile));
       Enumeration<JarEntry> entries = jarFile.entries();

       while (entries.hasMoreElements()) {
           JarEntry entry = entries.nextElement();
           InputStream is = jarFile.getInputStream(entry);

           //jos.putNextEntry(entry);
           //create a new entry to avoid ZipException: invalid entry compressed size
           jos.putNextEntry(new JarEntry(entry.getName()));
           byte[] buffer = new byte[4096];
           int bytesRead = 0;
           while ((bytesRead = is.read(buffer)) != -1) {
               jos.write(buffer, 0, bytesRead);
           }
           is.close();
           jos.flush();
           jos.closeEntry();
       }
       jos.close();
   }
}

A common error is:

Exception in thread "main" java.util.zip.ZipException: invalid entry compressed
                                                       size (expected 1665 but got 1680 bytes)
   at java.util.zip.ZipOutputStream.closeEntry(ZipOutputStream.java:206)
   at test.CopyZip.copyJarFile(CopyZip.java:63)
   at test.CopyZip.main(CopyZip.java:37)

It usually occurs when text file entries in the source jar file contain some non-ASCII characters such as ^I ^Z ^D ^C. Some common files are META-INF/COPYRIGHT.html, META-INF/LICENSE.txt, etc, probably because these files were created in a non-ASCII editor but saved as text files.

To avoid this type of
ZipException, always create a new JarEntry with the same name, and pass it to putNextEntry() method. Do not pass the existing jar entry from the source jar file to putNextEntry()
method.


Saturday, January 28, 2012

Java: Improvements to the client and desktop parts of Java SE 6 and Java SE 7 !!!


Client-Side Improvements in Java 6 and Java 7

Learn about the improvements to the client and desktop parts of Java SE 6 and Java SE 7, including the new applet plug-in, the Java Deployment Toolkit, shaped and translucent windows, heavyweight-lightweight mixing, and Java Web Start.

Introduction
Since the release of Java Platform, Standard Edition 6 (Java SE 6) in December of 2006, a lot of improvements have been made to the client and desktop parts of Java. In this article, we take a tour of Swing, and then we dive into some of the support technologies that let developers make great client apps, such as installation, Java Web Start, applets, and graphics improvements. Then we will take a peek at Java 7.