mardi 31 mars 2015

How to initialize SystemUsage of ActiveMQ with spring-boot?

I'm trying to initialize embedded activemq JMS using spring-boot. It works in general, but I want to also lower the memory usage. Therefore I'm trying to provide the SystemUsage as a bean.


But the SystemUsage bean is not taken into account and the activemq embedded has still the default configuration of 1GB . What might be wrong?



@EnableAutoConfiguration
@EnableJms
public class AppConfig {
@Bean
public SystemUsage systemUsage() {
MemoryPropertyEditor editor = new MemoryPropertyEditor();
SystemUsage system = new SystemUsage();

MemoryUsage memory = new MemoryUsage();
editor.setAsText("20mb");
memory.setLimit((long) editor.getValue());
system.setMemoryUsage(memory);

return system;
}
}

spring bean explicit singleton scope declaration

In below spring bean declaration, I wonder why do we need explicit scope="singleton". Isn't it redundant?



<bean class="com.foo.blah.JerseyJacksonConfigFactory" factory-method="getProvider" scope="singleton"/>



public class JerseyJacksonConfigFactory {
public static ClientConfig getConfig() {
JacksonJsonProvider jsonProvider = getProvider();
DefaultClientConfig config = new DefaultClientConfig();
config.getSingletons().add(jsonProvider);
return config;
}

public static JacksonJsonProvider getProvider() {
ObjectMapper mapper = getObjectMapper();
JacksonJsonProvider jsonProvider = new JacksonJsonProvider();
jsonProvider.setMapper(mapper);
return jsonProvider;
}

public static ObjectMapper getObjectMapper() {
return new ObjectMapper()
.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)
.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);
}
}

Spring-Social twitter-trends not working properly

I cloned the repo from github and as per the instruction over there I executed



$ ./gradlew tomcatRun


Command and the tomcat server was started and I login with my twitter credentials. Now, if I click on trends in the left tab, it gives a list of trends and I I click on any of em, they just give me a 404. Not sure what is causing it. Please help me fox this.


Looks like there is also a bug posted on the github about this.


How Spring container uses Dependency injection to create a bean

While learining Spring, I come to know that in spring every object is maintained by container and it uses dependency injection to create a bean. I want to know how spring container works internally for populating a bean with a new or existing dependent object. How it maintain every object mapping in container ?


DandelionException: The file 'resources/.......json' is wrongly formatted

I'm using spring boot with thymeleaf and dandelion. I'm using Gradle to build. The error does not show up when i execute the application as gradlew bootRun This error only occurs when I try to run the jar file using java -jar ....jar


NOTE When I remove the file 'resources/lib/icheck/icheck.jquery.json' i get rid of the error. So there can be some error in the JSON file. But I don't find any.


Here is my dandelion configuration



@Configuration
public class DandelionConfig {

@Bean
public DandelionDialect dandelionDialect() {
return new DandelionDialect();
}

@Bean
public DataTablesDialect dataTablesDialect(){
return new DataTablesDialect();
}

@Bean
public Filter dandelionFilter() {
return new DandelionFilter();
}

@Bean
public ServletRegistrationBean dandelionServletRegistrationBean() {
return new ServletRegistrationBean(new DandelionServlet(), "/dandelion-assets/*");
}
}


According to error message, this is the json file which has the error. 'resources/lib/icheck/icheck.jquery.json'



{
"name": "icheck",
"version": "1.0.2",
"title": "iCheck",
"author": {
"name": "Damir Sultanov",
"email": "info@fronteed.com",
"homepage": "http://fronteed.com/"
},
"licenses": [
{
"type": "MIT",
"url": "http://ift.tt/O8obFi"
}
],
"dependencies": {
"jquery": ">=1.7"
},
"description": "Highly customizable checkboxes and radio buttons (jQuery and Zepto). Features: identical inputs across different browsers and devices (both desktop and mobile), touch devices support (iOS, Android, BlackBerry, Windows Phone, Amazon Kindle), keyboard accessible inputs (Tab, Spacebar, Arrow up/down and other shortcuts), screenreader accessible inputs — (ARIA attributes for VoiceOver and others), customization freedom (use any HTML and CSS to style inputs or try 6 Retina-ready skins), lightweight size (1 kb gzipped). Provides 32 options to customize checkboxes and radio buttons, 11 callbacks to handle changes, 9 methods to make changes programmatically. Saves changes to original inputs, works carefully with any selectors.",
"keywords": [
"checkbox",
"radio",
"input",
"field",
"form",
"desktop",
"mobile",
"custom",
"replacement",
"accessibility",
"skins",
"ui",
"checked",
"disabled",
"indeterminate",
"css3",
"html5",
"tiny",
"lightweight",
"jquery",
"zepto"
],
"homepage": "http://ift.tt/1do44mv",
"docs": "http://ift.tt/19stLQK",
"demo": "http://ift.tt/1do44mv",
"download": "http://ift.tt/1do44mv",
"bugs": "http://ift.tt/1xTXfVj"
}


This is the error message I get when I execute the application.



oryAssetCache)
2015-04-01 00:00:41.545 INFO 9652 --- [ost-startStop-1] com.github.dandelion.core.Context : Asset processor found: JsMinProcessor
2015-04-01 00:00:41.548 INFO 9652 --- [ost-startStop-1] com.github.dandelion.core.Context : Asset processor found: CssMinProcessor
2015-04-01 00:00:41.556 INFO 9652 --- [ost-startStop-1] com.github.dandelion.core.Context : Asset processor found: CssUrlRewritingProcessor
2015-04-01 00:00:41.557 INFO 9652 --- [ost-startStop-1] com.github.dandelion.core.Context : Asset processors disabled. All assets will be left
untouched.
2015-04-01 00:00:42.173 ERROR 9652 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Exception starting filter dandelionFilter

com.github.dandelion.core.DandelionException: The file 'resources/lib/icheck/icheck.jquery.json' is wrongly formatted. Please correct it before continuing.
at com.github.dandelion.core.bundle.loader.spi.AbstractBundleLoader.loadBundles(AbstractBundleLoader.java:112)
at com.github.dandelion.core.Context.initBundleStorage(Context.java:315)
at com.github.dandelion.core.Context.init(Context.java:122)
at com.github.dandelion.core.Context.<init>(Context.java:101)
at com.github.dandelion.core.web.DandelionFilter.init(DandelionFilter.java:106)
at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:279)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:109)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4615)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5222)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1409)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1399)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: org.springframework.boot.loader.jar.ZipInflaterInputStream@556fdc2; line: 15, column: 4] (through reference chain: com.github.dandelion.c
ore.storage.BundleStorageUnit["dependencies"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:762)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:758)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.handleNonArray(StringCollectionDeserializer.java:222)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:164)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:154)
at com.fasterxml.jackson.databind.deser.std.StringCollectionDeserializer.deserialize(StringCollectionDeserializer.java:19)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:538)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:99)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:238)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:118)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2207)
at com.github.dandelion.core.bundle.loader.spi.AbstractBundleLoader.loadBundles(AbstractBundleLoader.java:104)
... 15 common frames omitted

Spring @Autowired of @Service classes works on Tomcat but not Resin

I have a 100% working solution in Tomcat 8.0.20 packaged as a WAR using Spring restful services and spring core libraries.


When I take the same WAR and drop it into Resin 4.0.36 (and also 4.0.43) my @Autowired @Services are not recognized whatsoever.


