Followers

Sunday, July 30, 2017

SOAP Web Service Basic

1)what is wsimport?
Ans: we Use this to creat Client side stub from WSDL. It comes with Java SE,So if you have set the path for Java in your system then it automatically available for use. Go to command prompt and type "wsimport",This is use to generate the Stub. Command - Create a folder and name it "Soap webservice" (you can give any name) and then go to that folder from Command prompt and give below command. wsimport -D -keep -s src http://www.webservicex.net/geoipservice.asmx?wsdl (Note: end point WSDL URL 'http://www.webservicex.net/geoipservice.asmx?wsdl' and if we use other two argument (-keep & -s src) to store source jave file in 'src' folder else once the client client code(.class) file generated it delets the Java source file.) Generated code structure- -net.webservicex.GeoIP.java -GeoIPService.java -net.webservicex.GeoIPServiceSoap.java -net.webservicex.GetGeoIP.java -net.webservicex.GetGeoIPContext.java -net.webservicex.GetGeoIPContextResponse.java -net.webservicex.GetGeoIPResponse.java -net.webservicex.ObjectFactory.java -net.webservicex.package-info.java
2)How to call the WS using client code?
Ans: Code snippet: Pass in programme argument the ip address i.e '212.58.246.79' String ippAddres = arg[0]; GeoIPService ipService = new GeoIPService(); GeoIPServiceSoap geoIPServiceSoap = ipService.getGeoIPServiceSoap(); GeoIP ip = geoIPServiceSoap.getGeoIP(ippAddres); System.out.println("Ip Address: " + ip.getIP() + " Country Name: " + ip.getCountryName());
3)What are the two ways to implement web services?
Ans: There are two ways to implemnt the web services: 1)Service First/code first - (Java file to WSDL generation with annotation @WebService) - (Top Down approach.) 2)Contract First / Interface First -(First WSDL we write then using 'wsimport' we generate the source file) - (Botom Up approach.)
4)How to remove a method from wsdl definition using annotation?
Ans:If we do not use any annotation then all the public method of service class will be autoamtically part of WSDL operation or we used annotation "@WebMethod" to be part of WSDL operation. So if we are using "@WebMethod" then we can add attribute like "@WebMethod(exclude=true)" so that the corresponding method will not be part of WSDL opeartion.
5)What is "targetNamespace" in wsdl?
Ans:It's behaviour similar to java package name. In a WSDL under one 'targetNamespace' all the 5 element were associated. It is autoderived from main java class package name in reverse order. We can specify on our own also.
6)What are the different element in wsdl?
Ans: There were 5 major element in WSDL. Root element "definitions".
1)portType -: It contain's one operation or method name {getPoductCatagories()} and one message as input parameter {getPoductCatagoriesRequest} and one message out put parameter {getPoductCatagoriesResponse}. So message can contains multiple input Object. "
"
2)types -: There are different object type which will be used to provide as input object or output object.Contains reference of XSD.
3)message -: It contains one single Object as input which might contains multiple object.Like request object will contains i.e "eimessageContext" & "payload" object.
4)binding -: Information about how the operation accept request and send response. like kind of prtocol going to use. - "http" protocol and style as 'document'.
5)service -:It contains details about service End Point. i.e 'Service' has a 'port' has a 'binding' has a 'portType' has 'message' has 'type'.
7)What is binding Style?
Ans: There are two kind of binding style are exist. 1)Document - This is default style.It define external file as 'xsd' file inside section for reference. xsd file contains actualy defination of input & output parameter. 2)RPC - When we define this style then parameter will not contains any reference. input and output parameter return type also define inside 'message' section. Code Snippet: @WebService @SOAPBinding(style=Style.RPC) public class ShopInfo{ @WebMethod @WebResult(partName="lookupOutput") public String getShopInfo(@WebParam(partName="lookupInput") String property) { String response = "Invalid property."; if ("shopName".equals(property)) { response = "Suresh Mart"; } else if ("since".equals(property)) { response = "Since 1982"; } return response; } }
8)JAXB implementation in WS?
Ans: Use follow code snippet: import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; @XmlRootElement(name = "Product") @XmlType(propOrder = { "price", "sku", "name" }) public class Product { private String Name; private String sku; private double price; /* * It is always mandatory to define a no-arg constructor * so that JAXB can initialize the Product object. * */ public Product() { } public Product(String name, String sku, double price) { this.Name = name; this.sku = sku; this.price = price; } @XmlElement(name="ProductName") public String getName() { return Name; } ... }
9)How we can publish Web service without any server?
Ans: use code snippet: public final class SureshMartPublisher { public static void main(String[] args) { Endpoint.publish("http://localhost:4848/productcatalogue", new ProductCatalogue()); } }

