Swagger implemetation Spring Web MVC not display model Schema - spring

I am trying to implementing Spring Web MVC with Swagger but problem is I could not getting model Schema.
I am attaching code with question which is given blow.
I'm following the below link:
http://raibledesigns.com/rd/entry/documenting_your_spring_api_with
the issue was that Swagger UI was displaying but for the post request it was not displaying the model schema.
POM.XML:
<dependency>
<groupId>com.mangofactory</groupId>
<artifactId>swagger-springmvc</artifactId>
<version>0.5.2</version>
</dependency>
Spring.xml:
<mvc:annotation-driven />
<context:component-scan base-package="com.ga" />
<mvc:default-servlet-handler />
<bean id="documentationConfig" class="com.mangofactory.swagger.configuration.DocumentationConfig" />
<context:property-placeholder location="classpath:spring/application.properties"
system-properties-mode="OVERRIDE" />
Customer Controller.java:
#Api(value="CustomerController",description="Customer Controller")
#RestController
public class CustomerController {
#ApiOperation(value="save",notes="These Method is used to Save all Customer Details with its Deployment ")
#RequestMapping(value = "/save", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Customer> saveCustomerDetails(#RequestBody Customer customer) throws CustomerException {
}
}
Application properties:
documentation.services.version=1.0
documentation.services.basePath=http://localhost:9090/XYZ

I just found the solution of the above issue.I just configure the swagger in my code internally.
i followed these link to configure the swagger.
https://github.com/ufasoli/spring-mvc-swagger-tutorial.
These really works for me.

Related

View not getting resolved in Spring mvc gradle application

web application is made with gradle sts project
i've added view Resolver like this
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".html" />
</bean>
it is hitting the url but wont return any view
#Controller
public class HomeController {
#RequestMapping(value = DatahubClientConstant.CLIENT_URL , method = RequestMethod.GET )
public ModelAndView getTestPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
//System.out.println("Hello World");
return new ModelAndView("home");
}
}
Tried to sysout it works
It doesnt return any view?
After Some Research i have found out that InternalViewResolver does not resolve html pages directly that's why i was not able to get the view.
Spring MVC ViewResolver not mapping to HTML files
This was a helpful question in resolving the issue. All it is doing is loading the html as static content.

How do I get my Spring Aspect to kick in for a #Valid annotation on a service method?

