Pages

Monday, October 27, 2014

Springs Security


Springs Security is a flexible and powerful authentication and access control framework to secure Spring-based Java web application.

Spring Security provides security services for J2EE-based enterprise software applications.

Application Security Areas:

There are two main areas for application securities.
  1. Authentication: Process of checking the user, who they claim to be.
  2. Authorization: Process of deciding whether an user is allowed to perform an activity within the application.

Spring Security Modules

Spring security code has been divided in different JARs(Can be considers as modules)
  1. Core (spring-security-core.jar) : Required. Contains core authentication and access-contol classes and interfaces, remoting support and basic provisioning APIs.
  2. Web (spring-security-web.jar): Required* if web authentication services and URL-based access-control is required.Contains filters and related web-security infrastructure code.

 Types or Levels:

1) URL
2) Method
3) ACL object level security.

more coming soon.......

Wednesday, May 30, 2012

Difference between two times in javascript


var secondsPerMinute = 60;
var minutesPerHour = 60;

function convertSecondsToHHMMSS(intSecondsToConvert) {
var hours = convertHours(intSecondsToConvert);
var minutes = getRemainingMinutes(intSecondsToConvert);
minutes = (minutes == 60) ? "00" : minutes;
var seconds = getRemainingSeconds(intSecondsToConvert);
return hours+":"+minutes;
}

function convertHours(intSeconds) {
var minutes = convertMinutes(intSeconds);
var hours = Math.floor(minutes/minutesPerHour);
return hours;
}
function convertMinutes(intSeconds) {
return Math.floor(intSeconds/secondsPerMinute);
}
function getRemainingSeconds(intTotalSeconds) {
return (intTotalSeconds%secondsPerMinute);
}
function getRemainingMinutes(intSeconds) {
var intTotalMinutes = convertMinutes(intSeconds);
return (intTotalMinutes%minutesPerHour);
}

function HMStoSec1(T) { // h:m:s
  var A = T.split(/\D+/) ; return (A[0]*60 + +A[1])*60 + +A[2] }
 
Sample code to get difference between two times using javascript 
var time1 = HMStoSec1("10:00:00");
var time2 = HMStoSec1("12:05:00");
var diff = time2 - time1;
document.write(convertSecondsToHHMMSS(diff));

Tuesday, January 31, 2012

Get the process id in java

Each application is treated as Process in our JVM. So how to get our running application in runtime. In java in lang package we are having a class called ManagementFactory. Which will help us to trace out process id of our running application.

     ManagementFactory.getRuntimeMXBean().getName()

It will returns the id in String format.
We need to use this command after each process or thread.
 
For Eg see the below examples: 
  
To Get the process id.  
import java.awt.BorderLayout;
import java.awt.Color;
import java.lang.management.ManagementFactory;

import javax.swing.JFrame;
import javax.swing.JTextArea;

public class SwingDemo {
     public static void main(String[] args) {
         try {
                JFrame f = new JFrame(System.nanoTime()+"");
                f.setSize(450, 450);
                f.setLocation(300,200);
                f.getContentPane().add(BorderLayout.CENTER, new JTextArea(10, 40));
                f.setVisible(true);
                f.setForeground(Color.BLUE);
              
                    //Process process = Runtime.getRuntime().exec("notepad.exe");
                    System.out.println("P id::=>" +
                                ManagementFactory.getRuntimeMXBean().getName()
                    );           
                    System.out.println("T id::=>" );
                    //    process.destroy();
            
             } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
          
          }
}

To Kill the process id       

  // serviceName should be the process id  which we got from the above application.
  // taskkill /IM command will work on windows only. Check out in web for OS dependent commands.
  public static void killProcess(String serviceName) throws Exception {

          Runtime.getRuntime().exec("taskkill /IM " + serviceName);  
  }


To check whether Process is running or not.

  public static boolean isProcessRunning(String serviceName) throws Exception {

         Process p = Runtime.getRuntime().exec(TASKLIST);
         Thread.sleep(1000);
         BufferedReader reader = new BufferedReader(new InputStreamReader(
           p.getInputStream()));
         String line;
         while ((line = reader.readLine()) != null) {

          System.out.println("om ::"+ line);
          if (line.contains(serviceName)) {
           return true;
          }
         }

         return false;
}

So i hope with the help of above sample code you can achieve process id of your applications.

Friday, January 20, 2012

Eclipse plugin for PhoneGap




Get the MDS AppLaud 1.2 Eclipse Plug-In!
  • In Eclipse ADT, Select Help -> Install New Software
  • Click Add to enter a new Repository site
  • The Name field is optional, "MDS AppLaud 1.2" suggested
  • In Location, enter the download site: https://svn.codespot.com/a/eclipselabs.org/mobile-web-development-with-phonegap/tags/r1.2/download
  • Select OK
  • Select the New Site and Check the box to the left of PhoneGap for Android
  • Click Finish and Follow the prompts
  • If your Eclipse installation doesn't yet include a web page editor for html files. Necessary for new Classic or Java editions.
    • Install New Software -> Work with: Indigo (or Helios) ->Web, XML Java EE, and OSGi Enterprise Development -> Web Page Editor
REF LINK: http://www.mobiledevelopersolutions.com/home/download

Camera Access using PhoneGap.

CAMERA 
         The camera object provides access to the device's default camera application.
Methods:
         camera.getPicture
           
             Takes a photo using the camera or retrieves a photo from the device's album. The image is returned as a base64 encoded String or as the URI of an image file. 

  navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] );  
