Problems with #Autowired, with a ManagedBean and an abstract class - spring

Well, I have an abstract class like this:
public abstract class BasicCrudMBImpl<Bean, BO> extends BasicMBImpl {
protected Bean bean;
protected List<Bean> beans;
protected BO boPadrao;
public void deletar() {
try {
((BasicBO) boPadrao).delete((AbstractBean) bean);
addInfoMessage("Registro deletado com sucesso");
beans = retornaBeansDoBanco();
bean = null;
} catch (BOException e) {
addErrorMessage(e.getMessage());
}
}
public void salvar(ActionEvent event) {
try {
if (((AbstractBean) bean).getId() == null) {
bean = (Bean) ((BasicBO) boPadrao).save((AbstractBean) bean);
addInfoMessage("Registro salvo com sucesso");
} else {
((BasicBO) boPadrao).update((AbstractBean) bean);
addInfoMessage("Registro atualizado com sucesso");
}
beans = retornaBeansDoBanco();
} catch (BOException e) {
FacesContext.getCurrentInstance().validationFailed();
addErrorMessage(e.getMessage());
}
}
public Bean getBean() {
return bean;
}
public void setBean(Bean bean) {
this.bean = bean;
}
public List<Bean> getBeans() {
try {
if (beans == null)
beans = (List<Bean>) retornaBeansDoBanco();
return beans;
} catch (BOException e) {
addErrorMessage(e.getMessage());
}
return null;
}
public void setBeans(List<Bean> beans) {
this.beans = beans;
}
// Deve ser implementado para carregar a query adequada ao bean necessário
public abstract List<Bean> retornaBeansDoBanco();
public abstract void novo(ActionEvent event);
public abstract void alterar(ActionEvent event);
public BO getBoPadrao() {
return boPadrao;
}
public abstract void setBoPadrao(BO boPadrao);
public void addErrorMessage(String componentId, String errorMessage) {
addMessage(componentId, errorMessage, FacesMessage.SEVERITY_ERROR);
}
public void addErrorMessage(String errorMessage) {
addErrorMessage(null, errorMessage);
}
public void addInfoMessage(String componentId, String infoMessage) {
addMessage(componentId, infoMessage, FacesMessage.SEVERITY_INFO);
}
public void addInfoMessage(String infoMessage) {
addInfoMessage(null, infoMessage);
}
private void addMessage(String componentId, String errorMessage,
FacesMessage.Severity severity) {
FacesMessage message = new FacesMessage(errorMessage);
message.setSeverity(severity);
FacesContext.getCurrentInstance().addMessage(componentId, message);
}
}
In ManagedBean I tried to inject the "boPadrao" with #Autowired, like this:
#ManagedBean(name = "enderecoMB")
#ViewScoped
public class EnderecoMBImpl extends BasicCrudMBImpl<Endereco, BasicBO> {
private static Logger logger = Logger.getLogger(EnderecoMBImpl.class);
private List<TipoEndereco> tiposEndereco;
private List<Logradouro> logradouros;
#PostConstruct
public void init() {
logger.debug("Inicializando componentes no PostConstruct");
beans = retornaBeansDoBanco();
tiposEndereco = (List<TipoEndereco>) boPadrao
.findByNamedQuery(TipoEndereco.FIND_ALL);
logradouros = (List<Logradouro>) boPadrao
.findByNamedQuery(Logradouro.FIND_ALL_COMPLETO);
}
#Override
public List<Endereco> retornaBeansDoBanco() {
return (List<Endereco>) getBoPadrao().findByNamedQuery(Endereco.FIND_ALL_COMPLETO);
}
#Override
public void novo(ActionEvent event) {
bean = new Endereco();
}
#Override
public void alterar(ActionEvent event) {
// TODO Auto-generated method stub
}
public List<TipoEndereco> getTiposEndereco() {
return tiposEndereco;
}
public void setTiposEndereco(List<TipoEndereco> tiposEndereco) {
this.tiposEndereco = tiposEndereco;
}
public List<Logradouro> getLogradouros() {
return logradouros;
}
public void setLogradouros(List<Logradouro> logradouros) {
this.logradouros = logradouros;
}
#Autowired
public void setBoPadrao(BasicBO boPadrao) {
this.boPadrao = boPadrao;
}
}
But this doesn't works, the boPadrao is always null, getting a "NullPointerException". The error occurs in method retornaBeansDoBanco();

Related

Class field in Netty ChannelInboundHandler could not autowired

