I need to embeed a LDAP server with spring for testing purposes. The following code works:
src/main/webapp/WEB-INF/web.xml
[...]
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
[...]
com.example.config.servlet.TestLDAPServerConfiguration
</param-value>
</context-param>
[...]
src/main/java/com/example/config/servlet/TestLDAPServerConfiguration.java
package com.example.config.servlet;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
#Configuration
#ImportResource({"/WEB-INF/test-ldap-server.xml"})
public class TestLDAPServerConfiguration {
}
src/main/webapp/WEB-INF/test-ldap-server.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:s="http://www.springframework.org/schema/security"
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.xsd">
<s:ldap-server ldif="classpath:users.ldif" root="dc=nestle,dc=com" port="33389"/>
</beans>
I do need to use AnnotationConfigWebApplicationContext instead of XmlWebApplicationContext. However, here I am using a class TestLDAPServerConfiguration which just imports a test-ldap-server.xml, and this test-ldap-server.xml just declares the ldap-server.
I'd like to remove the test-ldap-server.xml file. How can I do the equivalent of s:ldap-server with java code inside the TestLDAPServerConfiguration class? And where is this documented?
Try something like this;
protected static ApacheDSContainer server;
#BeforeClass
public static void startServer() throws Exception {
server = new ApacheDSContainer( "dc=yourdomain,dc=com", "classpath:test-server.ldif" );
server.setPort( 53389 );
server.afterPropertiesSet();
server.start();
}
#AfterClass
public static void stopServer() throws Exception {
if( server != null ) {
server.stop();
}
}
You can get guides from the spring-security-ldap source code.
Related
I've created a very simple application (Just an index file), and a Java Servlet filter.
I'm seeing the following error in the logs on deploy from Netbeans:
Deployment is in progress...
deploy?config=file%3A%2FC%3A%2FUsers%2Fuser%2FAppData%2FLocal%2FTemp%2Fcontext490289541373061276.xml&path=/EXD
http://localhost:8080/manager/deploy?config=file%3A%2FC%3A%2FUsers%2Fuser%2FAppData%2FLocal%2FTemp%2Fcontext490289541373061276.xml&path=/EXD
C:\Users\user\Documents\NetBeansProjects\EXDLogger\nbproject\build-impl.xml:1070: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 57 seconds)
There are not any errors in any of the other logs.
Any idea what is going on?
web.xml content:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 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">
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>EXDLogger</filter-name>
<filter-class>com.cn.filters.EXDLogger</filter-class>
<init-param>
<param-name>paramExclude</param-name>
<!-- Parameters which should be excluded from the hash in determining
if a request is unique. Separate multiple values with a ; -->
<param-value>PARAM_1;PARAM_2</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EXDLogger</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Class being called:
package com.cn.filters;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class EXDLogger implements Filter {
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
//Get the IP address of client machine.
String ipAddress = request.getRemoteAddr();
//Log the IP address and current timestamp.
System.out.println("IP "+ipAddress + ", Time "
+ new Date().toString());
chain.doFilter(req, res);
}
public void init(FilterConfig config) throws ServletException {
//Get init parameter
String testParam = config.getInitParameter("paramExclude");
//Print the init parameter
System.out.println("Test Param: " + testParam);
}
public void destroy() {
//add code to release any resource
}
}
I hacked an answer. I'm sure there are better ones. I updated the relevant section of my build-impl.xml as follows:
<target depends="init,-init-cos,compile,compile-jsps,-do-compile-single-jsp,-pre-dist,-do-tmp-dist-with-manifest,-do-tmp-dist-without-manifest,-pre-run-deploy,-pre-nbmodule-run-deploy,-run-deploy-nb,-init-deploy-ant,-deploy-ant,-run-deploy-am,-post-nbmodule-run-deploy,-post-run-deploy,-do-update-breakpoints" name="run-deploy"/>
<target if="netbeans.home" name="-run-deploy-nb">
<!-- <delete dir="${deployTarget}"/> -->
<copy toDir="${deployTarget}" overwrite="true">
<fileset dir="${build.web.dir}"></fileset>
</copy>
<copy toDir="${deployTarget}/WEB-INF/classes" overwrite="true">
<fileset dir="${build.classes.dir}"></fileset>
</copy>
<!-- <nbdeploy clientUrlPart="${client.urlPart}" debugmode="true" forceRedeploy="${forceRedeploy}"/> -->
</target>
I then added to my project.properties:
deployTarget=c:/xampp/tomcat/webapps/EXD
client.url=http://localhost:8080/EXD/
I'm integrating struts2, tiles3 and Freemarker (templates from a DB). The integration is mostly done, but the freemarker renderer is rendering to the result immediately instead of inserting its content into the template at the expected location.
Any advice on how to correct this?
Expected Output:
<!DOCTYPE html>
<html>
<body>
<h1>Template</h1>
<strong>A bold statement!</strong><div>a message from the Action...</div><div> I came from: the_location</div><div>a message from the Action...</div>
</body>
</html>
Actual Output (Not formatted for readability because this is a template issue and not an html issue so accuracy of output counts):
<strong>A bold statement!</strong><div>a message from the Action...</div><div> I came from: the_location</div>
<!DOCTYPE html>
<html>
<body>
<h1>Template</h1>
</body>
</html>
tiles-defs.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN" "http://tiles.apache.org/dtds/tiles-config_3_0.dtd">
<tiles-definitions>
<definition name="test_def2" template="/WEB-INF/template/template.jsp">
<put-attribute name="body" value="the_location" type="db_freemarker"/>
</definition>
</tiles-definitions>
/WEB-INF/template/template.jsp
<%#taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles" %>
<%#taglib prefix="s" uri="/struts-tags"%>
<%#page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<body>
<h1>Template</h1>
<tiles:insertAttribute name="body"/>
</body>
</html>
Created and registered a DbFreemarkerTilesRenderer with key "db_freemarker", this is the implementation of DbFreemarkerTilesRenderer:
package com.quaternion.struts2.result.freemarker;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tiles.request.Request;
import org.apache.tiles.request.freemarker.render.FreemarkerRenderer;
import org.apache.tiles.request.render.CannotRenderException;
import org.apache.tiles.request.servlet.ServletRequest;
public class DbFreemarkerTilesRenderer extends FreemarkerRenderer{
public DbFreemarkerTilesRenderer(){
super(null); //Expects a AttributeValueFreemarkerServlet
}
/** {#inheritDoc} */
#Override
public void render(String location, Request request) throws IOException {
if (location == null) {
throw new CannotRenderException("Cannot dispatch a null path");
}
ServletRequest servletRequest = org.apache.tiles.request.servlet.ServletUtil.getServletRequest(request);
HttpServletRequest httpRequest = servletRequest.getRequest();
HttpServletResponse httpResponse = servletRequest.getResponse();
DataBaseTemplateLoader dataBaseTemplateLoader = new DataBaseTemplateLoader();
try {
dataBaseTemplateLoader.render(location, httpRequest, httpResponse);
} catch (Exception ex) {
Logger.getLogger(DbFreemarkerTilesRenderer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The "DataBaseTemplateLoader" actually loads a freemarker template from a hard coded string, but it will load from a DB once this issue is resolved (see the render method the rest of the class is included for context, Struts2 developers will recognize it as a Result type, the idea being the Freemarker DB functionality can be provided directly to Struts2 as a Result):
package com.quaternion.struts2.result.freemarker;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.inject.Inject;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.ServletDispatcherResult;
import org.apache.struts2.views.freemarker.FreemarkerManager;
import org.apache.struts2.views.util.ContextUtil;
public class DataBaseTemplateLoader extends ServletDispatcherResult {
private static final Logger log = Logger.getLogger(DataBaseTemplateLoader.class.getName());
private String defaultEncoding = "ISO-8859-1"; //TODO: Hardcoded?
private FreemarkerManager freemarkerManager;
private Configuration configuration;
//Inject works if this is a Struts2 component (Result) however
//when using this from Tiles, the following is not injected...
#Inject
public void setFreemarkerManager(FreemarkerManager mgr) {
this.freemarkerManager = mgr;
}
public DataBaseTemplateLoader() {
super();
}
public DataBaseTemplateLoader(String location) {
super(location); //TODO: look up template based on "location" string
}
protected Configuration getConfiguration() throws TemplateException {
if (freemarkerManager == null){
//Force injection
freemarkerManager = ActionContext.getContext().getContainer().getInstance(FreemarkerManager.class);
}
return freemarkerManager.getConfiguration(ServletActionContext.getServletContext());
}
#Override
public void doExecute(String location, ActionInvocation invocation) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
render(location, request, response);
}
public void render(String location, HttpServletRequest request, HttpServletResponse response) throws Exception {
//location is String passed from Struts2 action which will formated
//in such a way to apply conventions though to view
//Format: namespace#action#method
//setLocation(location);
StringTemplateLoader stringLoader = new StringTemplateLoader();
//BOTH "name" and "source" will be retrieved from the DB
String name = "firstTemplate";
String source = "<strong>A bold statement!</strong><div>${action.message}</div><div> I came from: " + location + "</div>";
stringLoader.putTemplate(name, source);
// It's possible to add more than one template (they might include each other)
// String secondTemplate = "<#include \"greetTemplate\"><#greet/> World!";
// stringLoader.putTemplate("greetTemplate", secondTemplate);
freemarker.template.Configuration cfg = getConfiguration();
cfg.setTemplateLoader(stringLoader);
Template template = cfg.getTemplate(name);
Map map = ContextUtil.getStandardContext(ActionContext.getContext().getValueStack(), request, response);
response.setContentType("text/html;charset=" + defaultEncoding);
template.process(map, response.getWriter());
}
}
The Struts2 Action (not needed, just shows where "a message from the Action..." comes from:
package com.quaternion.tilesdb.action;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
/**
* Tests Tiles with Freemarker integration, where the freemarker template
* is parsed from a String, this is to allow later integration with freemarker
* database templates
*/
#ParentPackage("quaternion-results")
#Result(type="tiles", location="test_def2")
public class TilesFtlTest2 extends ActionSupport{
private String message = "a message from the Action...";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I just want to close this question off, the answer is I was missing tiles configuration from web.xml (the Freemarker servlet configuration).
Here is the web.xml which allows the above to work:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 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">
<listener>
<listener-class>com.quaternion.struts2.result.freemarker.MoreCompleteAutoloadTilesListener</listener-class>
<!--<listener-class>org.apache.tiles.extras.complete.CompleteAutoloadTilesListener</listener-class>-->
</listener>
<!-- Following is required to enable freemarker(ftl) support-->
<servlet>
<servlet-name>freemarker</servlet-name>
<servlet-class>org.apache.tiles.request.freemarker.servlet.SharedVariableLoaderFreemarkerServlet</servlet-class>
<!-- FreemarkerServlet settings: -->
<init-param>
<param-name>TemplatePath</param-name>
<param-value>/WEB-INF/template/</param-value>
</init-param>
<init-param>
<param-name>NoCache</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>ContentType</param-name>
<param-value>text/html</param-value>
</init-param>
<!-- FreeMarker settings: -->
<init-param>
<param-name>template_update_delay</param-name>
<param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
</init-param>
<init-param>
<param-name>default_encoding</param-name>
<param-value>ISO-8859-1</param-value>
</init-param>
<init-param>
<param-name>number_format</param-name>
<param-value>0.##########</param-value>
</init-param>
<init-param>
<param-name>org.apache.tiles.request.freemarker.CUSTOM_SHARED_VARIABLE_FACTORIES</param-name>
<param-value>tiles,org.apache.tiles.freemarker.TilesSharedVariableFactory</param-value>
</init-param>
<load-on-startup>5</load-on-startup>
</servlet>
<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>/index.action</welcome-file>
</welcome-file-list>
</web-app>
I am new to Struts2. I was trying to execute a simple Struts2 program.
Apparently my struts.xml is not invoking the action.
It shows a warning Server returned http response code 407 for url: "http://struts.apache.org/dtds/struts-2.1.7.dtd in my struts.xml.
struts.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN"
"http://struts.apache.org/dtds/struts-2.1.7.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="hello" class="com.FirstStruts.ExampleStruts" method="execute">
<result name="success">/Helloworld.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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
</web-app>
Action:
package com.FirstStruts;
public class ExampleStruts {
private String f_name;
private String l_name;
public String execute() throws Exception {
System.out.println("Hello. in execeute");
return "success";
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
}
When I try to execute, I am getting the error There is no Action mapped for namespace / and action name ExampleStruts.
I am using the jars mentioned in http://www.nabisoft.com/tutorials/struts2/basic-struts2-project-setup
Could you please help me with it?
Your action is called hello, no ExampleStruts, so it won't find it. Change your struts.xml file:
<action name="ExampleStruts" class="com.FirstStruts.ExampleStruts">
<result>/Helloworld.jsp</result>
</action>
or invoke the action correctly in your index.jsp.
Also, you need to extend your action from ActionSupport, so it will be recognized as an action.
i have two classes which i want to expose as a restful web services using apache cxf and spring but i am unable expose two web services of two different classes.i got a runtime exception while invoking second service.here are my web.xml,applicationcontext.xml and two classes which i am using in my project.plz any one fix this issue
`enter code here` web.xml
--------
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>ApacheCXF Sample Application</display-name>
<!-- Add for Spring support -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener- class>
</listener>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property</param-name>
<param-value>com.iton.restExamples.ServiceOneImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>AnotherCXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.iton.restExamples.ServiceTwoImpl</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/base/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>AnotherCXFServlet</servlet-name>
<url-pattern>/another/*</url-pattern>
</servlet-mapping>
</web-app>
applicatin context.xml
------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<context:component-scan base-package="com.example" />
<!-- <import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-jaxrs-binding.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
-->
<jaxrs:server id="restContainer" address="/">
<jaxrs:serviceBeans>
<ref bean="serviceOne"/>
<ref bean="serviceTwo"/>
</jaxrs:serviceBeans>
</jaxrs:server>
<bean id="serviceOne" class="com.iton.restExamples.ServiceOneImpl"></bean>
<bean id="serviceTwo" class="com.iton.restExamples.ServiceTwoImpl"></bean>
</beans>
ServiceOneImpl.java
---------------
package com.iton.restExamples;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
public class ServiceOneImpl implements ServiceOne {
public ServiceOneImpl() {
// TODO Auto-generated constructor stub
}
#Override
#GET
#Produces("text/plain")
#Path("/one")
public String mesgTwo(#QueryParam("msg") String mesgTwo) {
System.out.println(mesgTwo);
System.out.println("welcome message");
return mesgTwo;
}
}
SeriveTwoImpl.java
-------------------
package com.iton.restExamples;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
public class ServiceTwoImpl implements ServiceTwo {
public ServiceTwoImpl() {
// TODO Auto-generated constructor stub
}
#Override
#GET
#Produces("text/plain")
#Path("/two")
public String mesgTwo(String mesg) {
mesg="Welcome";
System.out.println(mesg);
System.out.println("welcome message in Serive two");
return mesg;
}
}
Try using #Path annotation at class level to differentiate between the two service classes.
When you define the service beans in application context, the address for both the beans is "/".
#Path("/ServiceOne")
public class ServiceOneImpl implements ServiceOne {....}
#Path("/ServiceTwo")
public class ServiceTwoImpl implements ServiceTwo {....}
I have a problem. I wanna create a Job but not when application is started.
I wanna invoke method from pingServcie but is null.
This is my code:
Job class
class MyJob implements Job {
def pingService
#Override
void execute(JobExecutionContext context) throws JobExecutionException {
pingService.checkPing()
}
}
I read somewhere that I need bean with my Service class, because Spring Autowire doesn't work in this case, so I create it (I never work with bean so I don't if this is correct).
I create resources.xml instead of resources.groovy
<?xml version="1.0" encoding="UTF-8"?>
<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">
<bean name="pingService" class="inzynierka.PingService" />
</beans>
But this doesn't work.
Finally, I did something like this.
class MyJob implements Job {
def PingService pingService
#Override
void execute(JobExecutionContext context) throws JobExecutionException {
JobDataMap dataMap = context.getJobDetail().getJobDataMap();
pingService = dataMap.getWrappedMap().get("pingService")
pingService.checkPing()
}
}
I passing params in different class like this
job.getJobDataMap().put("pingService", pingService)
and it works.