Why Swagger not showing all methods in same class? - spring

i'm trying to use swagger with my code , but not all methods are listing in swagger-ui some methods not show
i am using swagger 2.5.0 version ,and spring boot 2.1.0.RELEASE
my user rest controller
#RestController
#RequestMapping(value = "/rest")
public class UserRestController {
#Autowired
private UserService userService;
#RequestMapping(method = RequestMethod.GET, value = "/users")
public Iterator<User> getUsers() {
return userService.getUsers();
}
#RequestMapping(method = RequestMethod.GET, value = "/user/{id}")
public User getUser(#PathVariable("id") Long id) {
return userService.getUser(id);
}
#RequestMapping(method = RequestMethod.POST, value = "/user")
public User save(#RequestBody User user) {
User userValidation = userService.getUser(user.getId());
if (userValidation != null) {
throw new IllegalAddException("username already used !");
}
return userService.save(user);
}
#RequestMapping(method = RequestMethod.DELETE, value = "/user")
public User delete(#RequestBody User user) {
return userService.save(user);
}
}
and this my config code
#Configuration
#EnableSwagger2
public class SwaggerApi {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage("com.social.core.rest")).paths(PathSelectors.ant("/rest/*"))
.build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo("Social API", "Soccial api for gamerz zone.", "API TOS", "Terms of service",
new Contact("yali", "www.social.com", "prg#gmail.com"), "License of API",
"API license URL");
}
}
getUser method not showing in swagger ui , and the method worked when i hit url and already getting data
just three method are showing

I solved this issue by adding more star in paths with me config
paths(PathSelectors.ant("/rest/**"))

Related

Why Swagger ui don't show services in my maven project on Spring?

