Friday, December 7, 2012

Whats Apache Wicket?

Whats Apache Wicket?

Answer : Apache wicket is a lightweight, component based web application framework.It separates the html or UI completely from Java code, which makes it convenient for designer and programmers to work independently, besides there is no confusing HTML messed up with Java code in it. Its far more convenient than using JSP's where we have to put scriptlets and expressions to use java objects in UI.
Wicket provides many advantages over frameworks like struts and it can be easily integrated with core frameworks like hibernate, spring etc.

java.security.AccessControlException: access denied (java.io.FilePermission

I have a third party service which is being invoked from my J2ee Web application. I have created a remote client class to invoke this service but I am getting  the folllowing exception while trying to access the Remote Client from Weblogic 11 G Server.

<at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)>
  <at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:120)>
  <at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2277)>
  <at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2183)>
  <at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1454)>
  <at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)>
  <at weblogic.work.ExecuteThread.run(ExecuteThread.java:178)>
<at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)>
 <Warning> <mngd-srvr> <[ACTIVE] ExecuteThread: '0' for queue: 'weblogic.kernel.Default (self-tuning)'> <<anonymous>> <> <> <1349369405197> <BEA-2000161> <[Enhance] An exception was thrown while attempting to perform class file transformation on "com.test.services.objects.TestObject":
java.security.AccessControlException: access denied (java.io.FilePermission /srvrs/installed/servers/mngd-srvr/tmp/_WL_user/test-ear/ykrfd6/APP-INF/lib/testdataobjects.jar read)
        at java.security.AccessControlContext.checkPermission(AccessControlContext.java:374)
        at java.security.AccessController.checkPermission(AccessController.java:546)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
        at java.lang.SecurityManager.checkRead(SecurityManager.java:871)
        at java.io.File.isDirectory(File.java:752)
        at java.io.File.toURL(File.java:623)


Fix: It can be fixed by providing security policy in the Java Options in your setDomainEnv file under bin directory of web logic installation:

I placed a policy file with grant all security level and set its location in the java options.

1. Place grant_all.policy in your config folder:

 grant {
  permission java.security.AllPermission;
};

2.  Add the following in JAVA_OPTIONS in setDomainEnv.

-Djava.security.policy=C:\weblogic\testdomain\config\grant_all.policy





Tuesday, December 4, 2012

The setup requires the .NET Framework version 4.0.

I created a a setup Project for an application I created in .Net framework. But when installing it on a different machine it gave me following Error:

The setup requires the .NET Framework version 4.0. Please install the .NET Framework and run the setup again. The .NET Framework can be obtained  from the web. Would you like to do this now?








http://www.aneef.net/wp-content/uploads/2010/05/5-24-2010-4-00-44-PM.png



I found out that it looks for a specific version of .Net framework if you kept the the default value for Version (in this case 4.0). To resolve this we need to set the version to 'Any' so it run just fine independent of any specific version.

Here is how we configure it.

Under the Setup Project click on the Detected Dependencies.
Click on the Microsoft .Net Framework. Go to Properties window
Change the Version property to 'Any' (Or as per your preference)
Build teh Setup Project again and retry.

Monday, November 12, 2012

vb .Net null check for objects

How to check Null objects in VB.Net?

Solution:

 If IsNothing(myObject) Then
           
           ' Some Code
                                                          
End If

Thursday, November 8, 2012

Creating Public Synonym in Oracle

In Oracle we can create the public synonyms for the tables which users of other schema can refer to without specifying any schema name. Its an alternative name for data objects.
 
This is specifically useful when we are creating a generic script and do not want it to be schema specific.

For example the table called "employee" in the following query can be accessed without having to prefix the table name with the schema named testschema:


create or replace public synonym employee for testschema.employee ;


To drop the synonym use the following :

drop public synonym employee;






Synonyms can also be used for views, sequences, stored procedures, and other database objects.

Thursday, August 9, 2012

ResourceBundle How to get a String Array or ArrayList from a single propety

Following is  an example of how to get the array of string or list of properties from a Resource Bundle. We can specify the list of values in one property (single key) and obtain it as an string array or an array list in Java.

Here is an example of property file which has a list of key/value combination for employee's designations and its corresponding value.

EmployeeConfig.properties
====================
 employeeDesignations=\
           0=Director,\
           1=Manager,\
           2=Clerk,\
           3=Business Analyst,\
           4=Sales Executive,\

