Sunday, 17 December 2017

interview question of Exception Handling in Java

Q- What is exception??
Ans-Exception is abnormal condition which occured at runtime
abnormal means- it will not maintain normal flow.
We use exception to print a user friendly warning message to suer......
we can handle exception:-
1-try
2-catch
3-finally
4-throw
5-throws

Q- Why we use exception handling??
Ans-Here abnormal termination will happen..
Suppose 1000 line code is there inside method...
From 1000 line of code First 900 line code executed successfully and
900 to 905 there 5 line given some problem, if some problem occure in you code,
Than control will transfer to jvm, JVM  will analyze the problem, and it will create some exception related object, it will throw that object in your program, if you are not handling object
what will happen JVM will propogate that object to default exception handler
default excption handler will print error message and you program will terminated.
So because of 5 line, I dont want terminate entire program bcoz of 5 line i can use try and catch block


Hierarchy of Exception classes

exception handling in java

Type of Exception

  • Checked Exception
  • Un-Checked Exception

Checked Exception

Checked Exception-"if you code inside the method or constructor throwing some exception and if that exception is checked by compiler, compiler is forcing you to report about the exception by writting by try and catch block or by using throws keyword is called checked exception".
 are the exception which checked at compile-time. These exception are directly sub-class of java.lang.Exception class.
Only for remember: Checked means checked by compiler so checked exception are checked at compile-time.
checked exception

Un-Checked Exception

Un-Checked Exception-means this is aslo called runtime Exception, if some code inside the method throwing exception and compiler is not telling anything wheather exception you want to report or dont report, compiler is not informing anything is called unchecked exception.
 are the exception both identifies or raised at run time. These exception are directly sub-class of java.lang.RuntimeException class.

Note: In real time application mostly we can handle un-checked exception.
Only for remember: Un-checked means not checked by compiler so un-checked exception are checked at run-time not compile time.
unchecked exception


Difference between checked Exception and un-checked Exception

Checked ExceptionUn-Checked Exception
1checked Exception are checked at compile timeun-checked Exception are checked at run time
3e.g.
FileNotFoundException, NumberNotFoundException etc.
e.g.
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.


Use Five keywords for Handling the Exception

  • try
  • catch
  • finally
  • throws
  • throw
Syntax for handling the exception

Syntax

try
{
  // statements causes problem at run time 
}
catch(type of exception-1 object-1)
{
  // statements provides user friendly error message 
}
catch(type of exception-2 object-2)
{
  // statements provides user friendly error message
}
finally
{
  // statements which will execute compulsory 
}

Example without Exception Handling

Syntax

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
ans=a/0;
System.out.println("Denominator not be zero");  
}
}
Abnormally terminate program and give a message like below, this error message is not understandable by user so we convert this error message into user friendly error message, like "denominator not be zero".
exception

Example of Exception Handling

Example

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
} 
}
}

Custom Exception in Java

If any exception is design by the user known as user defined or Custom Exception. Custom Exception is created by user.

Rules to design user defined Exception

  1. Create a package with valid user defined name.
  2. Create any user defined class.
  3. Make that user defined class as derived class of Exception or RuntimeException class.
  4. Declare parametrized constructor with string variable.
  5. call super class constructor by passing string variable within the derived class constructor.
  6. Save the program with public class name.java
custom exception

Example

// save by AgeException.java
package nage;

public class AgeException extends Exception
{
public AgeException(String s) 
{
super(s);
}
}

Compile: javac -d . AgeException.java

Example

// save by CheckAge.java
package nage;

public class CheckAge
{
public void verify(int age)throws AgeException
{
if (age>0)
{
System.err.print("valid age");
}
else
{
AgeException ae=new AgeException("Invalid age");
throw(ae);
}
}
}

Compile: javac -d . CheckAge.java

Example

// save by VerifyAgeException

import nage.AgeException;
import nage.CheckAge;
import java.util.*;

public class VerifyAgeException
{
public static void main(String args[])
{
int a;
System.out.println("Enter your age");
Scanner s=new Scanner(System.in);
a=s.nextInt();
try
{
CheckAge ca=new CheckAge();
ca.verify(a);
}
catch(AgeException ae)
{
System.err.println("Age should not be -ve");
}
catch(Exception e)
{
System.err.println(e);
}
}
}

Compile: javac VerifyAgeException.java

custom exception


finally Block in Exception Handling

