How Do I Run My WAR in Jetty using Gretty plugin? - gradle

My current goal is to get gradle to start my web application running in a Jetty instance on my machine so that I can write Selenium tests against it. The Gretty plugin seems to be loading, but I haven't been able to find any actual instructions on how to create and configure a task to do that.
Part of the problem is that there is confusion with different versions and editions of the Gretty plugin. Just getting it to load in the first place was an exercise in trial-and-error.
I am trying to do the using Gradle 5.4.1 and Gretty 2.3.1, which I believe are the current versions (at this time).
I have three sub-projects "laoi" depends on "aofl" depends on "efl". The laoi build produces a WAR file. The task appRunWar seems to want to create and run its own WAR file, rather than using mine (at least that seems to be what's happening).
settings.gradle:
rootProject.name = 'aoi'
include 'cm', 'efl', 'aofl', 'laoi', 'uiTest'
build.gradle (laoi):
static def getDate() {
return new Date().format('yyyyMMdd-HHmmss')
}
final String timepickerAddonVersion = '1.6.3'
final String datatablesVersion = '1.10.19'
final String jqueryUIVersion = '1.12.1'
final String jqueryVersion = '3.2.1'
if (null == System.properties['aoi.release'] || null == System.properties['aoi.iteration']) {
if (null == System.env['RELEASE'] || null == System.env['ITERATION']) {
ext.ITERATION = "un"
ext.RELEASE = "dev"
} else {
ext.ITERATION = System.env['ITERATION']
ext.RELEASE = System.env['RELEASE']
}
} else {
ext.ITERATION = System.properties['aoi.iteration']
ext.RELEASE = System.properties['aoi.release']
}
System.setProperty('aoi.iteration', ext.ITERATION)
System.setProperty('aoi.release', ext.RELEASE)
if (null == System.properties['aoi.manifest']) {
if (null == System.env['MANIFEST']) {
System.out.println("Using default manifest name.")
ext.MANIFEST = "aoiManifest"
System.out.println("Manifest: ${ext.MANIFEST}")
} else {
ext.MANIFEST = System.env['MANIFEST']
}
} else {
ext.MANIFEST = System.properties['aoi.manifest']
}
System.setProperty('aoi.manifest', ext.MANIFEST)
System.out.println("Manifest: ${ext.MANIFEST}")
final String warFileName = 'aoi-'+ System.properties['aoi.release'] +'_'+ System.properties['aoi.iteration'] + ".war"
println "War file name: ${warFileName}"
final String sourceManifestName = "${ext.MANIFEST}.xml"
println "Source manifest name: ${sourceManifestName}"
def rootLibs = new File("${rootDir}/libs")
repositories {
mavenCentral()
jcenter()
flatDir {
dirs "${rootDir}/libs"
}
}
compileScala {
dependsOn ":efl:test", ":aofl:test"
}
task copyManifest(type: Copy) {
from('src/main/resources') {
include sourceManifestName
rename sourceManifestName, 'aoiManifest.xml'
}
into("${buildDir}/resources/main/bootstrap/liftweb")
}
task createVersionFile {
dependsOn "processResources"
doLast {
new File("${buildDir}/resources/main/aoiVersion.conf").text = "AOI_VERSION=" + System.properties['aoi.release'] +'-'+ System.properties['aoi.iteration'] + " (" + getDate() + ")"
new File("${buildDir}/resources/main/WebJarVersions.conf").text =
"""jQuery-Timepicker-Addon=$timepickerAddonVersion
datatables=$datatablesVersion
jquery=$jqueryVersion
jquery-ui=$jqueryUIVersion
jquery-ui-themes=$jqueryUIVersion
"""
}
}
war {
dependsOn ":aofl:test", "compileScala", "copyManifest", "processResources", "createVersionFile"
setDestinationDirectory(rootLibs)
setArchiveFileName(warFileName)
from('${buildDir}/resources/main') {
include '**/*.xml'
into("classes")
}
}
dependencies {
implementation project(":efl")
implementation project(":aofl")
implementation "org.webjars:jquery:$jqueryVersion"
implementation "org.webjars:jquery-ui:$jqueryUIVersion"
implementation "org.webjars:jquery-ui-themes:$jqueryUIVersion"
implementation "org.webjars:datatables:$datatablesVersion"
implementation "org.webjars:jQuery-Timepicker-Addon:$timepickerAddonVersion"
implementation 'org.webjars:webjars-servlet-2.x:1.1'
}

Since no answers were forthcoming I had to find an answer on my own.
Jetty has a feature that allows you to drop WAR files in a directory and it will load them. In order to make use of that, you have to either figure out what directory it's looking in, or tell it what directory to look in. I went for the second option.
The easiest way to specify a deploy directory is to put it in a "serverConfigFile" which is specified in the gretty options.
gretty {
serverConfigFile = "$contextFile"
servletContainer = 'jetty9.4'
jvmArgs <--- a bunch of arguments go here --->
}
Jetty comes with a bunch of configuration files in the "etc" directory. I viciously and blatantly plagiarized the main Jetty configuration file along with the deployment manager configuration file - but setting the path to one of my choosing. I created a task that writes the serverConfigFile.
task createJettyContextsFile {
doLast {
new File("$contextFile").text =
"""<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">
<!-- =============================================================== -->
<!-- Documentation of this file format can be found at: -->
<!-- https://www.eclipse.org/jetty/documentation/current/ -->
<!-- -->
<!-- Additional configuration files are available in JETTY_HOME/etc -->
<!-- and can be mixed in. See start.ini file for the default -->
<!-- configuration files. -->
<!-- -->
<!-- For a description of the configuration mechanism, see the -->
<!-- output of: -->
<!-- java -jar start.jar -? -->
<!-- =============================================================== -->
<!-- =============================================================== -->
<!-- Configure a Jetty Server instance with an ID "Server" -->
<!-- Other configuration files may also configure the "Server" -->
<!-- ID, in which case they are adding configuration to the same -->
<!-- instance. If other configuration have a different ID, they -->
<!-- will create and configure another instance of Jetty. -->
<!-- Consult the javadoc of o.e.j.server.Server for all -->
<!-- configuration that may be set here. -->
<!-- =============================================================== -->
<Configure id="Server" class="org.eclipse.jetty.server.Server">
<Arg name="threadpool"><Ref refid="threadPool"/></Arg>
<!-- =========================================================== -->
<!-- Add shared Scheduler instance -->
<!-- =========================================================== -->
<Call name="addBean">
<Arg>
<New class="org.eclipse.jetty.util.thread.ScheduledExecutorScheduler"/>
</Arg>
</Call>
<!-- =========================================================== -->
<!-- Http Configuration. -->
<!-- This is a common configuration instance used by all -->
<!-- connectors that can carry HTTP semantics (HTTP, HTTPS, etc.)-->
<!-- It configures the non wire protocol aspects of the HTTP -->
<!-- semantic. -->
<!-- -->
<!-- This configuration is only defined here and is used by -->
<!-- reference from other XML files such as jetty-http.xml, -->
<!-- jetty-https.xml and other configuration files which -->
<!-- instantiate the connectors. -->
<!-- -->
<!-- Consult the javadoc of o.e.j.server.HttpConfiguration -->
<!-- for all configuration that may be set here. -->
<!-- =========================================================== -->
<New id="httpConfig" class="org.eclipse.jetty.server.HttpConfiguration">
<Set name="secureScheme"><Property name="jetty.httpConfig.secureScheme" default="https" /></Set>
<Set name="securePort"><Property name="jetty.httpConfig.securePort" deprecated="jetty.secure.port" default="8443" /></Set>
<Set name="outputBufferSize"><Property name="jetty.httpConfig.outputBufferSize" deprecated="jetty.output.buffer.size" default="32768" /></Set>
<Set name="outputAggregationSize"><Property name="jetty.httpConfig.outputAggregationSize" deprecated="jetty.output.aggregation.size" default="8192" /></Set>
<Set name="requestHeaderSize"><Property name="jetty.httpConfig.requestHeaderSize" deprecated="jetty.request.header.size" default="8192" /></Set>
<Set name="responseHeaderSize"><Property name="jetty.httpConfig.responseHeaderSize" deprecated="jetty.response.header.size" default="8192" /></Set>
<Set name="sendServerVersion"><Property name="jetty.httpConfig.sendServerVersion" deprecated="jetty.send.server.version" default="true" /></Set>
<Set name="sendDateHeader"><Property name="jetty.httpConfig.sendDateHeader" deprecated="jetty.send.date.header" default="false" /></Set>
<Set name="headerCacheSize"><Property name="jetty.httpConfig.headerCacheSize" default="4096" /></Set>
<Set name="delayDispatchUntilContent"><Property name="jetty.httpConfig.delayDispatchUntilContent" deprecated="jetty.delayDispatchUntilContent" default="true"/></Set>
<Set name="maxErrorDispatches"><Property name="jetty.httpConfig.maxErrorDispatches" default="10"/></Set>
<Set name="blockingTimeout"><Property deprecated="jetty.httpConfig.blockingTimeout" name="jetty.httpConfig.blockingTimeout.DEPRECATED" default="-1"/></Set>
<Set name="persistentConnectionsEnabled"><Property name="jetty.httpConfig.persistentConnectionsEnabled" default="true"/></Set>
<Set name="requestCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.requestCookieCompliance" deprecated="jetty.httpConfig.cookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="responseCookieCompliance"><Call class="org.eclipse.jetty.http.CookieCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.responseCookieCompliance" default="RFC6265"/></Arg></Call></Set>
<Set name="multiPartFormDataCompliance"><Call class="org.eclipse.jetty.server.MultiPartFormDataCompliance" name="valueOf"><Arg><Property name="jetty.httpConfig.multiPartFormDataCompliance" default="RFC7578"/></Arg></Call></Set>
</New>
<!-- =========================================================== -->
<!-- Set the default handler structure for the Server -->
<!-- A handler collection is used to pass received requests to -->
<!-- both the ContextHandlerCollection, which selects the next -->
<!-- handler by context path and virtual host, and the -->
<!-- DefaultHandler, which handles any requests not handled by -->
<!-- the context handlers. -->
<!-- Other handlers may be added to the "Handlers" collection, -->
<!-- for example the jetty-requestlog.xml file adds the -->
<!-- RequestLogHandler after the default handler -->
<!-- =========================================================== -->
<Set name="handler">
<New id="Handlers" class="org.eclipse.jetty.server.handler.HandlerCollection">
<Set name="handlers">
<Array type="org.eclipse.jetty.server.Handler">
<Item>
<New id="Contexts" class="org.eclipse.jetty.server.handler.ContextHandlerCollection"/>
</Item>
<Item>
<New id="DefaultHandler" class="org.eclipse.jetty.server.handler.DefaultHandler"/>
</Item>
</Array>
</Set>
</New>
</Set>
<!-- =========================================================== -->
<!-- extra server options -->
<!-- =========================================================== -->
<Set name="stopAtShutdown"><Property name="jetty.server.stopAtShutdown" default="true"/></Set>
<Set name="stopTimeout"><Property name="jetty.server.stopTimeout" default="5000"/></Set>
<Set name="dumpAfterStart"><Property name="jetty.server.dumpAfterStart" deprecated="jetty.dump.start" default="false"/></Set>
<Set name="dumpBeforeStop"><Property name="jetty.server.dumpBeforeStop" deprecated="jetty.dump.stop" default="false"/></Set>
<Call name="addBean">
<Arg>
<New id="DeploymentManager" class="org.eclipse.jetty.deploy.DeploymentManager">
<Set name="contexts">
<Ref refid="Contexts" />
</Set>
<Call name="setContextAttribute">
<Arg>org.eclipse.jetty.server.webapp.ContainerIncludeJarPattern</Arg>
<Arg>.*/[^/]*servlet-api-[^/]*\\.jar\$|.*/javax.servlet.jsp.jstl-.*\\.jar\$|.*/org.apache.taglibs.taglibs-standard-impl-.*\\.jar\$</Arg>
</Call>
<Call id="webappprovider" name="addAppProvider">
<Arg>
<New class="org.eclipse.jetty.deploy.providers.WebAppProvider">
<Set name="monitoredDirName">
<Property>
<Name>jetty.deploy.monitoredPath</Name>
<Default>
<Property name="jetty.deploy.monitoredDir" deprecated="jetty.deploy.monitoredDirName" default="$deployDirectory"/>
</Default>
</Property>
</Set>
<Set name="defaultsDescriptor">
<Property>
<Name>jetty.deploy.defaultsDescriptorPath</Name>
<Default>
<Property name="jetty.home" default="." />/etc/webdefault.xml
</Default>
</Property>
</Set>
<Set name="scanInterval"><Property name="jetty.deploy.scanInterval" default="1"/></Set>
<Set name="extractWars"><Property name="jetty.deploy.extractWars" default="true"/></Set>
<Set name="configurationManager">
<New class="org.eclipse.jetty.deploy.PropertiesConfigurationManager">
</New>
</Set>
</New>
</Arg>
</Call>
</New>
</Arg>
</Call>
</Configure>
"""
}
}
Then I added a task to copy the WAR file into the correct directory.
task copyWar(type: Copy) {
dependsOn ":cm:buildPS", ":laoi:war", 'createJettyContextsFile'
from("$rootLibs") {
include "*.war"
}
into("$deployDirectory")
}
I had to tweak the task dependencies a bit, but now the Gretty tasks that start up the Jetty server will all run with my WAR file properly deployed.

Related

Setting up listener using IBM MQ in eclipse using wlp for java springboot application

Setting up listener using IBM MQ in eclipse using wlp for java springboot application
Hi, I am trying to set up listener using wlp in my local in eclipse,
following is the code :
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jms</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.jms</groupId>
<artifactId>javax.jms-api</artifactId>
<version>2.0</version>
</dependency>
java class:
#JmsListener(containerFactory = "jmsListenerContainerFactory", destination = test.queue)
public void recieve(Message message) {
log.info("inside message receiver");
try {
if (message instanceof TextMessage) {
message.acknowledge();
String json = ((TextMessage) message).getText();
/** To solve Json injection fortify issue **/
String sanitisedJsonMessage = JsonSanitizer.sanitize(json);
Gson gson = new Gson();
//business logic
} else {
log.error("ERROR ::: invalid message type");
message.acknowledge();
}
} catch (JsonSyntaxException | JMSException ex) {
log.error("ERROR: " + ex + ex.getMessage());
}
}
#Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() {
ConnectionFactory connectionfactory;
DefaultJmsListenerContainerFactory listenerFactory;
try {
log.info("inside listener factory");
#Cleanup
Context context = null;
listenerFactory = new DefaultJmsListenerContainerFactory();
context = new InitialContext();
connectionfactory = (ConnectionFactory) context.lookup(jms/ConnectionFactory);
listenerFactory.setConnectionFactory(connectionfactory);
listenerFactory.setSessionAcknowledgeMode(Session.CLIENT_ACKNOWLEDGE);
} catch (NamingException ex) {
log.error("ERROR: error looking up queue connection factory jndi {}", ex);
}
return listenerFactory;
}
Now I tried to set up my server.xml in wlp as per ibm guidelines as follows:
<server description="new server">
<!-- Enable features -->
<featureManager>
<feature>javaee-7.0</feature>
<feature>jndi-1.0</feature>
<feature>jaxws-2.2</feature>
<feature>localConnector-1.0</feature>
<feature>transportSecurity-1.0</feature>
<feature>servlet-3.1</feature>
<feature>mdb-3.2</feature>
<feature>wmqJmsClient-2.0</feature>
<feature>jsp-2.3</feature>
</featureManager>
<!-- Define an Administrator and non-Administrator -->
<basicRegistry id="basic">
<user name="admin" password="adminpwd" />
<user name="nonadmin" password="nonadminpwd" />
</basicRegistry>
<!-- Assign 'admin' to Administrator -->
<administrator-role>
<user>admin</user>
</administrator-role>
<keyStore id="defaultKeyStore" password="Liberty" />
<httpEndpoint host="*" httpPort="9081" httpsPort="9444"
id="defaultHttpEndpoint" />
<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true" />
<applicationMonitor updateTrigger="mbean" />
<enterpriseApplication
id="mqtest-ear"
location="mqtest-ear.ear"
name="mqtest-ear" />
<variable name="wmqJmsClient.rar.location"
value="path\to\wlp\wmq\wmq.jmsra.rar" />
<jmsQueueConnectionFactory
jndiName="jms/ConnectionFactory">
<properties.wmqJms transportType="CLIENT"
hostName="<test.correcthostname>" port="<test.correctportname>"
channel="<test.correctchannelname>" queueManager="<test.correctqmgrname>" useSSL="true"
headerCompression="SYSTEM" messageCompression="RLE"
sslCipherSuite="SSL_RSA_WITH_AES_256_CBC_SHA256"
targetClientMatching="true" />
<connectionManager></connectionManager>
</jmsQueueConnectionFactory>
<jmsQueue id="JMSQueue" jndiName="jms/InQueue">
<properties.wmqJms baseQueueName="test.queue"
baseQueueManagerName="<test.correctqmgrname>" receiveConversion="CLIENT_MSG"
putAsyncAllowed="DESTINATION" targetClient="MQ"
readAheadAllowed="ENABLED" />
</jmsQueue>
<!-- <resourceAdapter
location="${wmqJmsClient.rar.location}" id="resourceAdapter">
</resourceAdapter> -->
<keyStore id="keyAndTrustStore" password="password"
location="path\to\keyandtruststore"
type="PKCS12">
</keyStore>
I have downloaded latest resource adapter and 9.0.0.8-IBM-MQ-Java-InstallRA.jar,
When I run the application , I get constant error:
2020-01-10 11:21:16 ERROR o.s.j.l.DefaultMessageListenerContainer - Could not refresh JMS Connection for destination 'test.queue' - retrying using FixedBackOff{interval=5000, currentAttempts=12, maxAttempts=unlimited}. Cause: MQJCA1011: Failed to allocate a JMS connection.
what Can I do to make listener work
After trying and troubleshoting a lot, I found a solution to set up ibm mq message listener using springboot and jms locally in websphere liberty server version 19.0.0.6.
I used following steps to make listener work:
download resource adaptor 9.0.0.8-IBM-MQ-Java-InstallRA.jar
Run the jar, and a folder named wmq will be generated with required .rar file in it.
Place the wmq folder inside wlp server : path\to\wlp-webProfile8-19.0.0.6\wlp\usr\servers\defaultServer
if using keystores for ssl , place trust and key store .jks or .p12 file inside wlp server path\to\wlp-webProfile8-19.0.0.6\wlp\usr\servers\defaultServer\resources\security
create a new file name jvm.options with following details:
-Dcom.ibm.mq.cfg.useIBMCipherMappings=false
-Djavax.net.debug="all"
-Djdk.tls.client.protocols="TLSv1.2"
-Dhttps.protocols="TLSv1.2"
-Djavax.net.ssl.trustStore="path\to\keyandtruststore.jks"
-Djavax.net.ssl.trustStorePassword="secret"
-Djavax.net.ssl.keyStore="path\to\keyandtruststore.jks"
-Djavax.net.ssl.keyStorePassword="secret"
save file inside following location : path\to\wlp-webProfile8-19.0.0.6\wlp\usr\servers\defaultServer
now add required dependencies in pom.xml
I am using spring boot version 2.1.4.release and following are important dependecies which will be required:
<dependency>
<groupId>com.ibm.mq</groupId>
<artifactId>mq-jms-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>
now change the wlp server.xml as follows:
<!-- Enable features -->
<featureManager>
<feature>webProfile-8.0</feature>
<feature>localConnector-1.0</feature>
<feature>jndi-1.0</feature>
<feature>jaxws-2.2</feature>
<feature>transportSecurity-1.0</feature>
<feature>wmqJmsClient-2.0</feature>
<feature>jsp-2.3</feature>
<feature>servlet-4.0</feature>
<feature>jms-2.0</feature>
<feature>javaee-8.0</feature>
</featureManager>
<!-- Define an Administrator and non-Administrator -->
<basicRegistry id="basic">
<user name="admin" password="adminpwd"/>
<user name="nonadmin" password="nonadminpwd"/>
</basicRegistry>
<!-- Assign 'admin' to Administrator -->
<administrator-role>
<user>admin</user>
</administrator-role>
<!-- Automatically expand WAR files and EAR files -->
<applicationManager autoExpand="true"/>
<applicationMonitor updateTrigger="mbean"/>
<variable name="wmqJmsClient.rar.location" value="path\to\wlp-webProfile8-19.0.0.6\wlp\usr\servers\defaultServer\wmq\wmq.jmsra.rar"/>
<jmsQueueConnectionFactory jndiName="jms/ConnectionFactory" id="QueueConnectionFactory ">
<properties.wmqJms channel="channelName" headerCompression="NONE" hostName="host name" messageCompression="RLE" port="1414" queueManager="qmgrName" sslCipherSuite="TLS_RSA_WITH_AES_256_CBC_SHA256" targetClientMatching="true" transportType="CLIENT" temporaryModel="SYSTEM.DEFAULT.MODEL.QUEUE" pollingInterval="5s" rescanInterval="5s"/>
<connectionManager connectionTimeout="180s" maxPoolSize="20" minPoolSize="1" reapTime="180s" agedTimeout="0" maxIdleTime="30m"/>
</jmsQueueConnectionFactory>
<jmsQueue id="JMSQueue" jndiName="jms/testInQueue">
<properties.wmqJms putAsyncAllowed="DISABLED" readAheadAllowed="ENABLED" receiveConversion="CLIENT_MSG" targetClient="JMS" baseQueueName="queueName" baseQueueManagerName="qmgrName" failIfQuiesce="true" persistence="APP"/>
</jmsQueue>
<!-- <wmqJmsClient nativeLibraryPath="C:\Users\n78724\CRAS\resource adapter\lib"/> -->
<resourceAdapter id="resourceAdapter"
location="${wmqJmsClient.rar.location}">
<customize></customize>
</resourceAdapter>
<ssl id="keyAndTrustStore" keyStoreRef="defaultKeyStore" sslProtocol="TLSv1.2" trustStoreRef="defaultTrustStore"/>
<keyStore id="defaultKeyStore" location="path\to\wlp-webProfile8-19.0.0.6\wlp\usr\servers\defaultServer\resources\security\keyandtruststore.jks" password="secret"/>
<keyStore id="defaultTrustStore" location="path\to\wlp-webProfile8-19.0.0.6\wlp\usr\servers\defaultServer\resources\security\keyandtruststore.jks" password="secret"/>
<enterpriseApplication id="Test-ear" location="Test-ear.ear" name="Test-ear"/>
start the server
hope it helps.