#Note : a backslash ("\") is required if you are trying to span the property values to multiple lines. Its more readable.

In my application I want to show this list in a dropdown for which I need this as an ArrayList.

Here is my Code Snippet for the same.
============================================

    ArrayList<SelectItem> employeeDesignationList = new ArrayList<SelectItem>();
       
// Get the Resource Bundle instance.
        ResourceBundle resourceBundleConfig= getResourceBundle("EmployeeConfig.properties");
       
        String propertyStr = resourceBundleConfig.getValue("employeeDesignations");
       
        // Get an String Array from the comma separated string.
        String propertyArr[] = propertyStr.split(",");             
       
   
        /*
         * Now our values are key value pair i.e. 0=Director.
         * Hence we would need to split the values again with an equal ("=") as separator.
         */
        for(int i=0; i< propertyArr.length ; i++){
            String employeeDesignation[] = propertyArr[i].split("=");     
            String key = employeeDesignation[0];
            String value = employeeDesignation[1];
           
            employeeDesignationList.add(new SelectItem(key, value));          
        }
       
        System.out.println("Values Obtained :: \n ");      
      
        for(SelectItem item : employeeDesignationList) {
                System.out.println(item.getValue() + " :: " + item.getLabel());      
        }



============================================

In the above code we create an ArrayList "employeeDesignationList" which is a list of SelectItem  objects. The SelectItem is a class in JSF framework which is used by the Dropdown to populate the key/value pair. You can use a different object depending on the implementation.

I had to resort to the above solution as when I tried to use the ResourceBundle.getStringArray() method, I got a ClassCastException at runtime. Its return type is String[] but when you try to run the program it actually return a String object. I read that its advisable to Implement your own ResourceBudle object and override the getStringArray method to return an array. You can customize this method as required.


Thursday, August 2, 2012

JSF : Get a bean from Session, Request

To retrieve the session scoped bean or a request scope bean in JSF we can use  session map or request map respectively.


<faces-config>
    <managed-bean>
        <managed-bean-name>testSessionObject</managed-bean-name>
        <managed-bean-class>test.TestSessionObject</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
     </managed-bean>
    <managed-bean>
        <managed-bean-name>testRequestbject</managed-bean-name>
        <managed-bean-class>test.TestRequestbject</managed-bean-class>
        <managed-bean-scope>request</managed-bean-scope>
     </managed-bean>
<faces-config>

Java Code :

FacesContext context = FacesContext.getCurrentInstance(); 

// Get a Session scoped bean
Map sessionMap = context.getExternalContext().getSessionMap();

TestSessionObject  testSessionObject  = (TestSessionObject  ) map.get("testSessionObject");

// Get a Request scoped bean
Map requestMap = context.getExternalContext().getRequestMap();
TestRequestObject  testRequestObject  = (TestRequestObject  ) map.get("testRequestObject  ");


Friday, July 13, 2012

java.io.IOException: No such file or directory

The following lines of code caused this issue:


File imageFile = new File("/Users/test/main/tomcat/webapps/temp/"
  + UUID.randomUUID() + ".jpg");

imageFile.createNewFile(); // Exception Caused here.
imageFileUpload.writeTo(imageFile);



Exception Logs:

DEBUG - onSubmit called
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:883)
at com.test.web.common.form.UpdateImageForm.onSubmit(UpdateImageForm.java:297)
at org.apache.wicket.markup.html.form.Form.delegateSubmit(Form.java:1565)
at org.apache.wicket.markup.html.form.Form.process(Form.java:958)
at org.apache.wicket.markup.html.form.Form.onFormSubmitted(Form.java:920)
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.apache.wicket.RequestListenerInterface.invoke(RequestListenerInterface.java:182)
at org.apache.wicket.request.target.component.listener.ListenerInterfaceRequestTarget.processEvents(ListenerInterfaceRequestTarget.java:73)
at org.apache.wicket.request.AbstractRequestCycleProcessor.processEvents(AbstractRequestCycleProcessor.java:92)
at org.apache.wicket.RequestCycle.processEventsAndRespond(RequestCycle.java:1250)
at org.apache.wicket.RequestCycle.step(RequestCycle.java:1329)
at org.apache.wicket.RequestCycle.steps(RequestCycle.java:1436)
at org.apache.wicket.RequestCycle.request(RequestCycle.java:545)
at org.apache.wicket.protocol.http.WicketFilter.doGet(WicketFilter.java:486)
at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:319)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:857)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:680)