We're using Spring 3.2.11.RELEASE and Maven 3.0.3. I'm trying to set up validation of a parameter being passed into a service method. The method is below. Notice the #Valid annotation.
package org.mainco.subco.mypck.service;
#Service
#RemoteProxy
#Transactional
public class MypckServiceImpl implements MypckService {
#RemoteMethod
#Override
public String myMethod(#Valid final MyObjectDto request) {
// ...
}
}
Here is the aspect I have set up to help validate the object:
#Aspect
#Component
public class MyObjectValidatingAspect extends AbstractDWRAspectValidator<MyObjectDto>
{
#Before("execution(* org.mainco.subco.mypck.service.MypckService.myMethod(..))")
public void validateBefore(JoinPoint jp)
{
errors = new ArrayList<String>();
final MyObjectDto request = validate(jp);
validateMyObject(request);
throwErrors();
} // validateBefore
This is in included in my application context file:
<global-method-security pre-post-annotations="enabled">
</global-method-security>
<aop:aspectj-autoproxy/>
And this is what I've included in the Maven pom.xml file:
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.2</version>
</dependency>
Unfortunately when the method is invoked, the aspectj's validateBefore is never called. What else do I need to do so that this gets invoked?
Since Spring 3.1 there is the MethodValidationInterceptor which basically does what you want to achieve yourself. To have this interceptor applied the only thing you need to do is to register a MethodValidationPostProcessor in your application context.
By default it will check for the #Validated annotation from Spring but you can instruct it to scan for the #Valid annotation.
<bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor">
<property name="validatedAnnotationType" value="javax.validation.Valid" />
<property name="validator" ref="refToYOurLocalValidatorFactoryBean" />
</bean>
If you don't specify a validator the default JSR-303 validator mechanism will be used (or the more hibernate specific one if that is available). But I can imagine you want to reuse the already configured instance.

Consume webservice service in SPRING-WS using wsdl

I have WSDL with me .eg: /sample/hello?wsdl . I want to invoke the service the webservice by configuring in Spring-ws. I passed this wsdl as parameter to tags in springconfig.xml.
Can anyone please tell me how to consume this webservice in Spring-ws.
1. Set up project dependencies
add the following dependencies to the pom file:
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.1.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.2.5</version>
</dependency>
2. Set up web service application context
<?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-3.1.xsd">
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="contextPath" value="com.yourcomany.model" />
</bean>
<bean id="webServiceTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="marshaller" ref="marshaller"></property>
<property name="unmarshaller" ref="marshaller"></property>
<property name="messageSender">
<bean
class="org.springframework.ws.transport.http.HttpComponentsMessageSender" />
</property>
<property name="defaultUri"
value="http://<hostname>:<portnumber>/sample/hello" />
</bean>
</beans>
3. Set up model classes which would map to your SOAP request/response objects
For example, if your SOAP request XML looked like
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xxx="http://yourcomapny.com">
<soapenv:Header/>
<soapenv:Body>
<xxx:InputParameters>
<xxx:paramONE>1</xxx:paramONE>
</xxx:InputParameters>
</soapenv:Body>
</soapenv:Envelope>
and your SOAP response XML looked like:
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header>
...
</env:Header>
<env:Body>
<xxx:OutputParameters xmlns:xxx="http://yourcompany.com">
<xxx:paramONE>0</xxx:paramONE>
</xxx:OutputParameters>
</env:Body>
</env:Envelope>
the corresponding classes (under the package you specified in the marshaller bean: com.yourcompany.model) would be respectively:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "paramONE" })
#XmlRootElement(name = "InputParameters", namespace = "http://yourcompany.com")
public class InputParameters {
#XmlElement(required = true, namespace = "http://yourcompany.com")
private String paramONE;
public String getParamONE() {
return paramONE;
}
public void setParamONE(String paramONE) {
this.paramONE = paramONE;
}
}
and
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "paramONE" })
#XmlRootElement(name = "OutputParameters", namespace = "http://yourcompany.com")
public class OutputParameters {
#XmlElement(required = true, namespace = "http://yourcompany.com")
private BigDecimal paramONE;
public BigDecimal getParamONE() {
return this.paramONE;
}
public void setParamONE(BigDecimal paramONE) {
this.paramONE= paramONE;
}
}
4. Add an Object Factory (under package com.yourcompany.model) to create request/response objects
#XmlRegistry
public class ObjectFactory {
public ObjectFactory() {
}
public InputParameters createYourRequest() {
return new InputParameters();
}
public OutputParameters createYourResponse() {
return new OutputParameters();
}
}
5. Create a client to consume the service
Interface:
public interface YourService {
BigDecimal getValue(String paramOne);
}
Implementation
#Component("yourServiceClient")
public class YourServiceClient implements YourService {
private static final ObjectFactory WS_CLIENT_FACTORY = new ObjectFactory();
private WebServiceTemplate webServiceTemplate;
#Autowired
public YourServiceClient(WebServiceTemplate webServiceTemplate) {
this.webServiceTemplate = webServiceTemplate;
}
#Override
public BigDecimal getValue(String paramOne) {
InputParameters request = WS_CLIENT_FACTORY
.createYourRequest();
request.setParamONE(paramOne);
OutputParameters response = (OutputParameters) webServiceTemplate
.marshalSendAndReceive(request);
return response.getParamONE();
}
}
#Taoufik Mohdit answer is complete!!
To build the input and output objects you can use Webservice-Client: Common approach with Spring WS, JAXB and just one WSDL file? to some how build these objects automatically
Given that this question is still active I thought I would post an update that reflects a number of changes that the recent version of the Spring Web Services framework and Spring in general introduce:
The introduction of Spring Boot allows to leverage 'starter' POMs to simplify your Maven configuration. There is a specific spring-boot-starter-web-services starter for Spring-WS
Instead of specifying Spring configuration files using XML, Spring JavaConfig was introduced which provides a type-safe, pure-Java option for configuring Spring.
Generation of request/response objects based on a given WSDL file can be automated using Maven plugins. The plugin used by the Spring-WS examples is the maven-jaxb2-plugin.
The WebServiceTemplate is still the core class for client-side Web service access. For more information you can check this detailed example on how to consume a web service using Spring-WS starting from a WSDL file that I wrote.

Bypassing ViewResolver using #ResponseBody & Method Converters for JSON and XML only works for JSON

I'm creating a RESTful API that returns JSON or XML depending on the Accept header (application/json vs text/xml). I have this working fine for JSON but can't seem to get it working when for XML. I am testing using the Poster plugin client for Firefox.
I was under the impression that I just needed to add the Jackson and JAXB libraries to the app's classpath. Again, it works for JSON but not XML.
Originally I was getting 406 error when sending the Accept "text/xml" header. Then I added #XmlRootElement(name="contact") to my entity and now I'm getting a 500 error. Should I need to put #XmlRootElement on every entity?
Although the response is a 500 error, I don't see any errors reported in the console. I'm testing in Eclipse running Tomcat 7. Shouldn't i see some error in the console when i receive a 500 error?
My "mvc-dispatcher-servlet.xml" has <mvc:annotation-driven />
Here's the relevant code from my controller:
#Controller
#RequestMapping("/contacts")
public class ContactsController {
#Autowired
ContactsService contactsService;
#RequestMapping(value="/{id}",
method=RequestMethod.GET,
headers = {"Accept=application/json, text/xml"})
public #ResponseBody Contact getContact(#PathVariable("id") int id) {
Contact queryContact = new Contact(id);
Contact result = contactsService.getContact(queryContact);
return result;
}
}
The "mvc-dispatcher-servlet.xml" is really simple. Do I need anything other than:
<context:component-scan base-package="contactsapp.web.controller" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/"/>
I'm using Spring 3.1 and the following:
<dependency org="com.sun.xml.bind" name="jaxb-impl" rev="2.2.5-b10" conf="runtime->default"/>
<dependency org="org.codehaus.jackson" name="jackson-mapper-asl" rev="1.7.1" conf="runtime->default"/>
You should put
#XmlRootElement on Contact class to tell jackson how to parse.
It turns out I had it configured correctly. Once I enabled more verbose logging I realized I had circular dependencies in my entity classes and had to add #XmlTransient on those fields