Monday, July 3, 2017

Hiberante_Part_1

1)Hibernate Congiguration file explanation:
 -hibernate.cfg.xml


"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">



com.mysql.jdbc.Driver
jdbc:mysql://localhost/hibernatedb
suresh
suresh123

1

org.hibernate.dialect.MySQL5Dialect

org.hibernate.cache.NocacheProvider

true

update
//If I use "create" it always create new schema and insert data.






2)Where to define Entity name and Id name in class of hibernate?
Ans: Entity name we can define as : @Entity(name = "USER_DETAILS") public class UserDetails {} For "Id" Field name we can define two way: 1) @Id @Column(name = "USER_ID") private int userId; Or 2)above getter method @Id @Column(name = "USER_ID") public int getUserId() { return userId; } For generic Column also two way: 1)@Column(name = "USER_NAME") private String userName; Or 2)Abovet getter method @Column(name = "USER_NAME") public String getUserName() { return userName; }
  3)What is the role of java define "static"?
  Ans: It will not save the field column name or field value to Database. private static String description; public static String getDescription() { return description; } public static void setDescription(String description) { UserDetails.description = description; }
  4)What is AccessType is Hibernate? Ans: For best practice always use one type.There are two type of AccessType 1)FIELD (Default type) 2)PROPERTY If we mix both of them the 'transient' property will not work.So Alway use one type or Specify Access type.
5)What is behaviour of Data field in hibernate or use of '@Temporal'?
Ans: We can insert the Date field data in three Format:
 1)TimeStamp(This is default format, It saved both Date and time e.x: '2017-06-26 14:33:25'.) --> @Temporal(TemporalType.TIMESTAMP)
 2)Date(This will save only Date e.x: '2017-06-26'.) --> @Temporal(TemporalType.DATE)  3)Time(This will save only Time e.x: '14:34:37'.) --> @Temporal(TemporalType.TIME) Field Example: @Temporal(TemporalType.DATE) private Date joiningDate;
6)How to store lengthy string data or use of "@Lob"?
Ans: Define the field with annotation "@Lob".
 It has two kind of data storage:
 1)Byte stream (@Blob).
 2)Character Stream(@Clob).
7)What is Natural key & Surrogate key? 
Ans: Natural Key: They key which we can use as Primary key and having Business use. For example : emailId / mobileNumber/aadharcardNo/pan card number/SSN/username etc.
Surrogate key: Unique Key which is not having any Business use then we called Surrogate Key. for Example in Entity class we define we id field which is unique,auto increment etc. Annotation for generating Primary key as surrogate key: @Id @Column(name = "USER_ID") @GeneratedValue(strategy=GenerationType.AUTO) //GenerationType.IDENTITY or GenerationType.SEQUENCE or GenerationType.TABLE private int userId; GenerationType.AUTO:By default if we not specifty any strategy then it will be used.It's like increment by 1. GenerationType.IDENTITY: This is not a generic one.Some Database use Identity column featur for Primary key like mysql/sqlserver. GenerationType.SEQUENCE: Sequence object is use for Primary key like Oracle DB.Sequence object is used to matain the sequences. GenerationType.TABLE: A separate Table store the last value used as Primary Key and use next value for new record insertion.
  8)What is Value type & Embeded object?