Tuesday, July 10, 2012

Dos2Unix Command

We often get issues while using the text files copied from windows/mac to unix server.
The text file from windows/mac has some special characters for tabs, carriage return or line breaks etc.You can run vi command and see that ^M  character in the file. if it exists then you need to run the dos2unix command. dos2unix command formats the text files to be usable on unix environment.

Example :  The following example formats the file myWindowsTextFile.txt copied from windows, to  myUnixTextFile.txt on unix server.
 
$dos2unix myUnixTextFile.txt < myWindowsTextFile.txt

For more details on this command please refer to its documentation:
http://linuxcommand.org/man_pages/dos2unix1.html

Monday, July 9, 2012

Apache Wicket Interview Questions

Here are some of the technical Interview questions for Apache Wicket Framework used with Java J2ee framework.

Basic Questions:

Q.1 Whats Apache Wicket?
Answer
Q.2 How does Wicket work? What are the wicket Id's?
Q.3 Does Wicket provides the features of MVC framework?
Q.4 What are the steps to create a page in wicket?
Q.5 What are wicket components?
Q.6 What are Wicket panels and how do you use them?
Q.7 How do you configure the home page?
Q.8 What is the WebApplication class?
Q.9 What is a bookmarkable page?
Q.10 Does html files contain the java statements in Apache wicket?
Q.11 How do you set the Error Page in Wicket.
Q.11 What are the deployment modes in Wicket and where they are configured.


Advance Questions.
Q.1 What is a RequestProcessor, RequestCycle, ResourceLocator in Apache Wicket?
Q.2 How can you implement ResourceLocator? What are the advantages of the same?
Q.3 How Wicket is better/different than Struts?
Q.4 How can you handle run time exceptions in wicket? Whats is the use of onRuntimeException Method in RequestCycle Class?
Q5. Explain the use of AjaxRequestTarget?
Q.6 Explain Models in Wicket and its advantages. Explain LoadableDetachable Models.
Q.7 How do you use Form Validators in Wicket? How do you create custom validators?



Monday, July 2, 2012

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jstl/core cannot be resolved

While running a test jsp, getting following exception.

Jul 2, 2012 4:41:41 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:51)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:116)
    at org.apache.jasper.compiler.TagLibraryInfoImpl.generateTLDLocation(TagLibraryInfoImpl.java:316)
    at org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:149)
    at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:386)
    at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:450)


Following is the JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"  uri="http://java.sun.com/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<c:out value="Hello World"></c:out>
</body>
</html>



No tag "view" defined in tag library imported with prefix "f"

Exception while testing a demp jsp page.

SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /index.jsp(10,0) No tag "view" defined in tag library imported with prefix "f"
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:198)
    at org.apache.jasper.compiler.Parser.parseCustomTag(Parser.java:1187)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1422)
    at org.apache.jasper.compiler.Parser.parse(Parser.java:130)
    at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:255)
    at org.apache.jasper.compiler.ParserController.parse(ParserController.java:103)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:185)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:662)

ANTLRException unexpected char: '@'

Getting Following Exception while testing a selct query in Hibernate.