This leads me to believe that there is an environmental difference between Tomcat and Resin. Do I need to set some property or reference something explicitly to make the WAR work on Resin?



2015-03-30 17:26:25 WARN XmlWebApplicationContext:487 - Exception
encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userInfoWebService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private ca.abcc.service.user.UserService ca.abcc.controller.webservice.UserInfo.UserInfoWebService.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ca.abcc.service.user.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:70)
at com.caucho.server.dispatch.ServletConfigImpl.createServletImpl(ServletConfigImpl.java:1358)
at com.caucho.server.dispatch.ServletConfigImpl.createServlet(ServletConfigImpl.java:1254)
at com.caucho.server.dispatch.ServletConfigImpl.createServlet(ServletConfigImpl.java:1205)
at com.caucho.server.dispatch.ServletManager.init(ServletManager.java:251)
at com.caucho.server.webapp.WebApp.startImpl(WebApp.java:3777)
at com.caucho.server.webapp.WebApp.access$700(WebApp.java:208)
at com.caucho.server.webapp.WebApp$StartupTask.run(WebApp.java:5297)
at com.caucho.env.thread2.ResinThread2.runTasks(ResinThread2.java:173)
at com.caucho.env.thread2.ResinThread2.run(ResinThread2.java:118)
Caused by: org.springframework.beans.factory.BeanCreationException: Could
not autowire field: private ca.abcc.service.user.UserService
ca.abcc.controller.webservice.UserInfo.UserInfoWebService.userService;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type [ca.abcc.service.user.UserService] found for
dependency: expected at least 1 bean which qualifies as autowire candidate
for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
atorg.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostPr
ocessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 26 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type [ca.abcc.service.user.UserService] found
for dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{@org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 28 more
2015-03-30 17:26:25 ERROR DispatcherServlet:497 - Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userInfoWebService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private ca.abcc.service.user.UserService ca.abcc.controller.webservice.UserInfo.UserInfoWebService.userService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ca.abcc.service.user.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
{resin-50} WebApp[production/webapp/default/Impact.Auto.Online.Buyer.Portal] fail
[15-03-30 17:26:25.294] {resin-15} org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [ca.impactauto.service.user.UserService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1202)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:663)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:629)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:677)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:548)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:489)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
at javax.servlet.GenericServlet.init(GenericServlet.java:70)
at com.caucho.server.dispatch.ServletConfigImpl.createServletImpl(ServletConfigImpl.java:1358)
at com.caucho.server.dispatch.ServletConfigImpl.createServlet(ServletConfigImpl.java:1254)
at com.caucho.server.dispatch.ServletConfigImpl.createServlet(ServletConfigImpl.java:1205)
at com.caucho.server.dispatch.ServletManager.init(ServletManager.java:251)
at com.caucho.server.webapp.WebApp.startImpl(WebApp.java:3777)
at com.caucho.server.webapp.WebApp.access$700(WebApp.java:208)
at com.caucho.server.webapp.WebApp$StartupTask.run(WebApp.java:5297)
at com.caucho.env.thread2.ResinThread2.runTasks(ResinThread2.java:173)
at com.caucho.env.thread2.ResinThread2.run(ResinThread2.java:118)


Dispatcher Servlet:



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://ift.tt/GArMu6"
xmlns:context="http://ift.tt/GArMu7"
xmlns:p="http://ift.tt/1jdM0fE"
xmlns:mvc="http://ift.tt/1bHqwjR"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/GArMu6
http://ift.tt/1cnl1uo
http://ift.tt/GArMu7
http://ift.tt/1ldEMZY
http://ift.tt/1bHqwjR
http://ift.tt/1kF4x7W
">

<mvc:annotation-driven />
<!-- <mvc:default-servlet-handler/>-->
<!-- <context:annotation-config />-->
<context:component-scan base-package="ca.xyz.controller" />
<context:annotation-config />

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />-->
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>

<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

<mvc:view-controller path="/" view-name="welcome"/>

</beans>

Having issue with Spring mvc file upload

My spring WebInitializer class adds the dispatcher.setMultipartConfig(new MultipartConfigElement("/"))



public class WebInitializer implements WebApplicationInitializer {

private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
private static final String DISPATCHER_SERVLET_MAPPING = "/";
private static final Logger log = Logger.getLogger(WebInitializer.class);

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

AnnotationConfigWebApplicationContext ctx
= new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
log.debug(ctx);
// Add the servlet mapping manually and make it initialize automatically
ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(ctx));

dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING);
dispatcher.setLoadOnStartup(1);
dispatcher.setMultipartConfig(new MultipartConfigElement("/"));

EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);

CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceEncoding(true);

FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");

FilterRegistration.Dynamic security = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());
security.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
log.debug(security);

FilterRegistration.Dynamic sitemesh = servletContext.addFilter("sitemesh", new MySiteMeshFilter());
sitemesh.addMappingForUrlPatterns(dispatcherTypes, true, "*.jsp");

servletContext.addListener(new ContextLoaderListener(ctx));
}
}


My WebMvcConfig class has a multipartResolver() method with @Bean annotation.



@EnableWebMvc
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

private static final Logger log = Logger.getLogger(WebMvcConfig.class);

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
log.debug(configurer);
}

@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
log.debug(viewResolver);
return viewResolver;
}

@Bean
public SimpleMappingExceptionResolver exceptionResolver() {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();

Properties exceptionMappings = new Properties();

exceptionMappings.put("java.lang.Exception", "error/error");
exceptionMappings.put("java.lang.RuntimeException", "error/error");

exceptionResolver.setExceptionMappings(exceptionMappings);

Properties statusCodes = new Properties();

statusCodes.put("error/404", "404");
statusCodes.put("error/error", "500");

exceptionResolver.setStatusCodes(statusCodes);

log.debug(exceptionResolver);
return exceptionResolver;
}

@Bean
public CommonsMultipartResolver multipartResolver(){
CommonsMultipartResolver cmr = new CommonsMultipartResolver();
cmr.setDefaultEncoding("UTF-8");
cmr.setMaxUploadSize(-1);
return cmr;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
log.debug(registry);
}
}


The AppConfig class is used to just for importing necessary configuartion classes.



@Configuration
@ComponentScan(basePackages = {"edu.indstate.ics.transcript"})
@Import(value = {WebMvcConfig.class, SecurityConfig.class, DataConfig.class})
public class AppConfig {

}


UploadedFile class