Description 
  
Function camera.getPicture opens the device's default camera application so that the user can take a picture (if Camera.sourceType = Camera.PictureSourceType.CAMERA, which is the default). Once the photo is taken, the camera application closes and your application is restored.
If Camera.sourceType = Camera.PictureSourceType.PHOTOLIBRARY or Camera.PictureSourceType.SAVEDPHOTOALBUM, then a photo chooser dialog is shown, from which a photo from the album can be selected.
The return value will be sent to the cameraSuccess function, in one of the following formats, depending on the cameraOptions you specify:
  • A String containing the Base64 encoded photo image (default).
  • A String representing the image file location on local storage.
You can do whatever you want with the encoded image or URI, for example:
  • Render the image in an <img> tag (see example below)
  • Save the data locally (LocalStorage, Lawnchair, etc)
  • Post the data to a remote server
Note: The image quality of pictures taken using the camera on newer devices is quite good. Encoding such images using Base64 has caused memory issues on some of these devices (iPhone 4, BlackBerry Torch 9800). Therefore, using FILE_URI as the 'Camera.destinationType' is highly recommended.

Supported Platforms:
  • Android
  • Blackberry WebWorks (OS 5.0 and higher)
  • iPhone
  • Windows Phone 7 ( Mango )
Quick Example:  
  Take photo and retrieve Base64-encoded image:   
   navigator.camera.getPicture(onSuccess, onFail, { quality: 50 }); 
  function onSuccess(imageData) {
      var image = document.getElementById('myImage');
      image.src = "data:image/jpeg;base64," + imageData;
  }
  function onFail(message) {
      alert('Failed because: ' + message);
  } 

Take photo and retrieve image file location:  
   navigator.camera.getPicture(onSuccess, onFail, { quality: 50, 
      destinationType: Camera.DestinationType.FILE_URI }); 
  function onSuccess(imageURI) {
      var image = document.getElementById('myImage');
      image.src = imageURI;
  }
  function onFail(message) {
      alert('Failed because: ' + message);
  } 
 
 
FULL EXAMPLE:    
 


<!DOCTYPE html>
<html>
  <head>
    <title>Capture Photo</title>

    <script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
    <script type="text/javascript" charset="utf-8">

    var pictureSource;   // picture source
    var destinationType; // sets the format of returned value 

    // Wait for PhoneGap to connect with the device
    //
    document.addEventListener("deviceready",onDeviceReady,false);

    // PhoneGap is ready to be used!
    //
    function onDeviceReady() {
        pictureSource=navigator.camera.PictureSourceType;
        destinationType=navigator.camera.DestinationType;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoDataSuccess(imageData) {
      // Uncomment to view the base64 encoded image data
      // console.log(imageData);

      // Get image handle
      //
      var smallImage = document.getElementById('smallImage');

      // Unhide image elements
      //
      smallImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      smallImage.src = "data:image/jpeg;base64," + imageData;
    }

    // Called when a photo is successfully retrieved
    //
    function onPhotoURISuccess(imageURI) {
      // Uncomment to view the image file URI 
      // console.log(imageURI);

      // Get image handle
      //
      var largeImage = document.getElementById('largeImage');

      // Unhide image elements
      //
      largeImage.style.display = 'block';

      // Show the captured photo
      // The inline CSS rules are used to resize the image
      //
      largeImage.src = imageURI;
    }

    // A button will call this function
    //
    function capturePhoto() {
      // Take picture using device camera and retrieve image as base64-encoded string
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50 });
    }

    // A button will call this function
    //
    function capturePhotoEdit() {
      // Take picture using device camera, allow edit, and retrieve image as base64-encoded string  
      navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true }); 
    }

    // A button will call this function
    //
    function getPhoto(source) {
      // Retrieve image file location from specified source
      navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, 
        destinationType: destinationType.FILE_URI,
        sourceType: source });
    }

    // Called if something bad happens.
    // 
    function onFail(message) {
      alert('Failed because: ' + message);
    }

    </script>
  </head>
  <body>
    <button onclick="capturePhoto();">Capture Photo</button> <br>
    <button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
    <button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
    <button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
    <img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
    <img style="display:none;" id="largeImage" src="" />
  </body></html>  
 
Camera Success 
onSuccess callback function that provides the image data.  
function(imageData) {
    // Do something with the image
}
Parameter 
   imageData: Base64 encoding of the image data, OR the image file URI, 
   depending on cameraOptions used. (String) 
 
 Example: 
// Show image
//
function cameraCallback(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}
 Camera Error  
     onError callback function that provides an error me
function(message) {
    // Show a helpful message
} 
 parameters: 
     message: The message is provided by the device's native code. (String) 
 
Camera Options  
 Optional parameters to customize the camera settings.
{ quality : 75, 
  destinationType : Camera.DestinationType.DATA_URL, 
  sourceType : Camera.PictureSourceType.CAMERA, 
  allowEdit : true,
  encodingType: Camera.EncodingType.JPEG,
  targetWidth: 100,
  targetHeight: 100 }; 
Options: 
  • quality: Quality of saved image. Range is [0, 100]. (Number)
  • destinationType: Choose the format of the return value. Defined in navigator.camera.DestinationType (Number)
Camera.DestinationType = {                                                       
        DATA_URL : 0,                // Return image as base64 encoded string    
        FILE_URI : 1                 // Return image file URI                    
    };                                                                           