DEBUG - opened session at timestamp: 13411683004
DEBUG - unable to locate HQL query plan in cache; generating (from TestContents where contentId =@pContentId and contentType =@pContentType)
DEBUG - parse() - HQL: from TestContents where contentId =@ pContentId and pContentType =@ pContentType
DEBUG - converted antlr.ANTLRException
line 1:36: unexpected char: '@'
at org.hibernate.hql.antlr.HqlBaseLexer.nextToken(HqlBaseLexer.java:278)
at antlr.TokenBuffer.fill(TokenBuffer.java:69)
at antlr.TokenBuffer.LA(TokenBuffer.java:80)
at antlr.LLkParser.LA(LLkParser.java:52)
at org.hibernate.hql.antlr.HqlBaseParser.primaryExpression(HqlBaseParser.java:874)
at org.hibernate.hql.antlr.HqlBaseParser.atom(HqlBaseParser.java:3438)
at org.hibernate.hql.antlr.HqlBaseParser.unaryExpression(HqlBaseParser.java:3216)
at org.hibernate.hql.antlr.HqlBaseParser.multiplyExpression(HqlBaseParser.java:3098)
at org.hibernate.hql.antlr.HqlBaseParser.additiveExpression(HqlBaseParser.java:2818)
at org.hibernate.hql.antlr.HqlBaseParser.concatenation(HqlBaseParser.java:570)
at org.hibernate.hql.antlr.HqlBaseParser.relationalExpression(HqlBaseParser.java:2586)
at org.hibernate.hql.antlr.HqlBaseParser.equalityExpression(HqlBaseParser.java:2449)
at org.hibernate.hql.antlr.HqlBaseParser.negatedExpression(HqlBaseParser.java:2413)
at org.hibernate.hql.antlr.HqlBaseParser.logicalAndExpression(HqlBaseParser.java:2331)
at org.hibernate.hql.antlr.HqlBaseParser.logicalOrExpression(HqlBaseParser.java:2296)
at org.hibernate.hql.antlr.HqlBaseParser.expression(HqlBaseParser.java:2082)
at org.hibernate.hql.antlr.HqlBaseParser.logicalExpression(HqlBaseParser.java:1858)
at org.hibernate.hql.antlr.HqlBaseParser.whereClause(HqlBaseParser.java:454)
at org.hibernate.hql.antlr.HqlBaseParser.queryRule(HqlBaseParser.java:708)

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsf/core cannot be resolved

Getting following exception while trying to run a Test Dynamic Project in Eclipse.

Jul 2, 2012 4:06:17 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsf/core cannot be resolved in either web.xml or the jar files deployed with this application
    at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:51)
    at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
    at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:116)
    at org.apache.jasper.compiler.TagLibraryInfoImpl.generateTLDLocation(TagLibraryInfoImpl.java:316)
    at org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:149)
    at org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:386)
    at org.apache.jasper.compiler.Parser.parseDirective(Parser.java:450)
    at org.apache.jasper.compiler.Parser.parseElements(Parser.java:1397)
    at org.apache.jasper.compiler.Parser.parse(Parser.java:130)
    at org.apache.jasper.compiler.ParserController.doParse(ParserController.java:255)
    at org.apache.jasper.compiler.ParserController.parse(ParserController.java:103)
    at org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:185)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:354)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:334)
    at org.apache.jasper.compiler.Compiler.compile(Compiler.java:321)
    at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:592)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:328)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    at java.lang.Thread.run(Thread.java:662)

Friday, June 15, 2012

How to get the HttpSession, HttpServletRequest in JSF. Set the attribute in the session or get a parameter from session.

Here is a snippet to show how can we get the HttpSession, HttpServletRequest in JSF. Set the attribute in the session or get a parameter from session.
 
FacesContext context = FacesContext.getCurrentInstance(); 
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getRequest(); 
HttpSession httpSession = request.getSession(false); 

// To get the attribute
String testParam= (String) httpSession.getAttribute("testParam");

// To set the param
httpSession.setAttribute("testParam", "testValue");

Thursday, June 14, 2012

org.apache.openjpa.persistence.ArgumentException: There is no query with the name "getEmpployeesData" defined for any of the known persistent classes

Exception while trying a add a new Persistent Entity.

I added a new table in the database for Employee records. Created a bean for the same with a named query as shown below.

 @Entity
@NamedQuery(name = "getEmployeeData", query = "select EmployeeEntity from EMPLOYEE  EmployeeEntity where EmployeeEntity.DEPT=:deptId")
@Table(name = "EMPLOYEE")
public class EmployeeEntity {

}
Code to invoke this query.

EntityManager em;
....
....
Query getEmployeeDataQuery = em.createNamedQuery("getEmployeeData");
getEmployeeDataQuery.setParameter("deptId", deptId);           
ArrayList<Employee> employeeList= getEmployeeDataQuery .getResultList();



While trying to invoke this query I am getting following exception : 



SEVERE: Exception Occured : EJB Exception: ; nested exception is:
        <openjpa-1.1.1-SNAPSHOT-r422266:1172209 fatal user error> org.apache.openjpa.persistence.ArgumentException: There is no query with the name "getEmpployeesData" defined for any of the known persistent classes: [com.test.EmployeeEntity,com.test.EmployeeEntity].; nested exception is: <openjpa-1.1.1-SNAPSHOT-r422266:1172209 fatal user error> org.apache.openjpa.persistence.ArgumentException: There is no query with the name "getEmpployeesData" defined for any of the known persistent classe
