Monday, September 19, 2011

Identifying the state of hibernate objects practically

Emp instance=new Emp(); /* creating the transient object using the new operator which is not attached to database , which has to be saved in db usinh save or saveorupdate method of session object from sessionfactory */
instance.setEmpno(new Integer("111111"));
instance.setEname("sandeep");
instance.setJob("SE");
instance.setMgr(new Integer(6));
instance.setSal(546545646.89898);
instance.setHiredate(new Date());
com.DeptHome deptHome=new com.DeptHome();
Dept dept2=deptHome.findById(40);/* userdefined method findById persist object which is attached with session need to update not to save*/
instance.setDept(dept2);

empHome.attachDirty(instance);/*user defined method conatins save method of session object to save instance to db*/


------------------------------------------------------------
Emp emp=empHome.findById(7942);/* findById is user defined method to retrive the emp object using the emp id hence emp object is persist object attached to session which can be modified and save into database using the saveorupdate method of session object */

emp.setEname("hariesh");
empHome.attachsaveorupdate(emp);

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:85)
at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:70)
at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:90)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:168)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at com.EmpHome.attachsaveorupdate(EmpHome.java:137)
at com.EmpHome.main(EmpHome.java:76)


Solution
This Exception will arise in different scenario of save and saveOrupdate method of hibernate.
if Object is transient , need to save may occur this exception
Conditions.
1. Flushing the data before committing the object may lead to clear all object pending for persist.
2. If object has primary key which is auto generated and you are forcing has assigned key may cause the exception.
3. if you are cleaning the object before committing the object to database may lead this exception.
4. Zero or Incorrect ID:
Hibernate excepts an primary or id of null (not initialize while saving) has per point 2 to mean the object was not saved. If you set the ID to zero or something else, Hibernate will try to update instead of insert, or it lead may to throw this exception.
5.
Object Doesn’t Exist: This is the most easy to determine : has the object get deleted somehow? If so, trying to delete once again it will throw this exception.
6.
Object is Stale: Hibernate caches objects from the session. If the object was modified, and Hibernate doesn’t know about it, it will throw this exception — note the StaleStateException part of the exception.

so after committing the object to database need to flush or clear or clean it ,not before.

Friday, August 19, 2011

Different and best Swings Look and feel Themes


Here is the code

package com.gui;

import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class MainGUI extends JPanel implements ActionListener {

private static final long serialVersionUID = 1L;
private JButton jbmMetal = new JButton("Metal");
private JButton jbnMotif = new JButton("Motif");
private JButton jbnWindows = new JButton("Windows");
private JButton jbnliquid = new JButton("Liquid");
private JButton jbnstick = new JButton("Stick");
private JButton tatto = new JButton("JTatto Aluminium");
private JButton acryltatto = new JButton("JTatto Acryl");
private JButton Aerotatto = new JButton("JTatto Aero");
private JButton beristeintatto = new JButton("JTatto Bernstein");
private JButton lunatatto = new JButton("JTatto Luna");
private JButton minttatto = new JButton("JTatto mint");
private JButton smarttatto = new JButton("JTatto Smart");
private JButton hifitatto = new JButton("JTatto HiFi");
private JButton quaqua = new JButton("QuaQua");
public MainGUI() {
add(jbmMetal);
add(jbnMotif);
add(jbnWindows);
add(jbnliquid);
add(jbnstick);
add(tatto);
add(acryltatto);
add(Aerotatto);
add(beristeintatto);
add(lunatatto);
add(minttatto);
add(smarttatto);
add(hifitatto);
add(quaqua);
jbmMetal.addActionListener(this);
jbnMotif.addActionListener(this);
jbnWindows.addActionListener(this);
jbnliquid.addActionListener(this);
jbnstick.addActionListener(this);
tatto.addActionListener(this);
acryltatto.addActionListener(this);
Aerotatto.addActionListener(this);
beristeintatto.addActionListener(this);
lunatatto.addActionListener(this);
minttatto.addActionListener(this);
smarttatto.addActionListener(this);
hifitatto.addActionListener(this);
quaqua.addActionListener(this);
}


public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
String laf = "";
if (source == jbmMetal)
laf = "javax.swing.plaf.metal.MetalLookAndFeel";
else if (source == jbnMotif)
laf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
else if (source == jbnWindows)
laf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
else if (source == jbnliquid)
laf = "com.birosoft.liquid.LiquidLookAndFeel";
else if (source == jbnstick)
laf = "com.lipstikLF.LipstikLookAndFeel";
else if (source == tatto)
laf = "com.jtattoo.plaf.aluminium.AluminiumLookAndFeel";
else if (source == acryltatto)
laf = "com.jtattoo.plaf.acryl.AcrylLookAndFeel";
else if (source == Aerotatto)
laf = "com.jtattoo.plaf.aero.AeroLookAndFeel";
else if (source == beristeintatto)
laf = "com.jtattoo.plaf.bernstein.BernsteinLookAndFeel";
else if (source == lunatatto)
laf = "com.jtattoo.plaf.luna.LunaLookAndFeel";
else if (source == minttatto)
laf = "com.jtattoo.plaf.mint.MintLookAndFeel";
else if (source == smarttatto)
laf = "com.jtattoo.plaf.smart.SmartLookAndFeel";
else if (source == hifitatto)
laf = "com.jtattoo.plaf.hifi.HiFiLookAndFeel";
else if (source == quaqua)
laf = "ch.randelshofer.quaqua.QuaquaLookAndFeel";

try {
UIManager.setLookAndFeel(laf);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception excep) {
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Look and Feel Test");
frame.setSize(500, 300);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new MainGUI());
frame.setVisible(true);
Calculator calculator = new Calculator();
}


}