sourceType: Set the source of the picture.  Defined in 
nagivator.camera.PictureSourceType (Number) 
Camera.PictureSourceType = {
    PHOTOLIBRARY : 0,
    CAMERA : 1,
    SAVEDPHOTOALBUM : 2
};
  • allowEdit: Allow simple editing of image before selection. (Boolean)
  • EncodingType: Choose the encoding of the returned image file. Defined in navigator.camera.EncodingType (Number)
Camera.EncodingType = {                                                          
        JPEG : 0,               // Return JPEG encoded image                     
        PNG : 1                 // Return PNG encoded image                      
    };                                                                           
  • targetWidth: Width in pixels to scale image. Must be used with targetHeight. Aspect ratio is maintained. (Number)
  • targetHeight: Height in pixels to scale image. Must be used with targetWidth. Aspect ratio is maintained. (Number)
  • MediaType: Set the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM. Defined in nagivator.camera.
    MediaType (Number)Camera.MediaType = {
    PICTURE: 0,             // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType
    VIDEO: 1,               // allow selection of video only, WILL ALWAYS RETURN FILE_URI
    ALLMEDIA : 2            // allow selection from all media types
 
 
 
                                                                                                                                                                                                                    
REF Link:                                                                                                                                                                                                            
http://docs.phonegap.com/en/1.2.0/phonegap_camera_camera.md.html#camera.getPicture_full_example                        
     
              

 
 
 
 
 

PHONEGAP with Android


1. Requirements

  • Eclipse 3.4+
There is also a Terminal version of this tutorial that doesn't use Eclipse.

2. Install SDK + PhoneGap


3. Setup New Project


  • Launch Eclipse, then under the File menu select New > Android Project

  • In the root directory of the project, create two new directories:
    • /libs
    • /assets/www
  • Copy phonegap.js from your PhoneGap download earlier to /assets/www
  • Copy phonegap.jar from your PhoneGap download earlier to /libs
  • Copy xml folder from your PhoneGap download earlier to /res
  • Make a few adjustments too the project's main Java file found in the src folder in Eclipse: (view image below)
    • Change the class's extend from Activity to DroidGap
    • Replace the setContentView() line with super.loadUrl("file:///android_asset/www/index.html");
    • Add import com.phonegap.*;
    • Remove import android.app.Activity;
    •  
  • You might experience an error here, where Eclipse can't find phonegap-1.0.0.jar. In this case, right click on the /libs folder and go to Build Paths/ > Configure Build Paths. Then, in the Libraries tab, add phonegap-1.0.0.jar to the Project. If Eclipse is being temperamental, you might need to refresh (F5) the project once again.
  • Right click on AndroidManifest.xml and select Open With > Text Editor
  • Paste the following permissions under versionName: (view image below) 


  • < supports-screens android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:resizeable="true" android:anyDensity="true" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.RECORD_AUDIO" /> <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_CONTACTS" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.GET_ACCOUNTS" /> <uses-permission android:name="android.permission.BROADCAST_STICKY" />
  • Add android:configChanges="orientation|keyboardHidden" to the activity tag in AndroidManifest. (view image below)
  • Add a second activity under you appliction tag in AndroidManifest. (view image below)

<activity name="com.phonegap.DroidGap" label="@string/app_name" configchanges="orientation|keyboardHidden">
<intent-filter>
</intent-filter>
</activity>

4. Hello World

Now create and open a new file named index.html in the /assets/www directory. Paste the following code:



<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>



*phonegap.js might need to be replaced with phonegap.<version numer>.js

5A. Deploy to Simulator


  • Right click the project and go to Run As and click Android Application
  • Eclipse will ask you to select an appropriate AVD. If there isn't one, then you'll need to create it.

5B. Deploy to Device

  • Make sure USB debugging is enabled on your device and plug it into your system. (Settings > Applications > Development)
  • Right click the project and go to Run As and click Android Application

Tuesday, December 21, 2010

Java Framework Inventors

Here are the top 8 Java people, they’re created frameworks, products, tools or books that contributed to the Java community, and changed the way of coding Java.



8. Tomcat & Ant Founder




James Duncan Davidson, while he was software engineer at Sun Microsystems (1997–2001), created Tomcat Java-based web server, still widely use in most of the Java web projects, and also Ant build tool, which uses XML to describe the build process and its dependencies, which is still the de facto standard for building Java-based Web applications.
Related Links
1. James Duncan Davidson Twitter
2. James Duncan Davidson Wiki
3. James Duncan Davidson personal blog
4. Apache Ant
5. Apache Tomcat


7. Test Driven Development & JUnit Founder



Kent Beck, creator of the Extreme Programming and Test Driven Development software development methodologies. Furthermore, he and Erich Gamma created JUnit, a simple testing framework, which turn into the de facto standard for testing Java-based Web applications. The combine of JUnit and Test Driven Development makes a big changed on the way of coding Java, which causes many Java developers are not willing to follow it.
Related Links
1. Kent Beck Twitter
2. Kent Beck Wiki
3. Kent Beck Blog
4. JUnit Testing Framework
5. Extreme Programming Wiki
6. Test Driven Development Wiki
News & Interviews
1. Kent Beck: “We thought we were just programming on an airplane”
2. Interview with Kent Beck and Martin Fowler
3. eXtreme Programming An interview with Kent Beck
Kent Beck Books
1. Extreme Programming Explained: Embrace Change (2nd Edition)
2. Refactoring: Improving the Design of Existing Code
3. JUnit Pocket Guide



6. Java Collections Framework



Joshua Bloch, led the design and implementation of numerous Java platform features, including JDK 5.0 language enhancements and the award-winning Java Collections Framework. In June 2004 he left Sun and became Chief Java Architect at Google. Furthermore, he won the prestigious Jolt Award from Software Development Magazine for his book, “Effective Java”, which is arguably a must read Java’s book.
Related Links
1. Joshua Bloch Twitter
2. Joshua Bloch Wiki
News & Interviews
1. Effective Java: An Interview with Joshua Bloch
2. Rock Star Josh Bloch
Joshua Bloch Books
1. Effective Java (2nd Edition)
2. Java Concurrency in Practice



5. JBoss Founder




Marc Fleury, who founded JBoss in 2001, an open-source Java application server, arguably the de facto standard for deploying Java-based Web applications. Later he sold the JBoss to RedHat, and joined RedHat to continue support on the JBoss development. On 9 February 2007, he decided to leave Red Hat to pursue other personal interests, such as teaching, research in biology, music and his family.
Related Links
1. Marc Fleury Wiki
2. Marc Fleury Blog
3. JBoss Application Server
News & Interviews
1. Could Red Hat lose JBoss founder?
2. JBoss founder Marc Fleury leaves Red Hat, now what?
3. JBoss’s Marc Fleury on SOA, ESB and OSS
4. Resurrecting Marc Fleury


4. Struts Founder





Craig Mcclanahan, creator of Struts, a popular open source MVC framework for building Java-based web applications, which is arguably that every Java developer know how to code Struts. With the huge success of Struts in early day, it’s widely implemented in every single of the old Java web application project.
Related Links
1. Craig Mcclanahan Wiki
2. Craig Mcclanahan Blog
3. Apache Struts
News & Interviews
1. Interview with Craig McClanahan
2. Struts Or JSF?


3. Spring Founder




Rod Johnson, is the founder of the Spring Framework, an open source application framework for Java, Creator of Spring, CEO at SpringSource. Furthermore, Rod’s best-selling Expert One-on-One J2EE Design and Development (2002) was one of the most influential books ever published on J2EE.
Related Links
1. Rod Johnson Twitter
2. Rod Johnson Blog
3. SpringSource
4. Spring Framework Wiki
News & Interviews
1. VMware.com : VMware to acquire SpringSource
2. Rod Johnson : VMware to acquire SpringSource
3. Interview with Rod Johnson – CEO – Interface21
4. Q&A with Rod Johnson over Spring’s maintenance policy changes
5. Expert One-on-One J2EE Design and Development: Interview with Rod Johnson
Rod Johnson Books
1. Expert One-on-One J2EE Design and Development (Programmer to Programmer)
2. Expert One-on-One J2EE Development without EJB


2. Hibernate Founder



Gavin King, is the founder of the Hibernate project, a popular object/relational persistence solution for Java, and the creator of Seam, an application framework for Java EE 5. Furthermore, he contributed heavily to the design of EJB 3.0 and JPA.
Related Links
1. Gavin King Blog
2. Hibernate Wiki
3. Hibernate Framework
4. JBoss seam
News & Interviews
1. Tech Chat: Gavin King on Contexts and Dependency Injection, Weld, Java EE 6
2. JPT : The Interview: Gavin King, Hibernate
3. JavaFree : Interview with Gavin King, founder of Hibernate
4. Seam in Depth with Gavin King
Gavin King Books
1. Java Persistence with Hibernate
2. Hibernate in Action (In Action series)


1. Father of the Java programming language



James Gosling, generally credited as the inventor of the Java programming language in 1994. He created the original design of Java and implemented its original compiler and virtual machine. For this achievement he was elected to the United States National Academy of Engineering. On April 2, 2010, he left Sun Microsystems which had recently been acquired by the Oracle Corporation. Regarding why he left, Gosling wrote on his blog that “Just about anything I could say that would be accurate and honest would do more harm than good.”

Friday, December 3, 2010

Explain the term 'architecture of the application'?

Architecture is the set of rules (or framework) to bring in some common way of assembling or using J2EE components in the application. This helps in bringing consistency between codes developed by various developers in the team.

Monday, October 18, 2010

Java Deveoper 2010

Adam Bien: Java Developer of the Year (2010). This is one award announced by Oracle this year.

Wednesday, September 15, 2010

Mobile Devices

CDMA

Code-Division Multiple Access.

CDMA is a digital wireless technology. It is a general type of technology, implemented in many specific technologies. But the term "CDMA" is also commonly used to refer to one specific family of technologies (IS-95 and CDMA2000) used in the US by Sprint and Verizon Wireless. This technology competes with GSM, used by AT&T and T-Mobile.

CDMA is a "spread spectrum" technology, which means that it spreads the information contained in a particular signal of interest over a much greater bandwidth than the original signal.

Unlike many competing technologies, CDMA has no hard limit for the number of users who may share one base station (tower). Instead, with CDMA, additional users can connect until the base station determines that call quality would suffer beyond a set limit.

CDMA (IS-95) systems have been in commercial operation since 1995. CDMA networks operate in the 800 and 1900 MHz frequency bands with primary markets in the Americas and Asia.

IS-95 CDMA technology has also been called cdmaOne and cdma2000.

GSM

Global System for Mobile Communication.

GSM is the dominant 2G digital mobile phone standard for most of the world. It determines the way in which mobile phones communicate with the land-based network of towers.

GSM is one of two major mobile phone technologies in the U.S. The other is CDMA. AT&T and T-Mobile use GSM. Sprint and Verizon use CDMA. GSM is more prevalent in most other parts of the world, and especially in Europe.

Although GSM and CDMA provide similar basic features and services to end-users, (such as voice calling, text messaging, and data services,) they operate very differently at many technical levels. This makes GSM phones completely incompatible with CDMA networks, and vice-versa.

The most visible feature of GSM are SIM cards. SIM cards are removable, thumbnail-sized smart cards which identify the user on the network, and can also store information such as phone book entries. SIM cards allows users to switch phones by simply moving their SIM card from one phone to the other.

WCDMA

(Wideband Code Division Multiple Access)

Wideband CDMA is a third-generation (3G) wireless standard which utilizes one 5 MHz channel for both voice and data, initially offering data speeds up to 384 Kbps. WCDMA is the 3G technology used in the US by AT&T and T-Mobile.

There are several newer technologies that offer much faster data speeds, such as HSDPA, HSUPA, and HSPA. These do not replace WCDMA, but rather build on and enhance WCDMA. Therefore any phone with HSDPA also includes WCDMA by definition.

WCDMA is also referred to as UMTS - the two terms are effectively interchangeable.

WCDMA is the 3G standard that most GSM carriers are moving to. Parts of the WCDMA standard are based on GSM technology. WCDMA networks are designed to integrate with GSM networks at certain levels. Most WCDMA phones include GSM as well, for backward compatibility.

WCDMA borrows certain technology ideas from CDMA, as the name implies, but is in fact very different and incompatible with phones and networks using "CDMA" technology.

In Europe and Asia, WCDMA is being deployed in the all-new 2100 MHz frequency band. In North America, WCDMA is being deployed in the existing 1900 MHz (PCS) and 850 MHz (cellular) bands, as well as the newer 1700 MHz (AWS) band.


3G

3G Stands for 3rd-generation. Analog cellular phones were the first generation. Digital phones marked the second generation (2G).

3G is loosely defined, but generally includes high data speeds, always-on data access, and greater voice capacity.

The high data speeds are possibly the most prominent feature, and certainly the most hyped. They enable such advanced features as live, streaming video.

There are several different 3G technology standards. The most prevalent worldwide is UMTS, which is based on WCDMA. (The terms WCDMA and UMTS are often used interchangeably.) UMTS is the 3G technology of choice for most carriers that used GSM as their 2G technology.

The other major standard is cdma2000, which is an evolution of CDMA 2G technology. There are several types of cdma2000, each offering different data rates and levels of compatibility with 2G CDMA. EV-DO Rev A is the most common today.


UMTS

Universal Mobile Telecommunications System.

A third generation (3G) mobile communications technology that promises data transmission speeds of up to 2 megabits per second (Mbps), although actual speeds may be significantly lower at first, due to network capacity restrictions.

UMTS uses WCDMA technology, and the two terms are often used interchangeably with each other.

PCS

(Personal Communications Services)

1. The FCC-licensed frequency band near 1900 MHz.

2. A marketing term used to describe a wide variety of two-way digital wireless service offerings operating at 1900 MHz.

Wednesday, August 11, 2010

5 things you didn't know about ... JARs

Put it in a JAR

Normally, you build a JAR file after your code source has been compiled, collecting the Java code (which has been segregated by package) into a single collection via either the jar command-line utility, or more commonly, the Ant jar task. The process is straightforward enough that I won't demonstrate it here, though later in the article we'll return to the topic of how JARs are constructed. For now, we just need to archive Hello, a stand-alone console utility that does the incredibly useful task of printing a message to the console, shown in Listing 1:

Listing 1. Archiving the console utility

package com.tedneward.jars;

public class Hello
{
public static void main(String[] args)
{
System.out.println("Howdy!");
}
}


The Hello utility isn't much, but it's a useful scaffold for exploring JAR files, starting with executing the code.


1. JARs are executable

Languages like .NET and C++ have historically had the advantage of being OS-friendly, in that simply referencing their name at the command-line (helloWorld.exe) or double-clicking their icon in the GUI shell would launch the application. In Java programming, however, a launcher application — java — bootstraps the JVM into the process, and we have to pass a command-line argument (com.tedneward.Hello) indicating the class whose main() method we want to launch.

These additional steps make it harder to create user-friendly applications in Java. Not only does the end user have to type all of these elements at the command-line, which many end users would rather avoid, but chances are good that he or she will somehow fat-finger it and get an obscure error back.

The solution is to make the JAR file "executable" so that the Java launcher will automatically know which class to launch when executing the JAR file. All we have to do is introduce an entry into the JAR file's manifest (MANIFEST.MF in the JAR's META-INF subdirectory), like so:

Listing 2. Show me the entrypoint!

Main-Class: com.tedneward.jars.Hello



The manifest is just a set of name-value pairs. Because the manifest can sometimes be touchy about carriage returns and whitespace, it's easiest to use Ant to generate it when building the JAR. In Listing 3, I've used the manifest element of the Ant jar task to specify the manifest:

Listing 3. Build me the entrypoint!










All a user has to do to execute the JAR file now is specify its filename on the command-line, via java -jar outapp.jar. In the case of some GUI shells, double-clicking the JAR file works just as well.


2. JARs can include dependency information

It seems that word of the Hello utility has spread, and so the need to vary the implementation has emerged. Dependency injection (DI) containers like Spring or Guice handle many of the details for us, but there's still a hitch: modifying code to include the use of a DI container can lead to results like what you see in Listing 4:

Listing 4. Hello, Spring world!

package com.tedneward.jars;

import org.springframework.context.*;
import org.springframework.context.support.*;

public class Hello
{
public static void main(String[] args)
{
ApplicationContext appContext =
new FileSystemXmlApplicationContext("./app.xml");
ISpeak speaker = (ISpeak) appContext.getBean("speaker");
System.out.println(speaker.sayHello());
}
}


Because the -jar option to the launcher overwrites whatever happens to be in the -classpath command-line option, Spring needs to be on the CLASSPATH and in the environment variable when you run this code. Fortunately, JARs permit a declaration of other JAR dependencies to appear in the manifest, which implicitly creates the CLASSPATH without you having to declare it, shown in Listing 5:


Listing 5. Hello, Spring CLASSPATH!





value="./lib/org.springframework.context-3.0.1.RELEASE-A.jar
./lib/org.springframework.core-3.0.1.RELEASE-A.jar
./lib/org.springframework.asm-3.0.1.RELEASE-A.jar
./lib/org.springframework.beans-3.0.1.RELEASE-A.jar
./lib/org.springframework.expression-3.0.1.RELEASE-A.jar
./lib/commons-logging-1.0.4.jar" />





Notice that the Class-Path attribute contains a relative reference to the JAR files that the application depends on. You could also write this as an absolute reference or without a prefix entirely, in which case it would be assumed that the JAR files were in the same directory as the application JAR.

Unfortunately, the value attribute to the Ant Class-Path attribute has to appear in one line, because the JAR manifest can't cope with the idea of multiple Class-Path attributes. So, all of those dependencies have to appear on one line in the manifest file. Sure, it's ugly, but being able to java -jar outapp.jar is worth it!



3. JARs can be implicitly referenced

If you have several different command-line utilities (or other applications) that make use of the Spring framework, it might be easier to put the Spring JAR files into a common location that all of the utilities can reference. Doing so avoids having multiple copies of JARs popping up all over the filesystem. The Java runtime's common location for JARs, known as the "extension directory," is by default located in the lib/ext subdirectory, underneath the installed JRE location.