com.test.EmployeeEntity]
javax.ejb.EJBException: EJB Exception: ; nested exception is:
        <openjpa-1.1.1-SNAPSHOT-r422266:1172209 fatal user error> org.apache.openjpa.persistence.ArgumentException: There is no query with the name "getEmpployeesData" defined for any of the known persistent classes: [com.test.EmployeeEntity, com.test.EmployeeEntity].; nested exception is: <openjpa-1.1.1-SNAPSHOT-r422266:1172209 fatal user error> org.apache.openjpa.persistence.ArgumentException: There is no query with the name "getEmpployeesData" defined for any of the known persistent classe
s: [com.test.EmployeeEntity].
<openjpa-1.1.1-SNAPSHOT-r422266:1172209 fatal user error> org.apache.openjpa.persistence.ArgumentException: There is no query with the name "getEmpployeesData" defined for any of the known persistent classes: [com.test.EmployeeEntity]
        at org.apache.openjpa.meta.MetaDataRepository.getQueryMetaData(MetaDataRepository.java:1596)
        at org.apache.openjpa.persistence.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:895)
        at org.apache.openjpa.persistence.EntityManagerImpl.createNamedQuery(EntityManagerImpl.java:77)
        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 weblogic.deployment.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:111)
        at weblogic.deployment.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:78)
        at weblogic.deployment.BasePersistenceContextProxyImpl.invoke(BasePersistenceContextProxyImpl.java:92)
        at weblogic.deployment.TransactionalEntityManagerProxyImpl.invoke(TransactionalEntityManagerProxyImpl.java:18)
        at $Proxy178.createNamedQuery(Unknown Source)
        at services.EmployeeDataServiceBean.getEmpployeesData(EmployeeDataServiceBean.java:295)
        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.bea.core.repackaged.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:310)
        at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
        at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
        at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
        at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
        at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
        at com.oracle.pitchfork.spi.MethodInvocationVisitorImpl.visit(MethodInvocationVisitorImpl.java:34)
        at weblogic.ejb.container.injection.EnvironmentInterceptorCallbackImpl.callback(EnvironmentInterceptorCallbackImpl.java:54)
        at com.oracle.pitchfork.spi.EnvironmentInterceptor.invoke(EnvironmentInterceptor.java:42)
        at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
        at com.bea.core.repackaged.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
        at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
        at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
        at com.bea.core.repackaged.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
        at com.bea.core.repackaged.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
        at com.bea.core.repackaged.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
        at $Proxy183.getEmpployeesData(Unknown Source)
        at services.EmployeeDataService_4op81c_EmployeeDataServiceImpl.__WL_invoke(Unknown Source)
        at weblogic.ejb.container.internal.SessionRemoteMethodInvoker.invoke(SessionRemoteMethodInvoker.java:40)
        at services.EmployeeDataService_4op81c_EmployeeDataServiceImpl.getEmpployeesData(Unknown Source)
        at services.EmployeeDataService_4op81c_EmployeeDataServiceImpl_CBV.getEmpployeesData(Unknown Source)
        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 weblogic.ejb.container.internal.RemoteBusinessIntfProxy.invoke(RemoteBusinessIntfProxy.java:85)
        at $Proxy179.getEmpployeesData(Unknown Source)



Solution to the problem :

I forgot to add the persistent entity in my persistence.xml file. It resolved the issue,

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit transaction-type="JTA" name="TestDataService">
        <jta-data-source>TestDataService</jta-data-source>       
        <class>com.test.DeptEntity</class>
        <class>com.test.EmployeeEntity</class>
        <properties>
            <property name="showSql" value="true"/>
            <property name="formatSql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

Tuesday, June 12, 2012

In a JSF page I needed to hide a div component on the basis of a certain condition.

Here is an example of the Dept and Employee records. We have a  Div which displays the employee records when the "Show Employee Records" button is clicked. The div will be hidden if the dept object has no employees.

Following is the html snippet for the same.

<aa:zoneJSF id="AjaxResultsZone">
<div id="employeeRecordsDiv" style="visibility: #{deptBean.isEmployeeDataAvailable}">
---
---
---
</div>

