Jerry Jacob's Blog

JBoss Seam – ConcurrentRequestTimeoutException: Concurrent call to conversation

Posted in Java/ J2EE by jerlinworld on February 17, 2012

This problem is commonly seen in applications that use Ajax in the context of a long-running conversation. If the problem happens when a conversation is still active, it’s because one of the requests could not get a lock on the conversation in the allotted time period. Many developers run into this problem for the first time when using a CRUD application created by seam-gen. This entry explains the problem using the seam-gen application as an example.

Given below the reason why I got this exception:
I made 2 ajax calls one after another.


<h:inputText id="zip" value="#{location.instance.zip}">
   <a:support event="onblur" reRender="zipField" bypassUpdates="true" ajaxSingle="true"/>
   <a:support event="onchange" reRender="longitude,latitude" action="#{location.setGeocode()}"/>
</h:inputText>


The issue can be fixed by serializing the requests sent to the server so that they never contend for the conversation. This can be done using the eventsQueue attribute.
‘eventsQueue’ attribute provide a queue in which events are placed. All events are queued and requests are sent to the server serially. This is useful if the request to the server can take some time to execute (e.g. heavy computation, retrieving information from a slow source)


<h:inputText id="zip" value="#{location.instance.zip}">
   <a:support event="onblur" reRender="zipField" bypassUpdates="true" ajaxSingle="true" eventsQueue="default"/>
   <a:support event="onchange" reRender="longitude,latitude" eventsQueue="default" action="#{location.setGeocode()}"/>
</h:inputText>


Advertisements

Own ID Column for the Model in the Play! Framework

Posted in Java/ J2EE, Play Framework by jerlinworld on January 11, 2012

When you create Model entities in the Play! Framework, Play will provide a default id column.  If you need to use your own id column — say if you are given a database schema to work with — then you should extend a different Play class called GenericModel instead of Model class.  In addition to providing an @Id annotation, it also provides @GeneratedValue annotation. Here is its usage both with  Oracle and MySql.
MySql

@Entity
public class Tutorial extends GenericModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long tutorial_id;

Oracle

@Id
@GeneratedValue(strategy=SEQUENCE, generator="videoIdSeq")
@SequenceGenerator(name="videoId", sequenceName="video_id_seq", allocationSize=1)
@Column(name="video_id")
protected Long videoId;

Create zip files in Java

Posted in Java/ J2EE by jerlinworld on January 11, 2012

The output of the below Java program will be the creation of a zip file inside c:/ with the name test.zip
Taken from http://extreme-java.com



package com.example;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/** This class is a Java tutorial for creating zip file
 * 
 * @author Extreme Java
 */
public class Test{
 