public class UploadedFile {

private MultipartFile uploadedFile;
private String name = null;

public MultipartFile getUploadedFile() {
return uploadedFile;
}

public void setUploadedFile(MultipartFile uploadedFile) {
this.uploadedFile = uploadedFile;
this.name = uploadedFile.getOriginalFilename();
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


Edited uploadXML.jsp and added missing encyte attribute


2nd Edit added modelAttribute="uploadedFile"



<%@ taglib prefix="form" uri="http://ift.tt/IED0jK"%>

<div class="modal fade" id="uploadXMLTranscript" tabindex="-1" role="dialog" aria-hidden="true">
<form:form id="uploadXMLTranscriptForm" method="POST" modelAttribute="uploadedFile" enctype='multipart/form-data' action="uploadXMLTranscript?${_csrf.parameterName}=${_csrf.token}">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times; </span></button>
<h4 class="modal-title">Upload XML Transcript</h4>
</div>
<div class="modal-body">
<p>
<div class="input-group">
<label for="file">Transcript Id: </label>
<input id="file" type="file" name="uploadedFile" accept="text/xml" />
</div>
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" >Upload</input>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</form:form>
</div><!-- /.modal -->


and finally the controller class updated added @ModelAttribute instead of @RequestParam



@Controller
public class TranscriptUploadController {

private static final Logger logger = Logger.getLogger(TranscriptUploadController.class);

@Autowired
private TranscriptBo transcriptBo;

@RequestMapping(value = {"/", "/secure/uploadXMLTranscript**"}, method = RequestMethod.POST)
public String uploadXMLTranscript(@ModelAttribute("uploadedFile") UploadedFile file, ModelMap model) {
String userName = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

TranscriptStatusCounts transStatCount = transcriptBo.findTranscriptStatusCount();

logger.debug(file);

model.addAttribute("uploadedFile", new UploadedFile());
model.addAttribute("transStatCount", transStatCount);
model.addAttribute("userName", userName);

logger.debug("Preparing to transform uploadedFile object = " + file);

List<Swbhxml> transcripts = new ArrayList<>();
// transcripts.add(transcript);

model.addAttribute("transcripts", transcripts);
model.addAttribute("headerTitle", "Search by Transcript Last Name Results");

if (null != transcripts && transcripts.size() > 0) {
model.addAttribute("transcript", transcripts.get(0));
} else {
model.addAttribute("transcript", new Swbhxml());
}

return "secure/transcript/viewStudentTranscript";
}
}


I have been messing with this for a while and appreciate any assistance.


Thanks!


EDITED I saw I was missing encyte attribute on the form tag...


But now the error has changed to:



org.springframework.web.bind.MissingServletRequestParameterException: Required UploadedFile parameter 'uploadedFile' is not present


So...not sure what this means, I mean my controller method has the @RequestParam("uploadedFile") UploadedFile file


AND updated that to @ModelAttribute which now allows controller method to be hit...however, the UploadedFile object properties are null meaning that MultipartFile property is not being set...


addition edit added modelAttribute="uploadedFile" to form tag... still looks like custom model UploadedFile property is not binding to MultipartFile


Any ideas?


retrieve image from database using spring mvc

UserEntityManager.java



@RequestMapping(value = "getImages.do", method = RequestMethod.GET)
public byte[] getImage(final String username) {
Blob img = null;
byte[] imgData = null;
sql = "SELECT UserPhoto FROM u_logininfo WHERE LoginName = ?";

try {
img = jdbcTemplate.queryForObject(sql, new Object[]{username}, new RowMapper<Blob>() {

@Override
public Blob mapRow(ResultSet rs, int arg1)
throws SQLException {
Blob blob = rs.getBlob("UserPhoto");
return blob;
}

});

imgData = img.getBytes(1, (int) img.length());
return imgData;
//File file = new File
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}


And this is my controller


UserController.java



@RequestMapping(value = "getImages.do" , method = RequestMethod.GET)
private ModelAndView viewImages(Model model){
String userName = (String)SecurityContextHolder.getContext().getAuthentication().getName();
byte[] image = userEntityManager.getImage(userName);
model.addAttribute("images", image);
return new ModelAndView("Fun Zone/Photo");
}


and jsp



<div class="col-sm-2" style="margin-top: 288px; margin-left: 291px;">
<img src="getImages.do">
</div>


I want to display the image on the .jsp page using Spring MVC 3 But image not display in jsp.


Cannot convert value of type [org.springframework.web.client.RestTemplate] to required type [org.springframework.web.client.RestTemplate]

I am trying to use RestTemplate and getting below error only when I am trying to initialize the RestTemplate bean.



Cannot convert value of type [org.springframework.web.client.RestTemplate] to required type [org.springframework.web.client.RestTemplate] for property 'restTemplate': no matching editors or conversion strategy found



This is my bean configuration : Here i am initializing the restTemplate to use it in MyService.java class



<bean id="myService" class="com.test.MyService">
<property name="serviceUrl" value="http://ift.tt/1OVNsTI"/>
<property name="restTemplate" ref="restTemplate"/>
</bean>

<bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
</bean>


This is my java code



package com.test;
import org.springframework.web.client.RestTemplate;

public class MyService {

private String serviceUrl;
private RestTemplate restTemplate;

public String invoke(){
//restTemplate = new RestTemplate(); -- This works, if bean //initialization removed from spring xml file
String result = restTemplate.getForObject(serviceUrl, String.class);
return result;
}

//@Required
public void setServiceUrl(String serviceUrl) {
this.serviceUrl = serviceUrl;
}

public String getServiceUrl() {
return this.serviceUrl;
}

public RestTemplate getRestTemplate() {
return restTemplate;
}

public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
}


But same code is working if I create object of RestTemplate in java class itself and remove the



<bean id="restTemplate" class="org.springframework.web.client.RestTemplate"/>


from my spring xml file.


I want to use mvc:resource/ such as mvc:resources mapping="/images/" location="/images/"/ mvc:resources mapping="/resources/" location="/resources/"/in context-mvc.groovy,and i do not know how to write.hope someone can help me



import org.springframework.web.servlet.view.InternalResourceViewResolver

beans {
xmlns context: "http://ift.tt/GArMu7"


context."component-scan"("base-package" : "com.oberon.fm")

viewResolver(InternalResourceViewResolver) {
prefix = "/pages/"
suffix = ".jsp"
}
}

Spring 4 @Autowire not binding correctly?

I m trying to Autowire a bean to a implementation but it returns a null pointer Exception.



package org.com.api;
public interface Multiply{
public int multipler(int a, int b);
}
package org.com.core;
import org.com.api.Multiply;
public class MultiplyImpA implements Multiply{
public int multipler(int a, int b){
return a*b;
}
}
package org.com.core;
import org.com.api.Multiply;
public class MultiplyImpB implements Multiply{
public int multipler(int a, int b){
int total = 0;
for(int i = 1; i <=b; i++){
total += a;

}
return total;
}
}

package org.com.Service;
import org.com.api.Multiply;
public Calculator {
@Autowire
private Multiply multiply ;
public int calcMultiply(int a, int b){
return multiply.multipler(a,b);
}
}


In my applicationContext.xml I have added the following



<bean id="multiply" class="package org.com.core.MultiplyImpA" scope="prototype"/>


Now in runtime I get a NullPointerExpection. multiply is null.


for testing purpose I tried this. It works, I understand here I m explicitly getting the Bean. So this means the autowire didnt work ? is there something I m missing ?



Multiply m=(Multiply)factory.getBean("multiply");
System.out.println(m.multiplier(2,4);

Interceptor in Spring4 does not work

I am using Spring MVC 4.1.4 in my application, and I found that the Interceptor does not work as expected, it seems that the interceptor does not even get invoked:



public class AutheInterceptor implements HandlerInterceptor {
@Autowired
private UserService userService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
User user = userService.getUser();
return user != null;
}
//other methods omitted
}


And the mvc configuration(part):



<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="*"/>
<bean class="com.app.interceptor.AutheInterceptor">
<property name="userService" ref="userService"/>
</bean>
</mvc:interceptor>
</mvc:interceptors>


Full configuration: http://ift.tt/1FfK1lu


I have searched at google and sf, but I can not find anything helpful.


Spring context loader

I have a question about spring context. My application's using spring and spring scheduler. In web.xml, i declared:



<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


My question is:


If I declared org.springframework.web.context.ContextLoaderListener in web.xml, the scheduler will run twice, all beans are duplicate, and App start-up time about 160 seconds.


If I remove org.springframework.web.context.ContextLoaderListener, spring throws exception: No WebApplicationContext found: no ContextLoaderListener registered. And App start-up time reduce to 80 seconds.


How can i solve it? Thanks all!


Trouble starting rails application

I am very new to ruby on rails and I'm having this problem with creating a new controller for my "plans" resource:



rails generate controller plans
/Users/RentaroSatomi/.rbenv/versions/2.1.5/lib/ruby/gems/2.1.0/gems/bundler-1.8.0/lib/bundler/runtime.rb:34:in
'block in setup': You have already activated spring 1.3.3,
but your Gemfile requires spring 1.3.1.
Prepending 'bundle exec' to your command may solve this. (Gem::LoadError)


The error says something about having a wrong spring version, but I really don't know how to fix this.


spring @SessionAttributes and "Cannot create a session after the response has been committed"

I am trying to set and get a session attribute, but either I have misunderstood how it works or i've done something wrong.


Please could somebody explain why this doesn't work.


I have the following simple Spring Web MVC Controller



@Controller
@SessionAttributes("sessid")
@RequestMapping("sesstest")
public class SessTest
{
@RequestMapping("in")
@ResponseBody
public String in(ModelMap model){
String uuid = UUID.randomUUID().toString();
model.addAttribute("sessid", uuid);
return uuid;
}

@RequestMapping("out")
@ResponseBody
public String out(@ModelAttribute("sessid") String sesid){
return sesid;
}
}


This class should just set a session variable when calling /sesstest/in and then recall it when calling /sesstest/out


But It get the following exception when calling /in


(The stacktrace is shown on the console, the web output is OK)



java.lang.IllegalStateException: Cannot create a session after the response has been committed
at org.apache.catalina.connector.Request.doGetSession(Request.java:2872)
at org.apache.catalina.connector.Request.getSession(Request.java:2249)
at org.apache.catalina.connector.RequestFacade.getSession(RequestFacade.java:895)
at org.springframework.web.context.request.ServletRequestAttributes.getSession(ServletRequestAttributes.java:111)
at org.springframework.web.context.request.ServletRequestAttributes.setAttribute(ServletRequestAttributes.java:161)
at org.springframework.web.bind.support.DefaultSessionAttributeStore.storeAttribute(DefaultSessionAttributeStore.java:55)
at org.springframework.web.method.annotation.SessionAttributesHandler.storeAttributes(SessionAttributesHandler.java:124)
at org.springframework.web.method.annotation.ModelFactory.updateModel(ModelFactory.java:232)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.getModelAndView(RequestMappingHandlerAdapter.java:879)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:782)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:705)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1086)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:659)
at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1558)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1515)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)