I have a maven project with swagger, when I try to use http://localhost:8080/swagger-ui.html don´t show nothing like the image Swagger ui:
my dependencies are in version 7.0 (also I try with 6.2 and 6.3) and my code is:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
the controller is:
#RestController
#EnableAutoConfiguration
#SpringBootApplication
#EnableSwagger2
public class Example {
#Autowired
public AlfrescoService alfrescoService;
#ResponseBody
#RequestMapping(value = "/hello", method = RequestMethod.GET)
#ApiOperation(value = "Muestra mensaje", notes = "Retorna mensaje", response = ResponseMessage.class, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
#ApiResponses({
#ApiResponse(code = 200, message = "Documentos obtenidos existosamente.", response = ResponseMessage.class),
#ApiResponse(code = 404, message = "No se encontraron documentos.", response = ResponseMessage.class) })
String home() {
alfrescoService.obtieneSesion();
return "Hello World!";
}
#ResponseBody
#RequestMapping(value = "/", method = RequestMethod.GET)
String manchester() {
alfrescoService.obtieneSesion();
return "United";
}
#ResponseBody
#RequestMapping(value = "/uploadDocument", method = RequestMethod.POST)
String uploadFile(#RequestParam MultipartFile file, #RequestParam String title, #RequestParam String rut,
#RequestParam String userName, #RequestParam int year) throws Exception {
if (file.isEmpty()) {
return "No a ingresado el archivo";
} else {
alfrescoService.upload(file, title, rut, userName, year);
return "OK";
}
}
#ResponseBody
#RequestMapping(value = "/searchDocument", method = RequestMethod.GET)
String searchDocuments(String uuid) {
CmisObject doc = alfrescoService.searchDocuments(uuid);
String info = "uuid:" +
doc.getProperty("cmis:objectId").getValueAsString() + "\nTipo del Documento:"
+ doc.getProperty("bc:documentType").getValueAsString() + "\nId
Tipo de documento:"
+ doc.getProperty("bc:documentTypeId").getValueAsString() +
"\nCodigo tipo de documento:"
+ doc.getProperty("bc:idDocument").getValueAsString() + "\nFolio
Documento:"
+ doc.getProperty("bc:folioDocument").getValueAsString() +
"\nRut del Cliente:"
+ doc.getProperty("bc:rutClient").getValueAsString() + "\nNombre
del cliente:"
+ doc.getProperty("bc:clientName").getValueAsString() +
"\nNombre Documento:" + doc.getName();
return info;
}
#ResponseBody
#RequestMapping(value = "/deleteDocument", method = RequestMethod.POST)
String deleteDocument(String uuid) {
alfrescoService.deleteDocument(uuid);
return "Ok";
}
#ResponseBody
#RequestMapping(value = "/corruptPDF", method = RequestMethod.POST)
String corruptPDF(#RequestParam MultipartFile file) throws Exception {
return alfrescoService.corruptPDF(file);
}
#ResponseBody
#RequestMapping(value = "/consumeRest")
String consumeRest(#RequestParam(required=false,name="login") String login,
#RequestParam(required=false,name="password") String password) throws
SAXException, IOException, ParserConfigurationException {
return alfrescoService.consumeRest(login, password);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
I searched and re searched many times today but just only a post semms like my trouble but it didn´t work. I´m a practician sorry if a basic question.
You should have #Api at controller level, and #EnableSwagger2 is not required in controller class, as you did it already #Configuration class
#RestController
#EnableAutoConfiguration
#SpringBootApplication
#Api(value = "Read API",
description = "Rest APIs for read data etc",
produces = "application/json")
public class Example {
....
}
Also you need to define the API bean in your configuration class like the following;
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select().apis(RequestHandlerSelectors.basePackage("controller.package"))
.paths(PathSelectors.any())
.build().apiInfo(apiInfo());
}
Check this link for a working example
https://www.tuturself.com/posts/view?menuId=3&postId=1091

Swagger doesn't display information about methods - SpringBoot

I have an API in Java SpringBoot and I want to document it in Swagger.
I have done the following (I only include classes that contain some code related to Swagger):
Main class
#EnableSwagger2
public class ProvisioningApiApplication {
public static void main(String[] args) {
if (AuthConfigFactory.getFactory() == null) {
AuthConfigFactory.setFactory(new AuthConfigFactoryImpl());
}
SpringApplication.run(ProvisioningApiApplication.class, args);
}
#Bean
public Docket swaggerSpringMvcPluggin() {
return new Docket(DocumentationType.SWAGGER_2)
.useDefaultResponseMessages(false)
.apiInfo(apiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
#Component
#Primary
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
setSerializationInclusion(JsonInclude.Include.NON_NULL);
configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
enable(SerializationFeature.INDENT_OUTPUT);
}
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Provisioning API")
.version("0.0.1")
.build();
}
}
Controller
#RestController
#EnableAutoConfiguration
#CrossOrigin
public class RecursoController {
#Autowired
private Configuration configuration;
#Autowired
private TypeSpecService typeSpecService;
#Autowired
private IoTAgentService ioTAgentService;
#Autowired
private OrionService orionService;
#Autowired
private DeviceIdService deviceIdService;
#ApiOperation(value = "Put a device", nickname = "provisionDevice", tags = "Device")
#ApiResponses({
#ApiResponse(code = 200, message = "Ok", response = NewDeviceResponse.class)
})
#RequestMapping(method = RequestMethod.PUT, value = "/devices", consumes = "application/json", produces = "application/json")
public ResponseEntity<NewDeviceResponse> provisionDevice(#RequestBody NewDeviceRequest newDeviceRequest,
#RequestHeader("X-Auth-Token") String oAuthToken) {
// what my method does
}
The documentation results in the following swagger.json file:
{
swagger: "2.0",
info: {
version: "0.0.1",
title: "Provisioning API"
},
host: "localhost:8080",
basePath: "/"
}
As you can see, it only contains the name and the version of API but not the provisionDevice method.
I've tried everything but I can't figure it out what I'm doing bad. What am I missing?
Did you add #Api annotation in your class, where you have your main services?

Spring social returning wrong user profile