4 third party jars need to download

liquidlnf.jar
lipstikLF-1.1.jar
JTattoo.jar
quaqua.jar
quaqua-filechooser-only.jar

Wednesday, August 10, 2011

Converting audio/video files using ffmpeg

ffmpeg command can be used to convert the audio/video from one format to another format

Common ffmpeg Parameters
  • -i - Path\Filename of source file
  • -y - Overwrite the existing output file without prompting
  • -an - Disable audio
Video Related ffmpeg Parameters
  • -aspect - Set Aspect Ratio for the video (4:3, 16:9 or 1.3333, 1.7777)
  • -r - Set frame rate in Hz for the video
  • -s - Set video resolution size (Width x Height)
  • -sameq - Use same video quality as source
Audio Related ffmpeg Parameters
  • -ar - Set audio sampling rate (in Hz)
  • -acodec - Force audio codec, example mp3
  • -vol - Change audio volume (256=normal)
  • -ab - Set audio bit rate (in bits/s)
Syntax
ffmpeg Command

Video
  • Converting MOV to FLV using FFMPEG:
    ffmpeg -i movie.mov movie.flv
  • Converting Mpeg to FLV using FFMPEG:
    ffmpeg -i movie.mpeg movie.flv
  • Converting AVI to FLV using FFMPEG - convert movie.avi to movie.flv and resize the video resolution to 500×500:
    ffmpeg -i movie.avi -s 500×500 movie.flv
  • Converting 3GP to FLV using FFMPEG - convert movie.3gp to movie.flv, keep the original file settings and disable the audio content:
    ffmpeg -i movie.3gp -sameq -an movie.flv
  • Converting MPEG to 3GP using FFMPEG:
    ffmpeg -i movie.mpeg -ab 8.85k -acodec libamr_wb -ac 1 -ar 16000 -vcodec h263 -s qcif movie2.3gp
