Hibernate exception found in calling buildsessionfactory method - struts2

I'm finding the exception :-[java.lang.NoSuchMethodError: org.hibernate.internal.CoreMessageLogger.debugf(Ljava/lang/String;I)V]
while calling the buildsessionfactory method.
For this exception I haven't been able to connect with the database(mysql).
Here is my code:-
Action file :-
EmpAction.java:-
package techmyguru.actions;
import com.opensymphony.xwork2.ActionSupport;
//import com.opensymphony.xwork2.ModelDriven;
//import com.opensymphony.xwork2.Preparable;
public class EmpAction extends ActionSupport {
//Employee emp;
private int id;
private String password;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String execute()
{
try{
int i=EmpDao.register(this);
if(i==1)
{
return "success";
}
else
{
return "error";
}
}
catch(Throwable t)
{
t.toString();
return "fail";
}
}
}
here is my database connection file:-
package techmyguru.actions;
//import java.util.List;
//import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class EmpDao {
public static int register(EmpAction e) {
int i=0;
Configuration c=null;
SessionFactory sf=null;
Session session=null;
Transaction tr=null;
try
{
try
{
c=new Configuration().configure("hibernate.cfg.xml");
}catch(Throwable t)
{
System.out.println("configuration problem");
t.printStackTrace();
}
try{
sf = c.buildSessionFactory();
}catch(Throwable t)
{
System.out.println("sessionfactory problem");
t.printStackTrace();
}
try{
session=sf.openSession();
}catch(Throwable t)
{
System.out.println("session opening problem");
t.printStackTrace();
}
try{
tr=session.beginTransaction();
}catch(Throwable t)
{
System.out.println("transaction opening problem");
t.printStackTrace();
}
try{
tr.begin();
}catch(Throwable t)
{
System.out.println("transaction begining problem");
t.printStackTrace();
}
try{
i=(Integer)session.save(e);
}catch(Throwable t)
{
System.out.println("transaction saving problem");
t.printStackTrace();
}
try{
tr.commit();
}catch(Throwable t)
{
System.out.println("transaction commiting problem");
t.printStackTrace();
}
session.close();
return i;
}
catch(Throwable t)
{
t.toString();
return i;
}
}
}
here is my hibernate mapping
file Employee.hbm.xml:-
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 23, 2013 8:24:43 AM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="techmyguru.actions.EmpAction" table="employee">
<id name="id">
<column name="id" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="name" />
</property>
<property name="password" type="java.lang.String">
<column name="password" />
</property>
<property name="email" type="java.lang.String">
<column name="email" />
</property>
</class>
</hibernate-mapping>
here is my hibernate configuration file hibernate.cfg.xml:-
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="connection.pool_size">10</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="techmyguru/actions/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
struts.xml file:-
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<include file="struts-default.xml" />
<package name="default" extends="struts-default">
<action name="EmpAction" class="techmyguru.actions.EmpAction" method="execute">
<result name="success">success.jsp</result>
<result name="error">error.jsp</result>
<result name="fail">exception.jsp</result>
</action>
</package>
</struts>
web.xml:-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
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"
id="WebApp_ID" version="2.5">
<display-name>Struts2Hibernate1</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
<init-param>
<param-name>struts.devMode</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
error.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
operation failed.....
</body>
</html>
exception.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
exception occured....
</body>
</html>
index.jsp:-
<%# taglib uri="/struts-tags" prefix="s"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="EmpAction" method="post">
<s:textfield label="Enter name" name="name" value=""/>
<s:password label="Enter password" name="password" value=""/>
<s:textfield label="Enter email" name="email" value=""/>
<s:submit value="submit"/>
</s:form>
</body>
</html>
success.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
operation successfull.......!!!
</body>
</html>
and 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>Struts2Hibernate1</groupId>
<artifactId>Struts2Hibernate1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<sourceDirectory>src</sourceDirectory>
<resources>
<resource>
<directory>src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>WebContent</warSourceDirectory>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- <dependency>
<groupId>org.brickred</groupId>
<artifactId>socialauth-filter</artifactId>
<version>[2.4,)</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.4</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<type>jar</type>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jni</artifactId>
<version>8.0.8</version>
</dependency>
-->
<!--
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-junit-plugin</artifactId>
<version>2.2.3</version>
</dependency>
-->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.16.3</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts-taglib</artifactId>
<version>1.3.10</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts-core</artifactId>
<version>1.3.10</version>
<exclusions>
<exclusion>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>4.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>4.0.1.Final</version>
<classifier>tests</classifier>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.0.0.GA</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.1.0.CR2</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
<!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
<!-- optional -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-osgi</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-envers</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-proxool</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-infinispan</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.0.0.Beta1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>sonatype-oss-public</id>
<url>https://oss.sonatype.org/content/groups/public/</url>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>
</project>
I'm using maven in this project.
The error is given at the line:
SessionFactory sf = c.buildSessionFactory();
in the database connection file EmpDao.java.