<h:commandButton id="submitButton" type="button"
                                        value="Show Employee Records"
                                        onclick="showEmployeeRecords()" />
</aa:zoneJSF>

In the above example, we can put this div in an Ajax zone and on a submit event reload the azax zone.
by default the teh value of the flag  isEmployeeDataAvailable will be ''HIDDEN'.
The method showEmployeeRecords should invoke a method in the bean object which will set this flag value to 'VISIBLE' if the records in the bean exists.

Wednesday, June 6, 2012

Apache Wicket How to create a ListView with RadioGroup


Here is an example of showing a list of Employees under a department. We are using the RadioGroup and ListView Component for this example.

final Department department = (Department) this.getModelObject();
   ArrayList<Employee> employeesList = department.getEmployeesList();
//Create a Radio Group and then add a List View to this Radio Group As shown below.

RadioGroup<Integer> employeesRadioGroup = new RadioGroup<Integer>("employeesRadioGroup", new Model<Integer>(new Integer(0)));
employeesRadioGroup.add(new AjaxFormChoiceComponentUpdatingBehavior(){
/**
* 
*/
private static final long serialVersionUID = 1L;
@Override
protected void onUpdate(AjaxRequestTarget target) {
if(LOGGER.isDebugEnabled())
LOGGER.debug("Employee Radio Selected. You can add an Ajax Behavior on the selection of radio button.");
}
});
employeesRadioGroup.setOutputMarkupId(true);
employeesRadioGroup.setOutputMarkupPlaceholderTag(true);
employeesRadioGroup.setRenderBodyOnly(false);
add(employeesRadioGroup);

ListView empListView = new ListView("employeeListView", employeesList){
/**
*
* @see org.apache.wicket.markup.html.list.ListView#populateItem
*      (org.apache.wicket.markup.html.list.ListItem)
*/
@Override
protected void populateItem(final ListItem item) {

Employee employee = ((Employee)item.getModelObject());

String empId = employee.getEmployeeId();
String empName = employee.getEmployeeName();

if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Show Employee Record with Id :" + empId);
}
item.add(new Radio<Integer>("empSelectRadio", new Model<Integer>(item.getIndex()), employeesRadioGroup));
item.add(new Label("empId", empId).setEscapeModelStrings(false));
item.add(new Label("empName", empName) .setEscapeModelStrings(false));
}
};

if(employeesList.size() == 0){
error("No Employees Records Found.");
}

empListView.setOutputMarkupId(true);
empListView.setOutputMarkupPlaceholderTag(true);

employeesRadioGroup.add(empListView);


Here is the corresponding HTML to be added to your wicket Panel.

<table style="" wicket:id="employeesRadioGroup">
    <tr wicket:id="empListView">
        <td>
              <input type="radio" wicket:id="empSelectRadio"> <label wicket:id="empId">[Employee Id]</label>                                
        </td>
        <td>
            <a href="" wicket:id="empName">[Employee Name]</a>                                
        </td>
     </tr>
</table>

Friday, June 1, 2012

java.lang.RuntimeException: FacesContext not found

Getting Following Exception While trying to test a HelloWorld JSF Application. I am hitting the
Test.jsp page, and getting this exception. 
 
org.apache.jasper.JasperException: java.lang.RuntimeException: FacesContext not found
 org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:502)
 org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
 org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
 org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
java.lang.RuntimeException: FacesContext not found
 javax.faces.webapp.UIComponentClassicTagBase.getFacesContext(UIComponentClassicTagBase.java:321)
 javax.faces.webapp.UIComponentClassicTagBase.setJspId(UIComponentClassicTagBase.java:228)
 org.apache.jsp.Test_jsp._jspx_meth_f_005fview_005f0(Test_jsp.java:114)
 org.apache.jsp.Test_jsp._jspService(Test_jsp.java:88)
 org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
 org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
 org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 
 
 
 

Wednesday, May 30, 2012

/apps/test/script/test_script.sh: bad substitution Error while running script through Cron Job

I was getting the following error while running the shell script through Cron Job..

/apps/test/script/test_script.sh: bad substitution

I was using bash when running this script manually. But while scheduling this script in a cron job a different shell (K shell) was being used. I put the following as first line of my script and it worked fine:

Solution:

#!/bin/bash



Friday, May 25, 2012

