I am developing a Jax Ws and i want to add Soap Handler to use for WS authentication. A added a handler chain xml and a Soap Handler class but code never call the Soap Handler's method.I use JDK 8 and Tomcat 7. What can be the problem?
My handler chain xml as below:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE javaee:handler-chains>
<javaee:handler-chains xmlns:javaee="http://java.sun.com/xml/ns/javaee"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<javaee:handler-chain>
<javaee:handler>
<javaee:handler-class>com.vw.AuthHandler
</javaee:handler-class>
</javaee:handler>
</javaee:handler-chain>
</javaee:handler-chains>
My Soap Handler class a below:
import java.io.PrintStream;
import java.io.StringReader;
import java.util.Collections;
import java.util.Set;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class AuthHandler implements SOAPHandler<SOAPMessageContext> {
private static PrintStream out = System.out;
#Override
public Set<QName> getHeaders() {
return Collections.emptySet();
}
#Override
public boolean handleMessage(SOAPMessageContext context) {
Boolean outboundProperty = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (!outboundProperty) {
System.out.println("Hello!");
return true;
}
return false;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
System.out.println("Hello!");
return false;
}
#Override
public void close(MessageContext context) {
System.out.println("Hello!");
}
}
My Service is as below:
import javax.ejb.Stateless;
import javax.jws.HandlerChain;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import services.LoginOps;
import utilies.LoginParameters;
#WebService
#HandlerChain (file = "handlers.xml")
#SOAPBinding(style=SOAPBinding.Style.DOCUMENT,use=SOAPBinding.Use.LITERAL,parameterStyle=SOAPBinding.ParameterStyle.WRAPPED)
public class LService {
#WebMethod
public LoginParameters callStr(String str
}
...
Related
So I am attempting to write a basic Rest Controller in Spring Tool Suite with Spring annotations where I hit the endpoint "/health" and I receive the following message upon hitting the endpoint "Kafka Streaming App is healthy".
The only error I receive is the 404 status error when I check on the browser and I have already tried logging please help. I think the problem might be how I am calling the Controller in the Main Application class in Spring.
Main Application Class
package com.eds.kafka.streaming.app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
//import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
//#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
//#Configuration
//#EntityScan(basePackages = {"com.eds.kafka.streaming.model"})
//#ComponentScan(basePackages = { "com.eds.kafka.streaming.service", "com.eds.kafka.streaming.util", "com.eds.kafka.streaming.config", "com.eds.kafka.streaming.controller"}) //"com.tmobile.eds.infosec.volt.encr",
#ComponentScan(basePackages = {"com.eds.kafka.streaming"})
#SpringBootApplication
public class KafkaStreamingAppContainerApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(KafkaStreamingAppContainerApplication.class, args);
}
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(KafkaStreamingAppContainerApplication.class);
}
}
Controller Class
package com.eds.kafka.streaming.controller;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
#EnableAutoConfiguration
#PropertySource("classpath:application-${spring.profiles.active}.properties")
#RestController
public class MainController {
#RequestMapping(method = RequestMethod.GET, value = "/health", produces = "application/json")
#ResponseBody
public ResponseEntity home() {
System.out.println("Controller being configured!");
return new ResponseEntity("Kafka Streaming App is Healthy", HttpStatus.OK);
}
}
Please let me know if you have any advice and if needed I can provide a zipped version of the project if that is needed just message me.
I am trying to apply authentication to a few methods of rest services. So apply the annotation #NameBinding for reference to the class of the filter that will validate the authentication, but when doing the test the service passes the filter (it never enters to validate) showing "El msn es...", when it should return 401 Unauthorized .
NameBinding class:
package api.movil.token;
import javax.ws.rs.NameBinding;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
#Retention(value = RUNTIME)
#Target({TYPE, METHOD})
#NameBinding
public #interface JWTTokenNeeded {
}
Filter class:
package api.movil.token;
import io.jsonwebtoken.Jwts;
import javax.annotation.Priority;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import api.movil.util.KeyGenerator;
import java.io.IOException;
import java.security.Key;
#Provider
#Priority(Priorities.AUTHENTICATION)
#JWTTokenNeeded
public class JWTTokenNeededFilter implements ContainerRequestFilter {
public void filter(ContainerRequestContext requestContext) throws IOException {
System.out.println("entro --------------->");
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
System.out.println("#### authorizationHeader : " + authorizationHeader);
if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
System.out.println("#### invalid authorizationHeader : " + authorizationHeader);
throw new NotAuthorizedException("Authorization header must be provided");
}
String token = authorizationHeader.substring("Bearer".length()).trim();
try {
// Validate the token
KeyGenerator keyGenerator=new KeyGenerator();
Key key = keyGenerator.generateKey();
Jwts.parser().setSigningKey(key).parseClaimsJws(token);
System.out.println("#### valid token : " + token);
} catch (Exception e) {
System.out.println("#### invalid token : " + token);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
}
Rest service class:
package api.movil.servicios;
#Path("/users")
public class UserEndpoint {
#POST
#Path("/getPrueba")
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
#JWTTokenNeeded
public Response getPrueba(#FormParam("msn")String msn){
System.out.println(msn);
return Response.ok("El msn es "+msn).build();
}
}
Class of configuration:
package api.movil.servicios;
import java.util.Set;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
import api.movil.token.JWTTokenNeededFilter;
import api.movil.util.ExceptionHandler;
#ApplicationPath("rest")
public class ApplicationConfigura extends Application {
public Set<Class<?>> getClasses() {
return getRestClasses();
}
//Auto-generated from RESTful web service wizard
private Set<Class<?>> getRestClasses() {
Set<Class<?>> resources = new java.util.HashSet<Class<?>>();
resources.add(UserEndpoint.class);
resources.add(JWTTokenNeededFilter.class);
resources.add(ExceptionHandler.class);
return resources;
}
}
pom.xml:
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.7.0</version>
</dependency>
</dependencies>
I am using the weblogic application server.
This is part of that question.
I want to integrate one system and the system strong required input/output params. The system works by wsdl. That's why I created a web-service on java :
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import java.util.Date;
#SOAPBinding(style=SOAPBinding.Style.DOCUMENT)
public class WebServices {
#WebMethod
public PerformTransactionResult Test2(){
PerformTransactionResult performTransactionResult = new PerformTransactionResult();
performTransactionResult.setErrorMsg("test");
return performTransactionResult;
}
}
my PerformTransactionResult class is:
import org.apache.cxf.aegis.type.java5.XmlType;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "PerformTransactionResult")
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "PerformTransactionResult")
public class PerformTransactionResult {
private String errorMsg;
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
System, which I'm integrating want to get response like that:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<uws:PerformTransactionResult xmlns:uws="http://uws.provider.com/">
<errorMsg>Ok</errorMsg>
</uws:PerformTransactionResult>
</s:Body>
</s:Envelope>
My web-service is getting response:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ns1:Test2Response xmlns:ns1="http://wservices.myhost.lan/">
<return xmlns:ns2="http://wservices.myhost.lan/">
<errorMsg>test</errorMsg>
</return>
</ns1:Test2Response>
</soap:Body>
</soap:Envelope>
As you see, response should return PerformTransactionResult, not Test2Response. How to I implement that task ?
I have a schedule service which gets its job via REST as JSON.
The Resource class:
import java.io.IOException;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import de.fszm.scheduler.controller.SchedulerController;
import de.fszm.scheduler.entities.MySchedule;
#Path("/schedule")
public class ScheduleRESTResource {
#Inject
SchedulerController scheduleController;
#POST
#Path("/job")
#Consumes(MediaType.APPLICATION_JSON)
public void schedule(MySchedule schedule) throws IOException {
scheduleController.buildSchedule(schedule);
}
}
The ScheduleController:
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import de.fszm.scheduler.entities.MySchedule;
#Named
#RequestScoped
public class SchedulerController {
public void buildSchedule(MySchedule schedule) {
System.out.println("Test");
}
}
The SchedulerMain:
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.wildfly.swarm.container.Container;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import de.fszm.scheduler.controller.SchedulerController;
import de.fszm.scheduler.entities.MySchedule;
import de.fszm.scheduler.rest.JaxRSActivator;
import de.fszm.scheduler.rest.ScheduleRESTResource;
public class SchedulerMain {
public static void main(String[] args) {
try {
Container container = new Container();
container.start();
JAXRSArchive appDeployment = ShrinkWrap.create(JAXRSArchive.class);
appDeployment.addResource(ScheduleRESTResource.class);
appDeployment.addResource(JaxRSActivator.class);
appDeployment.addClass(MySchedule.class);
appDeployment.addClass(SchedulerController.class);
appDeployment.addAllDependencies();
container.deploy(appDeployment);
} catch (Exception e) {
e.printStackTrace();
}
}
}
And the MySchedule ist just a POJO
My problem is that when I POST JSON to the I get a NullPointerException for the injected SchedulerController.
I also have a beans.xml in src/main/webapp/WEB-INF and in my pom.xml I have the following dependency for CDI (weld)
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>weld</artifactId>
</dependency>
and
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>1.2</version>
</dependency>
I am using WildFly swarm 1.0.0 beta 6
What did I miss?
I think you are missing the Swarm CDI fraction.
Try adding this to your dependencies instead.
<dependency>
<groupId>org.wildfly.swarm</groupId>
<artifactId>cdi</artifactId>
</dependency>
I'm using spring-mvc version 4.1.6-RELEASE with Junit 4.12 and java 1.7, I have a controller for file uploading who works when I've tested it on server with Browser. But when I try to test it with junit the mockfilemultipart is always empty and I'm sure isn't so in the test class.
This is my servlet-context.xml
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- beans:import resource="../controller-context.xml"/-->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
<context:component-scan base-package="it.isfol.iweb" />
This is the controller
package it.isfol.iweb.controller.pianoattivita;
import it.isfol.iweb.bean.wrappers.PianoAttivitaWrapper;
import it.isfol.iweb.controller.common.IsfolController;
import it.isfol.iweb.exceptions.IWebFatalException;
import it.isfol.iweb.service.pianoattivita.FilePianoAttivitaService;
import it.isfol.iweb.util.SessionConstant;
import java.util.Arrays;
import java.util.Collection;
import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
#Controller
public class UploadPianoAttivitaController extends IsfolController {
/**
*
*/
private static final long serialVersionUID = 5455170192118107020L;
private static final String UPLOAD_PAGE = "upload/upload";
private final Logger logger = LoggerFactory.getLogger(UploadPianoAttivitaController.class);
#Autowired
private FilePianoAttivitaService filePianoAttivitaService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public String uploadHomePage(HttpSession session) {
logger.info("I'm home");
return goToUploadPage(session);
}
#RequestMapping(value = "/uploadInit", method = RequestMethod.GET)
public String uploadPageRedirect(HttpSession session) {
logger.info("redirect into upload");
return goToUploadPage(session);
}
#RequestMapping(value = "/uploadPiano", method = RequestMethod.POST, produces = MediaType.TEXT_PLAIN_VALUE)
#ResponseBody
public String upload(#RequestParam("files[]") MultipartFile[] files, HttpSession session) throws IWebFatalException {
logger.debug("Writing file to disk...");
try {
Collection<PianoAttivitaWrapper> piani = filePianoAttivitaService.getPianoAttivitaWrapperFromFiles(Arrays.asList(files), session.getId());
session.setAttribute(SessionConstant.PIANO_ATTIVITA_LIST_WRAPPER, piani);
} catch (IWebFatalException e) {
throw e;
} catch (Throwable t) {
logger.error(t.getLocalizedMessage(), t);
throw new IWebFatalException(t);
}
return "pianoAttivita";
}
private String goToUploadPage(HttpSession session) {
logger.debug("redirect on upload page");
sessionHelper.clearSessionPianoReference(session);
return UPLOAD_PAGE;
}
public void setFilePianoAttivitaService(FilePianoAttivitaService filePianoAttivitaService) {
this.filePianoAttivitaService = filePianoAttivitaService;
}
}
Then my abstract class for testing
package it.isfol.iweb;
import java.io.IOException;
import java.util.Properties;
import org.junit.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
#WebAppConfiguration(value = "src/main/webapp")
#ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml", "file:src/main/webapp/WEB-INF/spring/appServlet/servlet-context.xml" })
public abstract class IsfolIwebTester extends AbstractJUnit4SpringContextTests {
private final Logger logger = LoggerFactory.getLogger(IsfolIwebTester.class);
private Properties testProperties = new Properties();
#Autowired
private WebApplicationContext webapp;
protected MockMvc mockMvc;
#Before
public void setup() {
logger.debug("reading properties");
try {
testProperties.load(this.getClass().getResourceAsStream("/test-conf.properties"));
this.mockMvc = MockMvcBuilders.webAppContextSetup(webapp).build();
} catch (IOException e) {
logger.error(e.getMessage(), e);
} catch (Throwable e) {
logger.error(e.getLocalizedMessage(), e);
}
}
public String getProperty(String key) {
return testProperties.getProperty(key);
}
}
and finally the test class who extends the class above
package it.isfol.iweb.pianoattivita;
import it.isfol.iweb.IsfolIwebTester;
import org.apache.commons.io.FilenameUtils;
import org.apache.tika.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
public class FilePianoAttivitaTester extends IsfolIwebTester {
private final Logger logger = LoggerFactory.getLogger(FilePianoAttivitaTester.class);
#Test
public void testRunning() {
logger.debug("Test started");
try {
String originalFile = getProperty("test.file.pianoattivita.path");
String originalName = FilenameUtils.getName(originalFile);
byte[] content = IOUtils.toByteArray(getClass().getResourceAsStream(originalFile));
MockMultipartFile file = new MockMultipartFile("testJunit", originalName, null, content);
this.mockMvc.perform(MockMvcRequestBuilders.fileUpload("/uploadPiano").file(file)).andExpect(MockMvcResultMatchers.status().isOk()).andReturn().equals("pianoAttivita");
this.mockMvc.perform(MockMvcRequestBuilders.get("/pianoAttivita")).andExpect(MockMvcResultMatchers.view().name("upload/upload"));
} catch(Throwable t) {
logger.error(t.getLocalizedMessage(), t);
Assert.fail();
}
}
}
In the method upload of UploadPianoAttivitaController when I run Junit the param files[] contain 1 empty MultiPartFile, while when I run it on server and I upload a file from page everything is ok.
The name of your RequestParam for files must match with the MockMultipartFile name.
In your case is "files []" and in the mock is "testJunit", you can watch your HttpServletRequest params in your controller.
Try this way:
MockMultipartFile mockMultipartFile = new MockMultipartFile("file",
"OriginalName.txt",
"text/plain",
rateExceptionsFile);
mockMvc.perform(multipart(BASE_PATH + "/uploadFile")
.file(mockMultipartFile)
.contentType(MediaType.MULTIPART_FORM_DATA))
.andExpect(status().isOk());