Showing posts with label Exception. Show all posts
Showing posts with label Exception. Show all posts

Thursday, February 23, 2023

Caused by: java.lang.UnsupportedOperationException: PermittedSubclasses requires ASM9

After attempting to upgrade Spring Boot from version 2.7.3 to version 3.0.2, I encountered this error. I spent a few hours searching on Google to try to figure out the cause of the error. Eventually, I realized that the error was related to the version of Gradle that I was using. At the time, I had been using Gradle version 7.3.3. However, once I updated to Gradle version 8.0.1, the error was successfully resolved.


I also updated distributionUrl in gradle-wrapper.properties as shown below
distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip

Note - After above changes i removed .idea folder and restarted my intellij

Saturday, May 24, 2014

New Features of Java 7

Java 7 contains many new features, enhancements and bug fixes to improve efficiency to develop and run Java programs.

Here is a brief summary of the enhancements included with the Java 7 release:

  • Improved performance, stability and security.
  • Enhancements in the Java Plug-in for Rich Internet Applications development and deployment.
  • Java Programming language enhancements that enable developers with ease of writing and optimizing the Java code.
  • Enhancements in the Java Virtual machine to support Non-Java languages.

In this article, we will explore some of those capabilities through code samples.

1. Binary literals

You can use the binary number system (0s and 1s) to express integral types byte, short, int, and long. To specify a binary value, prefix the value with a 0b or 0B.


--------------------- Output ---------------------
a = -88
b = 112
c = 73
d = 1467

2. Underscore literals

To improve readability of numeric literals in the code, you can use underscores between digits to separate a group of digits. You can use as many underscores as you need.


--------------------- Output ---------------------
a = -86
b = 4554
c = 123456789
d = 111222333
e = 11.227799


Friday, February 14, 2014

Failure in loading native library db2jcct2, java.lang.UnsatisfiedLinkError: no db2jcct2 in java.library.path: ERRORCODE=-4472, SQLSTATE=null

com.ibm.db2.jcc.a.SqlException: [jcc][10389][12245][4.3.111] Failure in loading native library db2jcct2, java.lang.UnsatisfiedLinkError: no db2jcct2 in java.library.path:  ERRORCODE=-4472, SQLSTATE=null
at com.ibm.db2.jcc.a.dd.a(dd.java:660)
at com.ibm.db2.jcc.a.dd.a(dd.java:60)
at com.ibm.db2.jcc.a.dd.a(dd.java:94)
at com.ibm.db2.jcc.t2.a.a(a.java:37)
at com.ibm.db2.jcc.t2.T2Configuration.(T2Configuration.java:94)
at com.ibm.db2.jcc.DB2Driver.connect(DB2Driver.java:188)
at org.apache.tomcat.dbcp.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
at org.apache.tomcat.dbcp.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:113)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:524)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:588)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:617)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:625)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:657)
at com.hewitt.hro.ssb.dao.jdbc.JdbcBuildTypeDao.getBuildType(JdbcBuildTypeDao.java:100)
at com.hewitt.hro.ssb.dao.jdbc.JdbcBuildTypeDao.getBuildTypeWithArguments(JdbcBuildTypeDao.java:110)
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.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:299)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:139)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:107)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:161)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy4.getBuildTypeWithArguments(Unknown Source)
at com.hewitt.hro.ssb.admin.LinkedBuildTypeLocator.init(LinkedBuildTypeLocator.java:136)
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.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1147)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1110)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:431)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:254)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:144)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:163)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:271)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:128)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1047)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:843)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:427)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:254)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:144)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:163)
at org.directwebremoting.spring.SpringContainer.getBean(SpringContainer.java:105)
at org.directwebremoting.impl.ContainerMap.init(ContainerMap.java:53)
at org.directwebremoting.impl.ContainerMap.entrySet(ContainerMap.java:78)
at org.directwebremoting.spring.DwrController.afterPropertiesSet(DwrController.java:198)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1143)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1110)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:431)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:254)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:144)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:163)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:683)
at org.springframework.web.servlet.handler.AbstractUrlHandlerMapping.registerHandler(AbstractUrlHandlerMapping.java:248)
at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.registerHandlers(SimpleUrlHandlerMapping.java:125)
at org.springframework.web.servlet.handler.SimpleUrlHandlerMapping.initApplicationContext(SimpleUrlHandlerMapping.java:103)
at org.springframework.context.support.ApplicationObjectSupport.setApplicationContext(ApplicationObjectSupport.java:73)
at org.springframework.context.support.ApplicationContextAwareProcessor.postProcessBeforeInitialization(ApplicationContextAwareProcessor.java:86)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:304)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:431)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:254)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:144)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:251)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:163)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:284)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:352)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:311)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:258)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:229)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:115)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1189)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1103)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1010)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4915)
at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5242)
at org.apache.catalina.core.StandardContext$3.call(StandardContext.java:5237)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)