Spring boot logbcak to file is not working on tomcat

I am running spring boot as War on tomcat with logback to console and file.
as long as i run as Java application it is fine i can see logs in console and file.
but i dont see logs printed to file when run on server.
I tried setting logger manager also, didnt work. was wondering to know if some one has faced similar issue.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
<property name="LOG_FILE_MAX_SIZE" value="10MB" />
<property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
<property name="LOG_FILE_MAX_HISTORY" value="20" />
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>
Verify that you have the following dependency :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
or even if you have spring-boot-starter-web dependency added, logging should work.
and have the following in yml or properties file :
logging.path=logs
logging.file=${logging.path}/log.log
logging.pattern.file=%d{dd-MM-yyyy HH:mm:ss.SSS} [%thread] %-5level %logger{36}.%M - %msg%n
and you can also have a logback.xml and use the spring default base.xml in that so that all default spring configurations apply for your logging as well :
logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<logger name="org.springframework.web" level="DEBUG"/>
</configuration>
Here is my logback-spring.xml which i have
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<include resource="org/springframework/boot/logging/logback/file-appender.xml" />
<property name="LOG_FILE"
value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}/}app.log}"/>
<property name="LOG_FILE_MAX_SIZE" value="10MB" />
<property name="LOG_TOTAL_SIZE_CAP" value="100MB" />
<property name="LOG_FILE_MAX_HISTORY" value="20" />
<root level="INFO">
<appender-ref ref="FILE" />
</root>
</configuration>
I could fix it by writing the logs to a different folder looks application doesn't have write access the path, however i need to make some changes to springboot main class for loading application props based profile, please find the class below. not sure if others had to the same.
anyway i am glad it is working finally:)
public class Application extends SpringBootServletInitializer{
public String PROFILE = null;
private static String CONFIG_LOCATION = null;
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
//Grab the active profile from the servlet conext
PROFILE = servletContext.getInitParameter("spring.profiles.active");
CONFIG_LOCATION = servletContext.getInitParameter("spring.config.path");
super.onStartup(servletContext);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
//...and pass it to the boot application
application.application().setAdditionalProfiles(PROFILE);
return application.sources(Application.class).properties(getProperties());
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
//For Loading config from server
static Properties getProperties() {
Properties props = new Properties();
props.put("spring.config.location", CONFIG_LOCATION);
return props;
}
}
web.xml
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
</context-param>
<context-param>
<param-name>spring.config.path</param-name>
<param-value>classpath:app.config/</param-value>
</context-param>