This is working code You can try it.
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Session session = sessionFactory.openSession();
session.beginTransaction();
// process your business logic.
session.getTransaction().commit();

Related

confirm-ack and confirm-nack channel not getting invoked

I am trying to configure the ack & nack channel and am getting the error like
"Only one confirm call back channel can be configured at a time"
Below are the things which I tried:
1. confirm-correlation-expression="#root" //no result found
2. Changed the amqp template like below
<rabbit:connection-factory id="connectionFactory" host="localhost" publisher-confirms="true" publisher-returns="true" />
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" mandatory="true" /> <!-- for nacks -->
<rabbit:admin connection-factory="connectionFactory" />
/>
The error was not there but the ack channel is not getting invoked.
Can anyone help me on this?
Here the MQ config
<rabbit:template id="nonTransactionalRabbitTemplate"
connection-factory="nonTransactionalConnectionFactory"
mandatory="true"
channel-transacted="false"
confirm-callback="confirmCallback"
return-call`enter code here`back="returnCallback" />
<rabbit:connection-factory id="nonTransactionalConnectionFactory"
connection-factory="rabbitClientConnectionFactory"
publisher-confirms="true"
publisher-returns="true"/>
<rabbit:connection-factory id="nonTransactionalConnectionFactory"
connection-factory="rabbitClientConnectionFactory"
publisher-confirms="true"
publisher-returns="true"/>
<bean id="rabbitClientConnectionFactory" class="com.rabbitmq.client.ConnectionFactory" >
<property name="uri" value="${mq.uri}" />
<property name="requestedHeartbeat" value="30" />
</bean>
Here is my outbound adapter
<int-amqp:outbound-channel-adapter channel="abc"
routing-key="xyz"
amqp-template="amqpTemplate"
confirm-correlation-expression="payload"
confirm-ack-channel="successRespTransformChannel"
confirm-nack-channel="failureRespTransformChannel"
return-channel="failureRespTransformChannel"
mapped-request-headers="*"
Here is my service activator
<chain input-channel="successRespTransformChannel">
<int:header-enricher>
<error-channel ref="failed-publishing" />
</int:header-enricher>
<service-activator id="successResp" expression="#abc.addRequestTracking(payload.id,'success')"/>
</chain>
When using the template in the adapter, you must NOT set your own callbacks
confirm-callback="confirmCallback"
return-callback="returnCallback" />
The adapter sets itself as the callback for both confirms and returns. This fails since you have already set the callbacks.
<rabbit:template id="amqpTemplate" connection-factory="connectionFactory" mandatory="true" /> <!-- for nacks -->
mandatory enables returns, not nacks.
EDIT
I have no idea what you are doing wrong. I just wrote a quick test case...
#SpringBootApplication
#ImportResource("context.xml")
public class So36546646Application {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = SpringApplication.run(So36546646Application.class, args);
ctx.getBean("out", MessageChannel.class).send(new GenericMessage<>("foo"));
boolean received = ctx.getBean(MyService.class).latch.await(10, TimeUnit.SECONDS);
if (!received) {
System.err.println("Did not receive ack");
}
ctx.getBean(RabbitAdmin.class).deleteQueue(ctx.getBean(Queue.class).getName());
ctx.close();
}
public static class MyService {
private final CountDownLatch latch = new CountDownLatch(1);
public void handle(Message<?> ack) {
System.out.println("ack:" + ack);
latch.countDown();
}
}
}
and
<?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:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:int-amqp="http://www.springframework.org/schema/integration/amqp"
xmlns:int="http://www.springframework.org/schema/integration"
xsi:schemaLocation="http://www.springframework.org/schema/integration/amqp http://www.springframework.org/schema/integration/amqp/spring-integration-amqp.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd">
<rabbit:connection-factory id="cf" publisher-confirms="true" publisher-returns="true" host="localhost" />
<rabbit:template id="t" connection-factory="cf" mandatory="true" />
<rabbit:admin connection-factory="cf" />
<rabbit:queue id="anon" />
<int:channel id="out" />
<int-amqp:outbound-channel-adapter
channel="out"
amqp-template="t"
routing-key="#{anon.name}"
confirm-correlation-expression="payload"
confirm-ack-channel="acks"
confirm-nack-channel="acks"
return-channel="returns" />
<int:service-activator input-channel="acks" ref="service" />
<bean id="service" class="com.example.So36546646Application$MyService" />
<int:channel id="returns">
<int:queue />
</int:channel>
</beans>
and it worked fine:
ack:GenericMessage [payload=foo, headers={amqp_publishConfirm=true, id=5eed89bf-11b6-76a5-34ed-0091c6bac2c8, timestamp=1460464254229}]