If you get the above error try adding DB2 bin folder in the library path as shown in the below figure

Example - C:\Program Files (x86)\IBM\SQLLIB_01\BIN 

MyEclipse Servers -< (server) -> Configure Server Connector -> (Preferences pop up) -> MyEclipse -> Servers -> Tomcat -> Tomcat 7.x -> Paths -> Add DIR


Add the BIN directory and Click Apply/OK


nested exception is org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.ibm.db2.jcc.DB2Driver'

SEVERE: StandardWrapper.Throwable
Invocation of init method failed; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.ibm.db2.jcc.DB2Driver'
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.ibm.db2.jcc.DB2Driver'
Caused by: org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.ibm.db2.jcc.DB2Driver'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1429)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:113)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:329)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:405)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:413)
at org.springframework.jdbc.core.simple.SimpleJdbcTemplate.query(SimpleJdbcTemplate.java:107)
at com.hewitt.hro.dcd.modb.dao.jdbc.JdbcUserDao.preloadCache(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)

To get rid of above error you may need to add db2jcc4.jar or db2jcc.jar  in your applications classpath. To download Jar files : Click here.

Friday, February 7, 2014

Exception in thread "main" javax.xml.ws.WebServiceException

Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at: http://localhost:8080/SOAPWebservice/HelloWorldPort?wsdl. It failed with: 
Connection refused: connect.
at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.tryWithMex(RuntimeWSDLParser.java:162)
at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:144)
at com.sun.xml.ws.client.WSServiceDelegate.parseWSDL(WSServiceDelegate.java:263)
at com.sun.xml.ws.client.WSServiceDelegate.(WSServiceDelegate.java:226)
at com.sun.xml.ws.client.WSServiceDelegate.(WSServiceDelegate.java:174)
at com.sun.xml.ws.spi.ProviderImpl.createServiceDelegate(ProviderImpl.java:104)
at javax.xml.ws.Service.(Service.java:56)
at com.hewitt.ws.HelloWorldImplService.(HelloWorldImplService.java:55)
at com.hewitt.ws.TestClient.main(TestClient.java:7)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:519)
at java.net.Socket.connect(Socket.java:469)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:394)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:529)
at sun.net.www.http.HttpClient.(HttpClient.java:233)
at sun.net.www.http.HttpClient.New(HttpClient.java:306)
at sun.net.www.http.HttpClient.New(HttpClient.java:323)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:852)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:793)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:718)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1041)
at java.net.URL.openStream(URL.java:1009)
at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.createReader(RuntimeWSDLParser.java:805)
at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.resolveWSDL(RuntimeWSDLParser.java:262)
at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:129)
... 7 more

If you get above error, please check if the wsdl url is working fine. Just hit the URL in a browser and see if you get response. If not check with your service provider.

Example -
http://localhost:8080/SOAPWebservice/HelloWorldPort?wsdl

javax.xml.bind.MarshalException