org.apache.axis2.AxisFault: Missing wsse:Security header in request

Issue : org.apache.axis2.AxisFault: Missing wsse:Security header in request

951> <BEA-000000> <2012-05-24 12:09:31.949 AM <id 15> <[ACTIVE] ExecuteThread: '4' for queue: 'weblogic.kernel.Default (self-tuning)'> [SEVERE] org.apache.axis2.engine.AxisEngine receive : Missing
wsse:Security header in request
org.apache.axis2.AxisFault: Missing wsse:Security header in request
        at org.apache.rampart.handler.RampartReceiver.setFaultCodeAndThrowAxisFault(RampartReceiver.java:186)
        at org.apache.rampart.handler.RampartReceiver.invoke(RampartReceiver.java:99)
        at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
        at org.apache.axis2.engine.Phase.invoke(Phase.java:313)
        at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:262)
        at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:168)
        at org.apache.axis2.description.OutInAxisOperationClient.handleResponse(OutInAxisOperation.java:364)
        at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:421)
        at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
        at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)



Try putting a security Header in your Soap Request:

<soapenv:Header>
      <wsse:Security soapenv:mustUnderstand="1" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
         <wsse:UsernameToken wsu:Id="UsernameToken-32950583" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
            <wsse:Username>testuser</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">testpassword</wsse:Password>
         </wsse:UsernameToken>
      </wsse:Security>
   </soapenv:Header>


Monday, May 21, 2012

error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock'

Issue connecting to Mysql.

mysqld_safe mysqld from pid file /usr/local/mysql-5.5.15-osx10.6-x86_64/data/sanjay-ingoles-MacBook-Pro.local.pid ended

/usr/local/mysql/bin/mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)'
Check that mysqld is running and that the socket: '/tmp/mysql.sock' exists!


Resolution :

sudo /usr/local/mysql/bin/mysqld stop

Then
     shell> cd /usr/local/mysql
     shell> sudo ./bin/mysqld_safe

Then

/usr/local/mysql/bin/mysql -u username -p database

Sunday, March 4, 2012

Hibernate Error : org.hibernate.hql.ast.QuerySyntaxException: TestTable is not mapped [from TestTable}

Problem : Getting an exception while trying to get all the records from a TestTable.:

Following is the Hibernate Config for TestTable:


<hibernate-mapping>
    <class name="com.testapp.service.dataobjects.TestTableDO" table="testTable">
    <id name="testId" column="testId">
        <generator class="assigned"/>
    </id>
...
...
</class>
</hibernate-mapping>




And Following is the Java code to get all the records from the TestTable

List<TestTableDO> testTableResultSet = hibernateTemplate.find("from TestTable");



Solution: The problem is due to the name mismatch in the Hibernate table configurations and the Java Query.

As you can see the hibernate is configured to map the 'testTable' to the 'com.testapp.service.dataobjects.TestTableDO' whereas in Java it refers to 'TestTable' (database table name).
Because we have mapped it to 'TestTableDO' it should be referred as same in Java Query as follows:



List<TestTableDO> testTableResultSet = hibernateTemplate.find("from TestTableDO");

Cheers :)



Error Logs
org.hibernate.hql.ast.QuerySyntaxException: TestTable is not mapped [from TestTable]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:265)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:923)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:419)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:921)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:913)

Thursday, March 1, 2012

Shell Script to check and remove file with specific extension

help(){
        echo " This script checks for the employee files 'test_id001.dat' and delete the files with '*.dat' extension in the directory ${TEST_DIR}. Note : Make sure the TEST_DIR path is set as environment variable."

        exit;

}
if [[ $1 = "-help" ]]
        then
                help
fi

cd ${TEST_DIR}

for file in *.rules
do

## Extract a substring to get the Employee Id from the File Name
## i.e Employeed Id 'id001' in the file test_id001.dat
employeeid="${file##*_}"
employeeid="${employeddid%.*}"

echo " = Remove the file for Employee with ID - $employeeid, file location = ${TEST_DIR}$file"
rm -f ${TEST_DIR}$file

done

Wednesday, February 29, 2012

Delete JMS Messages from Weblogic 11G Server

To Delete the JMS messages from the Queue or Topic manually:
Go to JMS Queue or topic - > Monitoring -> select the queue and click on 'Show Messages' Button.
On the next page you have option to delete the messages.