Audio

  • Converting aac to mp3 using FFMPEG with MetaData - convert audio.aac to audio.mp3 with an audio rate of 22.05 Khz and audio BitRate of 32Khz, and will copy the metadata from .aac file to .mp3 file:
    ffmpeg -i audio.aac -ar 22050 -ab 32 -map_meta_data audio.mp3:audio.aac audio.mp3
  • Converting WMV to MP3 using FFMPEG
    ffmpeg -i audio.wmv audio.mp3
  • Converting WMV to FLV using FFMPEG - convert audio.wmv to audio.flv, generating only audio content:
    ffmpeg -i audio.wmv audio.flv
  • Converting AMR to MP3 using FFMPEG - convert audio.amr to audio.mp3, with an audio rate of 22.05 Khz:
    ffmpeg -i audio.amr -ar 22050 audio.mp3
  • Converting aac to mp3 using FFMPEG - convert audio.aac to audio.mp3, with an audio rate of 22.05 Khz and audio BitRate or 32Khz:
    ffmpeg -i audio.aac -ar 22050 -ab 32 audio.mp3
FFmpeg download

http://ffmpeg.arrozcru.org/autobuilds/


convert avi to flv like in youtube

ffmpeg -i video_origine.avi -ab 56 -ar 44100 -b 200 -r 15 -s 320x240 -f flv video_finale.flv





Tuesday, April 5, 2011

How to hide closed project in eclipse

Eclipse comes with a cool tiny feature t
hat many of us not know. You may want to Hide all those closed projects from your workspace in Project Explorer tab. Simply follow following steps and do this is few seconds!



Click on Customize view a pop will open

select the closed project and then say ok.
Three Steps hide the closed projects..

Tuesday, March 29, 2011

JSP File Naming Conventions

JSP Names

A JSP (file) name should always begin with a lower-case letter. The name may consist of multiple words, in which case the words are placed immediately adjacent and each word commences with an upper-case letter. A JSP name can be just a simple noun or a short sentence. A verb-only JSP name should be avoided, as it does not convey sufficient information to developers. For example:

    perform.jsp

is not as clear as

    performLogin.jsp

In the case of a verb being part of a JSP name, the present tense form should be used, since an action by way of backend processing is implied:

    showAccountDetails.jsp

is preferred over

    showingAccountDetails.jsp

How to handle JSTL tags Errors and exception while iterating






if we use capex.ROWColor means rowcolor declare as uppercase in java beans while iterating in jsp page using the JSTL tags its give exception , so while creating beans need to take care about the name convention in variable declaration in bean

How to read Excel Data (XLS,XLSX)

For both XLS and XLSX format no need to use the HSSF or XSSF package avaliable in POI
,u can make use of org.apache.poi.ss.usermodel for both format with same code no need to write seperately .

It works for both.

How to update Eclipse for SVN or How to use SVN with Eclipse

http://www.ibm.com/developerworks/opensource/library/os-ecl-subversion/

How to get CLOB data extending Spring Stored Procedure interface

declareParameter(new SqlOutParameter(OUT_PARAMETER, Types.CLOB ,null,new SqlReturnType()
{
public Object getTypeValue(CallableStatement cs, int i, int sqlType, String typeName)
throws SQLException
{
try
{
final Clob aClob = cs.getClob(i);
final Reader clobReader = aClob.getCharacterStream();
int length = (int) aClob.length();
char[] inputBuffer = new char[1024];
final StringBuffer outputBuffer = new StringBuffer();
while ((length = clobReader.read(inputBuffer)) != -1)
{
outputBuffer.append(inputBuffer, 0, length);
}
return outputBuffer.toString();
} catch (IOException e)
{
_log.info("Exception in processing the Clob data for retriving ");
throw new SQLException(e.toString());
}

}

}
));

How to convert array to List in Java

String commentArray[]={"1","2","3"}

List commentList=Arrays.asList(commentArray);

Difference between Error and Exception

) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable.


While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.)

What do u mean by NoClassDefFoundError

Consider if NoClassDefFoundError occurs which is something like

java.lang.NoClassDefFoundError

src/com/TestClass

does not mean that the TestClass class is not in the CLASSPATH. It means that the class TestClass was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (TestClass in this case) and look for code using static blocks or static members.

Difference Between instanceOf and IsInstance

1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.
if (obj instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}
2) instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.

Friday, March 25, 2011

How to create WAR and EAR in Eclipse

Web Tools Platform User Guide > Creating Web applications > Web projects
Importing Web archive (WAR) files