javax.xml.bind.MarshalException
 - with linked exception:
[com.sun.istack.SAXException2: unable to marshal type "com.javaxp.Employee" as an element because it is missing an @XmlRootElement annotation]
at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:331)
at com.sun.xml.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:257)
at javax.xml.bind.helpers.AbstractMarshallerImpl.marshal(AbstractMarshallerImpl.java:96)
at com.hewitt.ws.Test.marshalIt(Test.java:74)
at com.hewitt.ws.Test.displayEmpl(Test.java:58)
at com.hewitt.ws.Test.main(Test.java:28)
Caused by: com.sun.istack.SAXException2: unable to marshal type "com.hewitt.ws.Employee" as an element because it is missing an @XmlRootElement annotation
at com.sun.xml.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:244)
at com.sun.xml.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:303)
at com.sun.xml.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:490)
at com.sun.xml.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:328)
... 5 more

The process of convesrting a Java object to XML is known as Marshalling.

If you get above error, check for annotation @XmlRootElement in the class for which you are trying to do Marshalling. To know more, please see the example - JAXB marshalling and unmarshalling Hello World Example

Example - 

@XmlRootElement
public class Employee {
...
}

Thursday, February 6, 2014

java.lang.NoClassDefFoundError: com/sun/istack/localization/Localizable

java.lang.NoClassDefFoundError: com/sun/istack/localization/Localizable
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2818)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1148)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1643)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2818)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1148)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1643)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
at java.lang.Class.getConstructor0(Class.java:2699)
at java.lang.Class.newInstance0(Class.java:326)
at java.lang.Class.newInstance(Class.java:308)
at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:119)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4618)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)


If you get above error, you may need to add jaxb-core.jar in your applications classpath. You can download the file (example - jaxws-ri-2.2.8.zip file) from https://jax-ws.java.net/

Monday, January 27, 2014

Eclipse : Caused by: java.lang.ClassNotFoundException / Exception in thread "main"

java.lang.NoClassDefFoundError: com/javaxp/test
Caused by: java.lang.ClassNotFoundException: com.javaxp.Test
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
Exception in thread "main" 


There could be a couple of reasons for the above error

1. .class files not created properly

Try
Project -> Clean -> Clean all projects / Clean project selected below -> OK

2. JVM is not able to pick the classpath

Try
right click on the project -> Properties -> Java Compiler -> unclick the first box saying 'Enable project specific settings' -> Apply -> OK

3. A missing JAR file in the classpath

Try
right click on the project -> Properties -> Java Build Path -> Libraries -> (Remove unwanted missing jar files if any) -> OK

Hope this helps in most of the cases.

Wednesday, December 18, 2013

keytool error: java.io.FileNotFoundException: cacerts (Permission denied)

I got the error when trying to install a certificate into my keystore

Command -
keytool -import -alias aliasName -file fileName.cer -keystore cacerts
keytool -list -keystore cacerts

Solutions

Windows -
This could happen if you are not running the command prompt in administrator mode. Login with the user who has administrator privilege.

For Windows 7 and above - Go to run, type cmd and hit Ctrl+Shift+enter. This will open the command prompt in administrator mode.

For others windows -  Go to start -> all programs -> accessories -> right click command prompt and say run as administrator.

Linux -
First check the write permissions on the keystore. Also if needed login with root user and try the command.

Thursday, July 4, 2013

Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

Exception in thread "main" java.lang.Exception: Error Initializing Context: oracle.jdbc.driver.OracleDriver
at com.hewitt.appinv.sdc.db.LocalContextFactory.createLocalContext(LocalContextFactory.java:28)
at com.hewitt.appinv.sdc.db.TestJNDI.main(TestJNDI.java:14)
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at com.hewitt.appinv.sdc.db.LocalContextFactory.createLocalContext(LocalContextFactory.java:23)
... 1 more

If you see above error, Please add classes12.jar  in your applications classpath. Download it from here. classes12.jar  

