CAS with WebLogic Authenticates then error with 'principal' cannot be null - spring

I am trying to implement CAS with WebLogic 10.3.5 and not having much luck. Everything I read is about CAS with Tomcat. Have tried the exact config with Tomcat and it works like a dream but those in charge wont change to Tomcat. Anyways....
I can bring up the CAS login screen, and after checking the cas.log it authenticates but then seems to lose the principal.
I am using the maven overlay technique which seems good to begin with.
Also had the standard log4j dramas that everyone seems to have.
Have included stacktrace, deployerConfigContext.xml, pom.xml and weblogic.xml.
Here is the stacktrace:
2014-05-09 15:29:32,000 INFO [org.jasig.cas.ticket.registry.support.DefaultTicketRegistryCleaner] - <Beginning ticket cleanup.>
2014-05-09 15:29:32,000 INFO [org.jasig.cas.ticket.registry.support.DefaultTicketRegistryCleaner] - <0 tickets found to be removed.>
2014-05-09 15:29:32,000 INFO [org.jasig.cas.ticket.registry.support.DefaultTicketRegistryCleaner] - <Finished ticket cleanup.>
2014-05-09 15:29:37,443 INFO [org.jasig.cas.authentication.AuthenticationManagerImpl] - <org.jasig.cas.adaptors.generic.AcceptUsersAuthenticationHandler successfully authenticated [username: kwins]>
2014-05-09 15:29:37,445 INFO [org.jasig.cas.authentication.AuthenticationManagerImpl] - <Resolved principal kwins>
2014-05-09 15:29:37,445 INFO [org.jasig.cas.authentication.AuthenticationManagerImpl] - <org.jasig.cas.adaptors.generic.AcceptUsersAuthenticationHandler#120445d authenticated kwins with credential [username: kwins].>
2014-05-09 15:29:37,458 INFO [com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager] - <Audit trail record BEGIN
=============================================================
WHO: [username: kwins]
WHAT: supplied credentials: [username: kwins]
ACTION: AUTHENTICATION_SUCCESS
APPLICATION: CAS
WHEN: Fri May 09 15:29:37 EST 2014
CLIENT IP ADDRESS: 192.168.1.140
SERVER IP ADDRESS: 192.168.1.140
=============================================================
>
<09/05/2014 3:29:37 PM EST> <Error> <HTTP> <BEA-101017> <[ServletContext#1230935[app:cas module:cas.war path:/cas spec-version:2.5], request: weblogic.servlet.internal.ServletRequestImpl#2eb99e[
POST /cas/login HTTP/1.1
Connection: keep-alive
Content-Length: 114
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Origin: http://lh11-24.custman.com.au:7001
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://lh11-24.custman.com.au:7001/cas/login
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Cookie: ADMINCONSOLESESSION=J5fJTszB6RS91Y50wpZnqpBbPM7fpp12LQTvcPs1tnkP9GLKhhvT!-2133794881; JSESSIONID=sJ92Ts4pPgvtJPRMDT5zNLjbndXRLNPJCfj9B3x1TGX5J03XlpHN!-317454516
]] Root cause of ServletException.
org.springframework.webflow.execution.ActionExecutionException: Exception thrown executing [AnnotatedAction#1b55376 targetAction = [EvaluateAction#17a89ad expression = authenticationViaFormAction.submit(flowRequestContext, flowScope.credentials, messageContext), resultExpression = [null]], attributes = map[[empty]]] in state 'realSubmit' of flow 'login' -- action execution attributes were 'map[[empty]]'
at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:60)
at org.springframework.webflow.engine.ActionState.doEnter(ActionState.java:101)
at org.springframework.webflow.engine.State.enter(State.java:194)
at org.springframework.webflow.engine.Transition.execute(Transition.java:227)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.execute(FlowExecutionImpl.java:393)
Truncated. see log file for complete stacktrace
Caused By: org.springframework.binding.expression.EvaluationException: An OgnlException occurred getting the value for expression 'authenticationViaFormAction.submit(flowRequestContext, flowScope.credentials, messageContext)' on context [class org.springframework.webflow.engine.impl.RequestControlContextImpl]
at org.springframework.binding.expression.ognl.OgnlExpression.getValue(OgnlExpression.java:92)
at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:75)
at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145)
at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)
Truncated. see log file for complete stacktrace
Caused By: ognl.MethodFailedException: Method "submit" failed for object org.jasig.cas.web.flow.AuthenticationViaFormAction#ea66aa [java.lang.IllegalArgumentException: 'principal' cannot be null.
Check the correctness of #Audit annotation at the following audit point: execution(public abstract java.lang.String org.jasig.cas.CentralAuthenticationService.createTicketGrantingTicket(org.jasig.cas.authentication.principal.Credentials))]
at ognl.OgnlRuntime.callAppropriateMethod(OgnlRuntime.java:1265)
at ognl.ObjectMethodAccessor.callMethod(ObjectMethodAccessor.java:68)
at ognl.OgnlRuntime.callMethod(OgnlRuntime.java:1329)
at ognl.ASTMethod.getValueBody(ASTMethod.java:90)
at ognl.SimpleNode.evaluateGetValueBody(SimpleNode.java:212)
Truncated. see log file for complete stacktrace
Caused By: java.lang.IllegalArgumentException: 'principal' cannot be null.
Check the correctness of #Audit annotation at the following audit point: execution(public abstract java.lang.String org.jasig.cas.CentralAuthenticationService.createTicketGrantingTicket(org.jasig.cas.authentication.principal.Credentials))
at com.github.inspektr.audit.AuditActionContext.assertNotNull(AuditActionContext.java:81)
at com.github.inspektr.audit.AuditActionContext.<init>(AuditActionContext.java:63)
at com.github.inspektr.audit.AuditTrailManagementAspect.executeAuditCode(AuditTrailManagementAspect.java:149)
at com.github.inspektr.audit.AuditTrailManagementAspect.handleAuditTrail(AuditTrailManagementAspect.java:139)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
Truncated. see log file for complete stacktrace
>
deployerConfigContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!-- | This bean declares our AuthenticationManager. The CentralAuthenticationService
service bean | declared in applicationContext.xml picks up this AuthenticationManager
by reference to its id, | "authenticationManager". Most deployers will be
able to use the default AuthenticationManager | implementation and so do
not need to change the class of this bean. We include the whole | AuthenticationManager
here in the userConfigContext.xml so that you can see the things you will
| need to change in context. + -->
<bean id="authenticationManager" class="org.jasig.cas.authentication.AuthenticationManagerImpl">
<!-- Uncomment the metadata populator to allow clearpass to capture and
cache the password This switch effectively will turn on clearpass. <property
name="authenticationMetaDataPopulators"> <list> <bean class="org.jasig.cas.extension.clearpass.CacheCredentialsMetaDataPopulator">
<constructor-arg index="0" ref="credentialsCache" /> </bean> </list> </property> -->
<!-- | This is the List of CredentialToPrincipalResolvers that identify
what Principal is trying to authenticate. | The AuthenticationManagerImpl
considers them in order, finding a CredentialToPrincipalResolver which |
supports the presented credentials. | | AuthenticationManagerImpl uses these
resolvers for two purposes. First, it uses them to identify the Principal
| attempting to authenticate to CAS /login . In the default configuration,
it is the DefaultCredentialsToPrincipalResolver | that fills this role. If
you are using some other kind of credentials than UsernamePasswordCredentials,
you will need to replace | DefaultCredentialsToPrincipalResolver with a CredentialsToPrincipalResolver
that supports the credentials you are | using. | | Second, AuthenticationManagerImpl
uses these resolvers to identify a service requesting a proxy granting ticket.
| In the default configuration, it is the HttpBasedServiceCredentialsToPrincipalResolver
that serves this purpose. | You will need to change this list if you are
identifying services by something more or other than their callback URL.
+ -->
<property name="credentialsToPrincipalResolvers">
<list>
<!-- | UsernamePasswordCredentialsToPrincipalResolver supports the UsernamePasswordCredentials
that we use for /login | by default and produces SimplePrincipal instances
conveying the username from the credentials. | | If you've changed your LoginFormAction
to use credentials other than UsernamePasswordCredentials then you will also
| need to change this bean declaration (or add additional declarations) to
declare a CredentialsToPrincipalResolver that supports the | Credentials
you are using. + -->
<bean
class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver">
<property name="attributeRepository" ref="attributeRepository" />
</bean>
<!-- | HttpBasedServiceCredentialsToPrincipalResolver supports HttpBasedCredentials.
It supports the CAS 2.0 approach of | authenticating services by SSL callback,
extracting the callback URL from the Credentials and representing it as a
| SimpleService identified by that callback URL. | | If you are representing
services by something more or other than an HTTPS URL whereat they are able
to | receive a proxy callback, you will need to change this bean declaration
(or add additional declarations). + -->
<bean
class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />
</list>
</property>
<!-- | Whereas CredentialsToPrincipalResolvers identify who it is some
Credentials might authenticate, | AuthenticationHandlers actually authenticate
credentials. Here we declare the AuthenticationHandlers that | authenticate
the Principals that the CredentialsToPrincipalResolvers identified. CAS will
try these handlers in turn | until it finds one that both supports the Credentials
presented and succeeds in authenticating. + -->
<property name="authenticationHandlers">
<list>
<!-- | This is the authentication handler that authenticates services
by means of callback via SSL, thereby validating | a server side SSL certificate.
+ -->
<bean
class="org.jasig.cas.adaptors.generic.AcceptUsersAuthenticationHandler">
<property name="users">
<map>
<entry>
<key>
<value>kwins</value>
</key>
<value>welcome</value>
</entry>
<entry>
<key>
<value>weblogic</value>
</key>
<value>welcome1</value>
</entry>
</map>
</property>
</bean>
<!-- | This is the authentication handler declaration that every CAS
deployer will need to change before deploying CAS | into production. The
default SimpleTestUsernamePasswordAuthenticationHandler authenticates UsernamePasswordCredentials
| where the username equals the password. You will need to replace this with
an AuthenticationHandler that implements your | local authentication strategy.
You might accomplish this by coding a new such handler and declaring | edu.someschool.its.cas.MySpecialHandler
here, or you might use one of the handlers provided in the adaptors modules.
+ -->
<bean
class="org.jasig.cas.authentication.handler.support.SimpleTestUsernamePasswordAuthenticationHandler" />
</list>
</property>
</bean>
<!-- This bean defines the security roles for the Services Management application.
Simple deployments can use the in-memory version. More robust deployments
will want to use another option, such as the Jdbc version. The name of this
should remain "userDetailsService" in order for Spring Security to find it. -->
<!-- <sec:user name="##THIS SHOULD BE REPLACED##" password="notused" authorities="ROLE_ADMIN"
/> -->
<sec:user-service id="userDetailsService">
<sec:user name="weblogic" password="welcome1"
authorities="ROLE_ADMIN" />
</sec:user-service>
<!-- Bean that defines the attributes that a service may return. This example
uses the Stub/Mock version. A real implementation may go against a database
or LDAP server. The id should remain "attributeRepository" though. -->
<bean id="attributeRepository"
class="org.jasig.services.persondir.support.StubPersonAttributeDao">
<property name="backingMap">
<map>
<entry key="uid" value="uid" />
<entry key="eduPersonAffiliation" value="eduPersonAffiliation" />
<entry key="groupMembership" value="groupMembership" />
</map>
</property>
</bean>
<!-- Sample, in-memory data store for the ServiceRegistry. A real implementation
would probably want to replace this with the JPA-backed ServiceRegistry DAO
The name of this bean should remain "serviceRegistryDao". -->
<bean id="serviceRegistryDao" class="org.jasig.cas.services.InMemoryServiceRegistryDaoImpl">
<property name="registeredServices">
<list>
<bean class="org.jasig.cas.services.RegexRegisteredService">
<property name="id" value="0" />
<property name="name" value="HTTP and IMAP" />
<property name="description" value="Allows HTTP(S) and IMAP(S) protocols" />
<property name="serviceId" value="^(https?|imaps?)://.*" />
<property name="evaluationOrder" value="10000001" />
</bean>
<!-- Use the following definition instead of the above to further restrict
access to services within your domain (including subdomains). Note that example.com
must be replaced with the domain you wish to permit. -->
<!-- <bean class="org.jasig.cas.services.RegexRegisteredService"> <property
name="id" value="1" /> <property name="name" value="HTTP and IMAP on example.com"
/> <property name="description" value="Allows HTTP(S) and IMAP(S) protocols
on example.com" /> <property name="serviceId" value="^(https?|imaps?)://([A-Za-z0-9_-]+\.)*example\.com/.*"
/> <property name="evaluationOrder" value="0" /> </bean> -->
</list>
</property>
</bean>
<bean id="auditTrailManager"
class="com.github.inspektr.audit.support.Slf4jLoggingAuditTrailManager" />
<bean id="healthCheckMonitor" class="org.jasig.cas.monitor.HealthCheckMonitor">
<property name="monitors">
<list>
<bean class="org.jasig.cas.monitor.MemoryMonitor"
p:freeMemoryWarnThreshold="10" />
<!-- NOTE The following ticket registries support SessionMonitor: * DefaultTicketRegistry
* JpaTicketRegistry Remove this monitor if you use an unsupported registry. -->
<bean class="org.jasig.cas.monitor.SessionMonitor"
p:ticketRegistry-ref="ticketRegistry"
p:serviceTicketCountWarnThreshold="5000"
p:sessionCountWarnThreshold="100000" />
</list>
</property>
</bean>
</beans>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>portal</groupId>
<artifactId>cas-portal</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>cas-portal</name>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warName>cas</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-webapp</artifactId>
<version>${cas.version}</version>
<type>war</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
<version>1.0.b2</version>
<scope>provided</scope>
</dependency>
<!-- <dependency> <groupId>org.jasig.cas</groupId> <artifactId>cas-server-support-ldap</artifactId>
<version>${cas.version}</version> <exclusions> <exclusion> <artifactId>xml-apis</artifactId>
<groupId>xml-apis</groupId> </exclusion> <exclusion> <artifactId>opensaml</artifactId>
<groupId>org.opensaml</groupId> </exclusion> </exclusions> </dependency> -->
<dependency>
<groupId>org.jasig.cas</groupId>
<artifactId>cas-server-support-generic</artifactId>
<version>${cas.version}</version>
<type>jar</type>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
<scope>runtime</scope>
</dependency>
</dependencies>
<properties>
<cas.version>3.5.2.1</cas.version>
</properties>
<repositories>
<repository>
<id>ja-sig</id>
<url>http://oss.sonatype.org/content/repositories/releases/ </url>
</repository>
</repositories>
</project>
weblogic.xml
<?xml version="1.0" encoding="UTF-8"?>
<wls:weblogic-web-app xmlns:wls="http://xmlns.oracle.com/weblogic/weblogic-web-app" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd http://xmlns.oracle.com/weblogic/weblogic-web-app http://xmlns.oracle.com/weblogic/weblogic-web-app/1.2/weblogic-web-app.xsd">
<wls:context-root>cas</wls:context-root>
<wls:weblogic-version>10.3.5.0</wls:weblogic-version>
<wls:container-descriptor>
<wls:prefer-application-packages>
<wls:package-name>javax.xml.parsers.SAXParserFactory</wls:package-name>
<wls:package-name>org.opensaml.*</wls:package-name>
</wls:prefer-application-packages>
</wls:container-descriptor>
</wls:weblogic-web-app>

