I want to use Swagger with Spring MVC. I have following entries in the build.gradle file
compile 'com.mangofactory:swagger-springmvc:0.9.4'
compile 'com.wordnik:swagger-annotations:1.3.12'
compile 'org.webjars:swagger-ui:2.0.12'
I have enable it using #EnableSwagger annotation.
#EnableAutoConfiguration(exclude = {EmbeddedServletContainerAutoConfiguration.EmbeddedJetty.class, LiquibaseAutoConfiguration.class, org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class})
#EnableSwagger
#EnableWebMvc
#Configuration
public class App extends WebMvcConfigurerAdapter{
#Bean
ProtobufHttpMessageConverter protobufHttpMessageConverter() {
return new ProtobufHttpMessageConverter();
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
private SpringSwaggerConfig springSwaggerConfig;
#SuppressWarnings("SpringJavaAutowiringInspection")
#Autowired
public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
this.springSwaggerConfig = springSwaggerConfig;
}
#Bean
public SwaggerSpringMvcPlugin customImplementation(){
return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
.apiInfo(apiInfo())
.includePatterns(".*feed.*"); // assuming the API lives at something like http://myapp/api
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo(
"My Project's REST API",
"This is a description of your API.",
"API TOS",
"me#wherever.com",
"API License",
"API License URL"
);
return apiInfo;
}
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
registry.addResourceHandler("*.html").addResourceLocations("/");
}
}
But when run the application using spring boot and hit the endpoint http://localhost:8080/api-docs, I just see the response in Json,
{"apiVersion":"1.0","apis":[{"description":"Basic Error Controller","path":"/default/basic-error-controller","position":0},{"description":"Manage people","path":"/default/people","position":0}],"authorizations":{},"info":{"contact":"Contact Email","description":"Api Description","license":"Licence Type","licenseUrl":"License URL","termsOfServiceUrl":"Api terms of service","title":"default Title"},"swaggerVersion":"1.2"}
I copied the static files from swagger-ui and copied it to my /main/webapp/doc
I am still missing fancy UI.
Related
I'm using custom crudrespository to persist data in redis. However, I'm unable to autowire custom repository.
All the configuration seems correct and redis is running on my local.
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface CustomRepository extends CrudRepository<String,
Long> {
String get(String key);
void put(String key, String value);
}
//////////
public class StorageServiceImpl implements IStorageService {
#Autowired
private CustomRepository respository;
#Override
public void saveParameter() {
this.respository.put("key1","value1");
}
#Override
public String getParameter() {
return this.respository.get("key1");
}
/////
#Service
public interface IStorageService {
void saveParameter();
String getParameter();
}
///////
#SpringBootApplication(scanBasePackages = {"com.example.cache"})
#EnableRedisRepositories(basePackages = {"com.example.cache.repository"})
public class ApplicationConfiguration {
public static void main(String[] args){
SpringApplication.run(ApplicationConfiguration.class, args);
new StorageServiceImpl().saveParameter();
System.out.println(new StorageServiceImpl().getParameter());
}
}
When I try running this application using gradle bootRun, I get
Exception in thread "main" java.lang.NullPointerException
at com.example.cache.impl.StorageServiceImpl.saveParameter(StorageServiceImpl.java:16)
at com.example.cache.ApplicationConfiguration.main(ApplicationConfiguration.java:17)
Not sure what's wrong?
You can't use new on any bean, you need to #Autowire it. The annotations only work with spring managed beans at every level.
Add a new bean with a a storage service and a method that makes your call after it is created.
Also, I can't remember if the spring-boot creates the bean if there is only one implementation but I believe your StorageServiceImpl needs the #Service annotation, not the interface.
Delete this from your ApplicationConfiguration class.
new StorageServiceImpl().saveParameter();
System.out.println(new StorageServiceImpl().getParameter());
Then add this new class.
#Service
public class Startup {
#Autowired
IStorageService storageService;
#PostConstruct
public void init(){
storageService.saveParameter();
System.out.println(storageService().getParameter());
}
}
And you need a config
#Configuration
#EnableRedisRepositories
public class ApplicationConfig {
#Bean
public RedisConnectionFactory connectionFactory() {
return new JedisConnectionFactory();
}
#Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<byte[], byte[]> template = new RedisTemplate<byte[], byte[]>();
return template;
}
}
Hello i am trying to understand why do my requests not enter my api route.They seem to reach the server but they wont fan out in the MVC.
The server is running on: http://localhost:9300
The route i am requesting is : http://localhost:9300/api/getusers
Program
public class Program {
public static void Main(string[] args) {
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) {
var builder = new WebHostBuilder();
builder.UseStartup<Startup>();
var url = Address.Default.ToUrl();
builder.UseKestrel().UseUrls(url);
return builder;
}
}
Startup
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services) {
services.AddOptions();
services.AddMvc();
}
public IConfiguration Configuration;
public void Configure(IApplicationBuilder app) {
Debug.WriteLine("Entered server"); //enters successfully here
app.UseMvc(); //does not enter the controller
}
}
Controller
This is a simple controller with a GET method.The constructor is not invoked at all.Why would this happen?I know it when the server runs the first time ..it does a health check on its routes.
[ApiController]
class UserController : ControllerBase {
private static List<User> users = new List<User> {
new User{Id=0,Age=0,Name="Failed"},
new User{Id=12,Age=33,Name="Daniel"},
new User{Id=13,Age=33,Name="Marian"},
};
public UserController() {
Debug.WriteLine("Controller called"); //does not get called !
}
[HttpGet]
[Route("api/getusers")]
public async Task<HttpResponseMessage> GetUsers() {
await Task.Delay(1000);
return new HttpResponseMessage {
Content = new StringContent(users.ToJson()),
StatusCode = HttpStatusCode.OK
};
}
}
P.S Do i have to add anyything ? What am i missing i followed other implementations closely.
I've created the webapi project using dotnet new webapi.
I've managed to get to the url with the similar configuration by changing the access modifier of a similar controller. Try to add public keyword to the class UserController. So it should be public class UserController
I will provide more information about the configuration of the project if it is necessary and the step above does not help.
I have integrated the cordapp with spring boot .One strange observation we found that the response differs coming from the cordawebserver and spring boot server for example
Blockquote
API :GET: market/me
gives
{
“me”: {
“commonName”: null,
“organisationUnit”: null,
“organisation”: “PartyG-CT”,
“locality”: “Tokyo”,
“state”: null,
“country”: “JP”,
“x500Principal”: {
“name”: “O=PartyG-CT,L=Tokyo,C=JP”,
“encoded”: “MDExCzAJBgNVBAYTAkpQMQ4wDAYDVQQHDAVUb2t5bzESMBAGA1UECgwJUGFydHlHLUNU”
}
}
}
with Spring boot
while with cordawebserver we are getting :
{
“me”: “C=JP,L=Tokyo,O=PartyG-CT”
}
Same behaviour we are finding the same for different APIs Any help will be appreciated
#GET
#Path("peers")
#Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
// CordaX500Name
public Map<String, List<CordaX500Name>> getPeers() {
List<NodeInfo> nodeInfoSnapshot = proxy.networkMapSnapshot();
return ImmutableMap.of(
"peers",
nodeInfoSnapshot
.stream()
.map(node -> node.getLegalIdentities().get(0).getName())
.filter(name -> !name.equals(myLegalName) && !name.getOrganisation().equals(controllerName)
&& !name.getOrganisation().equals(NETWORK_MAP_NAME))
.collect(toList()));
}
//boot entry point
#SpringBootApplication
public class FacilityServer {
#Autowired
public static NodeRPCConnection nodeRPCConnection;
/**
* Starts our Spring Boot application.
*/
public static void main(String[] args) throws Exception {
SpringApplication springApplication = new SpringApplication();
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run(FacilityServer.class, args);
}
#EventListener(ApplicationReadyEvent.class)
public void initiateFacilityObserverPostStartup() throws Exception{
FacilityObserver.startFacilityWatch();
}
// this class for using the jersey instead of spring rest impltn
#Configuration
#ApplicationPath("rest")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
}
#PostConstruct
public void setUp() {
register(MarketApi.class);
//register(GenericExceptionMapper.class);
}
}
I found the solution ;According to the corda documentation we need to register cordajackson mapper .Then, we will be able to get the same response as in corda webserer.
for example:
List<StateAndRef<YourState>> vaultStatesList = vaultStates.getStates();
ObjectMapper mapper = JacksonSupport.createNonRpcMapper();
String json = mapper.writeValueAsString(vaultStatesList);
I have one maven spring project (as a library) and I am adding it as a dependency into spring maven project(web service).
I have some properties files in both projects. In library there is one validationmessages.properties file.
I am using hibernate validator annotations on my model.
For example,
#NotBlank(message = "{NotBlank-entityId}")
Private String entityId;
The class model which is in library,using as a request body in webservice.here library hibernate validation messages are not working in webservice.
Here's the code:
Model:
Task.java (In library)
public class Task {
#NotBlank(message = "{NotNull-EntityID}")
private String entityId;
public String getEntityId() {
return entityId;
}
public void setEntityId(final String entityId) {
this.entityId = entityId;
}
}
Taskvalidationmessages.properties (In library)
NotNull-EntityID = Entity ID can not be null.
TaskManagementConfiguration.java (In library)
#Configuration
#PropertySources({ #PropertySource("classpath:queries.properties"),
#PropertySource("classpath:Taskvalidationmessages.properties") })
#Import(DataSourceConfiguration.class)
public class TaskManagementConfiguration {
}
TaskResource.java (Controller in webservice project)
#RequestMapping(value = WebserviceConstant.CREATE_TASK, method = RequestMethod.POST, produces = WebserviceConstant.APPLICATION_JSON)
public ResponseEntity<CreateTaskResponse> createTask(
#Valid #RequestBody final Task request,
#RequestHeader(value = "access-token") final String accessToken) {
return new ResponseEntity<CreateTaskResponse>(
taskService.createTask(request, receivedToken), HttpStatus.CREATED);
}
App.java (In Web service project)
#Configuration
#SpringBootApplication
#PropertySources({ #PropertySource("classpath:user-queries.properties") })
#Import({ TaskManagementConfiguration.class })
public class App {
public static void main(final String[] args) {
SpringApplication.run(App.class, args);
}
}
Whenever I hit the resource url with empty value of entityId.
It gives error like:
{
"fieldErrors": [
{
"field": "entityId",
"code": 200,
"message": "{NotNull-EntityID}"
}
]
}
How can I add a custom resource location that is on for example my D drive in folder called Resources.
#Configuration
public class StaticResourceConfiguration extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
registry.addResourceHandler("/**").addResourceLocations("D:/Resources/");
}
}
This doesn't work.
This is my application class and the only other configuration file.
#SpringBootApplication
public class Application {
public static void main(String args[]){
SpringApplication.run(Application.class, args);
}
#Bean // for websocket endpoints
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
#Bean
public PasswordEncoder bcryptPasswordEncoder(){
return new BCryptPasswordEncoder();
}
}
You should state your location using the file prefix, check more here . So it should be
registry.addResourceHandler("/**").addResourceLocations("file:///D:/Resources/");
Try /D:/Resources/. Absolute path must start with /