Wednesday, July 3, 2013

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

Error :

javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1649)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:241)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:235)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1206)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:136)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:893)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1165)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1149)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:234)
at com.hewitt.appinv.sdc.URLReader.readURL(URLReader.java:18)
at com.hewitt.appinv.sdc.URLReader.main(URLReader.java:38)
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:323)
at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:217)
at sun.security.validator.Validator.validate(Validator.java:218)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:126)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:209)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:249)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1185)
... 13 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:174)
at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:238)
at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:318)
... 19 more


Thursday, March 21, 2013

Hibernate : To handle special characters in HQL


In this article we will see to handle special characters in HQL similar to PreparedStatement in JDBC. It can also used for additional security purpose like to avoid SQL Injection.

For example, I have a below function in my BookDAO class to get detail of a particular book. It accepts bookTitle as a parameter and returns list of books. Here assume bookTitle can contain special characters.

public List findBook(String bookTitle) {
try {
String queryString = "from BsBooks where bookTitle = :bookTitle";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter("bookTitle", bookTitle);
return queryObject.list();
} catch (RuntimeException re) {
throw re;
}
}

Note - the method setParameter(), it is used to set the value for bookTitle, which can contain special characters.

queryObject.setParameter("bookTitle", bookTitle);

The above method will give following error if you try to use it like - queryObject.setParameter(0, bookTitle);

Exception in thread "main" java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based!
at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterDescriptor(ParameterMetadata.java:79)
at org.hibernate.engine.query.ParameterMetadata.getOrdinalParameterExpectedType(ParameterMetadata.java:85)
at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:421)
at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:393)


To avoid it you can use it as a '?' placeholder. When you execute the query, you would need to supply the value for it, which would replace the '?' in the query in below function.

public List findBook(String bookTitle) {
try {
String queryString = "from BsBooks where bookTitle = ?";
Query queryObject = getSession().createQuery(queryString);
queryObject.setParameter(0, bookTitle);
return queryObject.list();
} catch (RuntimeException re) {
throw re;
}
}


Below are the variations of the method setParameter, to know please see the API.

setParameter(int position, Object val) - Bind a value to a JDBC-style query parameter.

setParameter(int position, Object val, Type type) - Bind a value to a JDBC-style query parameter.

setParameter(String name, Object val) - Bind a value to a named query parameter.

setParameter(String name, Object val, Type type) - Bind a value to a named query parameter.

setParameterList(String name, Collection vals)  - Bind multiple values to a named query parameter.

setParameterList(String name, Collection vals, Type type) - Bind multiple values to a named query parameter.

setParameterList(String name, Object[] vals) - Bind multiple values to a named query parameter.

setParameterList(String name, Object[] vals, Type type) - Bind multiple values to a named query parameter.

setParameters(Object[] values, Type[] types) - Bind values and types to positional parameters.

Monday, February 11, 2013

java.lang.Exception: Socket bind failed: [730048] Only one usage of each socket address (protocol/network address/port) is normally permitted.

In earlier post, we have seen how to rid of - java.net.BindException: Address already in use: JVM_Bind :8080. Today i saw another similar error, please see the error below.


java.lang.Exception: Socket bind failed: [730048] Only one usage of each socket address (protocol/network address/port) is normally permitted.  
    at org.apache.tomcat.util.net.AprEndpoint.init(AprEndpoint.java:649)
    at org.apache.tomcat.util.net.AprEndpoint.start(AprEndpoint.java:766)
    at org.apache.coyote.http11.Http11AprProtocol.start(Http11AprProtocol.java:137)
    at org.apache.catalina.connector.Connector.start(Connector.java:1122)
    at org.apache.catalina.core.StandardService.start(StandardService.java:540)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    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.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Feb 11, 2013 8:13:42 PM org.apache.catalina.core.StandardService start