	/** The method creates zip file and also creates an entry inside it
	 * 
	 * @param args is the command line arguments
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException  {
		//create a file output stream
		FileOutputStream zipFOS = new FileOutputStream("c://test.zip");
 
		//create a zip output stream from the file output stream created above.
		//zip output stream decorates file output stream
		ZipOutputStream zipoutStream = new ZipOutputStream(zipFOS);
 
		//creates an zip entry. You can create as many entries as you wish
		//Each entry represent a file with in the zip archive
		ZipEntry zipEntry = new ZipEntry("source1");
 
		//put the zip entry create above into the zip file
		zipoutStream.putNextEntry(zipEntry);
 
		//write some text into the zip entry created above.
		//Whatever is written will be added to last added zip entry
		zipoutStream.write(1);
 
		//close the zip entry.
		zipoutStream.closeEntry();
 
		//Finish the creation of zip file.
		zipoutStream.finish();
 
		//close the file output stream
		zipFOS.close();
 
		//close the zip output stream
		zipoutStream.close();
	}
}

Reading and Writing from/ to a file using javascript

Posted in Uncategorized by jerlinworld on October 12, 2010

var hello='Hello '; 
var world='World'; 

function WriteToFile() { 
var filename = 'c://hello.txt'; 
var fso = new ActiveXObject('Scripting.FileSystemObject'); 
if (fso.FileExists(filename)) { 
var a, forAppend, file; 
forAppend = 8; 
file = fso.OpenTextFile(filename, forAppend, false); 
file.WriteLine(world); 
file.WriteLine(hello); 
} 
else { 
var file = fso.CreateTextFile(filename, true); 
file.WriteLine(hello); 
file.WriteLine(world); 
} 
file.Close(); 
} 

function ReadFromFile() { 
var filename = 'c://hello.txt'; 
if (confirm('Do you want to see what we put on your computer?')) { 
var fso, a, forRead; 
forRead = 1; 
fso = new ActiveXObject('Scripting.FileSystemObject'); 
file = fso.OpenTextFile(filename, forRead, false); 
var world = file.readline(); 
var hello = file.readline(); 
file.Close(); 
document.write(world + '<br>'); 
document.write(hello); 
} 
} 

Create Word Documents Using Jasper API

Posted in Java/ J2EE by jerlinworld on March 9, 2010

All the basics for creating a document using Jasper API remains the same except the Exporter. Please refer to my earlier post to create PDF and RTF reports.

Given below is the code that would return the word document in byte array.
NOTE: You have to use the jasper api version 3.5.x or higher

public byte[] buildDocResume(final String ssnNumber) {

		final String sourceMethod = "buildDocResume";
		ResumeEngineImpl.log.entering(ResumeEngineImpl.sourceClass,
				sourceMethod, ssnNumber);
		byte[] docResume = null;
		try {
			final Seeker seeker = this.getSeekerBySsn(ssnNumber);
			final JasperPrint jasperPrint = this.renderResume(seeker);

			final JRDocxExporter docExporter = new JRDocxExporter();
			final ByteArrayOutputStream docStream = new ByteArrayOutputStream();
			docExporter.setParameter(JRDocxExporterParameter.JASPER_PRINT,
					jasperPrint);
			docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,
					docStream);
			docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
			docExporter.exportReport();
			docResume = docStream.toByteArray();
		} catch (final JRException e) {
			ResumeEngineImpl.log.logp(Level.WARNING,
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);
		} catch (final RuntimeException e) {
			ResumeEngineImpl.log.logp(Level.WARNING,
					ResumeEngineImpl.sourceClass, sourceMethod,
					"Exception caught:", e);
		}

		return docResume;
	}

Tip: The generated word document will be formatted using several nested tables. If the property, JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, is set to false, the table rows do not increase in height automatically and the user has to enlarge them manually in word.

Passing Arguments to .property file

Posted in Java/ J2EE by jerlinworld on February 24, 2010

Property File Sample

app.welcome= Welcome {0} and {1}.
app.bye=Bye {0} and {1}.

Jave Code using MessageFormat


String propText=resBundle.getString("app.welcome");
java.text.MessageFormat msgFormatter = new java.text.MessageFormat(propText);

// Write the dynamic args you want to replace 
Object[] messageArguments = {"Jerry","Jacob"};  
 
String finalText= msgFormatter.format(messageArguments);

UTF-8: Encoding Fix

Posted in Java/ J2EE by jerlinworld on December 14, 2009

I was trying to get the non-ascii characters from my property file to render correctly in my jsp file. My original property file was encoded using UTF-8 with the spanish translations for my application. While rendering the page, I was getting a few garbled text instead of pulling the proper spanish text from the property file. Here is the simple fix that I came across after researching on it for the whole day.

1. Made a copy of my original property file, messages_es.properties, and named it messages_es.original.properties
2. Run the file, messages_es.original.properties, through native2ascii to convert the characters to its unicode escape form. Here is the command line for this: native2ascii -encoding UTF-8 ages_es.original.properties messages_es.properties

This fix for the property file resolved my issues.

For more info, you may visit, http://java.sun.com/developer/JDCTechTips/2003/tt0506.html

Navigation while using Tiles with JSF

Posted in Java/ J2EE by jerlinworld on October 15, 2009

I would like to post a tip while using Tiles with JSF. I had to spend a few hours to fix the navigation issue that I experianced while coding my App.

I was using the body tile page for the ‘from-view-id’ element while coding the navigation rule. This is wrong and we should be using the actual page name.

Incorrect value for ‘from-view-id’

<navigation-rule>
		<from-view-id>/tilesContent/index_body.jsp</from-view-id>
		<navigation-case>
			<from-action>#{index.loginAction}</from-action>
			<from-outcome>success</from-outcome>
			<to-view-id>/login.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

Correct value for ‘from-view-id’

<navigation-rule>
		<from-view-id>/index.jsp</from-view-id>
		<navigation-case>
			<from-action>#{index.loginAction}</from-action>
			<from-outcome>success</from-outcome>
			<to-view-id>/login.jsp</to-view-id>
		</navigation-case>
	</navigation-rule>

Calling Java Web Service from VB 6.0

Posted in Visual Basic by jerlinworld on September 24, 2009

Given below is the code that I used successfully in my VB Application that call the Java web service.


Public Function ValidateSSN(ByVal Domain As String) As String
    Dim strSoapAction As String
    Dim strUrl As String
    Dim strXml As String

    strUrl = "http://" + Domain + "/JobRepository/services/DetermineJobCode"
    strSoapAction = "http://www.jerryjacob.com/JobRepositoryWS/getOccupations"
    strXml = "<?xml version=""1.0"" encoding=""utf-8""?>" & _
            "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:job=""http://www.jerryjacob.com/JobRepositoryWS/"">" & _
            "<soapenv:Header/>" & _
            "<soapenv:Body>" & _
            "<job:getJobs>" & _
            "<getJobsRequest>" & _
            "<jobTitle>Computer Programmers</jobTitle>" & _
            "<maximumResults>1</maximumResults>" & _
            "</getJobsRequest>" & _
            "</job:getJobs>" & _
            "</soapenv:Body>" & _
            "</soapenv:Envelope>"
 
    Debug.Print PostWebservice(strUrl, strSoapAction, strXml)
    ValidateSSN = PostWebservice(strUrl, strSoapAction, strXml)
End Function


Private Function PostWebservice(ByVal AsmxUrl As String, ByVal SoapActionUrl As String, ByVal XmlBody As String) As String
    Dim objDom As Object
    Dim objXmlHttp As Object
    Dim strRet As String
    Dim intPos1 As Integer
    Dim intPos2 As Integer
   
    On Error GoTo Err_PW
   
    ' Create objects to DOMDocument and XMLHTTP
    Set objDom = CreateObject("MSXML2.DOMDocument")
    Set objXmlHttp = CreateObject("MSXML2.XMLHTTP")
   
    ' Load XML
    objDom.async = False
    objDom.loadXML XmlBody

    ' Open the webservice
    objXmlHttp.open "POST", AsmxUrl, False
   
    ' Create headings
    objXmlHttp.setRequestHeader "Content-Type", "text/xml; charset=utf-8"
    objXmlHttp.setRequestHeader "SOAPAction", SoapActionUrl
   
    ' Send XML command
    objXmlHttp.send objDom.xml

    ' Get all response text from webservice
    strRet = objXmlHttp.responseText

    ' Close object
    Set objXmlHttp = Nothing
   
    ' Extract result
    intPos1 = InStr(strRet, "<score>") + 7
    intPos2 = InStr(intPos1, strRet, "</score>")
    If intPos1 > 7 And intPos2 > 0 Then
        strRet = Mid(strRet, intPos1, intPos2 - intPos1)
    End If
   
    ' Return result
    PostWebservice = strRet
   
Exit Function
Err_PW:
    PostWebservice = "Error: " & Err.Number & " - " & Err.Description

End Function

Comments Off on Calling Java Web Service from VB 6.0

Web Service Integration using JXPath

Posted in Java/ J2EE by jerlinworld on August 5, 2009

I was successful in integrating two web services using the JXPath API from Apache. My task was to generate a letter using the data obtained from a third party web service. I had to call another web service to get the letter template and the metadata that’s needed for printing the letter. Since these services were in no way related, I had to create a file; mapping the data items in our web service to the actual data in third party web service (key-value). Using this mapping file along with the JXPath API made the integration a piece of cake.

Now let me explain how the JXPath works. Consider this example:

String city = (String)JXPathContext.newContext(vendor).
         getValue("locations[address/zipCode='90210']/address/city");

This XPath expression is equivalent to the following Java code:

String city = null;
Collection locations = vendor.getLocations();
Iterator it = locations.iterator();
while (it.hasNext()){
    Location location = (Location)it.next();
    String zipCode = location.getAddress().getZipCode();
    if (zipCode.equals("90210")){
      city = location.getAddress().getCity();
      break;
    }
}

In my mapping file, I have my values stored as XPath strings. These XPath values were used to fetch the actual data from the third party web service using the JXPath API.