Spring xml to resource.groovy

I am doing configuration in resource.groovy. I am stuck on 'bean-method' xml, how it will be set in resource.groovy and how to pass arguments to the method.
XML config is:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/neo4j
http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd">
<context:component-scan base-package="neo4j"></context:component-scan>
j
<util:map id="config">
<entry key="ha.server_id" value="1" />
<entry key="ha.initial_hosts" value="127.0.0.1:5001,127.0.0.1:5002" />
<!-- put in more config parameters here, http://docs.neo4j.org/chunked/stable/ha-configuration.html -->
</util:map>
<bean id="graphDbFactory"
class="org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory" />
<bean id="graphDbBuilder" factory-bean="graphDbFactory" factory-method="newHighlyAvailableDatabaseBuilder">
<constructor-arg value="/home/alok/Desktop/data1" />
</bean>
<bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder"
factory-method="setConfig">
<constructor-arg ref="config" />
</bean>
<bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
factory-method="newGraphDatabase" destroy-method="shutdown" />
<neo4j:config graphDatabaseService="graphDatabaseService" base-package="neo4j"/>
<neo4j:repositories base-package="neo4j" />
</beans>
My resource.groovy is
beans = {
xmlns neo4j:"http://www.springframework.org/schema/data/neo4j"
xmlns context:"http://www.springframework.org/schema/context"
context.'component-scan'('base-package': 'neo4j')
neo4j.'repositories'('base-package':'neo4j')
// neo4j.'config'('storeDirectory':'target/db5', 'base-package':'neo4j')
graphDbFactory(HighlyAvailableGraphDatabaseFactory)
graphDbBuilder=ref('graphDbFactory'){
bean -> bean.factoryMethod='newHighlyAvailableDatabaseBuilder'
bean.constructorArgs=['/home/alok/Desktop/data1']
}
println "after"
graphDbBuilderFinal=ref('graphDbBuilder'){
bean -> bean.factoryMethod='setConfig'
server_id= ["1"]
initial_hosts= ["127.0.0.1:5001,127.0.0.1:5002"]
}
graphDatabaseService=ref('graphDbBuilderFinal'){
bean -> bean.factoryMethod='newGraphDatabase'
}
neo4j.'config'('base-package':'neo4j')
}
I am getting error bean name must not be empty.
This should work:
import org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory
beans = {
xmlns neo4j:"http://www.springframework.org/schema/data/neo4j"
xmlns context:"http://www.springframework.org/schema/context"
context.'component-scan'('base-package': 'neo4j')
neo4j.'repositories'('base-package':'neo4j')
// neo4j.'config'('storeDirectory':'target/db5', 'base-package':'neo4j')
def config = ['ha.server_id': 1, 'ha.initial_hosts': '127.0.0.1:5001,127.0.0.1:5002']
graphDbFactory(HighlyAvailableGraphDatabaseFactory)
graphDbBuilder(graphDbFactory: 'newHighlyAvailableDatabaseBuilder') { bean ->
bean.constructorArgs = ['/home/alok/Desktop/data1']
}
graphDbBuilderFinal(graphDbBuilder: 'setConfig') { bean ->
bean.constructorArgs = [config]
}
graphDatabaseService(graphDbBuilderFinal: 'newGraphDatabase') { bean ->
bean.destroyMethod = 'shutdown'
}
}
The syntax for beans with a factory instead of a class is:
graphDbBuilder(graphDbFactory:"newHighlyAvailableDatabaseBuilder") { bean ->
bean.constructorArgs = ...
}
Bean definitions must be method calls, your version has an assignment expression outside a bean definition block, which is not allowed.