Inside finallyblock we write the block of statements which will relinquish (released or close or terminate) the resource (file or database) where data store permanently.

finally block important points

  • Finally block will execute compulsory
  • Writing finally block is optional.
  • You can write finally block for the entire java program
  • In some of the circumstances one can also write try and catch block in finally block.

Example

class ExceptionDemo 
{
public static void main(String[] args) 
{
int a=10, ans=0;
try
{
ans=a/0;
}
catch (Exception e)
{
System.out.println("Denominator not be zero");
} 
finally
{
System.out.println("I am from finally block");
}
}
}

Output

Denominator not be zero
I am from finally block

Difference Between Throw and Throws Keyword

throw

throw is a keyword in java language which is used to throw any user defined exception to the same signature of method in which the exception is raised.
Note: throw keyword always should exist within method body.
whenever method body contain throw keyword than the call method should be followed by throws keyword.
throw exception

Syntax

class className
{
returntype method(...) throws Exception_class
{
throw(Exception obj)
}
}

throws

throws is a keyword in java language which is used to throw the exception which is raised in the called method to it's calling method throws keyword always followed by method signature.

Example

returnType methodName(parameter)throws Exception_class....
{
.....
}

Sunday, 26 November 2017

Working with Dynamic Query In Liferay

Introduction of Dynamic query:-

Liferay provides several ways by which we can retrieve data from database. One of them is dynamic query. You can easily fire complex query using dynamic query and it will reduce overhead of creating custom finder methods


How to build Dynamic Query:


DynamicQuery dynamicQuery= DynamicQueryFactoryUtil.forClass(Entity_Name.class, PortalClassLoaderUtil.getClassLoader());
OR
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(Entity_Name.class, PortletClassLoaderUtil.getClassLoader());


Note 1: If you working with dynamic query inside your custom portlet and trying to access liferay core entity (i.e, database) then use Portal Class Loader.

 Example like :
Dealing with Liferay's built in entities like Users, Organizations, Assets, AssetCategories 
As DynamicQuery API looks for current classloader, for access, but as you are dealing with Portal level
class [User.class], you have to specify portalClassLoader as below.

 ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();  
 DynamicQuery query =DynamicQueryFactoryUtil.forClass(User.class, portalClassLoader);  

-
Note 2: Dealing with custom entity within portlet.

DynamicQuery dynamicQuery=DynamicQueryFactoryUtil.forClass(Application.class);

