Monday, December 23, 2013


Web Services Beginner Guide

1) Create dynamic project as below.



2) create a package names 'com.net' in src and create below class with code.









3) Eclispe window -> preferences should be set as below.Becuase first run we are going to do using Apache Axis.





The tomcat server should have been added as below.

If tomcat is running, then it should show 'server' open in navigator. Else start the server in 'server' console by right clicking on shown server in console.

4) Have the tomcat server running within eclipse. Right clik project -> new -> web service and then browse the service class and give location and modify as below screen shot.


Below are the next set of screen shots u will get if you keep on doing next.


Sometimes when doing next we may get error.But click back and do next again.Then sometimes errors will dissapear.








4) when above is done, there will be separate client project created to test this.It will open up as below.



5)When we click on our service method, which is getRank, then we get below form to test the service.

6) Once input is done and invoke is clicked, it will show the input in result section as below and Sys out will be printed to console as below.

result section will show string only if the web service is returning a string.else if it is only a sys out, it will show the output in console.

http://localhost:8080/Test-WS-1Client/sampleTestServiceRankingProxy/TestClient.jsp

Test-WS-1Client= generated client project name
sampleTestServiceRankingProxy = here  'TestServiceRanking' is the class name including the service method which we have defined



7) Below is how to access the wsdl on diferent browser.

http://localhost:8080/Test-WS-1/services/TestServiceRanking?wsdl

Test-WS-1 = server project name
services = this is a must to include
TestServiceRanking = class name including the service method which we have defined




Wednesday, October 23, 2013

Jasper Report - How to print pdf, html and excel reports

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
import net.sf.jasperreports.view.JasperViewer;

public class ReportGeneration {

    public static void main(String[] args) {       

        InputStream inputStream;
        JasperReport jasperReport = null;
        try {
            // First, load JasperDesign from XML and compile it into JasperReport
            inputStream = new FileInputStream ("C:/MSC_project/JasperProjects/TestPro2/src/test_jasper_rep1.jrxml");
            JasperDesign jasperDesign = JRXmlLoader.load(inputStream);
            jasperReport = JasperCompileManager.compileReport(jasperDesign);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        // Second, create a map of parameters to pass to the report.
        Map parameters = new HashMap();
        parameters.put("Title", "Basic JasperReport");
        parameters.put("MaxSalary", new Double(25000.00));
        // Third, get a database connection

        // String dbUrl = props.getProperty("jdbc.url");
        String dbUrl = "jdbc:mysql://localhost:3306/struts_tiles1";
        // String dbDriver = props.getProperty("jdbc.driver");
        String dbDriver = "com.mysql.jdbc.Driver";
        // String dbUname = props.getProperty("db.username");
        String dbUname = "root";
        // String dbPwd = props.getProperty("db.password");
        String dbPwd = "123456";
        Connection conn;
        JasperPrint jasperPrint = null;
        // Load the JDBC driver
        try {
            Class.forName(dbDriver);
            // Get the connection
            conn = DriverManager.getConnection(dbUrl, dbUname, dbPwd);
            // Fourth, create JasperPrint using fillReport() ethod
            jasperPrint = JasperManager.fillReport(jasperReport,parameters, conn);
            // You can use JasperPrint to create PDF
            JasperManager.printReportToPdfFile(jasperPrint, "C:/BasicReport.pdf");


            JasperExportManager.exportReportToHtmlFile(jasperPrint, "C:/BasicReport.html" );

            JRXlsExporter exporter = new JRXlsExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "C:/BasicReport.xls" );

            exporter.exportReport();

            // coding For Excel:

            /*ByteArrayOutputStream outputByteArray = new ByteArrayOutputStream();
            OutputStream outputfile= new FileOutputStream(new File("C:/BasicReport.xls"));

             JRXlsExporter exporterXLS = new JRXlsExporter();
             exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
             exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, outputByteArray);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
             exporterXLS.exportReport();
             outputfile.write(outputByteArray.toByteArray()); */


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Or to view report in the JasperViewer
        JasperViewer.viewReport(jasperPrint);

    }

}


To print in to excel sheet we can use step 1 or step 2.But in both instances, chek the jasper report.jar version and add the poi jar version compatible. eg: poi-2.0-final-20040126.jar

step 1

JRXlsExporter exporter = new JRXlsExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRExporterParameter.OUTPUT_FILE_NAME, "C:/BasicReport.xls" );

            exporter.exportReport();