I try to autowire some service class in channelInboundhandler class field.
but when handler use repository field it always null.
Here is my Netty Configuration
my.netty:
server:
bind: 9000
#SpringBootApplication
public class NettyApplication {
public static void main(String[] args) {
SpringApplication.run(NettyApplication.class, args);
}
#Bean
NettyServerConfig serverConfig(#Autowired ServerHandler serverHandler) {
return NettyServerConfig.builder()
.propertiesPrefix("my.netty.server")
.channelInitializer(pipelineOf(loggingChannelHandler(), serverHandler))
.build();
}
#Bean
ChannelHandler loggingChannelHandler() {
return new LoggingHandler(INFO);
}
}
And channelinboundhandler, Service(Repository)
#Slf4j
#Component
#Sharable
public class ServerHandler extends ChannelInboundHandlerAdapter {
#Autowired ServerRepository repository; // always null
#Override
public void channelRead(ChannelHandlerContext ctx, Object object) throws Exception {
log.info("ServerHandler.channelRead()");
String data = repository.findOne();
log.info("data={}", data);
ctx.writeAndFlush(object);
}
}
#Repository
public class ServerRepository {
public String findOne() {
sleep(1000); // data-access time
return "data";
}
private void sleep(int millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Is There any Problem?

JavaFX custom controls created with a Builder and binding expressions

I’m using Spring together with JavaFx. To use spring bean as a custom control I need to use BuilderFactory and a Builder to get a bean from the context. Otherwice I don't have an application context
Parent.java
#Component
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ParentControl extends VBox {
#Autowired
ControlFXMLLoader controlFXMLLoader;
#Value("classpath:/parent.fxml")
private Resource fxml;
#PostConstruct
void load() throws IOException {
controlFXMLLoader.load(fxml.getURL(), this);
}
public ParentControl() {
//no application context
}
public LocalDate getDate() {
return LocalDate.now();
}
}
BeanBuilderFactory.java
#Component
public class BeanBuilderFactory implements BuilderFactory {
private Logger logger = LogManager.getLogger(BeanBuilderFactory.class);
#Autowired
private ConfigurableApplicationContext context;
public BeanBuilderFactory() {
}
private JavaFXBuilderFactory defaultBuilderFactory = new JavaFXBuilderFactory();
#Override
public Builder<?> getBuilder(Class<?> type) {
try {
String[] beanNames = context.getBeanNamesForType(type);
if (beanNames.length == 1) {
return new Builder<Object>() {
#Override
public Object build() {
return context.getBean(beanNames[0]);
}
};
} else {
return defaultBuilderFactory.getBuilder(type);
}
} catch (BeansException e) {
return defaultBuilderFactory.getBuilder(type);
}
}
}
And then I user this BuilderFactory to load fxml for a custom control
ControlFXMLLoader.java
#Component
public class ControlFXMLLoader {
private Logger logger = LogManager.getLogger(ControlFXMLLoader.class);
#Autowired
protected ConfigurableApplicationContext context;
#Autowired
protected BeanBuilderFactory beanBuilderFactory;
public Object load(URL fxmlUrl, Parent root, Object controller) throws IOException {
logger.debug("load");
javafx.fxml.FXMLLoader loader = new javafx.fxml.FXMLLoader(fxmlUrl);
loader.setControllerFactory(context::getBean);
loader.setBuilderFactory(beanBuilderFactory);
loader.setRoot(root);
loader.setController(controller);
return loader.load();
}
public Object load(URL fxmlUrl, Parent root) throws IOException {
return load(fxmlUrl, root, root);
}
}
Now I have a child custom control
ChildControl.java
#Component
#Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class ChildControl extends VBox {
public ChildControl() {
}
#Autowired
ControlFXMLLoader controlFXMLLoader;
#Value("classpath:/child.fxml")
private Resource fxml;
#PostConstruct
void load() throws IOException {
controlFXMLLoader.load(fxml.getURL(), this);
}
ObjectProperty<LocalDate> date = new SimpleObjectProperty<LocalDate>();
public LocalDate getDate() {
return date.get();
}
public void setDate(LocalDate date) {
this.date.set(date);
}
public ObjectProperty<LocalDate> dateProperty() {
return date;
}
#FXML
protected void doSomething() {
System.out.println("The button was clicked! " + date.get().toString());
}
}
And want to assign the date to the child from parent fxml
parent.fxml
<fx:root type="com.example.javafx.ParentControl" xmlns:fx="http://javafx.com/fxml">
<ChildControl date="${controller.date}"/>
</fx:root>
child.fxml
<fx:root type="com.example.javafx.ChildControl" xmlns:fx="http://javafx.com/fxml">
<TextField fx:id="textField"/>
<Button text="Click Me" onAction="#doSomething"/>
</fx:root>
The problem is that FXMLLoader doesn’t not allow to use Binding Expression together with a Builder. I got "Cannot bind to builder property." exception.
Below is the part of the code from FXMLLoader.java and the very last if that causes the problem.
Is there some other solution?
FXMLLoader.java
public void processPropertyAttribute(Attribute attribute) throws IOException {
String value = attribute.value;
if (isBindingExpression(value)) {
// Resolve the expression
Expression expression;
if (attribute.sourceType != null) {
throw constructLoadException("Cannot bind to static property.");
}
if (!isTyped()) {
throw constructLoadException("Cannot bind to untyped object.");
}
// TODO We may want to identify binding properties in processAttribute()
// and apply them after build() has been called
if (this.value instanceof Builder) {
throw constructLoadException("Cannot bind to builder property.");
}

Webflux doesn't support ResponseBodyAdvice yet?

Since ResponseBodyAdvice interface is in web.servlet package
How could I implement such functions in webflux?
I also have this problem, i found it can be done by HandlerResultHandler.
For Example, I extend ResponseBodyResultHandler to wrap all my response
First, you should write ResponseWrapper.java
public class ResponseWrapper extends ResponseBodyResultHandler {
private static MethodParameter param;
static {
try {
//get new params
param = new MethodParameter(ResponseWrapper.class
.getDeclaredMethod("methodForParams"), -1);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public ResponseWrapper(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver) {
super(writers, resolver);
}
private static Mono<Response> methodForParams() {
return null;
}
#Override
public boolean supports(HandlerResult result) {
boolean isMono = result.getReturnType().resolve() == Mono.class;
boolean isAlreadyResponse = result.getReturnType().resolveGeneric(0) == Response.class;
return isMono && !isAlreadyResponse;
}
#Override
#SuppressWarnings("unchecked")
public Mono<Void> handleResult(ServerWebExchange exchange, HandlerResult result) {
Preconditions.checkNotNull(result.getReturnValue(), "response is null!");
// modify the result as you want
Mono<Response> body = ((Mono<Object>) result.getReturnValue()).map(Response::success)
.defaultIfEmpty(Response.success());
return writeBody(body, param, exchange);
}
}
Then, add Bean in SpringBootApplication
#SpringBootApplication
public class SmartApplication {
#Autowired
ServerCodecConfigurer serverCodecConfigurer;
#Autowired
RequestedContentTypeResolver requestedContentTypeResolver;
#Bean
ResponseWrapper responseWrapper() {
return new ResponseWrapper(serverCodecConfigurer
.getWriters(), requestedContentTypeResolver);
}
//Spring start
public static void main(String[] args) {
SpringApplication.run(SmartApplication.class, args);
}
}
My response class, for reference
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Response<T> {
boolean success;
T data;
Object error;
String warning;
public Response() {
}
public static Response success() {
return success(null);
}
public static <T> Response success(T data) {
return new Response<T>().setSuccess(true).setData(data);
}
public static Response error(Throwable e) {
LogManager.getLogger(StackLocatorUtil.getCallerClass(2)).info(e);
return new Response().setSuccess(false).setError(e);
}
public static Response error(Object e) {
return new Response().setSuccess(false).setError(e);
}
public static Response error(String e) {
return new Response().setSuccess(false).setError(e);
}
/* get success */
public boolean isSuccess() {
return success;
}
/* set success */
public Response setSuccess(boolean success) {
this.success = success;
return this;
}
/* get data */
public Object getData() {
return data;
}
/* set data */
public Response setData(T data) {
this.data = data;
return this;
}
/* get error */
public Object getError() {
return error;
}
/* set error */
public Response setError(Object error) {
this.error = error;
return this;
}
}
i used ResponseBodyAdvise before spring 5.0. i think ResponseBodyResultHandler suport webflux since spring5.0.

GWT + Spring + Hiberante. With no reason at all

I'm learning how to integrate Spring with GWT and RequestFactory by doing this following example. I got a NullPointerException and I don't know why. Can anyone help me?
Here is my code:
#Repository
public class EmployeeDAO implements IEmployeeDAO {
#PersistenceContext
private EntityManager entity;
#Override
public Employee findById(Long id) {
Query query = entity.createQuery("from Employee where id = :param");
query.setParameter("param", id);
query.setMaxResults(1);
return (Employee) query.getSingleResult();
}
#Transactional(propagation = Propagation.REQUIRED)
#Override
public void save(Employee employee) {
entity.merge(employee);
}
#Override
public void remove(Employee employee) {
entity.remove(employee);
}
#SuppressWarnings("unchecked")
#Override
public List<Employee> getAllEmployee() {
Query query = entity.createQuery("from Employee");
return query.getResultList();
}
// ...
}
and:
#Service(value = IEmployeeDAO.class, locator = DaoLocator.class)
public interface EmployeeRequestContext extends RequestContext {
Request<EmployeeProxy> findById(Long id);
Request<Void> save(EmployeeProxy employee);
Request<Void> remove(EmployeeProxy employee);
Request<List<EmployeeProxy>> getAllEmployee();
Request<EmployeeProxy> findOneByName(String name);
}
and:
#ProxyFor(Employee.class)
public interface EmployeeProxy extends EntityProxy {
Long getId();
String getName();
String getSurname();
void setId(Long id);
void setName(String name);
void setSurname(String surname);
Long getVersion();
void setVersion(Long version);
}
The NullPointerException is throw in GWT Entry Point in method:
protected void refresh() {
context = createFactory().employeeRequest();
final EmployeeProxy ep = context.create(EmployeeProxy.class);
ep.setName("Jan");
ep.setSurname("Kowalski");
ep.setVersion(new Long(0));
context.save(ep).fire(new Receiver<Void>() {
#Override
public void onSuccess(Void response) {
employeeList.add(ep);
}
#Override
public void onFailure(ServerFailure error) {
System.out.println("error podczas zapisu");
}
});
context = createFactory().employeeRequest();
context.getAllEmployee().fire(new Receiver<List<EmployeeProxy>>() {
#Override
public void onSuccess(List<EmployeeProxy> response) {
System.out.println(" " + response); // NULL
}
#Override
public void onFailure(ServerFailure error) {
}
});
System.out.println("Bedziemy wyswietlac dane!");
updateTable(employeeList);
}
the last one: method which create Factory:
private static EmployeeRequestFactory createFactory() {
EmployeeRequestFactory factory = GWT.create(EmployeeRequestFactory.class);
factory.initialize(new SimpleEventBus());
return factory;
}
Please help me...
Please print the stacktrace for the NullPointerException. Only then can we analyze the cause for the exception.

window scope in spring?

i was wondering about the spring scope equivalent to window scope ?
according to the documentation here
http://static.springsource.org/spring/docs/3.0.0.M3/spring-framework-reference/html/ch04s04.html
i couldn't find any, so if there's a custom scope equivalent, can anyone please tell me, thanks.
EDIT: example of window scope in JSF
http://icefaces-showcase.icesoft.org/showcase.jsf?grp=compatMenu&exp=popup
One possible approach is having a session scoped bean that holds all the window sessions, and a window custom scope that access to the corresponding bean through that session scoped bean.
The required classes are:
Window Session
public class WindowSession {
private Map<String, Map<String,Object>> scopeMap = new HashMap<String, Map<String,Object>>();
private Map<String, Boolean> validSessions = new HashMap<String, Boolean>();
public WindowSession() {
super();
}
public Map<String, Map<String, Object>> getScopeMap() {
return scopeMap;
}
public void setScopeMap(Map<String, Map<String, Object>> scopeMap) {
this.scopeMap = scopeMap;
}
public Map<String, Boolean> getValidSessions() {
return validSessions;
}
public void setValidSessions(Map<String, Boolean> validSessions) {
this.validSessions = validSessions;
}
}
WindowIdContext
#Service
#Scope(value="request", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class WindowIdContext {
public static final String DEFAULT_SESSION_ID = "";
private String id = DEFAULT_SESSION_ID;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getQueryParamWithSessionId() {
if (DEFAULT_SESSION_ID.equals(id)) {
return "";
}
return "?" + WindowScope.WINDOW_ID_PARAM + "=" + id;
}
}
WindowSessionContext
#Service
#Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class WindowSessionContext {
private static SecureRandom random = new SecureRandom();
private WindowSession windowSession = new WindowSession();
#Autowired
private WindowIdContext windowIdContext;
public WindowSessionContext() {
windowSession.getValidSessions().put(WindowIdContext.DEFAULT_SESSION_ID, false);
}
public Object getObject(String name, ObjectFactory<?> objectFactory) {
String sessionId = windowIdContext.getId();
synchronized(this) {
if (!windowSession.getValidSessions().containsKey(sessionId)) {
windowSession.getValidSessions().put(sessionId, false);
}
Map<String,Object> sessionMap = windowSession.getScopeMap().get(sessionId);
if (sessionMap == null) {
sessionMap = new HashMap<String,Object>();
windowSession.getScopeMap().put(sessionId, sessionMap);
}
Object object = sessionMap.get(name);
if (object == null) {
object = objectFactory.getObject();
sessionMap.put(name, object);
}
return object;
}
}
public Object removeObject(String name) {
String sessionId = windowIdContext.getId();
synchronized(this) {
Map<String,Object> sessionMap = windowSession.getScopeMap().get(sessionId);
if (sessionMap == null) {
return null;
}
Object object = sessionMap.remove(name);
return object;
}
}
public String addSession() {
synchronized(this) {
String sessionId;
do {
sessionId = new BigInteger(130, random).toString(32);
} while (windowSession.getValidSessions().containsKey(sessionId));
windowSession.getValidSessions().put(sessionId, false);
return sessionId;
}
}
public void removeSession() {
String sessionId = windowIdContext.getId();
synchronized(this) {
windowSession.getScopeMap().remove(sessionId);
windowSession.getValidSessions().remove(sessionId);
}
}
public boolean isSessionValid(String sessionId) {
Boolean inUse = windowSession.getValidSessions().get(sessionId);
return inUse != null;
}
public boolean isSessionInUse(String sessionId) {
Boolean inUse = windowSession.getValidSessions().get(sessionId);
return inUse == true;
}
public synchronized boolean invalidateSession(String sessionId) {
Boolean valid = windowSession.getValidSessions().get(sessionId);
if (valid == null) {
return false;
}
if (sessionId.equals(WindowIdContext.DEFAULT_SESSION_ID)) {
windowSession.getValidSessions().put(sessionId, false);
} else {
windowSession.getValidSessions().remove(sessionId);
}
windowSession.getScopeMap().remove(sessionId);
for (Entry<String,Boolean> validSession : windowSession.getValidSessions().entrySet()) {
if (validSession.getValue() == true) {
return false;
}
}
return true;
}
public synchronized void setSessionInUse(String sessionId) {
windowSession.getValidSessions().put(sessionId, true);
}
public int getCount() {
return windowSession.getValidSessions().size();
}
}
WindowScope
public class WindowScope implements Scope {
private final int scope;
private static final int WINDOW_SCOPE = 40;
public static final String NAME = "window";
public static final String WINDOW_ID_PARAM = "windowid";
private ServletContext servletContext = null;
public WindowScope(ServletContext sc) {
servletContext = sc;
this.scope = WINDOW_SCOPE;
}
#Override
public Object get(String name, ObjectFactory<?> objectFactory) {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
WindowSessionContext windowSessionContext = applicationContext.getBean(WindowSessionContext.class);
return windowSessionContext.getObject(name, objectFactory);
}
#Override
public Object remove(String name) {
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
WindowSessionContext windowSessionContext = applicationContext.getBean(WindowSessionContext.class);
return windowSessionContext.removeObject(name);
}
#Override
public String getConversationId() {
return RequestContextHolder.currentRequestAttributes().getSessionId();
}
#Override
public void registerDestructionCallback(String arg0, Runnable arg1) {
}
#Override
public Object resolveContextualObject(String key) {
return null;
}
protected int getScope() {
return this.scope;
}
}
WindowScopeFilter
#Component("windowScopeFilter")
public class WindowScopeFilter implements Filter {
#Autowired
private WindowSessionContext windowSessionContext;
#Autowired
private WindowIdContext windowIdContext;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse = (HttpServletResponse)response;
String sessionId = httpRequest.getParameter(WindowScope.WINDOW_ID_PARAM);
if (sessionId != null) {
if (windowSessionContext.isSessionValid(sessionId)) {
windowIdContext.setId(sessionId);
} else {
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
} else {
windowSessionContext.setSessionInUse(WindowIdContext.DEFAULT_SESSION_ID);
}
chain.doFilter(request, response);
}
public void init(FilterConfig config) throws ServletException {
}
}
WindowScopeListener
#Component
public class WindowScopeListener implements ApplicationListener<ContextRefreshedEvent> {
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
WebApplicationContext applicationContext = (WebApplicationContext)event.getApplicationContext();
Scope windowScope = new WindowScope(applicationContext.getServletContext());
ConfigurableBeanFactory beanFactory = (ConfigurableBeanFactory)applicationContext.getAutowireCapableBeanFactory();
beanFactory.registerScope("window", windowScope);
}
}
Source with complete source code: http://notwithoutmycode.com/post/window/scope/in/spring

Resources