SEVERE: Failed to start connector [Connector[HTTP/1.1-8080]]
LifecycleException:  service.getName(): "Catalina";  Protocol handler start failed: java.lang.Exception: Socket bind failed: [730048] Only one usage of each socket address (protocol/network address/port) is normally permitted.  
    at org.apache.catalina.connector.Connector.start(Connector.java:1129)
    at org.apache.catalina.core.StandardService.start(StandardService.java:540)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    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.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
Feb 11, 2013 8:13:42 PM org.apache.coyote.ajp.AjpAprProtocol start
SEVERE: Error starting endpoint

Friday, December 28, 2012

Java - Get content type of a particular file



In many occasion you may require to check content type of a particular file. For example if a file is uploaded, it's not enough to check only file extension. For additional security you should also check the actual content type of a file so latter while processing the file no exception occurs. File could be Image, Excel, Text etc.

Let's see how this can be achieved in Java.

URL - This class represents a Uniform Resource Locator. It point to a particular resource, resource can be either a file , directory or an object. Here it refers to a file.

URLConnection - This is the super class of all classes that represent a communication link between an application and a URL.

openConnection() - This is the method of URL class which represents a connection to the remote object referred to by the URL.

getContentType() - This method of URLConnection class returns the content type of the file.

Monday, December 24, 2012

Hibernate Examples - Native SQL Queries


You can also express queries in the native SQL dialect of your database. This is useful if you want to utilize database-specific features such as query hints or the CONNECT keyword in Oracle. It also provides a clean migration path from a direct SQL/JDBC based application to Hibernate.

Hibernate3 allows you to specify handwritten SQL, including stored procedures, for all create, update, delete, and load operations.

To know more, click here.

For example - we can have methods in DAO for executing Native SQL as shown below.

public List executeNativeQuery(String query) {
return getSession().createSQLQuery(query).list();
}

public List executeQuery(String query) {
return getSession().createQuery(query).list();
}

You can pass native SQL query as shown below -

List allObjects = empDao.executeNativeQuery("Select emp_id, emp_name  from EMPLOYEE");

Iterator it = allObjects.iterator();
while(it.hasNext())
{
Object row[] = (Object[])it.next();
for(Object eachRow : row) {
System.out.println(eachRow.toString());
}
}

Below are the known errors and exception -

1. Exception in thread "main" org.hibernate.MappingException: No Dialect mapping for JDBC type: -1
at org.hibernate.dialect.TypeNames.get(TypeNames.java:79)
at org.hibernate.dialect.TypeNames.get(TypeNames.java:104)
at org.hibernate.dialect.Dialect.getHibernateTypeName(Dialect.java:393)
at org.hibernate.loader.custom.CustomLoader$Metadata.getHibernateType(CustomLoader.java:582)
at org.hibernate.loader.custom.CustomLoader$ScalarResultColumnProcessor.performDiscovery(CustomLoader.java:508)
at org.hibernate.loader.custom.CustomLoader.autoDiscoverTypes(CustomLoader.java:524)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1821)
at org.hibernate.loader.Loader.doQuery(Loader.java:697)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259)
at org.hibernate.loader.Loader.doList(Loader.java:2232)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129)
at org.hibernate.loader.Loader.list(Loader.java:2124)
at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312)
at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723)
at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)


Solution - Above exception occurs if you pass * to fetch all columns in SQL like - "Select * from EMPLOYEE". this should be avoided.


Thursday, October 18, 2012

Java : Read / Write Excel file (.xls or .xlsx) using Apache POI


We will see how we can read or write excel file (.xls or .xlsx) using Apache POI. To know more about Apache POI, click here.

You can download latest version of JAR files from http://poi.apache.org/download.html.

In our case we are using Apache POI 3.8. To run below example you will need to download poi-bin-3.8-20120326.zip file from http://poi.apache.org/download.html. You will get below JAR files, add those in your claspath.

  • dom4j-1.6.1.jar
  • xmlbeans-2.3.0.jar
  • poi-3.8-20120326.jar
  • poi-ooxml-3.8-20120326.jar
  • poi-ooxml-schemas-3.8-20120326.jar