A Web Archive (WAR) file is a portable, packaged Web application that you can import into your workspace.
Before importing a WAR file, you should first determine if the WAR file contains needed Java™ source files. When importing a WAR file into an existing Web project, the imported Web deployment descriptor files are either not changed or overwritten by the ones included in the imported WAR file, based on your response to the prompt that is provided. In either case, this action does not represent a merging of the two sets of deployment descriptors.
To import the Web project resources in a WAR file into your workspace, complete the following steps:
1. Select File > Import .
2. In the Import dialog, select WAR file and then click Next .
3. Locate the WAR file that you want to import using the Browse button.
4. The wizard assumes you want to create a new Web project with the same name as the WAR file. If you accept this choice, the project will be created with the same servlet version as specified by the WAR file and in the same location. If you want to override these settings, you can click New and specify your new settings in the Dynamic Web Project wizard.
5. Click Finish to populate the Web project.





War
Web Archive – How to create a war file from Eclipse


When we have finished with a project and want to deploy it elsewhere we create a WAR file. To do this,
1. Right click on the project and select Export > WAR file
2. Update the name or keep default and enter a Destination for where the WAR file will be created
3. Click Finish and your WAR file is generated.
You can now import the War file to your test or production environments. Refer to your application server documentation for instructions on how to deploy a web application from a WAR file.
That gets us started with creating web applications. In the next article we’ll look at how to setup Eclipse to use the BusinessObjects SDK and then create a simple logon page to test that all is set up correctly.


EAR

Just copy the generated .EAR to ...\server\default\deploy folder of JBoss.

Object State in Hibernate


The state of an object reflects the values contained in the attributes of an object at a given time. So whenever the values change, the state also changes to reflect the current values. The total number of states traversed by an object to reach its initial state is known as the life-cycle of the object. Following are the states that form the life-cycle of a persistent object, also known as life-cycle of persistence:


1. Transience
2. Persistence
3. Detachment
These are the states of an object. Starting from the transient state, moving on to the persistent state and reaching the detached state, this image should help you understand it better:

Each of the state transitions is associated with a task or an operation in object-oriented lingo. The details of what each state does to the persistent object and the operations that initiate the state transitions are as follows:
1. Transient State:Transient is the state of an object when it is not associated with any database. Any object instantiated using the new operator is in this state. Since they are not associated with any row of a table, they are destroyed (or become eligible to be collected by the garbage collector). Transient objects don’t come under the context of a transaction. That means if the values of a transient object are updated, calling the rollback() method doesn’t undo the changes made to the object.
2. Persistent State:An object is said to be in a persistent state when it has a database identity. An object having a database identity simply means that the identity of the object has been set using the primary key value of the table row it represents. In short, when the identity of the object contains the value of the primary key of the table row it reaches a persistent state. To make any transient object persistent, the save method of the Persistence manager has to be called. The most important characteristic feature of an object in the persistent state is that it takes part in transactional activities.
Even in the persistent state, the object stays in different states. Until the commit() method of transaction management is called with the object as a parameter, the object remains in the new state. Whenever any value held by a persistent object changes, the object becomes dirty. This state is not visible to the application. The trick used by Hibernate is known as Transparent Transaction-Level Write-Behind. The framework does this by delaying the synchronization of the object to the database table and then hides the details from the application.
This feature leads us to another feature where only those column values are updated which are modified. To do so the dynamic-update attribute of the node of the mapping file is used. Finally an object in the persistent state can be made transient by calling the delete() method of the Persistence manager with the object as a parameter.
3. Detached State:In Hibernate, when the transaction completes by calling the close() method on the Session object, the instances of persistence class lose their association with the Persistence manager. Thus the detached state is attained. In this state the object is no longer in sync with the database. Also Hibernate doesn’t care about the modifications being done to the object, as the object is no longer under the management of Hibernate. Though the Persistence or Transaction manager is no longer managing the object, it still contains the persistent data (data contained in the row of the corresponding table). This property makes it the most eligible candidate to be used as a Data Transfer Object in a multi-layered architecture.
How does this look in code? It looks something like this:
Session sess = sf.openSession();
Order o=new Order(); //transient state
// search and return
Query q = session.createQuery("from Order order where”+
+”order.id=:id");
q.setString(“id”,name);
List result = q.list();
if (list.size() == 0) {
System.out.println("No Order having id "
+ name);
System.exit(0);
}
o = (Order) list.get(0);//Persistent state
sess.close();

o.getOrderDate();//o is now detached
That clears the smoke around the life-cycle of a Persistent object. Now we can move on to more pressing issues -- issues related to associations and association mappings

Android Installation and SDK configuration with Eclipse Galileo

Hi Readers,

I have installed android and configured in eclipse. I dont know anything in android, But i tried to install with one of my friend. Finally i run the program. I would like to share this procedure to all, It may helpful to you,

Downloading the ADT PluginUse Update Manager feature of your Eclipse installation to install the latest revision of ADT on your development computer.
Assuming that you have a compatible version of the Eclipse IDE installed, as described in Preparing for Installation, above, follow these steps to download the ADT plugin and install it in your Eclipse environment.

1. Start Eclipse, then select Help > Install New Software....
2. Click Add, in the top-right corner.
3. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the following URL for the Location:
https://dl-ssl.google.com/android/eclipse/
Note: If you have trouble acquiring the plugin, try using "http" in the Location URL, instead of "https" (https is preferred for security reasons).
Click OK.
4. In the Available Software dialog, select the checkbox next to Developer Tools and click Next.
5. In the next window, you'll see a list of the tools to be downloaded. Click Next.
6. Read and accept the license agreements, then click Finish.
7. When the installation completes, restart Eclipse.
Updating the ADT Plugin
From time to time, a new revision of the ADT Plugin becomes available, with new features and bug fixes. Generally, when a new revision of ADT is available, you should update to it as soon as convenient.
In some cases, a new revision of ADT will have a dependency on a specific revision of the Android SDK Tools. If such dependencies exist, you will need to update the SDK Tools component of the SDK after installing the new revision of ADT. To update the SDK Tools component, use the Android SDK and AVD Manager, as described in Adding SDK Components.
To learn about new features of each ADT revision and also any dependencies on the SDK Tools, see the listings in the Revisions section. To determine the version currently installed, open the Eclipse Installed Software window using Help > Software Updates and refer to the version listed for "Android Development Tools".
Follow the steps below to check whether an update is available and, if so, to install it.
Eclipse 3.5 (Galileo) and 3.6 (Helios)
1. Select Help > Check for Updates.
If there are no updates available, a dialog will say so and you're done.
2. If there are updates available, select Android DDMS, Android Development Tools, and Android Hierarchy Viewer, then click Next.
3. In the Update Details dialog, click Next.
4. Read and accept the license agreement and then click Finish. This will download and install the latest version of Android DDMS and Android Development Tools.
5. Restart Eclipse.

Installation:1. Install Java (JDK)
2. Download the eclipse galileo and run in your machine.
3. Download the SDK from http://developer.android.com/sdk/index.html
4.Run the eclipse by clicking eclipse icon
5.Go to this url http://developer.android.com/sdk/eclipse-adt.html. Read the steps Eclipse 3.5 (Galileo).
6. You can confirm SDK is installed or not. Go to windows. You can Android SDK and AVD manager.Then click in this menu list.
7.You can see available package at left side, Just select it. The you can see one check box in right side. Just check it. After checking,you can see multiple package list, In that choose onle android 2.2 package.
8. Refresh it.
9. Go to Available package in left side. There you can confirm package is installed with SDK platform android 2,2 list.
10. Go to virtual device and give AVD name and target….
Setup is completed….
creating the Android first program:
1.File->new->others->android->android project
2.Fill the form with required input. Note:package name should be com.projectname.
3.In left side,right click the application and click run as -> android project.
4. You will get the output with android screen format.
Useful links while doing android setup…
http://whyandroid.com/android/216-how-to-install-the-android-sdk-on-windows-xp.html
http://developer.android.com/sdk/index.html
http://developer.android.com/sdk/eclipse-adt.html