Thanks!


Spring + JPA @OneToMany with orphanRemoval

I'm having a little (big) problem with Spring list form binding, and orphanRemoval. This exception occurs only when updating some item - insert and delete does work.


"A collection with cascade="all-delete-orphan" was no longer referenced by the owning entity instance: me.gerenciar.model.entity.PedidoItem.filhos"


Well, I have a form, and in this form, there are some items (children) that is dynamically inserted/deleted/updated on front-end with javascript.


I've made two other forms like this one, and they works perfectly, the only difference is that in this one, we have 3 hierarchy level, and the others were just 1 hierarchy level.


I know all that stuff that we can not set new dictionary like this: "this.children = children;" but this is made by Spring by reflection when binding the form entity. And as I had said, it did work on 2 other cases.


Here are my entities (without getters and setters).



//BaseEntity is just a generic way to override equals, toString and hashCode

@Entity
@Table(name = "PEDIDO")
public class Pedido extends BaseEntity
{
private static final long serialVersionUID = 1586104653460442257L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID_PEDIDO")
private Integer pedidoId;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID_PESSOA_ESTABELECIMENTO")
private Estabelecimento estabelecimento;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID_PESSOA_CLIENTE")
private Cliente cliente;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({ @JoinColumn(name = "ID_MESA", referencedColumnName = "ID_MESA", insertable = false, updatable = false), @JoinColumn(name = "ID_PESSOA_ESTABELECIMENTO", referencedColumnName = "ID_PESSOA", insertable = false, updatable = false) })
private Mesa mesa;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID_TURNO")
private Turno turno;

@DateTimeFormat(iso = ISO.DATE_TIME)
@Column(name = "DATA")
private Date data;

@Column(name = "DATA", updatable = false, insertable = false)
private String rawData;

@Column(name = "PRECO")
private BigDecimal preco;

@Column(name = "FINALIZADO")
private Boolean finalizado;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "pedido", orphanRemoval = true)
@OrderBy("ID_PEDIDO_ITEM_GRUPO DESC")
private List<PedidoItemGrupo> pedidoItemGrupos;

@Column(name = "DATA_ANO")
private Integer dataAno;

@Column(name = "DATA_MES")
private Integer dataMes;

@Column(name = "DATA_DIA")
private Integer dataDia;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ID_CHEQUE")
private Cheque cheque;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinTable(name = "PEDIDO_CARTAO", joinColumns = { @JoinColumn(name = "ID_PEDIDO", referencedColumnName = "ID_PEDIDO") }, inverseJoinColumns = { @JoinColumn(name = "ID_CARTAO", referencedColumnName = "ID_CARTAO") })
private List<Cartao> cartoes;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ID_DINHEIRO")
private Dinheiro dinheiro;

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ID_BOLETO")
private Boleto boleto;
}

@Entity
@Table(name = "PEDIDO_ITEM_GRUPO")
public class PedidoItemGrupo extends BaseEntity
{
private static final long serialVersionUID = 7785627059444833691L;

public static enum Tipo
{
DIVIDIDO, SOMADO
}

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID_PEDIDO_ITEM_GRUPO")
private Integer pedidoItemGrupoId;

@JsonIgnore
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID_PEDIDO")
private Pedido pedido;

@Column(name = "QUANTIDADE")
private BigDecimal quantidade;

@Column(name = "PRECO_UNITARIO")
private BigDecimal precoUnitario;

@Column(name = "PRECO")
private BigDecimal preco;

@Column(name = "DESCONTO")
private BigDecimal desconto;

@Column(name = "PRECO_FINAL")
private BigDecimal precoFinal;

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "pedidoItemGrupo", orphanRemoval = true)
@Where(clause = "EXISTS (SELECT * FROM PEDIDO_ITEM WHERE ID_PEDIDO_ITEM_PAI IS NULL)")
private List<PedidoItem> pedidoItens;
}

@Entity
@Table(name = "PEDIDO_ITEM")
public class PedidoItem extends BaseEntity
{
private static final long serialVersionUID = 5296905009119022656L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "ID_PEDIDO_ITEM")
private Integer pedidoItemId;

@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "ID_PEDIDO_ITEM_PAI")
private PedidoItem pai;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "pai", fetch = FetchType.EAGER, orphanRemoval = true)
private List<PedidoItem> filhos;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID_PRODUTO", insertable = false, updatable = false)
private Produto produto;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID_PRODUTO_CATEGORIA")
private ProdutoCategoria produtoCategoria;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumns({ @JoinColumn(name = "ID_PRODUTO", referencedColumnName = "ID_PRODUTO"), @JoinColumn(name = "TAMANHO", referencedColumnName = "TAMANHO") })
private ProdutoTamanho produtoTamanho;