Log4j write spring-security username

I am using log4j and spring-security in application, and the logger should write logs with username in every message. I am very new to all of this, can somebody help with advice or links? Maybe there is some standart ways of solving this?
Thank you.
EDIT
Using spring framework 3.1
My spring-security.xml is:
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/favicon.ico" security="none" />
<http auto-config="true">
<intercept-url pattern="/**" access="ROLE_ADMIN"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="detect_me" password="1111" authorities="ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>
And log4j.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p [%c] - %m%n" />
</layout>
</appender>
<appender name="R" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="/logs/urlbuilderweb.log"/>
<param name="DatePattern" value="'.'yyyy-MM-dd'.log'" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %p %t %c - %m%n" />
</layout>
</appender>
<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
<param name="BufferSize" value="10000"/>
<appender-ref ref="R"/>
</appender>
<logger name="org.springframework">
<level value="WARN"/>
</logger>
<logger name="org.directwebremoting">
<level value="WARN"/>
</logger>
<logger name="org.apache.http">
<level value="WARN"/>
</logger>
<logger name="org.hibernate">
<level value="WARN"/>
</logger>
<root>
<level value="INFO" />
<appender-ref ref="ASYNC"/>
</root>
</log4j:configuration>
You can use NDC feature.
Set up some filter / interceptor (depends on what presentation technology you use). Add nested diagnostic context (filter example):
public class LogDiagnosticContextFilter implements javax.servlet.Filter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
// do nothing
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
SecurityContext context = SecurityContextHolder.getContext();
if (context != null) {
Authentication authentication = context.getAuthentication();
if (authentication != null) {
NDC.push("Username=" + authentication.getName());
}
}
chain.doFilter(request, response);
NDC.pop();
}
#Override
public void destroy() {
// do nothing
}
}
Ensure that filter executed after Spring Security filter chain (web.xml):
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>logDiagnosticContextFilter</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
Add x to each interested log4j pattern:
%x %d %p %t %c - %m%n
Later when you call
LOGGER.info("some text");
anywhere in you code you will see
Username=corresponding_login some text
in your log

Struts2 parameters is coming null in action class when using Interceptors