Spring AOP and apache shiro configuration.Annotations not been scanned

I've been struggling with a configuration which requires a knowledge in AOP.
i must admit that AOP is that part i'm trying to get for a while without success.
It seems that my shiro annotations are not scanned and thus are ignored.
i've tried using shiro 1.1.0+ maven3+spring 3.0.5.RELEASE, hibernate 3.6.1.Final with ZK 5.0.6.
i got my hibernaterealm working , talking to database, i got the authentication working, i successfully(i believe) get the roles and permission loaded.
so to test the authorization side i have somewhere in my code this :
Subject currentUser = SecurityUtils.getSubject();
if (!currentUser.isPermitted("businessaccount:list")) {
throw new AuthorizationException("User not authorized");
}
and it works fine.
So i know my permissions were loaded.i'll be convenient for me using annotations to i've put it in implementation class, because i didn't plan on using interface at first place with my controller classes which are extending ZK GenericForwardController.
i've seen this bug and i've decided to do a try with one interface with the #RequiresPersmissions on methods.
apparently it's still not working as in it's giving access to unauthorized subject.there is no error in my log.Maybe i'm doing something wrong here are snippet of the codes:
#Component("layouteventhandler")
public class LayoutEventHandlerImpl extends GenericForwardComposer implements LayoutEventHandler {
Logger logger = Logger.getLogger(LayoutEventHandlerImpl.class);
Menuitem logout;
//...
#Override
public void onClick$pAccounts() {
try {
execution.sendRedirect("/accounts/personal/list");
} catch (Exception ex) {
logger.info("Error redirecting to personal accounts", ex);
}
}
#Override
public void onClick$bAccounts() {
try {
execution.sendRedirect("/accounts/business/list");
} catch (Exception ex) {
logger.info("Error redirecting to business accounts", ex);
}
}
//.....
}
its interface it :
public interface LayoutEventHandler {
#RequiresPermissions(value="personalaccount:list")
public void onClick$pAccounts();
#RequiresPermissions(value="businessaccount:list")
public void onClick$bAccounts();
//.....
}
here is my shiro applicationcontext
<bean id="hibernateRealm" class="com.personal.project.admin.webapp.security.DatabaseRealm" />
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="hibernateRealm" />
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator"
depends-on="lifecycleBeanPostProcessor">
<!-- <property name="proxyTargetClass" value="true" />-->
</bean>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!-- Secure Spring remoting: Ensure any Spring Remoting method invocations can be associated
with a Subject for security checks. -->
<bean id="secureRemoteInvocationExecutor" class="org.apache.shiro.spring.remoting.SecureRemoteInvocationExecutor">
<property name="securityManager" ref="securityManager"/>
</bean>
<!-- ... -->
is it in there something that i should do? thanks for reading and helping out
I don't know Shiro, but I'm guessing that you've put annotations on your bean classes which implement interfaces and then you're proxying them for security, transactions, and/or something else. When that happens, the object that's returned is a JDK dynamic proxy, which isn't an instance of your bean's concrete class, only of the interface it implements. Therefore any annotation scanning that depends on annotations in the concrete class won't find them.
To expand on Ryan Stewart's answer, you need to add
#Scope(proxyMode = ScopedProxyMode.TARGET_CLASS)
to the implementing class (not the interface) and move the Shiro annotations to it.
I encountered a similar problem when I was running two spring contexts. There is a parent root context that defined Database, Service, Security and non-SpringMVC web beans and a child web context for a Spring MVC REST api which contained the Controllers I want to proxy. The Configuration for each context was class path scanning separate packages.
In this case make sure that the DefaultAdvisorAutoProxyCreator and the AuthorizationAttributeSourceAdvisor beans that are requied are defined in the child web context (i.e. where the Rest Controllers are class path scanned) as defining them in the parent context does not work (the documentation on the DefaultAdvisorAutoProxyCreate is quite clear about this in hindsight!).
Posting this in case someone else encounters the same issue.

Resources