Error setting rewrite jetty 9.4.8

I'm trying to set url rewrite in jetty 9.4.8.
I am using configuration file below:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure.dtd">
<Configure class="org.eclipse.jetty.server.handler.ContextHandler">
<Set name="handler">
<New id="Rewrite" class="org.eclipse.jetty.rewrite.handler.RewriteHandler">
<Set name="handler">
<New class="org.eclipse.jetty.webapp.WebAppContext">
<Set name="contextPath">/QuestionWeb</Set>
<Set name="war"><SystemProperty name="jetty.base"/>\QuestionWeb.war</Set>
<Set name="extractWAR">true</Set>
<Set name="copyWebDir">true</Set>
</New>
</Set>
<Set name="rewriteRequestURI">true</Set>
<Set name="rewritePathInfo">false</Set>
<Set name="originalPathAttribute">requestedPath</Set>
<Call name="addRule">
<Arg>
<New class="org.eclipse.jetty.rewrite.handler.RewritePatternRule">
<Set name="pattern">/test</Set>
<Set name="replacement">/question</Set>
</New>
</Arg>
</Call>
</New>
</Set>
</Configure>
After starting the java -jar server start.jar, redirection only works first to access the address:
http://localhost:8080/QuestionWeb/queston
Then access the address:
http://localhost:8080/QuestionWeb/test
If I try to access address "http://localhost:8080/QuestionWeb/test" before that address "http://localhost:8080/QuestionWeb/queston" I get error status 404.
My Servelt Code:
#WebServlet("/question")
public class QuestonServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss:SSS");
public QuestonServlet() { }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().append(df.format(Calendar.getInstance().getTime())).append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

