I have a profile called "stage", I am trying to implement a web service but whenever I make a request I get some error, whenever I delete the profile annotation it works normally, I dont really know why it is not working with a profile here are some classes:
#SpringBootApplication
public class MyApp{
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.getEnvironment().setActiveProfiles("stage");
context.register(MyApp.class);
SpringApplication.run(MyApp.class, args);
}
}
#Profile("stage")
#Configuration
#PropertySource(value = { "classpath:jdbc.properties" })
public class StageDSConfig {
#Value("${jdbc.driverClassName}")
private String driverClassName;
#Value("${jdbc.url}")
private String jdbcURL;
#Value("${jdbc.username}")
private String username;
#Value("${jdbc.password}")
private String password;
#Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
#Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(jdbcURL);
dataSource.setUsername(username);
dataSource.setPassword(password);
DatabasePopulatorUtils.execute(createDatabasePopulator(), dataSource);
return dataSource;
}
private DatabasePopulator createDatabasePopulator() {
ResourceDatabasePopulator databasePopulator = new ResourceDatabasePopulator();
databasePopulator.setContinueOnError(true);
databasePopulator.addScript(new ClassPathResource("schema-mysql.sql"));
databasePopulator.addScript(new ClassPathResource("data-mysql.sql"));
return databasePopulator;
}
}
#EnableWs
#Configuration
public class WebServiceConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "ws")
public DefaultWsdl11Definition defaultActionWsdl11Definition(XsdSchema actionSchema) {
DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
wsdl11Definition.setPortTypeName("ActionPort");
wsdl11Definition.setLocationUri("/ws");
wsdl11Definition.setTargetNamespace("http://www.example.com/ws");
wsdl11Definition.setSchema(actionSchema);
return wsdl11Definition;
}
#Bean
public XsdSchema wsSchema() {
return new SimpleXsdSchema(new ClassPathResource("ws.xsd"));
}
}
and this is the error log:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring xml:lang="en">PreparedStatementCallback; bad SQL grammar [INSERT INTO logs(ipAddress,actionn,requestBody) values(?,?,?)]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: LOGS</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I believe you are not correctly activating the profile. With springBoot, you may set the profile like this:
new SpringApplicationBuilder(MyApp.class).profiles("stage").run(args);
Or, through an environment variable:
System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "stage");
SpringApplication.run(MyApp.class, args);
I think the problem is that you don't actually activate the "stage" profile, so the context is missing all the beans in StageDSConfig class and thus no schema is created
Related
I'm trying to send requests to my RestController, but it's not working, i have
#RestController
#RequestMapping(
value = "/cursos",
produces = MediaType.APPLICATION_JSON_UTF8_VALUE,
consumes = MediaType.APPLICATION_JSON_UTF8_VALUE
)
public class CursoRestController {
#Autowired
private CursoService cursoService;
#GetMapping
#ResponseStatus(HttpStatus.OK)
public List<Curso> listAll() {
System.out.println("Test");
return cursoService.findAll();
}
#PostMapping
public ResponseEntity<Void> save(#RequestBody Curso curso) {
cursoService.save(curso);
URI location = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}").buildAndExpand(curso.getId()).toUri();
return ResponseEntity.created(location).build();
}
I'm using Postman to send request, and when i send some request i get 400 error code, with no message or something to tell to me, what's happing, BUT when i try to open the same URL on the browser, I GET THE RESPONSE, i don't if i configured something wrong, i'm using theses classes to config my project
SpringRootConfig
#Configuration
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("br.com.gabriel.restful")
public class SpringRootConfig {
}
SpringInitConfig
public class SpringInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringRootConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[0];
}
#Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
SpringJpaConfig
#Configuration
public class SpringJpaConfig {
#Bean
public DataSource dataSource(){
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("org.postgresql.Driver");
ds.setUrl("jdbc:postgresql://localhost:5432/wildbuild");
ds.setUsername("postgres");
ds.setPassword("admin");
return ds;
}
#Bean
public EntityManagerFactory entityManagerFactory(){
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.setPackagesToScan("br.com.gabriel.restful.domain");
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setJpaProperties(jpaProperties());
factory.afterPropertiesSet();
return factory.getObject();
}
#Bean
public JpaTransactionManager jpaTransactionManager(){
JpaTransactionManager manager = new JpaTransactionManager();
manager.setEntityManagerFactory(entityManagerFactory());
manager.setJpaDialect(new HibernateJpaDialect());
return manager;
}
private Properties jpaProperties(){
Properties props = new Properties();
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.hbm2ddl.auto", "update");
return props;
}
}
My project have this structure:
project structure
I am studying java and spring and try to make my first spring mvc app. At first I made console app without spring mvc I used just only dao and service layers with JdbcTemplate. I have config file where I make Beans for DataSource and DataSourceInitializer for initializing database.
#EnableWebMvc
#EnableTransactionManagement
#ComponentScan("ru.stepev")
#PropertySource("classpath:config.properties")
public class UniversityConfig implements WebMvcConfigurer {
#Value("${driver}")
private String driver;
#Value("${url}")
private String url;
#Value("${user}")
private String user;
#Value("${pass}")
private String pass;
#Value("${schema}")
private Resource schema;
#Value("${data}")
private Resource data;
#Bean
public JdbcTemplate jdbcTamplate(DataSource dateSourse) {
return new JdbcTemplate(dateSourse);
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(pass);
return dataSource;
}
#Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
#Bean
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(schema);
resourceDatabasePopulator.addScript(data);
DataSourceInitializer dataSourceInitializer = new DataSourceInitializer();
dataSourceInitializer.setDataSource(dataSource);
dataSourceInitializer.setDatabasePopulator(resourceDatabasePopulator);
return dataSourceInitializer;
}
private final ApplicationContext applicationContext;
public UniversityConfig(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
#Bean
public SpringResourceTemplateResolver templateResolver() {
SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
templateResolver.setApplicationContext(applicationContext);
templateResolver.setPrefix("/WEB-INF/view/");
templateResolver.setSuffix(".jsp");
return templateResolver;
}
#Bean
public SpringTemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
templateEngine.setEnableSpringELCompiler(true);
return templateEngine;
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
registry.viewResolver(resolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
All shemes and data I stores in resourse folder. Without mvc everything were be ok. But when I have added MVC then I got java.io.FileNotFoundException org.springframework.jdbc.datasource.init.CannotReadScriptException: Cannot read SQL script from ServletContext resource [/schema.sql]; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/schema.sql]. DataSourceInitializer can't find schema.sql when I create my datebase. I have tried to solve this problem but I couldn't. I have next structure of project.enter image description here
I wil be very thaks for help me with this problem and sorry for my bad english.
I've found my mistake. I had an exception because I didn't put the word classpath before the file name in the properties file.
schema=classpath:schema.sql
data=classpath:data.sql
I have multiple end point and static wsdl, my application is created using Spring boot, I am unable to find a way to write junit test cases for various end point.
1. SoapServerConfig
#EnableWs
#Configuration
#ComponentScan
public class SoapServerConfig extends WsConfigurerAdapter {
#Bean
public ServletRegistrationBean messageDispatcherServlet(ApplicationContext appContext){
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(appContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean(servlet, "/ws/*");
}
#Bean(name = "beers")
public SimpleWsdl11Definition defaultWsdl11Definition(XsdSchema schema){
SimpleWsdl11Definition simpleWsdl11Definition = new SimpleWsdl11Definition();
simpleWsdl11Definition.setWsdl(new ClassPathResource("beer.wsdl"));
return simpleWsdl11Definition;
}
#Bean(name = "colddrink")
public SimpleWsdl11Definition defaultWsdl11Definition(XsdSchema schema){
SimpleWsdl11Definition simpleWsdl11Definition = new SimpleWsdl11Definition();
simpleWsdl11Definition.setWsdl(new ClassPathResource("colddrink.wsdl"));
return simpleWsdl11Definition;
}
#Bean
public XsdSchema beersSchema(){
return new SimpleXsdSchema(new ClassPathResource("xsd/beers.xsd"));
}
#Bean
public XsdSchema beersSchema(){
return new SimpleXsdSchema(new ClassPathResource("xsd/colddrink.xsd"));
}
BeerEndpointIntegrationTest.java
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = SoapServerConfig.class)
public class BeerEndpointIntegrationTest {
#Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
private Resource xsdSchema = new ClassPathResource("xsd/beers.xsd");
#Before
public void init(){
mockClient = MockWebServiceClient.createClient(applicationContext);
}
#Test
public void valid_xsd_request_response_test() throws IOException {
Source requestPayload = new StringSource(
"<beer:getBeerRequest xmlns:beer=\"http://memorynotfound.com/beer\">" +
"<beer:id>1</beer:id>" +
"</beer:getBeerRequest>");
Source responsePayload = new StringSource(
"<ns2:getBeerResponse xmlns:ns2=\"http://memorynotfound.com/beer\"></ns2:getBeerResponse>");
mockClient
.sendRequest(withPayload(requestPayload))
.andExpect(noFault())
.andExpect(payload(responsePayload))
.andExpect(validPayload(xsdSchema));
}
#Test
public void id_cannot_be_0_test() throws IOException {
Source requestPayload = new StringSource(
"<ns2:getBeerRequest xmlns:ns2=\"http://memorynotfound.com/beer\">" +
"<ns2:id>0</ns2:id>" +
"</ns2:getBeerRequest>");
mockClient
.sendRequest(withPayload(requestPayload))
.andExpect(serverOrReceiverFault());
}
}
In sample testcase I dint find a way to distinguish the declare url.
I have followed Spring boot Spring ws security for soap based web service but there is only one url here we have multiple
I am new at Spring and trying to xml based config to annotation basic. I read this tutorial amd coded. It works perfect with xml based config.
MVC Spring CRUD Tutorial
And now I converted all xml based config to annotation but I have a problem. I ried almost everything what I read but I didn't solve this problem.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.ulotrix.spring.controller.PersonController.setPersonService(com.ulotrix.spring.service.PersonService); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.ulotrix.spring.service.PersonService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
AppConfig.java
#EnableWebMvc
#Configuration
#ComponentScan({ "com.ulotrix.spring.controller" })
public class AppConfig extends WebMvcConfigurerAdapter {
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
builder.scanPackages("com.ulotrix.spring.model");
builder.addProperties(getHibernationProperties());
return builder.buildSessionFactory();
}
private Properties getHibernationProperties() {
Properties prop = new Properties();
prop.put("hibernate.format_sql", "true");
prop.put("hibernate.show_sql", "true");
prop.put("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
return prop;
}
#Bean(name = "dataSource")
public BasicDataSource dataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://localhost:3306/deneme_db2");
ds.setUsername("root");
ds.setPassword("xxx");
return ds;
}
#Bean
public HibernateTransactionManager txManger() {
return new HibernateTransactionManager(sessionFactory());
}
#Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
SpringMVCInitializer.java
public class SpringMvcInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext container) {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
rootContext.register(AppConfig.class);
// Manage the lifecycle of the root application context
container.addListener(new ContextLoaderListener(rootContext));
// Create the dispatcher servlet's Spring application context
AnnotationConfigWebApplicationContext dispatcherServlet = new AnnotationConfigWebApplicationContext();
dispatcherServlet.register(AppConfig.class);
// Register and map the dispatcher servlet
ServletRegistration.Dynamic dispatcher = container.addServlet("dispatcher", new DispatcherServlet(dispatcherServlet));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/");
}
}
PersonController.java
#Controller
public class PersonController {
private PersonService personService;
#Autowired(required = true)
#Qualifier(value = "personService")
public void setPersonService(PersonService ps) {
this.personService = ps;
}
#RequestMapping(value = "/persons", method = RequestMethod.GET)
public String listPersons(Model model) {
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
//For add and update person both
#RequestMapping(value = "/person/add", method = RequestMethod.POST)
public String addPerson(#ModelAttribute("person") Person p) {
if(p.getId() == 0) {
this.personService.addPerson(p);
}else {
this.personService.updatePerson(p);
}
return "redirect:/persons";
}
#RequestMapping(value = "/remove/{id}")
public String removePerson(#PathVariable("id") int id) {
this.personService.removePerson(id);
return "redirect:/persons";
}
#RequestMapping(value = "/edit/{id}")
public String editPerson(#PathVariable("id") int id, Model model) {
model.addAttribute("person", this.personService.getPersonById(id));
model.addAttribute("listPersons", this.personService.listPersons());
return "person";
}
}
The PersonService is defined in package com.ulotrix.spring.services, so change #ComponentScan({ "com.ulotrix.spring.controller" }) to #ComponentScan({ "com.ulotrix.spring" }) thanks to which spring can discover all the beans defined inside package spring.
I am trying to setup a page not found catch in my Spring WebMVCConfig bit its not working..
here is my config:
#Configuration
#EnableWebMvc
#PropertySource("classpath:application.properties")
#Import(DatabaseConfig.class)
#ImportResource("/WEB-INF/spring/applicationContext.xml")
public class WebMVCConfig extends WebMvcConfigurerAdapter {
private static final String MESSAGE_SOURCE = "/WEB-INF/classes/messages";
private static final Logger logger = LoggerFactory.getLogger(WebMVCConfig.class);
#Autowired
Environment env;
#Bean
public ViewResolver resolver() {
UrlBasedViewResolver url = new UrlBasedViewResolver();
url.setPrefix("/WEB-INF/view/");
url.setViewClass(JstlView.class);
url.setSuffix(".jsp");
return url;
}
#Bean(name = "messageSource")
public MessageSource configureMessageSource() {
logger.debug("setting up message source");
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename(MESSAGE_SOURCE);
messageSource.setCacheSeconds(5);
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver lr = new SessionLocaleResolver();
lr.setDefaultLocale(Locale.ENGLISH);
return lr;
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
logger.debug("setting up resource handlers");
registry.addResourceHandler("/resources/").addResourceLocations("/resources/**");
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
logger.debug("configureDefaultServletHandling");
configurer.enable();
}
#Override
public void addInterceptors(final InterceptorRegistry registry) {
registry.addInterceptor(new LocaleChangeInterceptor());
}
public #Bean HandlerExceptionResolver exceptionResolver() {
Properties mappings = new Properties();
mappings.put("org.springframework.web.servlet.PageNotFound", "404");
mappings.put(DataAccessException.class.getName(), "dataAccessFailure");
mappings.put(TransactionException.class.getName(), "dataAccessFailure");
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
resolver.setExceptionMappings(mappings);
return resolver;
}
#Bean
public DefaultAnnotationHandlerMapping mapping() {
DefaultAnnotationHandlerMapping m = new DefaultAnnotationHandlerMapping();
m.setDetectHandlersInAncestorContexts(true);
return m;
}
}
now if I put in a URL that is not mapped I would think it would goto my 404.jsp page?
The way to configure a custom error page (for 404 or any other error code) is in the web.xml...
<error-page>
<error-code>404</error-code>
<location>/my-custom-page-not-found.html</location>
</error-page>
The url can be a static page, a custom jsp or even a Spring controller.
You can use #ExceptionHandler annotated method or #ControllerAdvice class.
Several methods are described in this post of the forum.
Alternatively, you can also refer Spring Docs - Handling exceptions section.