Thursday, 14 May 2015

Object Creation in ATG Commerce

          After my yesterday's blog on Object Creation I was wondering how objects gets created in ATG Commerce. So here are my findings.
       
         I will be glad if anyone contribute or correct me in this Blog :).

Nucleus : (The Engine)

        ATG Commerce is a collection of Java Classes which creates an Environment called NUCLEUS which is the heart of ATG and responsible for everything happens in ATG Commerce.

        Nucleus understands the memory usage and optimization and creates objects ONLY when required/necessary. Just like the "main" method in our simple java classes, nucleus needs a "kick start" for classes which are to be initialized.

How Nucleus creates Object

        When you start up an application, Nucleus reads the configuration path, (a location where we keep our configuration files, which is generally the "config" folder of our ATG module). Within one of those directories is a file called Nucleus.properties (present in the config path of some out-of-the-box ATG module) that contains the name of the first component to create. The out-of-the-box Nucleus.properties looks like

$class=atg.nucleus.Nucleus
initialServiceName=
/Initial

       The initialServiceName property instructs Nucleus to configure and start up its initial service using Initial.properties (which is another configuration file, present in some out-of-the-box module's config path). The initial.properties looks like

$class=atg.nucleus.InitialService
initialServices=\
    /atg/Initial,\
    VMSystem,\
    /atg/dynamo/StartServers


        InitialService extends GenericService class which has a method called doStartService() Which act as the main() method of normal java class.

java.lang.Object
extended by atg.nucleus.logging.VariableArgumentApplicationLoggingImpl
extended by atg.nucleus.GenericService
extended by atg.nucleus.InitialService

         From here Internally it calls the the java.lang.Class.forName(String className) method returns the Class object associated with the class or interface with the given string name. And I concluded to this assumption because I seen the below error in my log and also we always put the full class name in the .property file of the component, which can be used to create the object of that class.

Class cls = Class.forName("java.lang.ClassLoader");

at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169) 


     We also can override the doStartService(), which can be used to create the object or start the component.

public void doStartService() throws ServiceException {
// our custom code

// which we want to execute at startup time
super
.doStartService();
}






     

Wednesday, 13 May 2015

Object Creation in Java

This is one question I was not able to reply recently in an Interview. After the Interview I thought of a google search and decided to blog my finding..

As of now I found four different way of creating an Object in JAVA. if there is any other way kindly comment it.

A. Using new Keyword
B. Using Class.forName()
C. Using clone()
D. Using object deserialization.

A. Using new Keyword.

     This is the most common one and most of the time we end up using this.

Example:

Point originOne = new Point(23, 94);
Rectangle rectOne = new Rectangle(originOne, 100, 200);
Rectangle rectTwo = new Rectangle(50, 100);

Three Parts of the New Statement:

Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object

B. Using Class.forName()

    The java.lang.Class.forName(String className) method returns the Class object associated with the class or interface with the given string name.

Parameters : className.. This is fully qualified name of the desired class.

Return Value : This method returns the Class object for the class with the specified name.

Exception

LinkageError -- if the linkage fails.

ExceptionInInitializerError -- if the initialization provoked by this method fails.

ClassNotFoundException -- if the class cannot be located.

Example:

The following example shows the usage of java.lang.Class.forName() method.
package com.tutorialspoint;

import java.lang.*;

public class ClassDemo {

public static void main(String[] args) {

try {
// returns the Class object for the class with the specified name
Class cls = Class.forName("java.lang.ClassLoader");

// returns the name and package of the class
System.out.println("Class found = " + cls.getName());
System.out.println("Package = " + cls.getPackage());
}
catch(ClassNotFoundException ex) {
System.out.println(ex.toString());
}
}
}
Let us compile and run the above program, this will produce the following result:
Class found = java.lang.ClassLoader
Package = package java.lang, Java Platform API Specification, version 1.6

C. Using Clone()

Why use..
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

MyObject anotherObject = new MyObject(); 
MyObject object = anotherObject.clone();

Few words about object cloning :


The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.



The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.


D. Using object deserialization.

Object deserialization is nothing but creating an object from its serialized form.

ObjectInputStream inStream = new ObjectInputStream(anInputStream ); 
MyObject object = (MyObject) inStream.readObject();

Object Serialization and Deserialization: 

Object Serialization is a mechanism where an object can be represented as a sequence of bytes that includes the object's data as well as information about the object's type and the types of data stored in the object.

After a serialized object has been written into a file, it can be read from the file and deserialized that is, the type information and bytes that represent that represent the object and its data can be used to recreate the object in memory. Its JVM independent, meaning an object can be serialized on one platform and deserialized on an entirely different plateform.

The Two Stream Classes to serialize:

1. ObjectInputStream.
2. ObjectOutputStream.

Significant Method for Serialization and Deserialization :

The ObjectOutputStream class contains many write methods for writing various data types, but one method in particular stands out:
public final void writeObject(Object x) throws IOException
The above method serializes an Object and sends it to the output stream. Similarly, the ObjectInputStream class contains the following method for deserializing an object:
public final Object readObject() throws IOException, 
ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The return value is Object, so you will need to cast it to its appropriate data type
Example :

Suppose that we have the following Employee class, which implements the Serializable interface:

public class Employee implements java.io.Serializable
{
public String name;
public String address;
public transient int SSN;
public int number;
public void mailCheck()
{
System.out.println("Mailing a check to " + name
+ " " + address);
}
}

Notice that for a class to be serialized successfully, two conditions must be met:

The class must implement the java.io.Serializable interface.

All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.