step 2

ByteArrayOutputStream outputByteArray = new ByteArrayOutputStream();
            OutputStream outputfile= new FileOutputStream(new File("C:/BasicReport.xls"));

             JRXlsExporter exporterXLS = new JRXlsExporter();
             exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
             exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, outputByteArray);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
             exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
             exporterXLS.exportReport();
             outputfile.write(outputByteArray.toByteArray());
Jasper Error - Document root element "jasperReport", must match DOCTYPE root "null".

I m getting below error when trying to compile jasper report.

SEVERE: Parse Error at line 2 column 438: Document root element "jasperReport", must match DOCTYPE root "null".
org.xml.sax.SAXParseException: Document root element "jasperReport", must match DOCTYPE root "null".
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.rootElementSpecified(XMLDTDValidator.java:1621)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1900)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:764)

below is how my .jrxml file looks like.

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="BasicReport" pageWidth="595" pageHeight="842" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="30" bottomMargin="30" uuid="36d77059-4949-41ea-ad78-41d8786ef809">
    <property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
    <property name="ireport.y" value="0"/>
    <parameter name="Title" class="java.lang.String"/>
    <parameter name="MaxSalary"


It can be fixed by introducing <DOCTYPE ... > to .jrxml file as below.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="scriptlet">
<property name="ireport.zoom" value="1.0"/>
    <property name="ireport.x" value="0"/>
 ........................................................................

Tuesday, October 22, 2013

Jasper Reporting Error -  Attribute "xmlns" must be declared for element type "jasperReport".

I am getting the below error when trying to compile my jasper report program.

SEVERE: Parse Error at line 9 column 33: Attribute "xmlns" must be declared for element type "jasperReport".
org.xml.sax.SAXParseException: Attribute "xmlns" must be declared for element type "jasperReport".
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:195)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:131)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:384)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:318)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.addDTDDefaultAttrsAndValidate(XMLDTDValidator.java:1275)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.handleStartElement(XMLDTDValidator.java:1940)
    at com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDValidator.startElement(XMLDTDValidator.java:764)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanStartElement(XMLDocumentFragmentScannerImpl.java:1363)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$ContentDriver.scanRootElementHook(XMLDocumentScannerImpl.java:1318)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3103)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:922)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)

My jrxml file looks like below.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jasperReport PUBLIC
"//JasperReports//DTD Report Design//EN"
"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
name="scriptlet" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="30" rightMargin="30" topMargin="30" bottomMargin="30"
whenResourceMissingType="Empty">
<property name="com.jasperassistant.designer.Grid" value="false"/>
<property name="com.jasperassistant.designer.SnapToGrid" value="false"/>
<property name="com.jasperassistant.designer.GridWidth" value="12"/>
<property name="com.jasperassistant.designer.GridHeight" value="12"/>
<queryString>
<![CDATA[]]>
</queryString>
..........................................................

The solution is below.

Instead of using both the DTD and the XML schema, stick to the DTD alone. In other words, instead of having the following lines in my JRXML file:


<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" 
name="report2" language="groovy" pageWidth="595" pageHeight="842" 
columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" 
bottomMargin="20">
 
I have put below two lines and it worked.
 
<!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd">
<jasperReport name="scriptlet">

Monday, October 21, 2013

Using iReport 5.1.0 Designer

After extracting zipfile and when truing to click on iReport icon in bin to execute iReport we may get below error.

To solve it we need to set JDK path in config file.

in etc folder, there is file named 'iReport'.Set path as below.


Then issues will be solved.

When initially start working, we have to copy DB library file to iReport lib folder and then click tools -> options -> classpath -> add jar and select whatever the jar file.

For eg: if it is oracle,then it will be ojdbc6.jar

Then click on 'datasource' as below.

Then create connection as below and test it to check wethre it is successful.


Then create new report as below.We can select any report template as below.Click on 'Open this template' button.


Below is the link for rest of instrucions.

http://community.jaspersoft.com/wiki/designing-report

http://community.jaspersoft.com/project/ireport-designer

  • To print the value of a field in the report, drag a field object from the report inspector to the design view. For example, drag a field into the detail band, a section of the report that is printed for each record/row in the query results. The title and the summary bands are printed just once in each report, while the page header and footer are printed once at the top and bottom of each page, respectively.
  • It is important that the textfields are all placed within the detail band.
Deploying Your Report - Deploying your report to JasperReports Server or within your own Java application. 