Spring+Hibernate- Getting 404 exception

I am new to Spring and Hibernate and I would like to create Restful Web services using these technologies.
I am getting 404 exception when calling the URL http://localhost:8080/RakeshMavenProject/book.
I have created controller,service,Dao classes and mentioned the configuration parameters in AppConfig.java
#Configuration
#EnableTransactionManagement
#ComponentScans(value = {#ComponentScan("com.example.ws.maven_web_service_project.service"),
#ComponentScan("com.example.ws.maven_web_service_project.dao")})
public class AppConfig {
#Bean
public LocalSessionFactoryBean sessionFactoryBean(){
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan(new String[] { "com.example.ws.maven_web_service_project.model" });
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/hibernate_test");
ds.setUsername("root");
ds.setPassword("root");
return ds;
}
private Properties hibernateProperties(){
Properties props = new Properties();
props.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
props.put("hibernate.show_sql", "true");
props.put("hibernate.hbm2ddl.auto", "update");
// Setting C3P0 properties
props.put("hibernate.c3p0.min_size", 5);
props.put("hibernate.c3p0.max_size", 20);
props.put("hibernate.c3p0.acquire_increment",
1);
props.put("hibernate.c3p0.timeout", 1800);
props.put("hibernate.c3p0.max_statements", 150);
return props;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(SessionFactory s){
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(s);
return txManager;
}
}
The code of server.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--><!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
--><Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener"/>
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
This connector uses the NIO implementation. The default
SSLImplementation will depend on the presence of the APR/native
library and the useOpenSSL attribute of the
AprLifecycleListener.
Either JSSE or OpenSSL style configuration may be used regardless of
the SSLImplementation selected. JSSE style configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true">
<SSLHostConfig>
<Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443 with HTTP/2
This connector uses the APR/native implementation which always uses
OpenSSL for TLS.
Either JSSE or OpenSSL style configuration may be used. OpenSSL style
configuration is used below.
-->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
maxThreads="150" SSLEnabled="true" >
<UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
<SSLHostConfig>
<Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
certificateFile="conf/localhost-rsa-cert.pem"
certificateChainFile="conf/localhost-rsa-chain.pem"
type="RSA" />
</SSLHostConfig>
</Connector>
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443"/>
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine defaultHost="localhost" name="Catalina">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/>
</Realm>
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t "%r" %s %b" prefix="localhost_access_log" suffix=".txt"/>
<Context docBase="RakeshMavenProject" path="/RakeshMavenProject" reloadable="true" source="org.eclipse.jst.jee.server:RakeshMavenProject"/></Host>
</Engine>
</Service>
</Server>
Update : I am mentioning the code of my controller class
#RestController
public class BookController {
#Autowired
private BookService bookService;
//#PostMapping("/book")
#RequestMapping(value="/book/", method= RequestMethod.POST,headers="Accept=application/json")
public #ResponseBody ResponseEntity<?> saveBook(#RequestBody Book book){
int bookId = bookService.saveBook(book);
return ResponseEntity.ok().body("Your Book with Id "+ bookId +" save successfully.");
}
// #GetMapping("/book/{id}")
#RequestMapping(value="/book/{id}", method= RequestMethod.GET,headers="Accept=application/json")
public #ResponseBody ResponseEntity<Book> getBook(#PathVariable("id") int bookId){
Book book = bookService.getBook(bookId);
return ResponseEntity.ok().body(book);
}
#RequestMapping(value="/book/", method= RequestMethod.GET,headers="Accept=application/json")
public #ResponseBody ResponseEntity<List<Book>> list() {
List<Book> books = bookService.listBooks();
return ResponseEntity.ok().body(books);
}
}
Please anyone help me to find the solution.
You need to specify mapping either at controller level #RestContoller('myController') or at each method level like
#RequestMapping(value="myController/book/", method= RequestMethod.POST,headers="Accept=application/json")
The your url will be http://localhost:8080/RakeshMavenProject/myController/book.
Your request mapping has a typo. try using
#RequestMapping(value="/book") or access your app using http://localhost:8080/RakeshMavenProject/book/
It should work fine if there are no further error.

