I am trying to use embedded database derby with spring framework. I can insert the data and read it. Everything works completely fine except for one thing that the database is not persisting. When I close the application and run it again the data is not present. I am guessing that the database is created again but don't know why.
My code:
#Configuration
#ComponentScan
#EnableAutoConfiguration
public class MainClass
{
#Bean
public DataSource dataSource()
{
// no need shutdown, EmbeddedDatabaseFactoryBean will take care of this
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
EmbeddedDatabase db = builder
.setType(EmbeddedDatabaseType.DERBY) //.HSQL, .H2 or .DERBY
.setName("some-db")
.addScript("/create-db.sql")
.build();
return db;
}
#Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource)
{
DataSourceTransactionManager d = new DataSourceTransactionManager(dataSource);
return d;
}
public static void main(String[] args)
{
ConfigurableApplicationContext context = new SpringApplicationBuilder(MainClass.class).headless(false).run(args);
MainFrame.mf = context.getBean(MainFrame.class);
MainFrame.mf.setVisible(true);
UserService userService = new UserService();
if(userService.isSignedIn())
{
MainFrame.mf.loggedIn();
}
else
{
MainFrame.mf.loggedOut();
}
}
}
And output logs by spring are
2017-09-17 20:41:53.461 INFO 3516 --- [ main] com.some.MainClass : Starting MainClass on maker with PID 3516 (C:\..\NetbeansProjects\..\target\classes started by verma in C:\..\NetbeansProjects\proj)
2017-09-17 20:41:53.469 INFO 3516 --- [ main] com.some.MainClass : No active profile set, falling back to default profiles: default
2017-09-17 20:41:53.571 INFO 3516 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:41:56.974 INFO 3516 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-09-17 20:41:57.007 INFO 3516 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-09-17 20:41:57.010 INFO 3516 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-09-17 20:41:57.278 INFO 3516 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-09-17 20:41:57.279 INFO 3516 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 3714 ms
2017-09-17 20:41:57.606 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-17 20:41:57.616 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-17 20:41:57.618 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-17 20:41:57.618 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-17 20:41:57.619 INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-17 20:41:58.028 INFO 3516 --- [ main] o.s.j.d.e.EmbeddedDatabaseFactory : Starting embedded database: url='jdbc:derby:memory:some-db;create=true', username='sa'
2017-09-17 20:41:58.883 INFO 3516 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executing SQL script from class path resource [create-db.sql]
2017-09-17 20:41:59.248 INFO 3516 --- [ main] o.s.jdbc.datasource.init.ScriptUtils : Executed SQL script from class path resource [create-db.sql] in 365 ms.
2017-09-17 20:42:00.907 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:42:01.052 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[POST]}" onto java.util.Map com.some.connection.ConnectionController.login(java.lang.String)
2017-09-17 20:42:01.055 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/logout],methods=[POST]}" onto org.springframework.http.ResponseEntity com.some.connection.ConnectionController.logout(java.lang.String)
2017-09-17 20:42:01.062 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-17 20:42:01.063 INFO 3516 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-17 20:42:01.153 INFO 3516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.155 INFO 3516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.250 INFO 3516 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.717 INFO 3516 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-09-17 20:42:01.829 INFO 3516 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-09-17 20:42:01.840 INFO 3516 --- [ main] com.some.MainClass : Started MainClass in 9.034 seconds (JVM running for 9.794)
2017-09-17 20:42:06.305 INFO 3516 --- [ Thread-6] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:42:06.314 INFO 3516 --- [ Thread-6] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2017-09-17 20:42:06.348 INFO 3516 --- [ Thread-6] o.s.j.d.e.EmbeddedDatabaseFactory : Shutting down embedded database: url='jdbc:derby:memory:some-db;create=true'
create-db.sql contents are
CREATE TABLE table_connection
(
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
ip VARCHAR(50) UNIQUE,
sessionId VARCHAR(50) DEFAULT NULL
);
SOLUTION:
Accepted answer pointed in right direction but the error was some-db;create=true failed to start. Then I looked at how Netbeans IDE was creating the derby connection. Problem was create=true, I think it's not supposed to be sent with the url but with properties as show in code below:
#Bean
public DataSource dataSource()
{
DriverManagerDataSource dm = new DriverManagerDataSource("jdbc:derby:some-db", "root", "root");
Properties properties = new Properties();
properties.setProperty("create", "true");
dm.setConnectionProperties(properties);
dm.setSchema("APP");
dm.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");
return dm;
}
#Bean(name="Application.dataSourceInitializer")
public DataSourceInitializer dataSourceInitializer(DataSource dataSource)
{
final DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
try
{
JdbcTemplate jdbc = new JdbcTemplate(dataSource);
jdbc.queryForList("SELECT id FROM table_connection");
}
catch(Exception e)
{
initializer.setDatabasePopulator(databasePopulator());
}
return initializer;
}
#Value("classpath:create-db.sql")
private Resource schemaScript;
private DatabasePopulator databasePopulator()
{
final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
populator.addScript(schemaScript);
return populator;
}
Script create-db.sql can give error if table already exists as no IF EXISTS in derby so wrapped it in try-catch.
Bean datasourceInitializer is named explicitly 'Application.dataSourceInitializer' as spring auto-configuration tends to override it. Check it here.
This is the core of your problem: jdbc:derby:memory:some-db;create=true
When you say 'memory' in your Derby JDBC Connection URL, you are telling Derby explicitly to make a non-durable database.
If you remove the 'memory:' from your JDBC Connectino URL, Derby will create a persistent, durable database in the 'some-db' directory on your hard disk.
Related
please, I need some help, I've been stuck with this error 2 days.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'adsController': Unsatisfied dependency expressed through field 'shortUrlService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'shortUrlServiceImpl': Unsatisfied dependency expressed through field 'shortUrlRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'shortUrlRepository' defined in com.codepressed.urlShortener.dao.ShortUrlRepository defined in #EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property desc found for type LocalDateTime! Traversed path: ShortUrl.creationDate.
Error display
This is my code:
Service class
#Service
public class AdvertisementServiceImpl implements AdvertisementService{
#Autowired
AdvertisementRepository advertisementRepository;
#Autowired
private MongoUtilsService mongoUtilsService;
#Override
public Advertisement save(Advertisement advertisement) {
advertisement.set_id(mongoUtilsService.getNextValue("AD"));
return advertisementRepository.insert(advertisement);
}
#Override
public void removeAd(Advertisement advertisement) {
advertisementRepository.delete(advertisement);
}
#Override
public Advertisement randomAd() {
List<Advertisement> allAds = advertisementRepository.findAll();
Random random = new Random();
return allAds.get(random.nextInt(allAds.size()-1));
}
}
My repository
#RepositoryRestResource
public interface AdvertisementRepository extends MongoRepository<Advertisement,Long> {
}
Controller class
#Controller
#RequestMapping("/ad")
public class AdsController {
#Autowired
AdvertisementService advertisementService;
#Autowired
ShortUrlService shortUrlService;
#GetMapping(value="/{id}")
public String getRandomAd(#PathVariable Long id, Model model){
model.addAttribute("ad", advertisementService.randomAd());
String url;
if (shortUrlService.findUrlById(id) != null){
url = shortUrlService.findUrlById(id);
}else if (shortUrlService.findUrlByCustom(String.valueOf(id)) != null){
url = shortUrlService.findUrlByCustom(String.valueOf(id));
}else {
url = "/error404.html";
}
model.addAttribute("url", url);
return "go";
}
I would like to use the ServiceImpl and Service but I don't know why wouldn't I be able to autowire them.
Additionaly, I have on my Config Class the following annotation:
#ComponentScan({"com.codepressed.urlShortener", "com.codepressed.urlShortener.dao",
"com.codepressed.urlShortener.service", "com.codepressed.urlShortener.controller"})
but doesn't seem to be enough...
please, any help is appreciated, I can't see the error or I don't understand it.
GITHUB REPO: https://github.com/codepressed/Jurly/tree/master/src/main/java/com/codepressed/urlShortener
I just cloned your code, on github.
I found that your method naming does not conform to the Spring-Data JPA specification.
Rename ShortUrlRepository method:
List<ShortUrl> findFirst10ByCreationDateDesc();
to:
List<ShortUrl> findFirst10ByOrderByCreationDateDesc();
When this problem is solved, run the application,console output:
No session repository could be auto-configured, check your configuration
So I created a mongo http session config:
package com.codepressed.urlShortener.config;
import org.springframework.context.annotation.Bean;
import org.springframework.session.data.mongo.JdkMongoSessionConverter;
import org.springframework.session.data.mongo.config.annotation.web.http.EnableMongoHttpSession;
import java.time.Duration;
#EnableMongoHttpSession
public class HttpSessionConfig {
#Bean
public JdkMongoSessionConverter jdkMongoSessionConverter() {
return new JdkMongoSessionConverter(Duration.ofMinutes(30));
}
}
Then I run the application again,No exception output!
2021-06-18 00:06:49.844 INFO 13960 --- [ main] c.c.u.UrlShortenerApplication : Starting UrlShortenerApplication using Java 11.0.10 on Mashiros-iMac.lan with PID 13960 (/Users/rat/IdeaProjects/Jurly/target/classes started by rat in /Users/rat/IdeaProjects/Jurly)
2021-06-18 00:06:49.850 INFO 13960 --- [ main] c.c.u.UrlShortenerApplication : No active profile set, falling back to default profiles: default
2021-06-18 00:06:50.295 INFO 13960 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2021-06-18 00:06:50.329 INFO 13960 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 32 ms. Found 2 MongoDB repository interfaces.
2021-06-18 00:06:50.667 INFO 13960 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-06-18 00:06:50.674 INFO 13960 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-06-18 00:06:50.674 INFO 13960 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.45]
2021-06-18 00:06:50.717 INFO 13960 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-06-18 00:06:50.718 INFO 13960 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 833 ms
2021-06-18 00:06:50.838 INFO 13960 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2021-06-18 00:06:50.875 INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:2, serverValue:1}] to 127.0.0.1:27017
2021-06-18 00:06:50.875 INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:2}] to 127.0.0.1:27017
2021-06-18 00:06:50.876 INFO 13960 --- [127.0.0.1:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=127.0.0.1:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=9, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=11069828}
2021-06-18 00:06:51.052 INFO 13960 --- [ main] org.mongodb.driver.connection : Opened connection [connectionId{localValue:3, serverValue:3}] to 127.0.0.1:27017
2021-06-18 00:06:51.067 INFO 13960 --- [ main] o.s.s.d.m.AbstractMongoSessionConverter : Creating TTL index on field expireAt
2021-06-18 00:06:51.536 INFO 13960 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-06-18 00:06:51.600 INFO 13960 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page template: index
2021-06-18 00:06:51.891 INFO 13960 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 1c0d09bd-73cc-42aa-8f6a-df157db252fe
2021-06-18 00:06:52.022 INFO 13960 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Will secure any request with [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#1e95f584, org.springframework.security.web.context.SecurityContextPersistenceFilter#1a336906, org.springframework.security.web.header.HeaderWriterFilter#39afe59f, org.springframework.security.web.csrf.CsrfFilter#3a3316b6, org.springframework.security.web.authentication.logout.LogoutFilter#57fce8b, org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#1b4ba615, org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter#3a9c11fb, org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter#54997f67, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#18e8eb59, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#20f63ddc, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#24f177f5, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#bf4e48e, org.springframework.security.web.session.SessionManagementFilter#43756cb, org.springframework.security.web.access.ExceptionTranslationFilter#48ee3c2d, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#e6e5da4]
2021-06-18 00:06:52.105 INFO 13960 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-06-18 00:06:52.115 INFO 13960 --- [ main] c.c.u.UrlShortenerApplication : Started UrlShortenerApplication in 2.542 seconds (JVM running for 3.116)
I think you should refer to the following tutorials:
Spring Session with MongoDB
Sorting Query Results with Spring Data
I run maven spring boot application with mvn spring-boot:run.
I declared https configuration with application.properties as follow:
server.port = 8443
server.ssl.key-store = keystore.jks
server.ssl.key-store-password = 123456
server.ssl.key-password = 123456
The spring started on right port with follow output:
2018-04-10 10:49:42.074 INFO 6794 --- [ main] ru.ias.Main : Starting Main on IAS-WS-UX02 with PID 6794 (/home/opshenichnikova/NetBeansProjects/bot-integrity/target/classes started by opshenichnikova in /home/opshenichnikova/NetBeansProjects/bot-integrity)
2018-04-10 10:49:42.077 INFO 6794 --- [ main] ru.ias.Main : No active profile set, falling back to default profiles: default
2018-04-10 10:49:42.147 INFO 6794 --- [ main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#41d792be: startup date [Tue Apr 10 10:49:42 MSK 2018]; root of context hierarchy
2018-04-10 10:49:42.834 INFO 6794 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2018-04-10 10:49:43.044 INFO 6794 --- [ main] org.eclipse.jetty.util.log : Logging initialized #3904ms to org.eclipse.jetty.util.log.Slf4jLog
2018-04-10 10:49:43.110 INFO 6794 --- [ main] o.s.b.w.e.j.JettyServletWebServerFactory : Server initialized with port: 8445
2018-04-10 10:49:43.120 INFO 6794 --- [ main] org.eclipse.jetty.server.Server : jetty-9.4.8.v20171121, build timestamp: 2017-11-22T00:27:37+03:00, git hash: 82b8fb23f757335bb3329d540ce37a2a2615f0a8
2018-04-10 10:49:43.318 INFO 6794 --- [ main] org.eclipse.jetty.server.session : DefaultSessionIdManager workerName=node0
2018-04-10 10:49:43.318 INFO 6794 --- [ main] org.eclipse.jetty.server.session : No SessionScavenger set, using defaults
2018-04-10 10:49:43.339 INFO 6794 --- [ main] org.eclipse.jetty.server.session : Scavenging every 660000ms
2018-04-10 10:49:43.355 INFO 6794 --- [ main] o.e.j.s.h.ContextHandler.application : Initializing Spring embedded WebApplicationContext
2018-04-10 10:49:43.356 INFO 6794 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1211 ms
2018-04-10 10:49:43.475 INFO 6794 --- [ main] o.s.b.w.servlet.ServletRegistrationBean : Servlet dispatcherServlet mapped to [/]
2018-04-10 10:49:43.477 INFO 6794 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-04-10 10:49:43.477 INFO 6794 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-04-10 10:49:43.477 INFO 6794 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-04-10 10:49:43.478 INFO 6794 --- [ main] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2018-04-10 10:49:43.480 INFO 6794 --- [ main] o.e.jetty.server.handler.ContextHandler : Started o.s.b.w.e.j.JettyEmbeddedWebAppContext#3f0831d8{/,[file:///tmp/jetty-docbase.8895474277820779181.8445/],AVAILABLE}
2018-04-10 10:49:43.481 INFO 6794 --- [ main] org.eclipse.jetty.server.Server : Started #4342ms
2018-04-10 10:49:43.720 INFO 6794 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#41d792be: startup date [Tue Apr 10 10:49:42 MSK 2018]; root of context hierarchy
2018-04-10 10:49:43.788 INFO 6794 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/admin/account/list],methods=[GET]}" onto public java.util.List<ru.ias.orm.Account> ru.ias.controllers.admin.AdminController.getAccounts()
2018-04-10 10:49:43.790 INFO 6794 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/admin/invoices],methods=[GET]}" onto public java.util.List<ru.ias.orm.Invoice> ru.ias.controllers.admin.InvoiceController.getInvoices(javax.servlet.http.HttpServletResponse)
2018-04-10 10:49:43.794 INFO 6794 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-04-10 10:49:43.794 INFO 6794 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-04-10 10:49:43.829 INFO 6794 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-10 10:49:43.830 INFO 6794 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-10 10:49:43.871 INFO 6794 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-04-10 10:49:44.049 INFO 6794 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2018-04-10 10:49:44.066 INFO 6794 --- [ main] o.e.j.s.h.ContextHandler.application : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-04-10 10:49:44.066 INFO 6794 --- [ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-04-10 10:49:44.076 INFO 6794 --- [ main] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 10 ms
2018-04-10 10:49:44.432 INFO 6794 --- [ main] o.e.jetty.util.ssl.SslContextFactory : x509=X509#22dbd246(jetty,h=[tbot-test.ias.su],w=[]) for SslContextFactory#2cfff4aa[provider=null,keyStore=file:///home/opshenichnikova/NetBeansProjects/bot-integrity/keystore.jks,trustStore=null]
2018-04-10 10:49:44.507 INFO 6794 --- [ main] o.e.jetty.server.AbstractConnector : Started ServerConnector#139688ed{SSL,[ssl, http/1.1]}{0.0.0.0:8445}
2018-04-10 10:49:44.509 INFO 6794 --- [ main] o.s.b.web.embedded.jetty.JettyWebServer : Jetty started on port(s) 8445 (ssl, http/1.1) with context path '/'
2018-04-10 10:49:44.512 INFO 6794 --- [ main] ru.ias.Main : Started Main in 2.726 seconds (JVM running for 5.372)
^C2018-04-10 10:52:08.108 INFO 6794 --- [ Thread-11] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext#41d792be: startup date [Tue Apr 10 10:49:42 MSK 2018]; root of context hierarchy
2018-04-10 10:52:08.109 INFO 6794 --- [ Thread-11] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown
2018-04-10 10:52:08.116 INFO 6794 --- [ Thread-11] o.e.jetty.server.AbstractConnector : Stopped ServerConnector#139688ed{SSL,[ssl, http/1.1]}{0.0.0.0:8445}
2018-04-10 10:52:08.119 INFO 6794 --- [ Thread-11] org.eclipse.jetty.server.session : Stopped scavenging
2018-04-10 10:52:08.121 INFO 6794 --- [ Thread-11] o.e.j.s.h.ContextHandler.application : Destroying Spring FrameworkServlet 'dispatcherServlet'
2018-04-10 10:52:08.122 INFO 6794 --- [ Thread-11] o.e.jetty.server.handler.ContextHandler : Stopped o.s.b.w.e.j.JettyEmbeddedWebAppContext#3f0831d8{/,[file:///tmp/jetty-docbase.8895474277820779181.8445/],UNAVAILABLE}
I try to access /admin/account/list path declared in controller:
package ru.ias.controllers.admin;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import ru.ias.orm.Account;
import ru.ias.config.HibernateUtil;
/**
*
* #author opshenichnikova
*/
#RestController
public class AdminController
{
#GetMapping("/admin/account/list")
#CrossOrigin(origins = "*")
public List<Account> getAccounts()
{
Session session = HibernateUtil
.getInstance()
.getSessionFactory()
.openSession();
session.beginTransaction();
Account account = new Account();
account.setFirstName("Olga");
account.setLastName("Pshenichnikova");
session.save(account);
session.getTransaction().commit();
List<Account> accounts = new ArrayList<>();
accounts.add(account);
return accounts;
}
}
The Main class declared as follow:
package ru.ias;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
#SpringBootApplication
public class Main extends SpringBootServletInitializer
{
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application
) {
return application.sources(Main.class);
}
public static void main(String[] args)
{
SpringApplication.run(Main.class, args);
}
}
Unfortunately I get follow response:
You are accessing the page via http, not https. Change the URL in your browser to https://localhost:8443/admin/account/list
I'm using spring boot 1.5.4, i'm following a tutorial where it shows that just by adding h2-console to the localhost:8080/ url you can access the console. But when i do that i have a 404 Whitelabel error.
These are the dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--WebJars-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>bootstrap</artifactId>
<version>3.3.5</version>
</dependency>
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.2.1</version>
</dependency>
<!--jpa and database-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
And this is the spring boot console log
2017-07-19 01:35:25.222 INFO 8644 --- [ main] c.e.s.SpringBootTest00Application : Starting SpringBootTest00Application on DESKTOP-K8Q0B2R with PID 8644 (started by Talon in C:\Users\Talon\Desktop\java netbeans\01\springBootTest00)
2017-07-19 01:35:25.225 INFO 8644 --- [ main] c.e.s.SpringBootTest00Application : No active profile set, falling back to default profiles: default
2017-07-19 01:35:25.544 INFO 8644 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#37574691: startup date [Wed Jul 19 01:35:25 CEST 2017]; root of context hierarchy
2017-07-19 01:35:27.236 INFO 8644 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-19 01:35:27.248 INFO 8644 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2017-07-19 01:35:27.249 INFO 8644 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15
2017-07-19 01:35:27.378 INFO 8644 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-07-19 01:35:27.378 INFO 8644 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1838 ms
2017-07-19 01:35:27.578 INFO 8644 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-07-19 01:35:27.582 INFO 8644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-19 01:35:27.584 INFO 8644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-07-19 01:35:27.584 INFO 8644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-07-19 01:35:27.584 INFO 8644 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-07-19 01:35:28.020 INFO 8644 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-07-19 01:35:28.037 INFO 8644 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [
name: default
...]
2017-07-19 01:35:28.122 INFO 8644 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {5.0.12.Final}
2017-07-19 01:35:28.123 INFO 8644 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found
2017-07-19 01:35:28.180 INFO 8644 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist
2017-07-19 01:35:28.219 INFO 8644 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-07-19 01:35:28.321 INFO 8644 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-07-19 01:35:28.742 INFO 8644 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000227: Running hbm2ddl schema export
2017-07-19 01:35:28.757 INFO 8644 --- [ main] org.hibernate.tool.hbm2ddl.SchemaExport : HHH000230: Schema export complete
2017-07-19 01:35:28.809 INFO 8644 --- [ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-07-19 01:35:29.119 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#37574691: startup date [Wed Jul 19 01:35:25 CEST 2017]; root of context hierarchy
2017-07-19 01:35:29.203 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String com.example.springBootTest00.controllers.IndexController.index()
2017-07-19 01:35:29.205 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product],methods=[POST]}" onto public java.lang.String com.example.springBootTest00.controllers.ProductController.saveOrUpdateProduct(com.example.springBootTest00.domain.Product)
2017-07-19 01:35:29.206 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product/edit/{id}]}" onto public java.lang.String com.example.springBootTest00.controllers.ProductController.edit(java.lang.Integer,org.springframework.ui.Model)
2017-07-19 01:35:29.206 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product/new]}" onto public java.lang.String com.example.springBootTest00.controllers.ProductController.newProduct(org.springframework.ui.Model)
2017-07-19 01:35:29.206 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product/delete/{id}]}" onto public java.lang.String com.example.springBootTest00.controllers.ProductController.deleteProduct(java.lang.Integer,org.springframework.ui.Model)
2017-07-19 01:35:29.206 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/products]}" onto public java.lang.String com.example.springBootTest00.controllers.ProductController.listProducts(org.springframework.ui.Model)
2017-07-19 01:35:29.206 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/product/{id}]}" onto public java.lang.String com.example.springBootTest00.controllers.ProductController.getProduct(java.lang.Integer,org.springframework.ui.Model)
2017-07-19 01:35:29.209 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-07-19 01:35:29.209 INFO 8644 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-07-19 01:35:29.243 INFO 8644 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-19 01:35:29.244 INFO 8644 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-19 01:35:29.284 INFO 8644 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-19 01:35:29.920 INFO 8644 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-07-19 01:35:29.983 INFO 8644 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-07-19 01:35:29.987 INFO 8644 --- [ main] c.e.s.SpringBootTest00Application : Started SpringBootTest00Application in 5.052 seconds (JVM running for 5.401)
I have some classes with #Service / #Controller working properly and all the requests are mapped to url strings other than h2-console. Should i import something else in the pom or configure something in application.properties ?
Writing in simple Steps:
In Application.properties file include
spring.h2.console.path=/h2
spring.h2.console.enabled=true
And in pom.xml Include devtools dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
re-package and open http://localhost:[port]/h2 you are all set
other properties you have to include is
spring.datasource.url=jdbc:h2:file:~/h2db
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
the file h2db will store in userprofile folder of windows
for example : C:\Users\[profile]
I am using latest release version of spring boot with camel-cxf to expose rest/soap web services. However since I have many services and some of them are not well defined, I want to register each of them one by one, catch if any exception occurs and continue with remaining valid services. But when I set camel.springboot.auto-startup=false I can not manage to open cxf service again. (Please note that timer route can be started this way). Any solution or suggestion ?
#Component
public class TestRoutes {
#Autowired CamelContext camelContext;
#Autowired Swagger2Feature swagger2Feature;
#PostConstruct
public void init(){
try {
camelContext.start();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HelloResponse response = new HelloResponse();
response.setCevap("response");
List<Object> providers = new ArrayList<>();
CxfRsComponent cxfComponent = new CxfRsComponent(camelContext);
CxfRsEndpoint serviceEndpoint = new CxfRsEndpoint("/rest2", cxfComponent);
serviceEndpoint.addResourceClass(Service1.class);
serviceEndpoint.setProviders(providers);
serviceEndpoint.setSynchronous(true);
serviceEndpoint.setAddress("/rest2");
serviceEndpoint.getFeatures().add(swagger2Feature);
RouteBuilder builder = new RouteBuilder(camelContext) {
#Override
public void configure() throws Exception {
from(serviceEndpoint)
.id(Service1.class.getCanonicalName()+"rest")
.log("${header.operationName} message here")
.setBody(constant(response));
from("timer:mytimer?period=5000")
.id("timer")
.log("hi");
}
};
try {
camelContext.startRoute(Service1.class.getCanonicalName()+"rest");
camelContext.startRoute("timer");
} catch (Exception e) {
e.printStackTrace();
}
}
}
2017-07-18 10:50:49.076 INFO 12052 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5149d738: startup date [Tue Jul 18 10:50:49 EEST 2017]; root of context hierarchy
2017-07-18 10:50:52.413 INFO 12052 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.apache.camel.spring.boot.CamelAutoConfiguration' of type [org.apache.camel.spring.boot.CamelAutoConfiguration$$EnhancerBySpringCGLIB$$5d14135] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2017-07-18 10:50:53.063 INFO 12052 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-07-18 10:50:53.085 INFO 12052 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2017-07-18 10:50:53.086 INFO 12052 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache
Tomcat/8.5.11
2017-07-18 10:50:53.341 INFO 12052 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2017-07-18 10:50:53.342 INFO 12052 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 4269 ms
2017-07-18 10:50:53.974 INFO 12052 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2017-07-18 10:50:53.976 INFO 12052 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'CXFServlet' to [/services/*]
2017-07-18 10:50:53.981 INFO 12052 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-07-18 10:50:53.982 INFO 12052 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-07-18 10:50:53.982 INFO 12052 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-07-18 10:50:53.982 INFO 12052 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2017-07-18 10:50:54.682 INFO 12052 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.19.1 (CamelContext: camel-1) is starting
2017-07-18 10:50:54.685 INFO 12052 --- [ main] o.a.c.m.ManagedManagementStrategy : JMX is enabled
2017-07-18 10:50:54.999 INFO 12052 --- [ main] o.a.c.i.converter.DefaultTypeConverter : Loaded 214 type converters
2017-07-18 10:50:55.064 INFO 12052 --- [ main] o.a.c.i.DefaultRuntimeEndpointRegistry : Runtime endpoint registry is in extended mode gathering usage statistics of all incoming and outgoing endpoints (cache limit: 1000)
2017-07-18 10:50:55.094 INFO 12052 --- [ main] o.a.camel.spring.SpringCamelContext : StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
2017-07-18 10:50:55.095 INFO 12052 --- [ main] o.a.camel.spring.SpringCamelContext : Total 0 routes, of which 0 are started.
2017-07-18 10:50:55.097 INFO 12052 --- [ main] o.a.camel.spring.SpringCamelContext : Apache Camel 2.19.1 (CamelContext: camel-1) started in 0.415 seconds
2017-07-18 10:50:55.301 WARN 12052 --- [ main] o.apache.cxf.jaxrs.utils.ResourceUtils : No resource methods have been found for resource class java.lang.Class
2017-07-18 10:50:55.433 INFO 12052 --- [ main] org.apache.cxf.endpoint.ServerImpl : Setting the server's publish address to be /rest1
2017-07-18 10:50:55.636 INFO 12052 --- [ main] org.reflections.Reflections : Reflections took 60 ms to scan 1 urls, producing 21 keys and 25 values
2017-07-18 10:50:56.106 INFO 12052 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#5149d738: startup date [Tue Jul 18 10:50:49 EEST 2017]; root of context hierarchy
2017-07-18 10:50:56.206 INFO 12052 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-07-18 10:50:56.208 INFO 12052 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-07-18 10:50:56.267 INFO 12052 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-18 10:50:56.267 INFO 12052 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-18 10:50:56.330 INFO 12052 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-18 10:50:57.591 INFO 12052 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2017-07-18 10:50:57.686 INFO 12052 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-07-18 10:50:57.694 INFO 12052 --- [ main] c.e.demo.AutoStartupFalseApplication : Started AutoStartupFalseApplication in 9.057 seconds (JVM running for 9.764)
The problem was if bus not set explicitly CamelCXF generates a default one which is not spring aware. So solution was generatin a SpringBus bean and wiring it to explicitly to the CxfRsEndpoint object.
In the configuration class
#Bean(destroyMethod = "shutdown")
public SpringBus cxf() {
return new SpringBus();
}
In the endpoint definition :
#Autowired Bus bus;
.
.
CxfRsEndpoint serviceEndpoint = new CxfRsEndpoint("/rest2", cxfComponent);
.
.
serviceEndpoint.setBus(bus);
Then it starts working as expected.
I'm building a web application using Spring Boot and MongoDB which will simply perform CRUD operations for employee Documents.
I'm getting this error "Request method 'POST' not supported" when I try to hit the create employee endpoint with the json.
My controller class is:
#RestController
#RequestMapping("/employeeapp/employees")
public class EmployeeController {
private final EmployeeService service;
#Autowired
public EmployeeController(EmployeeService service) {
this.service = service;
}
#RequestMapping(method = RequestMethod.POST)
#ResponseStatus(HttpStatus.CREATED)
public
#ResponseBody
Employee create(#RequestBody #Valid Employee employeeEntry) {
return service.create(employeeEntry);
}
#RequestMapping(value = "{id}", method = RequestMethod.DELETE)
public Employee delete(#PathVariable("id") long id) {
return service.delete(id);
}
#RequestMapping(method = RequestMethod.GET)
public List<Employee> findAll() {
return service.findAll();
}
#RequestMapping(value = "{id}", method = RequestMethod.GET)
public Employee findById(#PathVariable("id") long id) {
return service.findById(id);
}
#RequestMapping(value = "{id}", method = RequestMethod.PUT)
public Employee update(#RequestBody #Valid Employee employeeEntry) {
return service.update(employeeEntry);
}
#ExceptionHandler
#ResponseStatus(HttpStatus.NOT_FOUND)
public void handleEmployeeNotFound(EmployeeNotFoundException exception) {
}
}
Application class:
#SpringBootApplication
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
I've tried disabling csrf, adding #ResponseBody on the method but nothing seems to work.
EDIT
I'm hitting http://localhost:8080/employeeapp/employees with the POST request. The headers include Content-Type : application/json and with this json in the body:
{
"id" : 1,
"name" : "nikhil",
"dept" : "DCX"
}
Also, this is what i see in the logs when I hit the above URL with POST request.
2016-02-19 12:21:36.549 INFO 5148 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] :
Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-02-19 12:21:36.549 INFO 5148 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet :
FrameworkServlet 'dispatcherServlet': initialization started
2016-02-19 12:21:36.562 INFO 5148 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet :
FrameworkServlet 'dispatcherServlet': initialization completed in 13 ms
2016-02-19 12:21:36.595 WARN 5148 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound :
Request method 'POST' not supported
EDIT 2:
I checked the Spring boot logs, turns out the mappings are not being generated and instead spring is mapping to default services. Any idea why it might be happening?
[INFO] --- spring-boot-maven-plugin:1.3.2.RELEASE:run (default-cli) # EmployeeApp ---
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v1.3.2.RELEASE)
2016-02-19 14:51:00.690 INFO 5080 --- [ main] app.Application : Starting Application on DIN16003277 with PID 5080 (D:\!Nikhil\Documents\Code\EmployeeApp\target\classes started by nvibhav in D:\!Nikhil\Documents\Code\EmployeeApp)
2016-02-19 14:51:00.693 INFO 5080 --- [ main] app.Application : No active profile set, falling back to default profiles: default
2016-02-19 14:51:00.770 INFO 5080 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#46117566: startup date [Fri Feb 19 14:51:00 IST 2016]; root of context hierarchy
2016-02-19 14:51:01.987 INFO 5080 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-02-19 14:51:02.567 INFO 5080 --- [ main] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-02-19 14:51:03.026 INFO 5080 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2016-02-19 14:51:03.037 INFO 5080 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat
2016-02-19 14:51:03.039 INFO 5080 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.0.30
2016-02-19 14:51:03.172 INFO 5080 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2016-02-19 14:51:03.173 INFO 5080 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2409 ms
2016-02-19 14:51:03.689 INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'metricFilter' to: [/*]
2016-02-19 14:51:03.689 INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-02-19 14:51:03.690 INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-02-19 14:51:03.690 INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-02-19 14:51:03.690 INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*]
2016-02-19 14:51:03.691 INFO 5080 --- [ost-startStop-1] .e.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2016-02-19 14:51:03.691 INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'webRequestLoggingFilter' to: [/*]
2016-02-19 14:51:03.691 INFO 5080 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'applicationContextIdFilter' to: [/*]
2016-02-19 14:51:03.692 INFO 5080 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2016-02-19 14:51:04.011 INFO 5080 --- [ost-startStop-1] b.a.s.AuthenticationManagerConfiguration :
Using default security password: c652ec29-f926-40eb-bb5b-2bd9185bf6a5
2016-02-19 14:51:04.075 INFO 5080 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], []
2016-02-19 14:51:04.141 INFO 5080 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.security.web.util.matcher.AnyRequestMatcher#1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#71d64e0f, org.springframework.security.web.context.SecurityContextPersistenceFilter#68e32d1f, org.springframework.security.web.header.HeaderWriterFilter#30bd43e4, org.springframework.security.web.authentication.logout.LogoutFilter#6a766ce6, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#3111b148, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#75e89f1f, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#289e0d8f, org.springframework.security.web.session.SessionManagementFilter#4ec4999b, org.springframework.security.web.access.ExceptionTranslationFilter#3f4e33f9]
2016-02-19 14:51:04.181 INFO 5080 --- [ost-startStop-1] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: org.springframework.boot.actuate.autoconfigure.ManagementWebSecurityAutoConfiguration$LazyEndpointPathRequestMatcher#7f2a96e1, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#3ae13235, org.springframework.security.web.context.SecurityContextPersistenceFilter#5f36bdc8, org.springframework.security.web.header.HeaderWriterFilter#658ee520, org.springframework.security.web.authentication.logout.LogoutFilter#1ce1dc64, org.springframework.security.web.authentication.www.BasicAuthenticationFilter#51a29584, org.springframework.security.web.savedrequest.RequestCacheAwareFilter#120723a8, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#b2632d, org.springframework.security.web.authentication.AnonymousAuthenticationFilter#49cabfed, org.springframework.security.web.session.SessionManagementFilter#6c8e082f, org.springframework.security.web.access.ExceptionTranslationFilter#51f381ff, org.springframework.security.web.access.intercept.FilterSecurityInterceptor#3b3223fd]
2016-02-19 14:51:04.399 INFO 5080 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for #ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#46117566: startup date [Fri Feb 19 14:51:00 IST 2016]; root of context hierarchy
2016-02-19 14:51:04.471 INFO 5080 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2016-02-19 14:51:04.472 INFO 5080 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2016-02-19 14:51:04.506 INFO 5080 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-02-19 14:51:04.506 INFO 5080 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-02-19 14:51:04.549 INFO 5080 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-02-19 14:51:04.720 INFO 5080 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
2016-02-19 14:51:04.844 INFO 5080 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:5}] to localhost:27017
2016-02-19 14:51:04.845 INFO 5080 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[3, 2, 1]}, minWireVersion=0, maxWireVersion=4, maxDocumentSize=16777216, roundTripTimeNanos=565904}
2016-02-19 14:51:05.243 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/autoconfig || /autoconfig.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.244 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EnvironmentMvcEndpoint.value(java.lang.String)
2016-02-19 14:51:05.244 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/env || /env.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.245 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/configprops || /configprops.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.247 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics/{name:.*}],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.MetricsMvcEndpoint.value(java.lang.String)
2016-02-19 14:51:05.247 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/metrics || /metrics.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.250 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/mappings || /mappings.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.251 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/health || /health.json],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(java.security.Principal)
2016-02-19 14:51:05.251 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/trace || /trace.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.252 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/beans || /beans.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.252 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/info || /info.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.253 INFO 5080 --- [ main] o.s.b.a.e.mvc.EndpointHandlerMapping : Mapped "{[/dump || /dump.json],methods=[GET],produces=[application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.mvc.EndpointMvcAdapter.invoke()
2016-02-19 14:51:05.377 INFO 5080 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup
2016-02-19 14:51:05.391 INFO 5080 --- [ main] o.s.c.support.DefaultLifecycleProcessor : Starting beans in phase 0
2016-02-19 14:51:05.561 INFO 5080 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2016-02-19 14:51:05.567 INFO 5080 --- [ main] app.Application : Started Application in 5.207 seconds (JVM running for 11.036)
Following might help.
While you deploy the application, spring boot displays all the
available services on the console. Check the POST method to create
is being displayed or not. Check that there shouldn't be any contradiction with other services. GET/PUT/POST
If there are services not deployed, try adding '/' before other services - GET, PUT, POST.
Adding exception handler(link) to check the client input request to check the POJO structure.
Check the URL - If any global path for app/name added with
configuration.(link)
Try to remove headers - Content-Type in the request header and post
the request again
Following are different things that can happen. Need not to be followed in order.
EDIT:
Run the following to check whether your controller is being enabled and considered by the spring application or not.
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
System.out.println("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
System.out.println(beanName);
}
}
}
If your #SpringBootApplication annotated class and controller are in different packages it does not pick it by default class scan.
It works in almost all demos because bootstrapping class (#SpringBootApplication annotated class) and rest controller class reside in the same package and loaded to spring context.
// Make your class accessible to spring like this
#SpringBootApplication(scanBasePackageClasses = {GreetingController.class})
public class BootPocApplication {
OR
// give the base package name like this
#SpringBootApplication(scanBasePackages = {"com.tryout"})
public class BootPocApplication {
For me the issue was that the #RequestBody class was not accessible since it was an internal class.
Making it public/static made it accessible and solved this issue
public static class MyClassDto {
public String name;
public String comment;
public String key;
}
For me this error occurred when i used #RequestParam in method definition:
#RequestMapping(value = "/balance",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_VALUE)
public FinancialMsgResponse balance(#RequestParam(value = "requestMessage") FinancialMsgRequest requestMessage) throws Exception {
return new FinancialMsgResponse();
}
So when i remove the #RequestParam the error
Request method 'POST' not supported
is gone away.
good luck
Just follow this
#Controller
#RequestMapping(
method={RequestMethod.POST,RequestMethod.GET,RequestMethod....}
)
public class YourController{
.
.
.
}