The JRE is a customizable location, but it is so rarely customized within a given Java environment that it's entirely safe to assume that lib/ext is a safe place to store JARs, and that they will be implicitly available on the Java environment's CLASSPATH.



4. Java 6 allows classpath wildcards

In an effort to avoid huge CLASSPATH environment variables (which Java developers should have left behind years ago) and/or command-line -classpath parameters, Java 6 introduced the notion of the classpath wildcard. Rather than having to launch with each and every JAR file explicitly listed on an argument, the classpath wildcard lets you specify lib/*, and all of the JAR files listed in that directory (not recursively), in the classpath.

Unfortunately, the classpath wildcard doesn't hold for the previously discussed Class-Path attribute manifest entry. But it does make it easier to launch Java applications (including servers) for developer tasks such as code-gen tools or analysis tools.


5. JARs hold more than code

Spring, like so many parts of the Java ecosystem, depends on a configuration file that describes how the environment should be established. As written, Spring depends on an app.xml file that lives in the same directory as the JAR file — but it's entirely common for developers to forget to copy the configuration file alongside the JAR file.

Some configuration files are editable by a sysadmin, but a significant number of them (such as Hibernate mappings) are well outside of the sysadmin's domain, which leads to deployment bugs. A sensible solution would be to package the config file together with the code — and it's doable because a JAR is basically a ZIP in disguise. Just include config files in the Ant task or the jar command-line when building a JAR.

JARs can also include other types of files, not just configuration files. For instance, if my SpeakEnglish component wanted to access a properties file, I could set that up like Listing 6:

Listing 6. Respond at random

package com.tedneward.jars;

import java.util.*;

public class SpeakEnglish
implements ISpeak
{
Properties responses = new Properties();
Random random = new Random();

public String sayHello()
{
// Pick a response at random
int which = random.nextInt(5);

return responses.getProperty("response." + which);
}
}


Putting responses.properties into the JAR file means that there's one less file to worry about deploying alongside the JAR file. Doing that just requires including the responses.properties file during the JAR step.

Once you've stored your properties in a JAR, though, you might wonder how to get them back. If the data desired is co-located inside the same JAR file, as it is in the previous example, then don't bother trying to figure out the file location of the JAR and crack it open with a JarFile object. Instead, let the class's ClassLoader find it as a "resource" within the JAR file, using the ClassLoader getResourceAsStream() method shown in Listing 7:

Listing 7. ClassLoader locates a Resource

package com.tedneward.jars;

import java.util.*;

public class SpeakEnglish
implements ISpeak
{
Properties responses = new Properties();
// ...

public SpeakEnglish()
{
try
{
ClassLoader myCL = SpeakEnglish.class.getClassLoader();
responses.load(
myCL.getResourceAsStream(
"com/tedneward/jars/responses.properties"));
}
catch (Exception x)
{
x.printStackTrace();
}
}

// ...
}


You can follow this procedure for any kind of resource: configuration file, audio file, graphics file, you name it. Virtually any file type can be bundled into a JAR, obtained as an InputStream (via the ClassLoader) and used in whatever fashion suits your fancy.


In conclusion

This article has covered the top five things most Java developers don't know about JARs — at least based on history and anecdotal evidence. Note that all of these JARs-related tips are equally true for WARs. Some tips (the Class-Path and Main-Class attributes in particular) are less exciting in the case of WARs, because the servlet environment picks up the entire contents of a directory and has a predefined entry point. Still, taken collectively, these tips move us beyond the paradigm of "Okay, start by copying everything in this directory ..." In so doing, they also make deploying Java applications much simpler.

Next up in this series: 5 things you didn't know about performance monitoring for Java applications.



Author: Ted Neward
Ref Site: http://www.ibm.com/developerworks/java/library/j-5things6.html

Tuesday, August 10, 2010

Java Best Practices

Quote 1: Avoid creating unnecessary objects and always prefer to do Lazy Initialization

Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code.
view source

01 public class Countries {
02
03 private List countries;
04
05 public List getCountries() {
06
07 //initialize only when required
08 if(null == countries) {
09 countries = new ArrayList();
10 }
11 return countries;
12 }
13 }
Quote 2: Never make an instance fields of class public

Making a class field public can cause lot of issues in a program. For instance you may have a class called MyCalender. This class contains an array of String weekdays. You may have assume that this array will always contain 7 names of weekdays. But as this array is public, it may be accessed by anyone. Someone by mistake also may change the value and insert a bug!
view source

1 public class MyCalender {
2
3 public String[] weekdays =
4 {"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
5
6 //some code
7
8 }

Best approach as many of you already know is to always make the field private and add a getter method to access the elements.
view source

1 private String[] weekdays =
2 {"Sun", "Mon", "Tue", "Thu", "Fri", "Sat", "Sun"};
3
4 public String[] getWeekdays() {
5 return weekdays;
6 }

But writing getter method does not exactly solve our problem. The array is still accessible. Best way to make it unmodifiable is to return a clone of array instead of array itself. Thus the getter method will be changed to.
view source

1 public String[] getWeekdays() {
2 return weekdays.clone();
3 }
Quote 3: Always try to minimize Mutability of a class

Making a class immutable is to make it unmodifiable. The information the class preserve will stay as it is through out the lifetime of the class. Immutable classes are simple, they are easy to manage. They are thread safe. They makes great building blocks for other objects.

However creating immutable objects can hit performance of an app. So always choose wisely if you want your class to be immutable or not. Always try to make a small class with less fields immutable.

To make a class immutable you can define its all constructors private and then create a public static method
to initialize and object and return it.
view source

01 public class Employee {
02
03 private String firstName;
04 private String lastName;
05
06 //private default constructor
07 private Employee(String firstName, String lastName) {
08 this.firstName = firstName;
09 this.lastName = lastName;
10 }
11
12 public static Employee valueOf (String firstName, String lastName) {
13 return new Employee(firstName, lastName);
14 }
15 }
Quote 4: Try to prefer Interfaces instead of Abstract classes

First you can not inherit multiple classes in Java but you can definitely implements multiple interfaces. Its very easy to change the implementation of an existing class and add implementation of one more interface rather then changing full hierarchy of class.

Again if you are 100% sure what methods an interface will have, then only start coding that interface. As it is very difficult to add a new method in an existing interface without breaking the code that has already implemented it. On contrary a new method can be easily added in Abstract class without breaking existing functionality.
Quote 5: Always try to limit the scope of Local variable

Local variables are great. But sometimes we may insert some bugs due to copy paste of old code. Minimizing the scope of a local variable makes code more readable, less error prone and also improves the maintainability of the code.

Thus, declare a variable only when needed just before its use.

Always initialize a local variable upon its declaration. If not possible at least make the local instance assigned null value.
Quote 6: Try to use standard library instead of writing your own from scratch

Writing code is fun. But “do not reinvent the wheel”. It is very advisable to use an existing standard library which is already tested, debugged and used by others. This not only improves the efficiency of programmer but also reduces chances of adding new bugs in your code. Also using a standard library makes code readable and maintainable.

For instance Google has just released a new library Google Collections that can be used if you want to add advance collection functionality in your code.
Quote 7: Wherever possible try to use Primitive types instead of Wrapper classes

Wrapper classes are great. But at same time they are slow. Primitive types are just values, whereas Wrapper classes are stores information about complete class.

Sometimes a programmer may add bug in the code by using wrapper due to oversight. For example, in below example:
view source

1 int x = 10;
2 int y = 10;
3
4 Integer x1 = new Integer(10);
5 Integer y1 = new Integer(10);
6
7 System.out.println(x == y);
8 System.out.println(x1 == y1);

The first sop will print true whereas the second one will print false. The problem is when comparing two wrapper class objects we cant use == operator. It will compare the reference of object and not its actual value.

Also if you are using a wrapper class object then never forget to initialize it to a default value. As by default all wrapper class objects are initialized to null.
view source

1 Boolean flag;
2
3 if(flag == true) {
4 System.out.println("Flag is set");
5 } else {
6 System.out.println("Flag is not set");
7 }

The above code will give a NullPointerException as it tries to box the values before comparing with true and as its null.
Quote 8: Use Strings with utmost care.

Always carefully use Strings in your code. A simple concatenation of strings can reduce performance of program. For example if we concatenate strings using + operator in a for loop then everytime + is used, it creates a new String object. This will affect both memory usage and performance time.

Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly. For example:
view source

1 //slow instantiation
2 String slow = new String("Yet another string object");
3
4 //fast instantiation
5 String fast = "Yet another string object";
Quote 9: Always return empty Collections and Arrays instead of null

Whenever your method is returning a collection element or an array, always make sure you return empty array/collection and not null. This will save a lot of if else testing for null elements. For instance in below example we have a getter method that returns employee name. If the name is null it simply return blank string “”.
view source

1 public String getEmployeeName() {
2 return (null==employeeName ? "": employeeName);
3 }
Quote 10: Defensive copies are savior

Defensive copies are the clone objects created to avoid mutation of an object. For example in below code we have defined a Student class which has a private field birth date that is initialized when the object is constructed.
view source

01 public class Student {
02 private Date birthDate;
03
04 public Student(birthDate) {
05 this.birthDate = birthDate;
06 }
07
08 public Date getBirthDate() {
09 return this.birthDate;
10 }
11 }

Now we may have some other code that uses the Student object.
view source

1 public static void main(String []arg) {
2
3 Date birthDate = new Date();
4 Student student = new Student(birthDate);
5
6 birthDate.setYear(2019);
7
8 System.out.println(student.getBirthDate());
9 }

In above code we just created a Student object with some default birthdate. But then we changed the value of year of the birthdate. Thus when we print the birth date, its year was changed to 2019!

To avoid such cases, we can use Defensive copies mechanism. Change the constructor of Student class to following.
view source

1 public Student(birthDate) {
2 this.birthDate = new Date(birthDate);
3 }

This ensure we have another copy of birthdate that we use in Student class.
Two bonus quotes

Here are two bonus Java best practice quotes for you.
Quote 11: Never let exception come out of finally block

Finally blocks should never have code that throws exception. Always make sure finally clause does not throw exception. If you have some code in finally block that does throw exception, then log the exception properly and never let it come out :)
Quote 12: Never throw “Exception”

Never throw java.lang.Exception directly. It defeats the purpose of using checked Exceptions. Also there is no useful information getting conveyed in caller method.
More Quotes from Java Developers

Do you have a quote that is not included in above list? Well, feel free to add your Java best practice quote using comment below. Write your quote and explain it in 2-3 lines. I will add all those user generated quotes in this section.
Quote #13: Avoid floating point numbers

It is a bad idea to use floating point to try to represent exact quantities like monetary amounts. Using floating point for dollars-and-cents calculations is a recipe for disaster. Floating point numbers are best reserved for values such as measurements, whose values are fundamentally inexact to begin with. For calculations of monetary amounts it is better to use BigDecimal.

Followed URL:

http://viralpatel.net/blogs/2010/02/most-useful-java-best-practice-quotes-java-developers.html

Tuesday, December 22, 2009

Struts Action internal mechanism

An Action is an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request. The controller (RequestProcessor) will select an appropriate Action for each request, create an instance (if necessary), and call the execute method.

Actions must be programmed in a thread-safe manner, because the controller will share the same instance for multiple simultaneous requests. This means you should design with the following items in mind:

* Instance and static variables MUST NOT be used to store information related to the state of a particular request. They MAY be used to share global resources across requests for the same action.

* Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if those resources require protection. (Generally, however, resource classes should be designed to provide their own protection where necessary.

When an Action instance is first created, the controller will call setServlet with a non-null argument to identify the servlet instance to which this Action is attached. When the servlet is to be shut down (or restarted), the setServlet method will be called with a null argument, which can be used to clean up any allocated resources in use by this Action.

Sunday, November 8, 2009

Liferay Extension Environment

1) Download the liferay source from liferay.com
2) Now you need to create two property files those are
release.< computerName > .proerties
app.server.< computeName > .properties
3) Add following content to newly created relese. < computeName > .property file

lp.ext.dir= -- location where to create extension folder--

Eg: lp.ext.dir=D:/hytv/source/ext-env
(Note: Remember this ext-env directory should not be existed physically in specified location)

Now add the below content to newly created file app.server. < computerName > . property file.

app.server.tomcat.dir= < Specify the Tomcat location >

Eg:

##
## Server Type
##

app.server.type=tomcat
app.server.tomcat.version=5.5
app.server.tomcat.dir=D:/hytv/source/apache-tomcat-5.5.27
app.server.tomcat.classes.global.dir=${app.server.tomcat.dir}/lib
app.server.tomcat.lib.endorsed.dir=${app.server.tomcat.dir}/lib/ext
app.server.tomcat.lib.global.dir=${app.server.tomcat.dir}/lib/ext
app.server.tomcat.lib.support.dir=${app.server.tomcat.dir}/lib/ext
app.server.tomcat.zip.name=liferay-portal-tomcat-5.5-${downloads.version}.zip


Note: this file is useful to creates the total tomcat environment of Tomcat and replaces those in specified tomcat server files.


4) Now create a project in Netbeans
NewProject --> Java --> Java-freeform-Project.



5) Now specify the location of liferay source code folder, and build.xml location.




6) Here you can customize the ant build as per your requirement.



7) Now you can choose jdk source levels, and encoding technique.



8) Now click on finish button to get the src project. Here you can see the created project will be shown on netbeans IDE.



9) Ignore the errors if you got in Net beans project. Now expand the build.xml file by clicking on + button.

10) Right click on deploy option and then click on Run target.
11) Now Right click on build-ext option then click on Run target.
12) You have successfully created the liferay extension environment.
13) Now you can open the ext-env folder as netbeans project.
14) Here you need to copy the app.server. < computerName > . properties
and release. < computerName > . properties files from liferay source to ext-env folders.

15) Now if you want to change database, or any other related things then you can just add the necessary changes in portal-ext.properties file of ext-env file.

Eg: Adding new database specification.

# MySQL
#
jdbc.default.driverClassName=com.mysql.jdbc.Driver
jdbc.default.url=jdbc:mysql://localhost/lportal234?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false
jdbc.default.username=root
jdbc.default.password=kmipl


16) Click on build.xml, run the deploy option for every modification.
17) Now Start the tomcat server. (which is specified in app.server. < computerName > . properties file).