Related

How to build project by Spring Boot + Mybatis + Mybatis Generator?

I follow mybatis official website to build my project step by step, but it always can not work well, so I hope you could give me a fully guide from beginning to the end, many thanks.
Step 1. Build a new spring boot project named booking.
This step is basically, I will skip it.
Step 2. Add mybatis-generator to project.
This could help us to generate entity and mapper class mybatis needed automatically, it's very useful for us to save our time.
Add plugin config in pom.xml
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
</dependencies>
</plugin>
Create generatorConfig.xml at base resources path.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MySqlContext" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/booking?useSSL=false"
userId="root"
password="123456">
<property name="nullCatalogMeansCurrent" value="true" />
</jdbcConnection>
<javaModelGenerator targetPackage="com.clycle.booking.entity" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.clycle.booking.mapper" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.clycle.booking.mapper" targetProject="C:\Users\a243903\projects\booking\webapi\src\main\java">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="%">
</table>
</context>
</generatorConfiguration>
Create maven Run/Debug Configuration to run this plugin.
It will generate all entity, mapper class and mapper xml automatically. -Dmybatis.generator.overwrite=true, means it will overwrite existing entity or mapper class when run mybatis generator with maven.
Step 3. Add mybatis to this project.
Add mybatis dependency in pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
Create mybatis-config.xml at base resources path.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<package name="com.clycle.booking.entity" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value="" />
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/booking" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.clycle.booking.mapper" />
<!--<mapper resource="com/clycle/booking/mapper/ShopMapper.xml" />-->
</mappers>
</configuration>
Add #MapperScan for application main class.
#SpringBootApplication
#MapperScan({"com.clycle.booking.mapper"})
public class BookingApplication {
public static void main(String[] args) {
SpringApplication.run(BookingApplication.class, args);
}
}
Autowired mapper interface to operate your database.
#Autowired
private ShopMapper shopMapper;
#PostMapping(RoutePath.SHOP_LIST)
public List<Shop> GetList() {
try {
return shopMapper.selectAll();
} catch (Exception ex) {
return null;
}
}
You can download this project: https://github.com/yyqian/spring-boot-mybatis-generator .
Everything just work fine on my computer.