How to use PayloadLoggingInterceptor and SOAPLoggingInterceptor interceptors while consuming a third party web service

In my application, I am consuming a third party web-service that is provided by my client.
I have developed my application on Spring and Hibernate framework and in one module I am consuming this third party web-service url. I have generated web-service stubs using
javab2-maven-plugin
The maven plugin in declared as below in my pom.xml file :
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>1.5</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- Package to store the generated file -->
<packageName>com.equifax.unsolicited.wsdl.stub</packageName>
<!-- Treat the input as WSDL -->
<wsdl>true</wsdl>
<!-- Input is not XML schema -->
<xmlschema>false</xmlschema>
<!-- The WSDL file that you saved earlier -->
<schemaFiles>Duk_CIS_Send_CreditStatus.wsdl</schemaFiles>
<!-- The location of the WSDL file -->
<schemaDirectory>${project.basedir}/src/main/wsdl</schemaDirectory>
<!-- The output directory to store the generated Java files -->
<outputDirectory>${project.basedir}/src/main/java</outputDirectory>
<!-- Don't clear output directory on each run -->
<clearOutputDir>false</clearOutputDir>
</configuration>
</plugin>
And I am using the auto-generated JAXB java classes to call the web service. I have created a service bean which call the web service :
#Service("unsolicitResponseService")
public class UnsolicitResponseServiceImpl implements UnsolicitResponseService{
private static final Logger LOGGER = Logger.getLogger(UnsolicitResponseServiceImpl.class);
#Autowired
private WebServiceTemplate webServiceTemplate;
#Override
public void sendUnsolicitResponse() {
LOGGER.debug("Calling Duke Web Service to Send Unsolicit Response ... ");
try{
ObjectFactory objecFactory = new ObjectFactory();
CreditStatusMsgType creditStatusMessage = objecFactory.createCreditStatusMsgType();
creditStatusMessage.setMessageHeader(createMessageHeader(objecFactory));
//WRAP THE CLASS AS THE INSTANCE OF JAXBELEMENT OTHERWISE IT WILL THROW MISSING ROOTELEMENT ERROR
JAXBElement<CreditStatusMsgType> creditStatusMessageJaxbElement = objecFactory.createSendCreditStatus(creditStatusMessage);
//CREATE STRING WRITER TO LOG THE REQUEST
Object response = this.webServiceTemplate.marshalSendAndReceive(creditStatusMessageJaxbElement);
LOGGER.debug("Jumio Web Service Response Reponse :"+response);
LOGGER.debug("Unsolicit Response sent to Duke Successfully.");
}catch(Exception ex){
LOGGER.error("Exception generated while calling Web Service to send unsolicit Response : "+ex.getLocalizedMessage(),ex);
}
}
Below is the xml configuration where I have declared interceptors to log the request and response :
<?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:sws="http://www.springframework.org/schema/web-services"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<!-- DEFINE SOAP VERSION USED BY A WSDL -->
<bean id="soapMessageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory">
<property name="soapVersion">
<!-- FOR TEXT/XML -->
<util:constant static-field="org.springframework.ws.soap.SoapVersion.SOAP_11"/>
</property>
</bean>
<!-- LOCATION OF THE GENERATED JAVA FILEs -->
<oxm:jaxb2-marshaller id="marshaller" contextPath="com.equifax.unsolicited.wsdl.stub"/>
<!-- CONFIGURE THE SPRING WEB SERVICE -->
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="soapMessageFactory"/> <property name="marshaller" ref="marshaller"/>
<property name="unmarshaller" ref="marshaller"/>
<property name="defaultUri" value="https://partnerstg.duke-energy.com:4443/DukCISSendCreditStatus?wsdl"/>
</bean>
<sws:interceptors>
<bean id="jumioPeyLoadLoggingInterceptor" class="com.test.datasource.logging.interceptor.PayloadLoggingInterceptor">
</bean>
<bean id="jumioSOAPLoggingInterceptor" class="com.test.datasource.logging.interceptor.SOAPLoggingInterceptor">
</bean>
</sws:interceptors>
</beans>
And I also have added and new logging category to enable the logger level to DEBUG mode :
Above code is calling the web service successfully. But the interceptors are not getting called. So I am not able to log the XML request and response.
Here, I am assuming that, these interceptors will not work while consuming the service. Let me know if I am wrong here.
I am referring Spring Web Service from HERE . This website has given explanation interceptors while publishing a web-service.
Kindly let me know should we use this interceptors while consuming a web-service ? Or How should I print request and response which are JAXB-ELEMENT ?
I am adding here solution which I have implemented. There are two ways by which we can implement this solution. I have implemented the second one from below list using JAXBContext and Marshaller.
1> Log Request/Response By interceptor.
We can not use PayloadLoggingInterceptor or SOAPLoggingInterceptor when we are consuming the web service.
We need to use ClientInterceptor when we are consuming the web service. ClientInterceptor is implemented by PayloadValidatingInterceptor class which is used to intercept the request/response and validate the it based on xsd schema.
For that we need to provide interceptor reference as below :
<bean id="MyPayloadValidatingInterceptor" class="com.equifax.ic.datasource.jumio.ws.logging.interceptor.JumioPayloadValidatingInterceptor">
<property name="schema" value="file:WebContent/WEB-INF/schemas/account-balance-service.xsd" />
<property name="validateRequest" value="false" />
<property name="validateResponse" value="false" />
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="soapMessageFactory"/> <property name="marshaller" ref="marshaller"/>
<property name="unmarshaller" ref="marshaller"/>
<property name="defaultUri" value="https://partnerstg.duke-energy.com:4443/DukCISSendCreditStatus?wsdl"/>
<property name="interceptors">
<list>
<ref bean="MyPayloadValidatingInterceptor"/>
</list>
</property>
</bean>
2> Log Request/Response by using JAXBContext
This is the solution which I have implemented in my application as we should not use PayloadValidatingInterceptor only to log reqeust/response.
private void logJAXBRequest(JAXBElement<CreditStatusMsgType> creditStatusMessageJaxbElement){
LOGGER.debug("Logging Web Service Request ...");
StringWriter writer = null;
StreamResult streamResult = null;
StringBuffer buffer = null;
try{
writer = new StringWriter();
streamResult = new StreamResult(writer);
JAXBContext jaxbContext = JAXBContext.newInstance(CreditStatusMsgType.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.marshal(creditStatusMessageJaxbElement, streamResult);
buffer = writer.getBuffer();
LOGGER.debug("JAXB Webservice Request : "+ buffer.toString());
writer.close();
}catch(Exception ex){
LOGGER.error("Exception generated while creating XML Logs of JAXB Request :",ex);
}
}
He everyone, colleagues.
There are two main ways to show XML requests / responses:
First of all you have to add log4j dependency into your pom.xml file:
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
Then you have to place log4j.properties file into a classpath of your application. When I develop SOAP services I often use Spring WS Maven artefact. Unfortunately, a usual resources folder is not created from scratch and you have to create it manually. Then you place log4j.properties file there. The contents of log4j config depends on the approach you want to use (see items below). Obtained structure is following:
Use a standard Message Logging and Tracing approach & log4j.properties file. Nothing should be configured, developed, written except log4j config file contents. The contents of log4j config should be the following (use these contents as is):
log4j.rootCategory=DEBUG, stdout
log4j.logger.org.springframework.ws.client.MessageTracing.sent=TRACE
log4j.logger.org.springframework.ws.client.MessageTracing.received=DEBUG
log4j.logger.org.springframework.ws.server.MessageTracing=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%p [%c{3}] %m%n
Use a PayloadLoggingInterceptor & log4j.properties file. Some config changes should be applied, but this approach is more flexible, as for me. First of all you have to add PayloadLoggingInterceptor into a MessageDispatcherServlet config 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:context="http://www.springframework.org/schema/context" xmlns:sws="http://www.springframework.org/schema/web-services" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.ln.springws"/>
<sws:annotation-driven/>
<sws:interceptors>
<bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />
</sws:interceptors>
<sws:dynamic-wsdl id="holiday" portTypeName="HumanResource" locationUri="http://localhost:8080/holidayService/" targetNamespace="http://spring-ws-holidays.com/hr/definitions">
<sws:xsd location="/WEB-INF/hr.xsd"/>
</sws:dynamic-wsdl>
</beans>
And at last place the following contents to log4j.properties file:
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c] - <%m>%n
And as a result of both approaches you will have something like that in a console:

Resources