@JsonIgnore
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "ID_PEDIDO_ITEM_GRUPO")
private PedidoItemGrupo pedidoItemGrupo;

@Column(name = "QUANTIDADE")
private BigDecimal quantidade;

@Column(name = "PRECO_UNITARIO")
private BigDecimal precoUnitario;

@Column(name = "PRECO")
private BigDecimal preco;

@Column(name = "DESCONTO")
private BigDecimal desconto;

@Column(name = "PRECO_TOTAL_UNITARIO")
private BigDecimal precoTotalUnitario;

@Column(name = "PRECO_TOTAL")
private BigDecimal precoTotal;

@Column(name = "PRECO_TOTAL_FINAL")
private BigDecimal precoTotalFinal;
}


If you guys need more details I'll immediately post it. thank you so much!




I have tried this also: http://ift.tt/1BJF9Az


no succeed =(, got null pointer exception when spring try to bind List filhos


Proper Way to layer Spring JPA based DAO using Spring Boot Framework

Am new to Spring Boot & JPA...


Let's say I have two entities mapped to two tables which are joined in a database.


Student-1------<-Course


Also, lets presume that the database is already created and populated.


This depicts that one student has many courses...


My Student Entity:



@Entity
public class Student {

@OneToMany(mappedBy="student")
private List<Courses> courses;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Student_Id")
private long studentId;

@Column(name = "Student_Name")
private String studentName;

protected Student() { }

// Getters & Setters
}


My Course Entity:



@Entity
public class Course {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "Course_Id")
private long courseId;

@Id
@Column(name = "Student_Id")
private long studentId;

@ManyToOne
@PrimaryKeyJoinColumn(name="Student_Id", referencedColumnName="Student_Id")
private Student student;

@Column(name = "Course_Name")
private String courseName;

// Getters & Setters

}


In Spring Boot's Tutorial Guides, it illustrates how to extend a CrudRepository interface, but it doesn't specify how to setup a Spring based DAO which contains custom finder methods which use HQL and EntityManager inside it.


Is the following DAO and DaoImpl correct?



public interface CourseDao {
List<Course> findCoursesByStudentName(String studentName);
}

@Repository
public class CourseDaoImpl implements CourseDao {

@PersistenceContext
EntityManager em;

public List<Course> findCoursesByStudentName(String studentName) {
String sql = "select c.courseName" +
"from Course c, Student s " +
"where c.course_id = s.student_id " +
"and s.studentName = :studentName ";

Query query = em.createQuery(sql);
query.setParameter("studentName", studentName);
return query.getResultList();
}
}


And then in the client code, for example, in the main class:



public class Application {

@Autowired
CustomerDao dao;

public static void main (String args []) {
List<Course> courses = dao.findCoursesByStudentName("John");
}
}


Is this the standard way to use HQL inside Spring DAOs ? I've seend examples of the @Transactional annotation being prepended to the DAO class's impl (e.g. CustomerDAOImpl) ?


Please let me know if this is the write way to structure my Spring Boot app or am I supposed to extend / add to the CrudRepository only?


If someone could correct my example and point me to a URL which talks about HQL using Entities that are joined, I would be very grateful.


The Spring Boot guides didn't depict joins or DAOs - I just need to learn how to properly create finder methods which emulate select statement which return lists or data structures.


Thanks for taking the time to read this...


How to check for Request Scope availability in Spring?

I'm trying to setup some code that will behave one way if spring's request scope is available, and another way if said scope is not available.


The application in question is a web app, but some things can be initiated by Quartz Scheduler or JMX


E.g.



@Named
class MySingletonBean{
@Inject
private MyRequestScopedBean myRequestScopedBean;

public void someMethod(){
if(/* your awesome solution here */){
myRequestScopedBean.invoke();
}else{
//do something else
}
}
}


Assuming myRequestScopedBean is request scoped.


I know this can be done with a try-catch around the invocation of myRequestScopedBean but that seems really clunky, so I'm wondering if anyone knows of an elegant Spring way to interrogate something to see if request-scoped beans are available.


Many thanks!


How to properly cancel the HTTP request if they are taking too much time?

Since starting, I was always confuse of how to deal with InterruptedException and how to properly cancel the http request if they are taking too much time. I have a library in which I am making an URL basis on user id passed in DataKey object and then make http call to the URL using AsyncRestTemplate.


I am using exchange method of AsyncRestTemplate which returns back a ListenableFuture.


Below is my code -



public class DataClient implements Client {

// using spring 4 AsyncRestTemplate
private final AsyncRestTemplate restTemplate = new AsyncRestTemplate();

@Override
public DataResponse executeSync(DataKey keys) {
Future<DataResponse> responseFuture = executeAsync(keys);
DataResponse response = null;

try {
response = responseFuture.get(keys.getTimeout(), TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
// do we need to catch InterruptedException here and interrupt the thread?
Thread.currentThread().interrupt();
// also do I need throw this RuntimeException at all?
throw new RuntimeException("Interrupted", ex);
} catch (TimeoutException ex) {
// log here and return DataResponse object
responseFuture.cancel(true); // terminating the tasks that got timed out so that they don't take up the resources? Will this work?
} catch (Exception ex) {
// log here and return DataResponse object
}

return response;
}

@Override
public ListenableFuture<DataResponse> executeAsync(final DataKey keys) {

final SettableFuture<DataResponse> responseFuture = SettableFuture.create();
final org.springframework.util.concurrent.ListenableFuture orig =
restTemplate.exchange(createURL(keys), HttpMethod.GET, keys.getEntity(), String.class);

orig.addCallback(
new ListenableFutureCallback<ResponseEntity<String>>() {
@Override
public void onSuccess(ResponseEntity<String> result) {
responseFuture.set(new DataResponse(result.getBody(), DataErrorEnum.OK,
DataStatusEnum.SUCCESS));
}

@Override
public void onFailure(Throwable ex) {
DataLogging.logErrors(ex, DataErrorEnum.ERROR_SERVER, keys);
responseFuture.set(new DataResponse(null, DataErrorEnum.ERROR_SERVER,
DataStatusEnum.ERROR));
}
});

// propagate cancellation back to the original request
responseFuture.addListener(new Runnable() {
@Override public void run() {
if (responseFuture.isCancelled()) {
orig.cancel(false); // I am keeping this false for now
}
}
}, MoreExecutors.directExecutor());
return responseFuture;
}
}


And we are calling like this -



// if calling executeSync() method directly
DataResponse response = DataClientFactory.getInstance().executeSync(dataKey);


Is it possible to interrupt AsyncRestTemplate call if request is taking too long? I believe, we cannot interrupt RestTemplate calls but not sure on AsyncRestTemplate whether we can do that or not.


Also I am not sure how do I verify whether AsyncRestTemplate calls can be interrupted or not.


Cross Origin error except when trace logging enabled

I have a pretty standard spring REST service. It has been working just fine until one of our clients tried to use one particular method that had not been called from a browser before. This method is getting the familiar Cross Origin error. No other methods in our service get the error as we have implemented spring's version of a CORS filter.


We could not duplicate the error on our development or test systems, only on production. To try and figure out what was going on, we used Probe to temporarily set the production logs to TRACE. Suddenly the method worked perfectly, no error. We were able to confirm that setting the logs to TRACE or ALL on all 3 systems cleared the error, whereas DEBUG and above resulted in the error (development and test systems are default set to ALL). I have further narrowed it down to setting just our service implementation class to TRACE fixes the problem.


To make it even more confusing, I found a way to not get the error on that method regardless of the logging level. The input for that method is a session id in the standard format, such as 1891d2f2-3510-4e12-af62-132098424ae4. If I remove the hyphens, or basically put any value in there without hyphens, the method does not get a cross origin error. Of course the method does not return data, just the expected error of session id not found. But you wouldn't get that message if cross origin stops the call. Unfortunately I don't really have a way to create a valid session id without the hyphens. Other methods that have a session id as a parameter or as part of the request body do not get an error, only this one where the id is part of the url.


The versions we are using:



  • Java 6

  • Spring 4.1.4

  • log4j 1.2.16

  • Tomcat 7.0.52

  • jquery 1.11.1


Example request URL:



http://ift.tt/1OWJJ8q


Controller Request Mapping:



@Autowired
private MyManagementService mms;

@RequestMapping(value="/getsession/{sessionId}", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
@Transactional(readOnly=true)
public @ResponseBody Session getSession(@PathVariable("sessionId") String sessionId) throws MyServiceException {
Session s = mms.getSession(sessionId);
return s;
}


Implemented Service Method:



@Override
@Transactional(readOnly=true)
public Session getSession(String sessionId) throws MyRequestedDataNotFoundException {
logger.info("Retrieve session [{}]", sessionId);
Session session = Session.findSession(sessionId);
if (session==null) {
String message = String.format("Session [%s] was requested by [%s] but could not be found", sessionId, SecurityAttributeHelper.getAuthenticatedUser());
logger.warn(message);
throw new MyRequestedDataNotFoundException(message);
}
return session;
}


Javascript to call the method:



<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript">
<script type="text/javascript">
var $ = jQuery.noConflict();

$(document).ready(function () {
$.support.cors = true;
});

function makeCall(turl,user,pass) {
console.log(turl);
$.ajax({
url: turl,
type: "GET",
data: null,
dataType: "json",
headers: {
"Authorization": "Basic " + btoa(user+":"+pass),
"Content-Type": "application/json"
},
success : function(d){
alert("Success");
console.log(d);
},
error : function(e){
alert("Error");
console.log(e);
}
});
}
</script>


Sample of the logs when successful: (nothing in logs if error)



2015-03-31 21:35:13,484 TRACE ** >>> getSession: called by [MYUSER] starts with args([1891d2f2-3510-4e12-af62-132098424ae4]) ** com.mycompany.myservice.service.MyManagementServiceImpl
2015-03-31 21:35:13,486 INFO ** Retrieve session [1891d2f2-3510-4e12-af62-132098424ae4] ** com.mycompany.myservice.service.MyManagementServiceImpl
2015-03-31 21:35:13,853 TRACE ** <<< getSession: called by [MYUSER] ends with data = [Session[key1=value1,key2=value2,key3=value3]] ** com.mycompany.myservice.service.MyManagementServiceImpl


To get around the issue, we have temporarily set that class file to TRACE in production, but that is not a good long term solution. Any ideas for what might be causing the problem?


Thread pool queue with unique tasks

I'm using ThreadPoolTaskExecutor (of spring) in order to execute some tasks asynchronously.


The required task will load some object from an external DB into my system memory. I'm using max thread pool size of 10 and max queue size of 100.


Suppose that all 10 threads are occupied getting objects from my DB and a task is created, it will go to the queue. Now another task is created that should get the same object (same key in DB) from the DB, it will also go to the queue (assuming all 10 threads are still occupied).


So my queue might get full easily with duplicated tasks which will get executed in turn and I don't want this to happen.


I thought that a solution should come in the form of a unique collection which serves as the thread pool queue. Under the hood ThreadPoolTaskExecutor uses LinkedBlockingQueue which does not provide uniqueness.


I thought of a few possible solutions but none satisfies me:



  • Using ThreadPoolExecutor instead of ThreadPoolTaskExecutor. The ThreadPoolExecutor provides a constructor which lets me determine the thread pool queue type, but it needs to implement the BlockingQueue interface. I could not find an implementation that preserve uniqueness.


This led me to try and extend LinkedBlockingQueue and override add:



public boolean add(E e)
if(!this.contains(e)) {
return super.add(e);
} else {
return false;
}
}


But as far as I can tell this will lead to a major performance reduction since the contains method is limited by O(n) - bad idea.


What could solve my problem? I'm aiming for a good performance (in case of memory-performance trade offs I don't mind giving up memory for performance).


How to bind a JDBC datasource to JNDI context "java:comp/env/jdbc" when not to use web.xml

How to bind a JDBC datasource to JNDI context java:comp/env/jdbc only using code-based approach.


We need to write resource-ref in the web.xml for binding a dataSource to JNDI local context java:comp/env/jdbc. But I want to use only org.springframework.web.context.AbstractContextLoaderInitializer instead of web.xml(the old approach).


We know the method InitialContext#createSubcontext. But some application servers(e.g. Websphere) do not accept to edit the context java:comp/env/jdbc/.


Any solutions?


Versions:



  • Spring 4.0.7

  • Servlet 3.0


Angular Js post date Bad Request in Java Spring mvc

In Java Spring MVC project, I post an object to a @RestController and the object I post has an date property. If I remove this property, the post works successfully. But with the date property, it returns a 400 bad request. In the dto the Date is java.util.Date


Method in controller:



@RequestMapping(value = "/users/createPetition", method = RequestMethod.POST)
public @ResponseBody PetitionDTO addPetition(@RequestBody PetitionRequestDTO petitionDto, Model model) { ...


PetitionRequestDTO



public class PetitionRequestDTO {

private Long userId;

private Long categoryId;

private String title;

private String description;

private Date initialDate;

private String address; //getters setters


The angular js call



if ($scope.petitionForm.$valid) {
$http.post(getCompletePath("users/createPetition"), JSON.stringify($scope.newPetition))
.success(function (petition) {

}).error(function (data, status, headers, config) {

});


In the js the date has the next value: Thu Mar 19 2015 00:00:00 GMT-0300 (Argentina Standard Time)


The complete json is:



"{"selectedCategory":{"id":3,"name":"Plomero","description":"Plomeria"},"name":"aaa","title":"bbb","description":"ccc","initialDate":"2015-03-19T03:00:00.000Z","address":"asd","categoryId":3}"

Java embedded jetty is accepting HTTP TRACE method

I'm trying to disable HTTP TRACE method in embedded Jetty. In Jetty doc's is info that HTTP trace is disabled by default, but for embedded it is still enabled. I was trying to disable trace as a security constraint as is done in jetty.xml.



ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS | ServletContextHandler.SECURITY);
servletHandler.setClassLoader(Server.class.getClassLoader());
servletHandler.setContextPath("/");
servletHandler.addEventListener(new ContextLoaderListener());
servletHandler.addServlet(new ServletHolder(new CXFServlet()), "/*");
servletHandler.setInitParameter("contextClass", AnnotationConfigWebApplicationContext.class.getName());
servletHandler.setInitParameter("contextConfigLocation", BeansConfig.class.getName());
servletHandler.setInitParameter("javax.ws.rs.Application", DispatcherConfig.class.getName());

/*
* <security-constraint>
* <web-resource-collection>
* <web-resource-name>Disable TRACE</web-resource-name>
* <url-pattern>/</url-pattern>
* <http-method>TRACE</http-method>
* </web-resource-collection>
* <auth-constraint/>
* </security-constraint>
*/
Constraint constraint = new Constraint();
constraint.setName("Disable TRACE");

ConstraintMapping mapping = new ConstraintMapping();
mapping.setConstraint(constraint);
mapping.setMethod("TRACE");
mapping.setPathSpec("/"); // this did not work same this mapping.setPathSpec("/*");

ConstraintSecurityHandler securityHandler = (ConstraintSecurityHandler) servletHandler.getSecurityHandler();
securityHandler.addConstraintMapping(mapping);


Example output from soapUI:



HTTP/1.1 200 OK
Content-Type: message/http
Content-Length: 143
Server: Jetty(9.0.6.v20130930)

TRACE / HTTP/1.1
Connection: keep-alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Host: 192.168.33.115
Accept-Encoding: gzip,deflate

What is the best way to encapsulate multiple service calls using Spring?

I need to call one third party service and if it succeeds, then i will call another service of my application. What is the best approach to encapsulate this calls? and ensure that its become a single transaction?


For Example, call this services in one single point:



public class ThirdPartyService(){

sendProduct(){
// Call external service
}

}

public class ProductService(){

confirmProduct(){
// Do stuff
}

}

Can access spring oauth2 protected resource without access token

Using :



  • spring-security 3.2.5

  • spring-security-oauth 2.0.7 (oauth2)

  • grant_type : authentication_code


I have no problem getting authentication_code and access token. The problem I have is that if I call a "protected" resource, I can access it with no token at all. Here is the security config of the "not-really-protected" resource :



<security:http pattern="/api/user/**" create-session="never" entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager">
<security:anonymous enabled="false" />
<security:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" />
<security:custom-filter ref="userResourceServer" before="PRE_AUTH_FILTER" />
<security:access-denied-handler ref="oauthAccessDeniedHandler" />
</security:http>


The Oauth2AuthenticationProcessingFilter is saying



No token in request, will continue chain.



I found this other post wich seems to describe the same problem, but the solution presented is to add <security:intercept-url pattern="/**" access="IS_AUTHENTICATED_FULLY" />, wich I already have.


Also, tough maybe not related, the request to the protected resource receive à Set-cookie header, defining a jsessionid. It seems not normal to me since I specify create-session="never".


I expected an unauthorized call to this resource to return a 403 since I use OAuth2AccessDeniedHandler.


Can someone help me with this ?


Note that I am pretty sure that this security config is kicking in because in my protected resource(a spring-mvc controller), SecurityContextHolder.getContext().getAuthentication() returns null. If I completely disable the above security config, the same line returns an anonymous authentication.


EDIT : Detailed configuration information.


First I have the token enpoint configuration :



<security:http pattern="/api/oauth/token"
create-session="stateless"
authentication-manager-ref="clientAuthenticationManager">
<security:intercept-url pattern="/api/oauth/token"
access="IS_AUTHENTICATED_FULLY" />
<security:anonymous enabled="false" />
<security:http-basic entry-point-ref="clientAuthenticationEntryPoint" />
<security:access-denied-handler ref="oauthAccessDeniedHandler" />
</security:http>


Then the resource endpoint configuration (as shown at the beginning of the question) :



<security:http pattern="/api/user/**"
create-session="never"
entry-point-ref="oauthAuthenticationEntryPoint"
access-decision-manager-ref="accessDecisionManager">
<security:anonymous enabled="false" />
<security:intercept-url pattern="/api/user/**"
access="IS_AUTHENTICATED_FULLY" />
<security:custom-filter ref="userResourceServer"
before="PRE_AUTH_FILTER" />
<security:access-denied-handler ref="oauthAccessDeniedHandler" />
</security:http>


And then the "generic" url configuration :



<security:http name="genericSecurityConfiguration" entry-point-ref="customLoginEntrypoint">
<security:form-login authentication-failure-url="/index.jsp"
authentication-success-handler-ref="customAuthenticationSuccessHandler"
authentication-failure-handler-ref="customAuthenticationFailureHandler"
login-page="/index.jsp"
login-processing-url="/solapCore/identification2"
username-parameter="username"
password-parameter="password"
/>
<security:session-management invalid-session-url="/index.jsp?invalidSession=true" session-authentication-strategy-ref="sas" />
<security:custom-filter position="LOGOUT_FILTER" ref="logoutFilter"/>
<security:custom-filter before="FILTER_SECURITY_INTERCEPTOR" ref="monitoringFilter"/>
<security:access-denied-handler ref="solapcoreAccessDeniedHandler"/>
</security:http>


Other oauth specific configuration in the same file :



<bean id="oauthAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="oauth" />
</bean>

<bean id="clientAuthenticationEntryPoint" class="org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint">
<property name="realmName" value="oauth/client" />
<property name="typeName" value="Basic" />
</bean>

<bean id="accessDecisionManager" class="org.springframework.security.access.vote.UnanimousBased">
<constructor-arg>
<list>
<bean class="org.springframework.security.oauth2.provider.vote.ScopeVoter" />
<bean class="org.springframework.security.access.vote.RoleVoter" />
<bean class="org.springframework.security.access.vote.AuthenticatedVoter" />
</list>
</constructor-arg>
</bean>

<security:authentication-manager id="clientAuthenticationManager">
<security:authentication-provider user-service-ref="clientDetailsUserService" />
</security:authentication-manager>

<bean id="clientDetailsUserService" class="org.springframework.security.oauth2.provider.client.ClientDetailsUserDetailsService">
<constructor-arg ref="clientDetails" />
</bean>
<bean id="oauthAccessDeniedHandler" class="org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler" />

<oauth:authorization-server
client-details-service-ref="clientDetails"
token-services-ref="tokenServices"
user-approval-handler-ref="userApprovalHandler">
<oauth:authorization-code />
</oauth:authorization-server>

<oauth:resource-server id="userResourceServer"
resource-id="oauth2/user"
token-services-ref="tokenServices" />

<oauth:client-details-service id="clientDetails">
<oauth:client client-id="someClientID"
authorized-grant-types="authorization_code"
authorities="SOME_AUTHORITY" scope="read" secret="secret" />
</oauth:client-details-service>

<security:global-method-security pre-post-annotations="enabled" proxy-target-class="true">
<security:expression-handler ref="oauthExpressionHandler" />
</security:global-method-security>

<oauth:expression-handler id="oauthExpressionHandler" />
<oauth:web-expression-handler id="oauthWebExpressionHandler" />

<bean id="tokenStore" class="org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore" />

<bean id="tokenServices" class="org.springframework.security.oauth2.provider.token.DefaultTokenServices">
<property name="tokenStore" ref="tokenStore" />
<property name="supportRefreshToken" value="true" />
<property name="clientDetailsService" ref="clientDetails" />
</bean>


Finaly, my dispatcher servlet and filterChain configuration in web.xml :



<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>

<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Struts2/Hibernate/Spring alternative?

I'm looking for new technologies (supported if possible) to update existing WebAdmin projects and to use going forward. The WebAdmin projects are simple web interfaces for a few (<100) users to be able to view and update their SQL database with combining updating multiple tables from a single page. Being able to upload documents to a server. And also logging/auditing each user action.


Currently our projects are designed with a Struts2/Hibernate/Spring setup using Envers to handle auditing.


Struts2 seems to be out of support now as the last stable release was 2.3.20 / December 7, 2014. Hibernate also has caused some problems with debugging its SQL queries and setting up cascading table saves. And while there seems to be some Envers documentation, there doesn't seem to be many examples on how to use it properly (setup with automatic initial table creation seems to be capable for the auditing tables, but I have not been able to find an example of it).


Hibernate has a few alternatives that I've seen (Light weight alternative to Hibernate?):



  • ORMLight

  • jOOQ

  • MyBatis


And Struts2 has a few I've heard of as well:



  • Grails (Groovy on Rails)

  • JSF (JavaServer Faces)


But I cannot find another pair of web interface and SQL database connections that is current, easy to setup, easy to debug, but powerful enough to handle cascading table structures. Grails was the top of the list as an alternative, but after attempting to reach outside of its intended use setup and debugging became much harder than our current Struts2/Hibernate/Spring setup. There also seems to be few benefits for using JSF over Struts2 without its equal drawbacks.


I'm not expecting some magical application structure to fix all of my problems. And while Struts2 is no longer supported since it has been around for a while there is a lot of documentation and 3rd party support for it. I would just like to know what else is out there and if anything new has been created.


Spring MVC 1 to 1 mapping of a URL to .HTML without exposing path

I am using Spring 4.1.5 with Boot 1.2 on a webservice that does not serve up any JSPs. I don't want to add a JSP servlet but I want it to serve up a single canary page that shows in a prettier html type format the information that would be provided at the /manage/health endpoint.


I have a file in webapp/canary/canary.html I want to serve this up from the url: www.mywebservice.com:9343/canary, exactly like that, NOT canary.html


I tried doing this:



@Configuration
public class CanaryConfiguration extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/canary")
.addResourceLocations("/canary/canary.html");
}
}