I'm using Spring Social LinkedIn to retrieve user profiles with a custom ConnectController since I want to the user to login and retrieve the profile in one step. The issue is that sometimes the first user in the system is returned instead of the currently logged in user.
Here is my CustomConnectController
#Controller
#RequestMapping("/connect")
public class CustomConnectController extends ConnectController {
#Inject
public CustomConnectController(ConnectionFactoryLocator connectionFactoryLocator,
ConnectionRepository connectionRepository) {
super(connectionFactoryLocator, connectionRepository);
}
#Override
protected String connectView(String providerId) {
return "redirect:/hey/" + providerId + "Connect";
}
#Override
protected String connectedView(String providerId) {
return "redirect:/hey/" + providerId + "Connected";
}
}
and my webcontroller
#Controller
public class WebController {
#Autowired
private LinkedIn linkedin;
#Autowired
private ConnectionRepository repository;
#RequestMapping(value = "/hey/linkedinConnected", method = RequestMethod.GET)
public String linkedinConnected(HttpServletRequest request, Model model, Locale locale) {
if (repository.findConnections("linkedin").isEmpty()
|| !linkedin.isAuthorized()) {
return "redirect:/connect/linkedin";
}
LinkedInProfile userProfile = linkedin.profileOperations().getUserProfile();
return "loggedinpage";
}
#RequestMapping(value = "/hey/linkedinConnect", method = RequestMethod.GET)
public String linkedinConnect(HttpServletRequest request, Model model, Locale locale) {
if (repository.findConnections("linkedin").isEmpty()
|| !linkedin.isAuthorized()) {
return "redirect:/connect/linkedin";
}
LinkedInProfile userProfile = linkedin.profileOperations().getUserProfile();
return "loggedinpage";
}
}
Any ideas of what I'm doing wrong?

Spring Social Facebook Template always return same user

I am using Spring Social 2.0.2.RELEASE to provide social login with Facebook. My problem is that Spring Social always return the same first user when I use FacebookTemplate. Here the example:
```
#Autowired
private Facebook facebook;
#RequestMapping(value = "/facebook/login", method = RequestMethod.GET)
public ModelAndView handleFacebookLogin(HttpServletResponse response) {
//always the same user
User profile = facebook.fetchObject("me", User.class, "id", "name", "link", "email");
return new ModelAndView("redirect:/dashboard");
}
```
I also have a Custom ConnectController:
```
#Controller
#RequestMapping("/connect")
public class CustomConnectController extends ConnectController {
#Autowired
public CustomConnectController(ConnectionFactoryLocator connectionFactoryLocator,
ConnectionRepository connectionRepository) {
super(connectionFactoryLocator, connectionRepository);
}
#Override
protected RedirectView connectionStatusRedirect(String providerId, NativeWebRequest request) {
return new RedirectView("/facebook/login");
}
}
```
If a open two browsers and try to login with different users, it always return the first one. My current solution is just copy the entire ConnectController to my app and change the behaviour. It is terrible and I hope that I am making a big mistake.
I had the same issue and solved the problem by creating this class:
#Configuration
public class UniqueSessionUserID extends SocialConfigurerAdapter {
#Override
public UserIdSource getUserIdSource() {
return new UserIdSource() {
#Override
public String getUserId() {
RequestAttributes request = RequestContextHolder.getRequestAttributes();
String uuid = (String) request.getAttribute("_socialUserUUID", RequestAttributes.SCOPE_SESSION);
if (uuid == null) {
uuid = UUID.randomUUID().toString();
}
request.setAttribute("_socialUserUUID", uuid, RequestAttributes.SCOPE_SESSION);
return uuid;
}
};
}
}
Here is a link where it is explained in more detail why this is necessary:
Spring Social Facebook more than one user

Does Swagger UI support #PathVariable binding?

Currently when I'm testing the Swagger UI for a GET request that binds the "id" path variable to a data object, the dataType of the "id" field is Model, instead of a Long.
For instance, here is the method in the RestController:
#RequestMapping(value = "/{id}", method = GET)
public AwardVO getAwardById(#PathVariable("id") Award award) {
LOG.info("inside the get award method: "+award);
if (award == null) {
throw new AwardNotFoundException();
}
return new AwardVO(award);
}
Here is the resulting documentation:
So when I pass a Long to the input field, I don't receive the desired record. Is this type of binding supported in Swagger, or do I need to just need to do a lookup for the record and pass the PathVariable as a Long?
Version of Swagger: compile "com.mangofactory:swagger-springmvc:0.9.5"
SwaggerConfig:
#Configuration
#EnableSwagger
public class SwaggerConfig extends WebMvcConfigurerAdapter {
private SpringSwaggerConfig springSwaggerConfig;
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
public SwaggerSpringMvcPlugin customImplementation() {
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig).apiInfo(
apiInfo())
.genericModelSubstitutes(ResponseEntity.class)
.includePatterns("/v1/.*", "/register/.*");
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("API", "API",
"API terms of service", "email#gmail.com",
"API Licence Type", "API License URL");
return apiInfo;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
Thanks.
It seems like it should work as expected if you replace #PathVariable with #ModelAttribute.
To answer your question, yes it does support #PathVariable, but only primitives or strings.

Resources