(Refer this link: http://community.jaspersoft.com/wiki/deploying-reports)
When you design and preview a report in iReport Designer, iReport Designer produces a Jasper file. This file is all you need in your Java application to generate and display the report (in addition to JasperReports Library, of course).

The report execution is performed by the JasperReports library, so you have to include all the required jars in your application. Which jars? If you do not have a problem shipping a lot of jars, you can include all the jars provided in JasperReports Library. However JasperReports includes many jars that you may not need as well.



















Saturday, October 19, 2013

How to solve this The server does not support version 3.0 of the J2EE Web module specification.?

This happens becasue different tomcat versions support, different servlet specsbelow links give which supports which version.Tomcat5.5.x supports servlet/jsp spec 2.4/2.0 (Does not support annotations).

You need to upgrade to tomcat7.x to be able to run servlet/jsp spec 3.0/2.2

http://tomcat.apache.org/whichversion.html

Ways to solve the problem. Change version to 2.5 to run in tomcat 5.5 or Run your application with version 3.0 in tomcat 7.



Normally you'd simply go to properties->Project Facets and then change the Dynamic Web Module to a lower version. However for me that is not working. It tells me "Cannot change the version of project facet Dynamic Web Module to 2.5"

 Refer this link.

http://keensknowledgeaccumulation.blogspot.com/2013/02/server-does-not-support-version-30-of.html

Friday, October 18, 2013

Error - 'Project facet Java version 1.7 is not supported in eclipse' 

It can be that java 1.7 is not installed in your system then you can use java version that is already installed in your system.



Following Steps could resolve this error by setting up current version in project facet

Step 1: Right Click over your Project on Project Explorer and click on Properties. Step 2: Goto java build path->Libraries
 Check JRE System Library Jars and also check it is JDK 1.6 or 1.7
Step 3:Go to "Project Facet" and select your current java version available.

  
click apply then ok.

Sunday, October 6, 2013

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session


save method:- it is used to insert the newly created object in datastore.(Basically identifier value will be 0 for this). Like i create a new customer and call save operation , it will persist it in datastore and generate the identifier.
So calling save again will result in another row in the db.

update method:- it is used to update the already persistent object in datastore.(Basically identifier value will be some non zero value for this). Like i load a new customer and call update operation after update of some field value, it will update it in datastore .As per my understanding it should fail with some exception because as per api update is for detached object.

update updates an object in the session. So if the object is in the session it will update. If the object is not in the session, you should call merge. I believe calling update for a detached instance will result in an exception.
 
saveorupdate method:- it will call either of above based on unsaved-value checks. so if we have persistent customer object . Now if we update last name of his and create a new account also, then saveorupdate will take care of it. 
 
Merge method :- it will like update but here if persistent object with the same identifier is already there in session it will update the detached object values in persistent object and save it. Right? But if If there is no persistent instance currently associated with the session, this will load the persistent object from datastore and then update the value of detached object in loaded persistent object and then update it.

 above chek again pls
http://stackoverflow.com/questions/7475363/differences-among-save-update-saveorupdate-merge-method-in-session-object

Rather than sing update if we use, merge this can be solved.

How to apply atheme to Struts2 Forms

Sometimes even if we try to align 2 components in UI of struts form, they will not get aligned.For eg: I needed to have two text boxes in one row.So in such a situation I can do below.

For eg: When you use a Struts 2 tag such as s:select in your web page, the Struts 2 framework generates HTML that styles the appearance and controls the layout of the select control. The style and layout is determined by which Struts 2 theme is set for the tag. Struts 2 comes with three built-in themes: simple, xhtml, and css_xhtml. If you don’t specify a theme, then Struts 2 will use the xhtml theme by default.

I can either change struts.xml as below.Then it will apply all pages.


<struts>
<constant name="struts.ui.theme" value="simple" />

......................

</struts>


xhtml layout
The xhtml theme renders out a two-column table. If a different layout is needed, do not write your own HTML. Create a new theme or utilize the simple theme.

If we get the issue of labels of text fields missing we can have like below.

<table>
     <tr>

              <td><label for="a" class="label" theme="simple">Firstname:</label></td>
              <td><s:textfield id="a" name="username" label="Username" size="20" theme="simple"/></td>

               <td><label for="b" class="label" theme="simple">LastName:</label></td>
              <td><s:textfield id="b" name="lastName" label="lastName" size="20" theme="simple"/></td>

</tr>
<tr><s:submit method="execute" label="login" align="center" /></tr>
</table>

 It will show components in one row.

How To Handle Multiple Submit Buttons in Struts 2

JSP File:
<s:form name="inquiryForm" method="post" theme="simple" > 
   Select roll no : 
   <s:select style="width: 200px;" 
      list="#{'1':'Student 01', '2':'Student 02', '3':'Student 03', '4':'Student 04'}"
      id="projectName" 
      name="studentRollNo" 
      readonly="false" 
      headerKey="-1" 
      headerValue="--- Select ---" 
   /> 
   <s:submit cssClass="page" action="academics" value="academics" /> 
   <s:submit cssClass="page" name="sports" value="sports" /> 
   <s:submit cssClass="page" name="library" value="library" /> 
</s:form>
 
struts.xml:
`

<package name="default" extends="struts-default"> <action name="academics" class="ViewAcademics" > <result name="success">pages/ViewAcademics.jsp</result> </action> <action name="sports" class="ViewSports" > <result name="success">pages/ViewSports.jsp</result> </action> <action name="library" class="ViewLibrary" > <result name="success">pages/ViewLibrary.jsp</result> </action> </package>


----------------------------------------------------------


Often, we have multiple submit buttons within a single form. The below is just a simple way of identifying which button was clicked, and which actions to take.
There are, of course, many ways of doing this, including the use of JavaScript to identify the actions, etc... You're welcome to pick and choose whichever method you find most useful. Struts 2 is flexible enough.

Form

<button type="submit" value="Submit" name="submit">
<button type="submit" value="Clear" name="clear">

Action with boolean properties

class MyAction extends ActionSupport {
   private boolean submit;
   private boolean clear;
   public void setSubmit(boolean submit) {
      this.submit = submit;
   }
   public void setClear(boolean clear) {
      this.clear = clear;
   }
   public String execute() {
      if (submit) {
         doSubmit();
         return "submitResult";
      }
      if (clear) {
         doClear();
         return "clearResult";
      }
      return super.execute();
   }
}

Explanation

The boolean properties 'submit' and 'clear' will be set to 'true' or 'false' according weather the submit or clear form element is present in the submitted form.
In this case, the properties are boolean, therefore the values set would be boolean.
There is another method, using String properties, described below...

Form

<button type="submit" value="Submit" name="buttonName">
<button type="submit" value="Clear" name="buttonName">

Action with String properties

class MyAction extends ActionSupport {
   private String buttonName;
   public void setButtonName(String buttonName) {
      this.buttonName = buttonName;
   }
   public String execute() {
      if ("Submit".equals(buttonName)) {
         doSubmit();
         return "submitResult";
      }
      if ("Clear".equals(buttonName)) {
         doClear();
         return "clearResult";
      }
      return super.execute();
   }
}

Explanation

In this case, the properties are String, therefore the values set are also String in nature.
I don't really like this method, as it ties in the Action to the Form. (What happens if you want different text to show up on the button ? You would have to change both the form as well as the corresponding action.)

There are other ways to achieve the same functionality. There are pros and cons to each methods.

The more elegant solution is probably by using multiple mappings for same Action. This way you don't need to set "struts.enable.DynamicMethodInvocation" to "true".

In JSP

<s:form method="post" action="mySubmitAction">
    <s:submit value="Submit"/>
    <s:submit value="Clear" action="myClearAction"/>
</form>
In struts.xml

<action name="mySubmitAction" class="MyAction" method="submit">
       <result>submit.jsp</result>
</action>
<action name="myClearAction" class="MyAction" method="clear">
       <result>submit.jsp</result>
</action>
Then in MyAction class

public String submit() throws Exception {
    // submit button logic here
    return SUCCESS;
}
public String clear() throws Exception {
    // clear button logic here
    return SUCCESS;
}

For best practice, if you have common data loaded / managed by your actions (submit & clear), then for example, you can define a MyBaseAction class, extended by MySubmitAction and MyClearAction class. Then this is how they looks like:
In struts.xml

<action name="mySubmitAction" class="MySubmitAction">
       <result>submit.jsp</result>
</action>
<action name="myClearAction" class="MyClearAction">
       <result>submit.jsp</result>
</action>
You don't need to specify a method name anymore, that means we will use the default execute() method.
Then in the MyAction, MySubmitAction and MyClearAction class
MyAction.java
public class MyAction extends ActionSupport {
    // common data or logic here
}
MySubmitAction.java
public class MySubmitAction extends MyAction {
    public String execute() throws Exception {
        // submit button logic here
        return SUCCESS;
    }
}
MyClearAction.java
public class MyClearAction extends MyAction {
    public String execute() throws Exception {
        // clear button logic here
        return SUCCESS;
    }
}

 
How to redirect to another action within Struts.xml file - Struts2

<action name="contact-form"
            class="net.viralpatel.contact.view.ContactAction" method="search">
            <result name="success" type="tiles">/contactCrud.tiles</result>
 </action>

<action name="delete"
            class="net.viralpatel.contact.view.ContactAction" method="delete">
            <result name="success" type="chain">contact-form</result>
 </action>

Above is taken from the struts.xml

when we delete, it redirects to 'contact-form' action and does whatever within that action.

Saturday, October 5, 2013

Hibernate Error : org.hibernate.PropertyValueException: not-null property references a null or transient value

This occured when DB id column is not null and auto generated and my hbm has defined the id column as

<generator class="native" />

org.hibernate.PropertyValueException: not-null property references a null or transient value: net.viralpatel.contact.model.Contact.created
    at org.hibernate.engine.Nullability.checkNullability(Nullability.java:95)
    at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:313)
    at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550)
    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:546)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
    at $Proxy6.save(Unknown Source)
    at net.viralpatel.contact.controller.ContactManager.add(ContactManager.java:27)
    at net.viralpatel.contact.view.ContactAction.add(ContactAction.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:453)...


Solution:


Hibernate Error :  failed.org.hibernate.PropertyNotFoundException: Could not find a getter for firstname in class net.viralpatel.contact.model.Contact

I get below error in a struts 2 + hibernate 3 project and below is mapping file.

<property name="firstname" type="string" not-null="false" length="30" column="firstName" />

And below is how the domain class property is named.

private String firstName;

Below is how column in DB is named.

firstName   VARCHAR(30)

when execute the add action from jsp page i get below error.

failed.org.hibernate.PropertyNotFoundException: Could not find a getter for firstname in class net.viralpatel.contact.model.Contact
Oct 6, 2013 11:51:32 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet default threw exception
org.hibernate.PropertyNotFoundException: Could not find a getter for firstname in class net.viralpatel.contact.model.Contact
    at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:306)
    at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:299)
    at org.hibernate.mapping.Property.getGetter(Property.java:294)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:268)
    at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:148)
    at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:76)
    at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:80)
    at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:325)
    at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:457)
    at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:131)
    at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:84)
    at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:261)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1327)
    at net.viralpatel.contact.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
    at net.viralpatel.contact.util.HibernateUtil.<clinit>(HibernateUtil.java:8)
    at net.viralpatel.contact.view.ContactAction.<init>(ContactAction.java:21)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at java.lang.Class.newInstance0(Class.java:355)
    at java.lang.Class.newInstance(Class.java:308)
    at com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:130)......................

Solution :

Property in hbm and pojo class are different.
They should be the same.
Hibernate Error :  org.hibernate.PropertyNotFoundException: Could not find a getter for cell_no in class net.viralpatel.contact.model.Contact

My hbm has below property.




Initial SessionFactory creation failed.org.hibernate.PropertyNotFoundException: Could not find a getter for cell_no in class net.viralpatel.contact.model.Contact
Oct 5, 2013 11:53:46 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet default threw exception
org.hibernate.PropertyNotFoundException: Could not find a getter for cell_no in class net.viralpatel.contact.model.Contact
    at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:306)
    at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:299)
    at org.hibernate.mapping.Property.getGetter(Property.java:294)

Hibernate Error – java.lang.NoClassDefFoundError:javax/transaction/Synchronization

This is caused by missing of the “jta.jar“, usually happened in Hibernate transaction development.

java.lang.NoClassDefFoundError: javax/transaction/Synchronization
 at org.hibernate.impl.SessionImpl.<init>(SessionImpl.java:213)
 at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:473)
 at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:497)
 at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:505)
 at com.mkyong.common.App.main(App.java:13)
Caused by: java.lang.ClassNotFoundException: javax.transaction.Synchronization
 at java.net.URLClassLoader$1.run(Unknown Source)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClass(Unknown Source)
 at java.lang.ClassLoader.loadClassInternal(Unknown Source)
 ... 5 more

Solution

You can download “jta.jar” from default Maven central, JBoss or Java.net repositories.