example1:-
1.SELECT * FROM User_ WHERE lastName='Bloggs'
Dynamic Query:
DynamicQuer  dynamicQuery  = DynamicQueryFactoryUtil.forClass(User.class, PortalClassLoaderUtil.getClassLoader());
dynamicQuery.add(PropertyFactoryUtil.forName("lastName").eq("Bloggs"));
List<User> userList = UserLocalServiceUtil.dynamicQuery(dynamicQuery);
Example2:-
DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(MyCustomTable.class);
dynamicQuery.add(PropertyFactoryUtil.forName("status").eq("Pending")
dynamicQuery.add(PropertyFactoryUtil.forName("userId").eq(10122);

Above query will search in table MycustomTable for records which has status as

Pending and userId as 10122. If you want to sort your records in particular order that also you can do.  Example3:- 2. SELECT * FROM User_ WHERE lastName like 'ord%' Dynamic Query: DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(User.class,
PortalClassLoaderUtil.getClassLoader()); dynamicQuery.add(PropertyFactoryUtil.forName("lastName").like("ord%")); List<User> userList = UserLocalServiceUtil.dynamicQuery(dynamicQuery);
About Dynamic Query: I am assuming that you are aware of Liferay Service Builder and
you have basic understanding of persisting data by service builder tool.
Consider that you have developed your portlet and you have persisted
a lot many records in the database. You are a java developer and
you don't have much knowledge on queering database.
Liferay Dynamic Query is the rescue in this case.
Liferay provides API to query the database just like writing java program.
You don't need to bother about low level database query.
One point to remember here that Dynamic Query is only to fetch data. Below are the API we will be working with to write dynamic query. com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil com.liferay.portal.kernel.dao.orm.DynamicQuery com.liferay.portal.kernel.dao.orm.Criterion com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil com.liferay.portal.kernel.dao.orm.Projection com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil com.liferay.portal.kernel.dao.orm.ProjectionList com.liferay.portal.kernel.dao.orm.OrderFactoryUtil

Monday, 18 September 2017

Get value from hidden field - jQuery

How can I get the value using jQuery?

<input type="hidden" value="" id='h_v' class='h_v'>

Use val() instead of text() var hv = $('#h_v').val(); alert(hv);

Wednesday, 6 September 2017

Check Null with ternary operator

At its most basic, the ternary operator, also known as the conditional operator, can be used as an alternative to the Java if/then/else syntax, but it goes beyond that, and can even be used on the right hand side of Java statements.


Example:-

<c:out value="<%=item.getMiddleName()!=null?item.getFirstName()+' '+item.getMiddleName()+' '+item.getLastName():item.getFirstName()+' '+item.getLastName()%>"></c:out>

Thursday, 17 August 2017

Clear form input fields except radio/select menu values?

Clear form input fields except radio/select menu values?


First way  ---


$(':input','#myform').not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');

                          (OR)


$('#FormIDReset').trigger('click');
<button class=" " type="reset" id="FormIDReset">Clear</button>


Wednesday, 4 January 2017

JQuery DataTable Sample Example

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css"/>

<div>
<table id="regionTable" class="table table-hover table-striped table-bordered">
 <thead>
     <tr>
          <th>OrganizationId</th>
         <th>Parent OrganizationId</th>
         <th>Type</th>
          <th>Code</th>
         <th>Action</th>
     </tr>
 </thead>
 <tbody>
 
    <tr>
     <td>fhf</td>
     <td>fh</td>
     <td>fhf</td>
     <td>fh</td>
     <td><button class="edit" >Edit File</button>
      <a href="#"> <button class="remove" >Delete File</button></a></td>
   
    </tr>
   
   
 
 

 </tbody>
</table>
</div>


<script type="text/javascript">
$(document).ready(function() {
    $('#regionTable').DataTable();
} );
</script>

Sunday, 11 September 2016

JSON Serialization in Liferay

Many times we have requirement to convert Liferay service response or any list into JSON object. Most of the time we are doing this manually.

JSONArray jsonArr = JSONFactoryUtil.createJSONArray();
for (User user : userList)
{
JSONObject json = JSONFactoryUtil.createJSONObject();
json.put("name", user.getFullName());
json.put("id", user.getUserId());
jsonArr.put(json);
}
return jsonArr.toString();



There are other ways as well by which we can convert List into JSON string.
Service builder has support for JSON  serialization,too. The json-enabled attribute of entity tag specifies whether or not the entity should be annotated for JSONserialization.
By default, if the remote-service value is true, then thejson-enabled value is true.
Column tag has the same attribute, json-enabled.
It specifies whether or not the column should be annotated for JSON serialization. By default, if the json-enabled value in the entity element is true, then the json-enabled value in the column element is true.


<entity name="TestJSON" table="json_test" local-service="true" remote-service="false" json-enabled="true">
<!-- PK fields -->
<column name="keyId" type="long" primary="true" />
<!-- Audit fields -->
<column name="companyId" type="long" />
<column name="groupId" type="long" />
<!-- Other fields -->
<column name="firstName" type="String" json-enabled="true" />
<column name="lastName" type="String" json-enabled="true"/>
<column name="email" type="String" json-enabled="false"/>
<!-- Finder methods -->
</entity>

json enabled is true for enttity TestJson so all the column tags will have by default json-enabled as true.
In case if you want to exclude any property to not to appear when you serialize then you can set json-enabled as false. For email column json-enabled is set to false.



Now you can easily convert your list returned using Liferay services into JSON format.

JSONSerializer jsonSerializer = JSONFactoryUtil.createJSONSerializer();
String json = jsonSerializer.serialize(list);



Same way you can use serialize OOB data as well like user.

 List<User> userList = UserLocalServiceUtil.getUsers(-1, -1);
 String json = JSONFactoryUtil.looseSerialize(userList);

 By default collections are excluded from serialization . You can include them using below way.
 String json  = JSONFactoryUtil.looseSerialize(userList,"organizations")

 Covert List to JSONArray:-

Might be you won't be aware that you can't use existing portal *JsonSerializer.java class in Liferay plugin portlets. So if you want to get JsonArray response of existing liferay service then you can use below code :


import net.sf.json.JSONArray;

List myList = UserLocalserviceUtil.getUsers();
JSONArray jsonArray = JSONArray.fromObject(MyList);