When I am using Interceptors, the values on Action class coming as null. I have removed the Interceptors, the values coming perfect from the JSP page.
Login.jsp
<s:form id="loginFrm" name="loginFrm" action="LoginAction">
<s:textfield key="username"/>
<s:password key="password"/>
<s:submit/>
</s:form>
LoginAction.java
public class LoginAction {
private static Logger LOGGER = Logger.getLogger(LoginAction.class);
private String username;
private String password;
public String execute() throws Exception {
LOGGER.info("LoginAction : authenticate()");
LOGGER.info("LoginAction : {[" + username + "],["+password+ "]}");
return "success";
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Bulk Fund Switching</display-name>
<context-param>
<param-name> org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG </param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.struts2.tiles.StrutsTilesListener </listener-class>
</listener>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>jsp/Login.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.xml (working version)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="BFSView,BFSMessages" />
<package name="home-default" extends="struts-default" namespace="/">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<interceptors>
<interceptor name="AuthenticationInterceptor" class="com.lv.bfs.controller.interceptor.AuthenticationInterceptor"></interceptor>
<interceptor-stack name="SecureStack">
<interceptor-ref name="AuthenticationInterceptor" />
</interceptor-stack>
</interceptors>
<action name="LoginAction" class="com.lv.bfs.controller.action.LoginAction">
<result name="success">jsp/Welcome.jsp</result>
<result name="error">/jsp/Login.jsp</result>
</action>
</package>
</struts>
struts.xml (Not working version )
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="BFSView,BFSMessages" />
<package name="home-default" extends="struts-default" namespace="/">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<interceptors>
<interceptor name="AuthenticationInterceptor" class="com.lv.bfs.controller.interceptor.AuthenticationInterceptor"></interceptor>
<interceptor-stack name="SecureStack">
<interceptor-ref name="AuthenticationInterceptor" />
</interceptor-stack>
</interceptors>
<action name="LoginAction" class="com.lv.bfs.controller.action.LoginAction">
<interceptor-ref name="SecureStack"></interceptor-ref>
<result name="success">jsp/Welcome.jsp</result>
<result name="error">/jsp/Login.jsp</result>
</action>
</package>
</struts>
AuthenticationInterceptor.java
public class AuthenticationInterceptor extends AbstractInterceptor {
private static Logger LOGGER = Logger.getLogger(AuthenticationInterceptor.class);
private static final long serialVersionUID = 1844249996954274967L;
public String intercept(ActionInvocation invocation) throws Exception {
LOGGER.info("intercept : START");
return invocation.invoke();
}
}
Logs statements (both cases)
12:39:05,533 INFO [AuthenticationInterceptor] intercept : START
12:39:05,533 INFO [LoginAction] LoginAction : authenticate()
12:39:05,533 INFO [LoginAction] LoginAction : {[null],[null]}
12:09:05,533 INFO [LoginAction] LoginAction : authenticate()
12:09:05,533 INFO [LoginAction] LoginAction : {[admin],[admin]}
Any suggestions?
When you define an interceptor stack for a specific action you must define all the interceptors for that action. In this case, you are only defining your custom interceptor, meaning the "params" interceptor doesn't run, so the action properties won't be set.
Either define a new stack that includes the normal S2 interceptors, or include those interceptors (or stack) in your action configuration.

Struts2 - The requested list key 'Products' could not be resolved

I am new to Struts 2 and trying to see whether I can populate a drop down box with the list of values but still I am not able to get it working.
Following is my Action class (Portal.java):
public class Portal extends ActionSupport {
private Map Products;
private String product;
public Portal(){
Products = new HashMap();
Products.put("1", "Java");
Products.put("2", "C++");
}
public Map getProducts() {
return Products;
}
public void setProducts(Map Products) {
this.Products = Products;
}
public String getProduct() {
return product;
}
public void setProduct(String product) {
this.product = product;
}
public String execute() {
return SUCCESS;
}
}
Following is my Portal.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Portal</title>
</head>
<body>
<h2>Portal</h2>
<s:form action="result" namespace="/">
<h4>
<s:select label="Select Product"
name="product"
headerKey="-1"
headerValue="Select Product"
list="Products"
/>
</h4>
<h4>
<s:submit label="Submit" name="submitButton" align="center" />
</h4>
</s:form>
Following is my result.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org
/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Results Page</title>
</head>
<body>
<h1>Portal</h1>
<h4>
Selected Product : <s:property value="product"/>
</h4>
</body>
</html>
Following is my struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.ognl.allowStaticMethodAccess" value="false" />
<package name="default" extends="struts-default" namespace="/">
<action name="result" class="com.abc.xyz.Portal">
<result name="error">Portal.jsp</result>
<result name="success">Result.jsp</result>
</action>
</package>
</struts>
Following is my web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" 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" id="WebApp_ID" version="2.5">
<display-name>Portal</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>Portal.jsp</welcome-file>
</welcome-file-list>
</web-app>
When I execute this on Tomcat 6 server, I get following error:
SEVERE: Servlet.service() for servlet jsp threw exception
tag 'select', field 'list', name 'product': The requested list key 'Products' could
not be resolved as a collection/array/map/enumeration/iterator type. Example:
people or people.{name} - [unknown location]
But when I replace list="Products" with list="#{'1':'Java', '2':'C++'}", then it works perfectly fine .. I don't know what am I missing so that the list is not being shown.
Please help.
Memory is not allocated for Map Products.
Just before setting the values for the Products write -
Products = new Map();
then set the values to the map. This will help to populate the values of the Products on the View.
Java is case sensitive... list="products" is what you want not list="Products"
Edit: see the comments under this question, you should have a getter or change the access to Products to public.
According to Struts2 data prepopulation should be done by PreparableInterceptor and you have to override prepare method.
public void prepare() throws Exception {
Products = new HashMap();
Products.put("1", "C#");
Products.put("2", "Java");
}
Actually when you open your Portal.jsp it look on valuestack but it didn't get that's why this error come.Because on load the corresponding action is not calling,you have to call action onload.Implement Preparable interface and override the prepare method and in that method you write your code.``
Refer my answer to this similar question: Struts2 list couldn't be resolved
For additional details refer:
https://struts.apache.org/docs/message-resource-files.html

Resources