Ans: The data which is not having any meaning of it's own.It's used by other object to have meaningful data. For example AnY user might contains a Address details.So for User Table Address details will be a Value object. User_details(Entity Object) Address(Value object) Embeded object can be define as: @Embeddable public class Address { } Use is main Entity class as: @Entity @Table(name = "USER_DETAILS") public class UserDetails { @Embedded private Address address; } It will Create all the column define in embedded Object also in main Entity class.
9)How to override Attribute Column name of Embedded object?
Ans: Refer entity class code:
 @Entity
 @Table(name = "USER_DETAILS")
 public class UserDetails {

@Embedded
 @AttributeOverrides({
@AttributeOverride(name = "street", column = @Column(name = "HOME_STREET_NAME")), @AttributeOverride(name = "city", column = @Column(name = "HOME_CITY_NAME")), @AttributeOverride(name = "state", column = @Column(name = "HOME_STATE_NAME")), @AttributeOverride(name = "pincode", column = @Column(name = "HOME_PIN_CODE")) })  private Address homeAddress;

@Embedded
 @AttributeOverrides({
 @AttributeOverride(name = "street", column = @Column(name = "OFFICE_STREET_NAME")),  @AttributeOverride(name = "city", column = @Column(name = "OFFICE_CITY_NAME")),  @AttributeOverride(name = "state", column = @Column(name = "OFFICE_STATE_NAME")),  @AttributeOverride(name = "pincode", column = @Column(name = "OFFICE_PIN_CODE")) }) private Address officeAddress;
 }
10)How to insert collection of Embeded Element into Entity?
Ans: This scenario occured when we do not know how many of Instance of Emebeded Object will be associated with main entity. For example : All the address One guy stayed while renewing the new passport.
 @Entity
 @Table(name = "USER_DETAILS")
 public class UserDetails {
 @ElementCollection
 Set listOfAddress = new HashSet();
 }
 In Test class we need to use like:
 Address a1 = new Address();
 a1.setStreet("This is my address");
 a1.setCity("Bangalore");
 a1.setState("Karnataka");
 a1.setPincode("560008");
 Address a11 = new Address();
 a11.setStreet("11-This is my address");
 a11.setCity("11-Bangalore");
 a11.setState("11-Karnataka");
 a11.setPincode("11-560008");
 user1.getListOfAddress().add(a1);
 user1.getListOfAddress().add(a11);

Monday, May 22, 2017

Java Integer Cache Tricks

I want to discuss a bit about Integer cache things in this blogs.

Integer class implemented Cache Technique for value range from -128 to 127 same as String Cache Technique which is based of Fly-Weight Design pattern.
They(Integer class developer) have decided to do this because they felt this range can be frequent used in Java code. So better to give in-built cache mechanism rather then always creating new Java Object.

If you Explore the Integer Java class You will find below piece of code used for Caching Technique.

/**
     * Cache to support the object identity semantics of autoboxing for values between
     * -128 and 127 (inclusive) as required by JLS.
     *
     * The cache is initialized on first usage.  The size of the cache
     * may be controlled by the {@code -XX:AutoBoxCacheMax=} option.
     * During VM initialization, java.lang.Integer.IntegerCache.high property
     * may be set and saved in the private system properties in the
     * sun.misc.VM class.
     */

    private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

Now the Question is if I felt I want to Increase the Caching integer range need to be greate then (-128 to 127) in this scenario we need to do below,
Either we need to pass the VM argument as -XX:AutoBoxCacheMax= where Size is high from above code snippet.
(Note: There is one Constraint like we can not set the Min value although.May be in future version of Java they can include this.)

If you are running from Eclipse then Please check the below Screen shot:
Step1:












Step2:

















Here as per screen shot it can Cache from -128 till 500.
If you give integer value >500 again the behavior is same as per screen shot 1.

Again You need to pass the argument in VM arguments: section in Run Configuration.
If You pass in Program Arguments it will not Work.