Please see the self explanatory Java code.

Friday, June 29, 2012

JSTL : How to use fmt:message and ResourceBundle

There are two ways you can access values from a property file. Mostly a text value which can change in future are kept in property file and access it using fmt:message and ResourceBundle in JSP and JAVA respectively so that if the text values are changed in future it wont affect our code. We just need to change in property file and rest all will be taken care implicitly.

Lets see how to use fmt:message and ResourceBundle in JSP and JAVA respectively.

1. In JSP

If you need to access the property value in JSP, first lets create a property file lets say prop.properties. Add prop.properties in src folder of your application.

prop.properties

key1=This is value1
key2=This is value2

Add the mapping in web.xml or Spring's dispatcher-servlet.xml as shown below

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="prop" />
</bean>

Note the value="prop" it says to load prop.properties from the src folder. Now through JSP you can access the property by its key as shown below

<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

<fmt:bundle basename="prop">
<fmt:message key="key1"/>
<fmt:message key="key2"/>
</fmt:bundle>

2. In Java

Also you may need to access these properties in a JAVA program it could be either bean or any controller. You can access using java.util.ResourceBundle as shown below.

String value1 = ResourceBundle.getBundle("prop").getString("key1");
String value2 = ResourceBundle.getBundle("prop").getString("key2");

Note : You may get below error

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/fmt cannot be resolved in either web.xml or the jar files deployed with this application

To solve above error you need to include jstl-1.2.jar in your application's classpath. It could be possible that your application is not able to detect jstl-1.2.jar file.

Friday, May 18, 2012

Java simple iCalendar iCal4j example

iCalendar is a computer file format which allows Internet users to send meeting requests and tasks to other Internet users, via email, or sharing files with an extension of .ics. iCal4j is an API which is used to modifying existing iCalendar data or creating new iCalendar data. To know more about iCal4j, click here.

About the example

ICalendarExample.java will create a .ics file lets say mycalendar.ics. It will create a calender event, you can customize it according to your requirement. You can send this generated file via email.

For running below example you will need to add below mentioned JAR files in your classpath.
  • ical4j-1.0.3.jar
  • backport-util-concurrent-3.1.jar
  • commons-logging-1.1.1.jar
  • commons-lang-2.6.jar

To download the above JAR file, click here.

Thursday, May 10, 2012

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

If you get below mentioned error

org.apache.jasper.JasperException: The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application
 org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:53)
 org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:409)
 org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:116)
 org.apache.jasper.compiler.TagLibraryInfoImpl.generateTLDLocation(TagLibraryInfoImpl.java:310)
 org.apache.jasper.compiler.TagLibraryInfoImpl.<init>(TagLibraryInfoImpl.java:152)
 org.apache.jasper.compiler.Parser.parseTaglibDirective(Parser.java:410)
 org.apache.jasper.compiler.Parser.parseDirective(Parser.java:475)
 org.apache.jasper.compiler.Parser.parseElements(Parser.java:1425)
 org.apache.jasper.compiler.Parser.parse(Parser.java:138)
 org.apache.jasper.compiler.ParserController.doParse(ParserController.java:239)
 org.apache.jasper.compiler.ParserController.parse(ParserController.java:102)
 org.apache.jasper.compiler.Compiler.generateJava(Compiler.java:197)
 org.apache.jasper.compiler.Compiler.compile(Compiler.java:372)
 org.apache.jasper.compiler.Compiler.compile(Compiler.java:352)
 org.apache.jasper.compiler.Compiler.compile(Compiler.java:339)
 org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:594)
 org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:344)
 org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:391)
 org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
 org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
 org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
 org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1060)
 org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:798)
 org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
 org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
 org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
 javax.servlet.http.HttpServlet.service(HttpServlet.java:722)