That doesn't work however.


It is expecting the handler to provide a file name. So in otherwords the location should be something like: /canary/


and the handler would something like: /canary/**


With that, the URL www.mywebservice.com:9343/canary/canary.html would work like a charm.


HOWEVER, I want the URL to resolve www.mywebservice.com:9343/canary to webapp/canary/canary.html without me having to type the html.


This is really easy in a jsp servlet because you can set the suffix ect...


I looked at ResourceResolver but it didn't make sense to me how I would link that into my current configuration.


It looks like what I want:



Provides mechanisms for resolving an incoming request to an actual Resource and for obtaining the public URL path that clients should use when requesting the resource.



See: ResourceResolver Documentation


Any help would be very beneficial.


Also I am very aware that I can put html in the resources/static and several other places that are automatically configured. That always requires the .html to be typed, which is not what I want in this case so that won't work. Thanks!


how to automatically store the metadata of files in a mysql database and sync them?

how to automatically store ,in a mysql database, the metadata of files in a directory in my filesystem . When I update , delete , add ...a file I want its metadata to be updated or added to a mysql database . I need this in my webapp (spring+angularjs) that allows users to see their files on a ubuntu server .


Exception handling by scheduled-tasks element of Task namespace

I am using the scheduled-tasks element of the task namespace for scheduling a job.


<task:scheduled-tasks> <task:scheduled ref="BeanA" method="retrieve" cron="${cron}"/> </task:scheduled-tasks>



public void retrieve() throws InstantiationException,IllegalAccessException,ClassNotFoundException,SQLException{}


The method retrieve throws certain exceptions, i don't want to handle the exception in the method itself due to some requirements, How can i ascertain that the job runs even if a particular run throws an exception?


How to exchange signals between applications?

I have two unconnected applications. One is the main app that performs the business logic and CRUD on database.


A 2nd app periodically rebuilds a database cache (long running taks). I want to send a signal to the main app when the rebuild starts, and when it's finished, as the main app should take specific actions while rebuilding takes place.


How could I achive this best using spring-boot?


Vaadin 7.4 , Spring, Tomcat 7 , Change context root using @WebServlet

I'm using Vaadin 7.4 with Spring using the "spring4vaadin" - Project. I'm deploying the Application on a Tomcat 7.0.29 with Servlet API 3.0.


I deploy the Application under the Root-Context of Tomcat ("/") and I'm using the @WebServlet-Annotation to set the actual context of the App to "/esb/*":



@WebServlet( value = "/esb/*" , asyncSupported = true )
public static class Servlet extends SpringVaadinServlet {


}


But every time when I navigate to the App-URL "http://localhost:8080/esb/" I get the error message: "Failed to load the bootstrap javascript ./../VAADIN/vaadinBootstrap.js?v=7.4.0" in a Browser-Pop-Up from Vaadin.


By web.xml looks like this:



<web-app id="ESAB_Cutting_Prototyping" version="3.0"
xmlns="http://ift.tt/nSRXKP"
xmlns:xsi="http://ift.tt/ra1lAU"
xsi:schemaLocation="http://ift.tt/nSRXKP
http://ift.tt/1u51vgk"
metadata-complete="false">
</web-app>


If I set the context in the Tomcat Deployment-Configuration of my Intellij IDE it works without any problems.


I have no idea what to do - any help is greatly appreciated.


How to create a simple rendezvous client-server socket cannel?

I'm trying to create a simple RendezvousChannel for client-server communication. My applications start both fine, but the message is never send. Why?


client:



@Component
public class Sender {
@Autowired
@Qualifier("clientChannel")
private MessageChannel chan;

@PostConstruct
public void send() {
MessagingTemplate template = new MessagingTemplate();
Message<?> message = new Message<String>() {
@Override
public String getPayload() {
return "TEST";
}

@Override
public MessageHeaders getHeaders() {
return new MessageHeaders(null);
}
};

System.out.println("sending...");
Message<?> result = template.sendAndReceive(chan, message);
System.out.println("send: " + result.getPayload());
}
}


@MessageEndpoint
public class ClientEndpoint {
@Bean
public MessageChannel clientChannel() {
return new RendezvousChannel();
}

@Bean
public TcpConnectionFactoryFactoryBean clientFactory() {
TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean();
fact.setType("client");
fact.setHost("localhost");
fact.setPort(5555);
fact.setUsingNio(true);
fact.setSingleUse(true);
return fact;
}

@Bean
public TcpOutboundGateway out(TcpNioClientConnectionFactory factory, @Qualifier("clientChannel") MessageChannel clientChannel) throws Exception {
TcpOutboundGateway gate = new TcpOutboundGateway();
gate.setConnectionFactory(factory);
gate.setReplyChannel(clientChannel);
return gate;
}
}


server:



@Component
public class Receiver {
@ServiceActivator(inputChannel = "serverChannel", poller = @Poller(fixedDelay = "1000", maxMessagesPerPoll = "1"))
public String hello(String input) throws Exception {
System.out.println("Hello: " + input);
return "Hello: " + input;
}
}

@MessageEndpoint
public class ServerEndpoint {
@Bean
public TcpInboundGateway serverGateway(TcpConnectionFactoryFactoryBean factory, @Qualifier("serverChannel") MessageChannel serverChannel) throws Exception {
TcpInboundGateway gate = new TcpInboundGateway();
gate.setConnectionFactory(factory.getObject());
gate.setRequestChannel(serverChannel);
return gate;
}

@Bean
public TcpConnectionFactoryFactoryBean clientFactory() {
TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean();
fact.setType("server");
fact.setHost("localhost");
fact.setPort(5555);
fact.setUsingNio(true);
fact.setSingleUse(true);
return fact;
}

@Bean
public MessageChannel serverChannel() {
return new RendezvousChannel();
}
}


First I start the server, then the client. The client keeps ganging at "sending...", and the server never receives a message. Why?