Spring Maven JUnit NoClassDefFoundError:org/springframework/context /ApplicationContextException

I have created a spring legacy project using Spring STS and xml configuration file spring-context.xml. I am trying to test my DAO class using JUnit (Run as > Maven test) but I get the following error:
initializationError(net.mozaikdev.samples.dao.test.AddressDAOTest) Time elapsed: 0.006 sec <<< ERROR!
org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.test.context.support.DelegatingSmartContextLoader]: Constructor threw exception; nested exception is java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:177)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:123)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:146)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.resolveContextLoader(AbstractTestContextBootstrapper.java:467)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:357)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildMergedContextConfiguration(AbstractTestContextBootstrapper.java:303)
at org.springframework.test.context.support.AbstractTestContextBootstrapper.buildTestContext(AbstractTestContextBootstrapper.java:109)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:135)
at org.springframework.test.context.TestContextManager.<init>(TestContextManager.java:120)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTestContextManager(SpringJUnit4ClassRunner.java:151)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.<init>(SpringJUnit4ClassRunner.java:142)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.junit.internal.builders.AnnotatedBuilder.buildRunner(AnnotatedBuilder.java:104)
at org.junit.internal.builders.AnnotatedBuilder.runnerForClass(AnnotatedBuilder.java:86)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
at org.junit.internal.requests.ClassRequest.getRunner(ClassRequest.java:33)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:250)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:141)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextException
at org.springframework.test.context.support.DelegatingSmartContextLoader.<init>(DelegatingSmartContextLoader.java:63)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:165)
... 32 more
Caused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContextException
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 38 more
I don't understand why I'm getting this exception since I have declared in my pom.xml the dependency to spring-context:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.mozaikdev</groupId>
<artifactId>eshop-sample-spring-legacy</artifactId>
<name>eshop-sample-spring-legacy</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<repositories>
<repository>
<id>repository.spring.release</id>
<name>Spring GA Repository</name>
<url>http://repo.spring.io/release</url>
</repository>
<repository>
<id>repository.spring.milestone</id>
<name>Spring Milestone Repository</name>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<properties>
<java-version>1.8</java-version>
<org.springframework-version>5.0.0.RC3</org.springframework-version>
<org.hibernate-version>5.2.10.Final</org.hibernate-version>
<org.aspectj-version>1.8.10</org.aspectj-version>
<org.slf4j-version>1.7.25</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${org.hibernate-version}</version>
</dependency>
<!-- MariaDB Connector J -->
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>2.1.1</version>
</dependency>
<!-- HikariCP connection pool -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
</project>
Here is my JUnit test:
#ContextConfiguration(locations = "classpath:application-context.xml")
#RunWith(SpringJUnit4ClassRunner.class)
public class AddressDAOTest {
#Autowired
private AddressDAO addressDAO;
private static final String STREET_1 = "street_1";
private static final String STREET_2 = "street_2";
private static final Integer ZIP_CODE = new Integer(1234);
private static final String CITY = "city";
private static final String REGION = "region";
private static final String COUNTRY = "country";
private static final Boolean IS_DELIVERY_ADDRESS = new Boolean(false);
#Test
#Transactional
#Rollback(value = true)
public void testPersistAndFindById() {
Address address = new Address();
address.setStreet_1(STREET_1);
address.setStreet_2(STREET_2);
address.setZipCode(ZIP_CODE);
address.setCity(CITY);
address.setRegion(REGION);
address.setCountry(COUNTRY);
address.setIsDeliveryAddress(IS_DELIVERY_ADDRESS);
addressDAO.persist(address);
Long id = address.getId();
address = addressDAO.findById(id);
Assert.assertEquals(STREET_1, address.getStreet_1());
Assert.assertEquals(STREET_2, address.getStreet_2());
Assert.assertEquals(ZIP_CODE, address.getZipCode());
Assert.assertEquals(CITY, address.getCity());
Assert.assertEquals(REGION, address.getRegion());
Assert.assertEquals(COUNTRY, address.getCountry());
Assert.assertEquals(IS_DELIVERY_ADDRESS, address.getIsDeliveryAddress());
}
#Test
#Transactional
#Rollback(value = true)
public void testFindAll() {
Address address1 = new Address();
address1.setStreet_1(STREET_1);
address1.setStreet_2(STREET_2);
address1.setZipCode(ZIP_CODE);
address1.setCity(CITY);
address1.setRegion(REGION);
address1.setCountry(COUNTRY);
address1.setIsDeliveryAddress(IS_DELIVERY_ADDRESS);
Address address2 = new Address();
address2.setStreet_1(STREET_1_UPDATE);
address2.setStreet_2(STREET_2_UPDATE);
address2.setZipCode(ZIP_CODE_UPDATE);
address2.setCity(CITY_UPDATE);
address2.setRegion(REGION_UPDATE);
address2.setCountry(COUNTRY_UPDATE);
address2.setIsDeliveryAddress(IS_DELIVERY_ADDRESS_UPDATE);
addressDAO.persist(address1);
addressDAO.persist(address2);
List<Address> addressesList = addressDAO.findAll();
Assert.assertNotNull(addressesList);
Assert.assertTrue(addressesList.size() >= 2);
Assert.assertTrue(addressesList.contains(address1));
Assert.assertTrue(addressesList.contains(address2));
}
}
And finally the application-context.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Enable annotation configuration -->
<context:annotation-config />
<!-- Scan packages for Spring annotations -->
<context:component-scan base-package="net.mozaikdev.samples.dao" />
<context:component-scan base-package="net.mozaikdev.samples.dao.test" />
<!-- Database connection configuration -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="jdbcUrl" value="${spring.datasource.jdbcUrl}"/>
<property name="driverClassName" value="${spring.datasource.driverClassName}"/>
<property name="username" value="${spring.datasource.username}"/>
<property name="password" value="${spring.datasource.password}"/>
<property name="poolName" value="${spring.datasource.hikari.poolName}"/>
<property name="connectionTimeout" value="${spring.datasource.hikari.connectionTimeout}"/>
<property name="maximumPoolSize" value="${spring.datasource.hikari.maximumPoolSize}"/>
<property name="idleTimeout" value="${spring.datasource.hikari.idleTimeout}"/>
<property name="connectionTestQuery" value="${spring.datasource.hikari.connectionTestQuery}"/>
<property name="maxLifetime" value="${spring.datasource.hikari.maxLifetime}"/>
</bean>
<!-- HikariCP datasource bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
<constructor-arg index="0" ref="hikariConfig"/>
</bean>
<!-- Enables annotation-driven transaction management. -->
<tx:annotation-driven/>
<!--
Creates the transaction manager bean that integrates the used JPA provider with the
Spring transaction mechanism.
-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- Specifies the default settings that are compatible with Hibernate. -->
<bean id="hibernateJpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
<!-- Creates the Hibernate entity manager factory bean -->
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="packagesToScan" value="net.mozaikdev.samples.domain"/>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${spring.jpa.properties.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${spring.jpa.properties.hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${spring.jpa.properties.hibernate.format_sql}</prop>
<prop key="hibernate.generate_statistics">${spring.jpa.properties.hibernate.generate_statistics}</prop>
</props>
</property>
</bean>
<!-- Enable support for annotation-driven Spring MVC controllers -->
<!-- <mvc:annotation-driven/> -->
I have cleaned my project using Run as > Maven clean and Project > Clean..., and I updated the project Maven > Update project but nothing works. I am stuck now, if somebody can help me to solve this exception it would be great?
Thanks in advance.
Pay attention on root cause error.
It's clear enough:
Caused by: java.lang.ClassNotFoundException:
org.springframework.context.ApplicationContextException
Put Spring lib in your classpath.
Ok I solved that. When I ran run as > maven install it gave me the following error:
maven error reading C:\Users\569128763\.m2\repository\org\springframework\spring-context\5.0.0.RC3\spring-context-5.0.0.RC3.jar invalid LOC header (bad signature)
So the jar file for spring-context was corrupted, I just deleted the springframework directory from my m2 repository and did Maven > Update project, then launched maven install once again and it worked.

CannotGetJdbcConnectionException with myBatis +GAE + cloudSQL

I'm new to Google App Engine.
I'm trying to use myBatis to connect to google cloudSQL in my maven GAE.
When I tring to SELECT data from cloudSQL, I'll got Exceptions.
At first, I think there might be a SQL statement problem but I can't find it...
Then, when I changed my SQL statements into 'UPDATE',
exceptions also changed from
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
to
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
So I think there's no error in my SQL statements. My app can read XML file and combine SQL sentences successfully. The problem is that I can't get jdbcConnection... But why?
Could anyone give some suggestion...?
Thanks!
Here are my codes and exceptions:
exceptions
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
### The error may exist in gcloud/myapp/sqlMap/mytestProject.xml
### The error may involve mytestProject.getAllChara
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:73)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:365)
at com.sun.proxy.$Proxy16.selectList(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:188)
at gcloud.myapp.dao.CharacterDataDao.getAllChara(CharacterDataDao.java:29)
at gcloud.myapp.service.MytestProjectService.getAllCharaTest(MytestProjectService.java:36)
at gcloud.myapp.controller.MytestProjectController.to_index(MytestProjectController.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:42)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:177)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1166)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:454)
at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:461)
at com.google.tracing.CurrentContext.runInContext(CurrentContext.java:276)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:320)
at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:312)
at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:458)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
### The error may exist in gcloud/myapp/sqlMap/mytestProject.xml
### The error may involve mytestProject.getAllChara
### The error occurred while executing a query
### Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:23)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:104)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:95)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:91)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:42)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:355)
... 42 more
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Internal error.
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:80)
at org.mybatis.spring.transaction.SpringManagedTransaction.openConnection(SpringManagedTransaction.java:80)
at org.mybatis.spring.transaction.SpringManagedTransaction.getConnection(SpringManagedTransaction.java:66)
at org.apache.ibatis.executor.BaseExecutor.getConnection(BaseExecutor.java:279)
at org.apache.ibatis.executor.SimpleExecutor.prepareStatement(SimpleExecutor.java:69)
at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:56)
at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:267)
at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:141)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:105)
at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:81)
at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:101)
... 49 more
Caused by: java.sql.SQLException: Internal error.
at com.google.appengine.api.rdbms.RdbmsApiProxyClient$ApiProxyBlockingInterface.makeSyncCall(RdbmsApiProxyClient.java:109)
at com.google.appengine.api.rdbms.RdbmsApiProxyClient$ApiProxyBlockingInterface.openConnection(RdbmsApiProxyClient.java:71)
at com.google.cloud.sql.jdbc.internal.SqlProtoClient.openConnection(SqlProtoClient.java:58)
at com.google.cloud.sql.jdbc.Driver.connect(Driver.java:65)
at com.google.cloud.sql.jdbc.Driver.connect(Driver.java:25)
at com.google.appengine.api.rdbms.AppEngineDriver.connect(AppEngineDriver.java:83)
at java.sql.DriverManager.getConnection(DriverManager.java:571)
at java.sql.DriverManager.getConnection(DriverManager.java:187)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:173)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:164)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:149)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:119)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77)
... 59 more
controller
package gcloud.myapp.controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import gcloud.myapp.service.MytestProjectService;
#Controller
public class MytestProjectController {
#Autowired
MytestProjectService mytestProjectService = new MytestProjectService();
#RequestMapping("/")
public String to_index(Model model) throws SQLException, IOException {
List<Map<String, String>> charaList = mytestProjectService.getAllCharaTest();
model.addAttribute("charaList", charaList);
return "index";
}
}
service
package gcloud.myapp.service;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import gcloud.myapp.dao.CharacterDataDao;
#Service("MytestProjectService")
public class MytestProjectService implements IMytestProjectService {
#Autowired
CharacterDataDao characterDataDao = new CharacterDataDao();
#Override
public List<Map<String, String>> getAllCharaTest() throws SQLException, IOException{
List<Map<String, String>> charaList = characterDataDao.getAllChara();
return charaList;
}
}
dao
package gcloud.myapp.dao;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import java.io.IOException;
public class CharacterDataDao extends SqlSessionDaoSupport implements ICharacterDataDao {
#Override
public List<Map<String, String>> getAllChara() throws SQLException, IOException {
List<Map<String, String>> charaList = getSqlSession().selectList("getAllChara");
return charaList;
}
}
sqlMap(mytestProject.xml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mytestProject">
<resultMap id="charaListMap" type="java.util.Map">
<result property="id" column="ID" jdbcType="VARCHAR" />
<result property="name" column="CHARANAME_CH" jdbcType="VARCHAR" />
</resultMap>
<select id="getAllChara" resultMap="charaListMap">
<![CDATA[
SELECT ID, CHARANAME_CH
FROM charainfo
]]>
</select>
</mapper>
myBatis config
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="gcloud/myapp/sqlMap/mytestProject.xml" />
</mappers>
</configuration>
spring config
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- basic -->
<context:component-scan base-package="gcloud.myapp" />
<!-- basic -->
<!-- view , the rules defined to resolve the view names -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- basic -->
<property name="prefix" value="/WEB-INF/page/" />
<property name="suffix" value=".jsp" />
<property name="order" value="1" />
</bean>
<!-- sqlSessionFactory -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.google.appengine.api.rdbms.AppEngineDriver" />
<property name="url" value="jdbc:google:rdbms://mytestproject:mytestproject-db/mytestproject" />
<property name="username" value="**my user name**" />
<property name="password" value="**my password**" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="/WEB-INF/config/SqlMapConfig.xml" />
</bean>
<bean id="characterDataDao" class="gcloud.myapp.dao.CharacterDataDao">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>SpringServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- if without "init-param", framework will try to load the application
context from a file named [servlet-name]-servlet.xml in WEB-INF directory. -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/SpringConfig.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
pom
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<groupId>gcloud.myapp</groupId>
<artifactId>MytestProject</artifactId>
<properties>
<app.id>**my app id**</app.id>
<app.version>1</app.version>
<appengine.version>1.9.44</appengine.version>
<gcloud.plugin.version>1.9.44</gcloud.plugin.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven.compiler.showDeprecation>true</maven.compiler.showDeprecation>
<archiveClasses>true</archiveClasses>
<org.springframework-version>4.1.6.RELEASE</org.springframework-version>
</properties>
<prerequisites>
<maven>3.3.9</maven>
</prerequisites>
<dependencies>
<!-- Compile/runtime dependencies -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-1.0-sdk</artifactId>
<version>${appengine.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test Dependencies -->
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-testing</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-api-stubs</artifactId>
<version>${appengine.version}</version>
<scope>test</scope>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- com.mysql.jdbc.Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.2</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.1.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.1.1</version>
</dependency>
</dependencies>
<build>
<!-- for hot reload of the web application-->
<outputDirectory>${project.build.directory}/${project.build.finalName}/WEB-INF/classes</outputDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<archiveClasses>true</archiveClasses>
<webResources>
<!-- in order to interpolate version from pom into appengine-web.xml -->
<resource>
<directory>${basedir}/src/main/webapp/WEB-INF</directory>
<filtering>true</filtering>
<targetPath>WEB-INF</targetPath>
</resource>
</webResources>
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>appengine-maven-plugin</artifactId>
<version>${appengine.version}</version>
<configuration>
<enableJarClasses>false</enableJarClasses>
<version>${app.version}</version>
<!-- Comment in the below snippet to bind to all IPs instead of just localhost -->
<!-- address>0.0.0.0</address>
<port>8080</port -->
<!-- Comment in the below snippet to enable local debugging with a remote debugger
like those included with Eclipse or IntelliJ -->
<!-- jvmFlags>
<jvmFlag>-agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=n</jvmFlag>
</jvmFlags -->
</configuration>
</plugin>
<plugin>
<groupId>com.google.appengine</groupId>
<artifactId>gcloud-maven-plugin</artifactId>
<version>${gcloud.plugin.version}</version>
<configuration>
<set_default>true</set_default>
</configuration>
</plugin>
</plugins>
</build>
</project>
2017/1/18 3:40pm update:
Not cloudSQL authorization problem.
I've tried
Connection conn = DriverManager.getConnection("jdbc:google:mysql://**url**/**databaseName**?user=**userName**&password=**password**");
and connected to database successfully.(can do SQL operations.)
............solved it.
It's just a dataSource URL error.
in my spring-config
<!-- sqlSessionFactory -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.google.appengine.api.rdbms.AppEngineDriver" />
<property name="url" value="jdbc:google:rdbms://mytestproject:mytestproject-db/mytestproject" />
<property name="username" value="**my user name**" />
<property name="password" value="**my password**" />
</bean>
change
<property name="url" value="jdbc:google:rdbms://mytestproject:mytestproject-db/mytestproject" />
to
<property name="url" value="jdbc:google:mysql://mytestproject:us-central1:mytestproject-db/mytestproject" />
and then it works.

ActiveMQ not freeing up the disk storage for queue

When throwing a significant amount of load to an ActiveMQ queue it seems to enqueue/dequeue messages as it's supposed to, but the storage remains full.
This causes the producer to block after some time, when the storage gets to 100%, which in turn causes the application to stop responding to requests.
This is the relevant activeMQ Spring configuration that we're using:
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd
http://activemq.apache.org/schema/core
http://activemq.apache.org/schema/core/activemq-core.xsd">
<!-- =====================================================
Broker Configuration
===================================================== -->
<broker id="appEmbeddedBroker"
xmlns="http://activemq.apache.org/schema/core"
brokerName="${msg.embedded.broker.name}"
persistent="true"
dataDirectory="${msg.embedded.broker.data.directory}"
useJmx="true" >
<destinationPolicy>
<policyMap>
<policyEntries>
<policyEntry topic=">" >
<pendingMessageLimitStrategy>
<constantPendingMessageLimitStrategy limit="1000"/>
</pendingMessageLimitStrategy>
</policyEntry>
</policyEntries>
</policyMap>
</destinationPolicy>
<managementContext>
<managementContext connectorPort="${msg.embedded.broker.jmx.port}" createConnector="false"/>
</managementContext>
<persistenceAdapter>
<levelDB directory="${msg.embedded.broker.db.directory}" />
</persistenceAdapter>
<systemUsage>
<systemUsage>
<memoryUsage>
<memoryUsage percentOfJvmHeap="10"/>
</memoryUsage>
<storeUsage>
<storeUsage limit="${msg.embedded.broker.system.usage.store.usage}"/> <!-- Configured for 200Mb -->
</storeUsage>
<tempUsage>
<tempUsage limit="${msg.embedded.broker.system.usage.temp.usage}"/> <!-- Configured for 40Mb -->
</tempUsage>
</systemUsage>
</systemUsage>
<plugins>
<!-- Configure authentication; Username, passwords and groups -->
<simpleAuthenticationPlugin anonymousAccessAllowed="false">
<users>
<authenticationUser username="app" password="${msg.embedded.broker.app.password}"
groups="users"/>
</users>
</simpleAuthenticationPlugin>
</plugins>
<transportConnectors>
<transportConnector name="tcp" uri="tcp://0.0.0.0:${msg.embedded.broker.port}?maximumConnections=1000&wireFormat.maxFrameSize=104857600"/>
</transportConnectors>
<shutdownHooks>
<bean xmlns="http://www.springframework.org/schema/beans" class="org.apache.activemq.hooks.SpringContextHook" />
</shutdownHooks>
</broker>
<!-- =====================================================
Client Connections
===================================================== -->
<bean id="embeddedAmqConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory" depends-on="appEmbeddedBroker" >
<property name="brokerURL" value="${msg.embedded.broker.url}" />
<property name="userName" value="${msg.embedded.client.app.username}" />
<property name="password" value="${msg.embedded.broker.app.password}" />
</bean>
<bean id="embeddedAmqPooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory" >
<property name="connectionFactory" ref="embeddedAmqConnectionFactory" />
<property name="maxConnections" value="${msg.embedded.client.connection.pool.max}" />
</bean>
When querying the beans:
$>get QueueSize EnqueueCount DequeueCount
#mbean = org.apache.activemq:brokerName=app-embedded,destinationName=the.queue.name.local,destinationType=Queue,type=Broker:
QueueSize = 0;
EnqueueCount = 17821;
DequeueCount = 17821;
And:
#mbean = org.apache.activemq:brokerName=app-embedded,type=Broker:
StoreLimit = 209715200;
StorePercentUsage = 100;
TempLimit = 41943040;
TempPercentUsage = 0;
So, the question would be: Why if all messages are getting dequeued we still see 100% of storage usage?
There can be many reasons for this depending on you broker configuration and usage. First thing to check is what the contents of your DLQ are, then look on the console for other destinations that are holding onto messages. Due to the way things are propagated through the KahaDB journal logs it is possible that they create a chain that cannot be broken until you purge some other Queues or rollback any Transactions that are still inflight etc.
There is a guide on the ActiveMQ site that covers how to start debugging the situation that should help get you started.
Also try running the latest broker release, there are fixes that have gone into these components that try and address these sorts of situations.

After integrating Infinispan 5.2.1 second level cache occurred org.springframework.beans.factory.BeanDefinitionStoreException

I am using Infinispan L2 cache with Tomcat 6, Hibernate 4 Spring 3.5 and Junit 4.10. After integrating Infinispan cache I have encountered an exception when try to run application
Could not resolve placeholder 'hibernate.connection.password' in string value "${hibernate.connection.password}": Could not resolve placeholder 'hibernate.connection.password' in string value "${hibernate.connection.password}"
All the hibernate.properties file and spring files are in relevant places where they were in previously.
My Infinspan configuration is
<globalJmxStatistics enabled="true" jmxDomain="org.infinispan" allowDuplicateDomains="true"/>
<transport
transportClass="org.infinispan.remoting.transport.jgroups.JGroupsTransport"
clusterName="infinispan-hibernate-cluster"
distributedSyncTimeout="50000"
strictPeerToPeer="false">
<properties>
<property name="configurationFile" value="jgroups.xml"/>
</properties>
</transport>
</global>
<default>
</default>
<namedCache name="my-cache-entity">
<clustering mode="replication">
<stateRetrieval fetchInMemoryState="false" timeout="60000"/>
<sync replTimeout="20000"/>
</clustering>
<locking isolationLevel="READ_COMMITTED" concurrencyLevel="1000"
lockAcquisitionTimeout="15000" useLockStriping="false"/>
<eviction maxEntries="10000" strategy="LRU"/>
<expiration maxIdle="100000" wakeUpInterval="5000"/>
<lazyDeserialization enabled="true"/>
<!--<transaction useSynchronization="true"
transactionMode="TRANSACTIONAL" autoCommit="false"
lockingMode="OPTIMISTIC"/>-->
<loaders passivation="false" shared="false" preload="false">
<loader class="org.infinispan.loaders.cluster.ClusterCacheLoader"
fetchPersistentState="false"
ignoreModifications="false" purgeOnStartup="false">
<properties>
<property name="remoteCallTimeout" value="20000"/>
</properties>
</loader>
</loaders>
</namedCache>
This is Spring configuration for the placeholders
<bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:tomcat-jdbc-pool.properties</value>
<value>classpath:hibernate.properties</value>
</list>
</property>
</bean>

Resources