Probably the reason could be you have used below mentioned taglib in your JSP file.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

You need to get the right version of JSTL in your application's classpath, they use different URIs. If that one's not working, try downloading JSTL 1.2 (jstl-1.2.jar) from http://download.java.net/maven/1/jstl/jars/jstl-1.2.jar, or pull down the 1.1 JSTL jars.

To know more about JSTL Taglib, Please see below links.
http://docs.oracle.com/javaee/5/tutorial/doc/bnake.html
http://jakarta.apache.org/taglibs/doc/standard-doc/GettingStarted.html

Tuesday, August 31, 2010

Java : How to throw custom Exception

In java many times we required to throw our own custom Exception. We can throw our custom Exception by creation our own Exception class which will extend from class java.lang.Exception.

Before going to example lets look at few points about Exception Handling from book "Sun Certified Java Programmer SCJP 5" by Kathy sierra.

Handling Exceptions
  • Exceptions come in two flavors: checked and unchecked.
  • Checked exceptions include all subtypes of Exception, excluding classes
    that extend RuntimeException.
  • Checked exceptions are subject to the handle or declare rule; any method
    that might throw a checked exception (including methods that invoke methods
    that can throw a checked exception) must either declare the exception
    using throws, or handle the exception with an appropriate try/catch.
  • Subtypes of Error or RuntimeException are unchecked, so the compiler
    doesn't enforce the handle or declare rule. You're free to handle them, or to
    declare them, but the compiler doesn't care one way or the other.
  • If you use an optional finally block, it will always be invoked, regardless of
    whether an exception in the corresponding try is thrown or not, and regardless
    of whether a thrown exception is caught or not.
  • The only exception to the finally-will-always-be-called rule is that a finally
    will not be invoked if the JVM shuts down. That could happen if code
    from the try or catch blocks calls System.exit().
  • Just because finally is invoked does not mean it will complete. Code in the
    finally block could itself raise an exception or issue a System.exit().
  • Uncaught exceptions propagate back through the call stack, starting from
    the method where the exception is thrown and ending with either the first
    method that has a corresponding catch for that exception type or a JVM
    shutdown (which happens if the exception gets to main(), and main() is
    "ducking" the exception by declaring it).
  • You can create your own exceptions, normally by extending Exception or
    one of its subtypes. Your exception will then be considered a checked exception,
    and the compiler will enforce the handle or declare rule for that exception.
  • All catch blocks must be ordered from most specific to most general.
    If you have a catch clause for both IOException and Exception, you must
    put the catch for IOException first in your code. Otherwise, the IOException
    would be caught by catch(Exception e), because a catch argument
    can catch the specified exception or any of its subtypes! The compiler will
    stop you from defining catch clauses that can never be reached.
  • Some exceptions are created by programmers, some by the JVM.

Lets see a simple example which will throw a custom Exception.

In this example we have a method acceptsEvenNumber(int number) which accepts only even number, it it encounters odd number it throws our custom Exception ie "MyException".
Here our class MyException extends java.lang.Exception also observe the constructor MyException(String message) which calls its super constructor.

To know more look API.

/* MyException.java */

public class MyException extends Exception {

    public MyException(String message) {
        super(message);
    }
  
    //This method throws custom Exception
    public static void acceptsEvenNumber(int number) throws MyException {
      
        if(number %2 == 0) {
          
            System.out.println("It is Even number");
        }
        else {
          
            throw new MyException("Odd number not allowed");
        }
      
    }

    public static void main(String[] args) {
      
        try {
           

            //acceptsEvenNumber(23); //odd number
            acceptsEvenNumber(22); //even number
          
        } catch (MyException e) {
          
            e.printStackTrace();
        }
    }

}



Output

When Even Number

#>java MyException
It is Even number

When Odd Number

#>java MyException
MyException: Odd number not allowed
        at MyException.acceptsEvenNumber(MyException.java:16)
        at MyException.main(MyException.java:25)