If you are curious to know if a Java Standard Class is serializable or not, check the documentation for the class. The test is simple: If the class implements java.io.Serializable, then it is serializable; otherwise, it's not.

Serializing an Object:

The ObjectOutputStream class is used to serialize an Object. The following SerializeDemo program instantiates an Employee object and serializes it to a file.

When the program is done executing, a file named employee.ser is created. The program does not generate any output, but study the code and try to determine what the program is doing.

Note: When serializing an object to a file, the standard convention in Java is to give the file a .ser extension.

import java.io.*;

public class SerializeDemo
{
public static void main(String [] args)
{
Employee e = new Employee();
e
.name = "Reyan Ali";
e
.address = "Phokka Kuan, Ambehta Peer";
e
.SSN = 11122333;
e
.number = 101;
try
{
FileOutputStream fileOut =
new FileOutputStream("/tmp/employee.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(e);
out.close();
fileOut
.close();
System.out.printf("Serialized data is saved in /tmp/employee.ser");
}catch(IOException i)
{
i
.printStackTrace();
}
}
}

Deserializing an Object:

The following DeserializeDemo program deserializes the Employee object created in the SerializeDemo program. Study the program and try to determine its output:

import java.io.*;
public class DeserializeDemo
{
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("/tmp/employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e
= (Employee) in.readObject();
in.close();
fileIn
.close();
}catch(IOException i)
{
i
.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c
.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}



Here are following important points to be noted:

The try/catch block tries to catch a ClassNotFoundException, which is declared by the readObject() method. For a JVM to be able to deserialize an object, it must be able to find the bytecode for the class. If the JVM can't find a class during the deserialization of an object, it throws a ClassNotFoundException.

Notice that the return value of readObject() is cast to an Employee reference.

The value of the SSN field was 11122333 when the object was serialized, but because the field is transient, this value was not sent to the output stream. The SSN field of the deserialized Employee object is 0.

More About Serialization and deserialization : http://www.tutorialspoint.com/java/java_serialization.htm


     Source
http://www.tutorialspoint.com/java/lang/class_forname.htm
https://javabeanz.wordpress.com/2007/09/13/different-ways-to-create-objects/
http://www.javatpoint.com/object-cloning

Tuesday, 5 May 2015

CyberSource Reason Code 102 (Invalid field)

Reason Code 102 in details

Reply Flag (SCMP) : DINVALIDDATA

Description : Declined - One or more fields in the request contains invalid data.

Possible Action : See the reply fields missingFields_0....N for which fields are invalid. Resend the request with correct information

The Issue  :

   Recently couple of order failed where I work giving reason code 102 from cyber source. After investigation I found that the  Ship to Company field is having value like below.

For Order A : "C/O: XYZ Company"
For Order B : just "-"

The Reason :    

 Upon more investigation we found that the ship to company which is a String but don't accept colon ":" and single symbol as company name. This occurs with hyphens and slashes even through they works when they are combined with other characters in the field (Which is not there in any cyber source documentation). 

The Solution :   

 So the best possible solution is to avoid entering invalid data (below is the details how data can be valid or invalid) and use real company name instead of single symbol or special character. This also need to keep in mind during designing and implementation.  

Additional Field validation added in January, 2013

      As part of its commitment to maintain industry-leading security and data integrity, CyberSource has implemented additional front-end validation of transaction data entering its systems.
        Starting late January, 2013, values of specific API fields submitted to the production environment, regardless of connection method, must pass additional validation as outlined below.


Customer Name/Suffix/Title,
Ship-To Name

May start with a letter, number, or question mark (?)
Subsequent characters can be any of following:

letters
numbers
question mark (?)
dash (-)
single quote (')
period (.)
comma (,)
forward slash (/)
'at' sign (@)
ampersand (&)
parentheses ( or )
exclamation point (!)
plus sign (+)
colon (:)                            (applicable to Ship-To Name)

Customer E-mail
*  Must be valid e-mail address format  (example:  <string>@<string>.<string>) and must adhere to the standard format recommendations put forth in RFC 5322
* Phone numbers or Social Security numbers will be blocked


Company Name,
Ship-To Company Name

May start with a letter, number, or question mark (?)
Subsequent characters can be any of the following:

letters
numbers
apostrophe (')
period (.)
comma (,)
forward slash (/)
ampersand (&)
'at' sign (@)
question mark (?)
parenthesis ()
dash (-)
pound sign (#)
exclamation point (!)
plus sign (+)


Customer Phone Number

* Must be a valid phone number format
* May contain any of the following:.

  numbers
  letters
  dash (-)
  parenthesis ()
  plus sign (+)
  comma (,)
 asterisk (*)
 period (.)
 pound sign (#)
 forward slash (/)
 * Must have a minimum of 6 digits and a maximum of 32 digits (see examples below)

Passes minimum number of digits validation:
 '1-800-709-CYBS' is evaluated as '1800709' (non-digits not counted)

Fails minimum number of digits validation:
'1-800-8AB-LISE' is evaluated as '18008' (non-digits not counted)
'418-GO4-LISE' is evaluated as '4184'
'1-800-LISE' is evaluated as '1800'

Merchant Reference Number,
Order Number,
Customer E-mail,
Comments
Phone numbers and Social Security numbers will be blocked


Company Name,
Ship-To Company Name,
Customer Account ID,
Subscription Title

Phone numbers, Social Security numbers, and e-mail addresses will be blocked

Source :

1.  https://support.cybersource.com/cybskb/index?page=content&id=C1251&actp=search&viewlocale=en_US&searchid=1430844176310

2.  https://support.cybersource.com/cybskb/index?page=content&id=C156

  SyntaxError : (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape Solution:...