I try to lookup a #Stateless bean inside a POJO which is in the same package where the bean is. The bean is not null when I use it in my #ManagedBean controller class and I can do CRUD operations.
Here is the code for lookup in ArticlesBundle.java:
public class ArticlesBundle extends ResourceBundle{
protected static final String BASE_NAME = "ArticlesLcl.findForLocale";
private Map<String,String> messages = new HashMap<>();
private Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
protected final Control DB_CONTROL = new DBControl();
public ArticlesBundle(){
setParent(ResourceBundle.getBundle(BASE_NAME, FacesContext.getCurrentInstance().getViewRoot().getLocale(), DB_CONTROL));
}
protected ArticlesBundle(Locale locale){
setParent(ResourceBundle.getBundle(BASE_NAME, locale, DB_CONTROL));
}
public ArticlesBundle(Map<String,String> messages){
this.messages = messages;
}
#Override
protected Object handleGetObject(String key){
return messages != null ? messages.get(key) : parent.getObject(key);
}
#Override
public Enumeration<String> getKeys(){
return parent.getKeys();
}
protected class DBControl extends Control{
#Override
public ResourceBundle newBundle
(String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
throws IllegalAccessException, InstantiationException, IOException
{
String language = locale.getLanguage();
Map<String,String> messages = getArticless(locale);
System.out.println("getArticles("+language+") = "+getArticles(locale));
return new ArticlesBundle(messages);
}
public Map<String,String> getArticles(Locale locale){
String language = locale.getLanguage();
try {
Context ctx = new InitialContext();
ArticlesLclFacade arBean = (ArticlesLclFacade) ctx.lookup("java:gesht/ArticlesLclFacade");
List<ArticlesLcl> articles = arBean.getArticles(language);
for(Iterator<ArticlesLcl> it = articles.iterator(); it.hasNext();){
ArticlesLcl article = it.next();
messages.put(article.getArId().getArId().toString(), article.getArTitle());
}
} catch (NamingException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
return messages;
}
}
}
In ArticlesFacade:
#Stateless
public class ArticlesFacade extends AbstractFacade<ArticlesLcl> {
#PersistenceContext(unitName = "gtestPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public ArticlesFacade() {
super(ArticlesLcl.class);
}
public List<ArticlesLcl> getArticless(String language){
Query q = em.createNamedQuery("ArticlesLcl.findForLocale", ArticlesLcl.class);
q.setParameter("lang", language);
return q.getResultList();
}
}
Faces-Config.xml
<resource-bundle>
<base-name>com.gesht.bundles.ArticlesBundle</base-name>
<var>article</var>
</resource-bundle>
It throws the following exception:
SEVERE: javax.naming.NamingException: Lookup failed for 'java:gtest/ArticlesLclFacade' in SerialContext[myEnv={java.naming.factory.initial=com.sun.enterprise.naming.impl.SerialInitContextFactory, java.naming.factory.state=com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl, java.naming.factory.url.pkgs=com.sun.enterprise.naming} [Root exception is javax.naming.NameNotFoundException: No object bound to name java:gtest/ArticlesLclFacade]
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:518)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:455)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at javax.naming.InitialContext.lookup(InitialContext.java:411)
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1436)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1400)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1296)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:841)
at com.gtest.bundles.test.<init>(test.java:50)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at java.lang.Class.newInstance0(Class.java:372)
at java.lang.Class.newInstance(Class.java:325)
at java.util.ResourceBundle$Control.newBundle(ResourceBundle.java:2571)
at java.util.ResourceBundle.loadBundle(ResourceBundle.java:1436)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1400)
at java.util.ResourceBundle.findBundle(ResourceBundle.java:1354)
at java.util.ResourceBundle.getBundleImpl(ResourceBundle.java:1296)
at java.util.ResourceBundle.getBundle(ResourceBundle.java:1028)
at com.sun.faces.application.ApplicationResourceBundle.getResourceBundle(ApplicationResourceBundle.java:124)
at com.sun.faces.application.ApplicationAssociate.getResourceBundle(ApplicationAssociate.java:608)
at com.sun.faces.application.ApplicationImpl.getResourceBundle(ApplicationImpl.java:700)
at javax.faces.application.ApplicationWrapper.getResourceBundle(ApplicationWrapper.java:526)
at com.sun.faces.el.FacesResourceBundleELResolver.getValue(FacesResourceBundleELResolver.java:83)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:103)
at com.sun.el.parser.AstValue.getValue(AstValue.java:179)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:224)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
at javax.faces.component.UIOutput.getValue(UIOutput.java:169)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:355)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeDynamicBody(PanelGridRenderer.java:92)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeBody(PanelGridRenderer.java:60)
at org.primefaces.component.panelgrid.PanelGridRenderer.encodeEnd(PanelGridRenderer.java:49)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:61)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:45)
at org.primefaces.renderkit.CoreRenderer.renderChild(CoreRenderer.java:59)
at org.primefaces.renderkit.CoreRenderer.renderChildren(CoreRenderer.java:45)
at org.primefaces.component.datagrid.DataGridRenderer.encodeTable(DataGridRenderer.java:156)
at org.primefaces.component.datagrid.DataGridRenderer.encodeMarkup(DataGridRenderer.java:91)
at org.primefaces.component.datagrid.DataGridRenderer.encodeEnd(DataGridRenderer.java:53)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1764)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1757)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1760)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:402)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at org.ocpsoft.rewrite.faces.RewriteViewHandler.renderView(RewriteViewHandler.java:186)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:191)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: javax.naming.NameNotFoundException: No object bound to name java:gtest/ArticlesLclFacade
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:772)
at com.sun.enterprise.naming.impl.GlassfishNamingManagerImpl.lookup(GlassfishNamingManagerImpl.java:744)
at com.sun.enterprise.naming.impl.JavaURLContext.lookup(JavaURLContext.java:177)
at com.sun.enterprise.naming.impl.SerialContext.lookup(SerialContext.java:498)
... 108 more
I use Glassfish Server 3+
#Stateless(mappedName="articlesLclFacade")
public class ArticlesLclFacade extends AbstractFacade {
then in your try clause
ArticlesLclFacade arBean = (ArticlesLclFacade)ctx.lookup("articlesLclFacadee");
Or I can guess you can also use the EJB annotation as this :
#EJB
private ArticlesLclFacade arBean;
I used syntax ArticlesLclFacade arBean = (ArticlesLclFacade) ctx.lookup("java:global/gtest/ArticlesLclFacade"); and there is no more NamingException thrown.
Related
I have the next piece of code:
Main class
#SpringBootApplication
#EnableScheduling
public class GeolocalizacionApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(GeolocalizacionApplication.class, args);
}
}
Dao
#Transactional
#Repository
public class UsigRequestPersistanceDaoImpl implements UsigRequestPersistanceDao {
#PersistenceContext
private EntityManager em;
public List<UsigRequestPersistance> getRequest() {
Query query = em.createQuery("select v.requestId from UsigRequestSeq v").getFirstResult();
}
}
Model class
#Entity
#Table(name= "seq_usig_request", schema = "xxxx")
public class UsigRequestSeq {
#Id
#Column(name = "request_id", nullable = false)
private Integer requestId;
public Integer getRequestId() {
return requestId;
}
public void setRequestId(Integer requestId) {
this.requestId = requestId;
}
}
Configuration
#Configuration
#EnableTransactionManagement
public class DatabaseConfiguration {
#Bean
public LocalSessionFactoryBean sessionFactory(){
LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource());
sessionFactoryBean.setPackagesToScan("xxxx");
sessionFactoryBean.setHibernateProperties(hibernateProperties());
return sessionFactoryBean;
}
#Bean
public DataSource dataSource(){
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.teradata.jdbc.TeraDriver");
dataSource.setUrl("jdbc:teradata://teradata.xxxx/TMODE=ANSI,CHARSET=UTF8");
dataSource.setUsername("xxxx");
dataSource.setPassword("xxxx");
return dataSource;
}
#Bean(name = "properties")
public Properties hibernateProperties(){
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.TeradataDialect");
//properties.put("hibernate.show_sql", "true");
return properties;
}
#Bean
#Autowired
public HibernateTransactionManager transactionManager(){
HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
hibernateTransactionManager.setSessionFactory(sessionFactory().getObject());
return hibernateTransactionManager;
}
}
Application.properties
spring.jpa.database-platform=org.hibernate.dialect.TeradataDialect
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Then I do have a controller, but I think it's not necessary to put it here. In my controller y havec a method which calls getRequest() method.
Here I have some of the stack
java.lang.NullPointerException: null
at com.xxxx.Geolocalizacion.dao.UsigRequestPersistanceDaoImpl.getRequest(UsigRequestPersistanceDaoImpl.java:82) ~[classes/:na]
at com.xxxx.Geolocalizacion.controller.GeoController.ejecutar(GeoController.java:51) ~[classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_181]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_181]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_181]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_181]
I believe that I have problems with the createQuery native method, I debug the program and there's where it breaks, but I canĀ“t finds why. Am I missing something?
I'm writing an Spring-boot application that needs to connect to at least 2 databases.
I have 1 project per database in order to define their domains, 1 project per database in order to define their services and 1 Vaadin project for the UI.
- a business domain entity sample
#Entity
#Table(name="T_PARAMETER")
public class Parameter extends BaseIdEntity implements Serializable {
#Column(name="par_cls")
#NotNull
private String parameterClass;
#Column(name="par_cd")
#NotNull
private String parameterCode;
#Column(name="par_lan")
#NotNull
private String language;
#Column(name="par_sht_val")
#NotNull
private String parameterValueShort;
#Column(name="par_lng_val")
#NotNull
private String parameterValueLong;
- a authentication domain entity sample
#Entity
#Table(name="t_user", schema="authenticate")
public class User extends BaseIdEntity implements Serializable {
#Id
#Column(name="user_cd")
private String userCode;
#Column(name="pwd")
#NotNull
private String password;
#Column(name="new_pwd_req")
#NotNull
private boolean passwordRequired;
#Column(name="acc_lck")
#NotNull
private boolean accountLocked;
There are repositories onto these 2 entities beans, they just extends the JpaRepository as hereunder:
public interface ParameterRepository extends JpaRepository<Parameter,Integer>{}
the services are defined as hereunder:
#Service
#Transactional(transactionManager="authenticateTransactionManager")
public class ServiceParameterImpl implements ServiceParameter {
private final static Logger log = LoggerFactory.getLogger(ServiceParameterImpl.class);
#Autowired
private ParameterRepository parameterRepository;
#Override
#Transactional(readOnly=true,transactionManager="authenticateTransactionManager")
public List<Parameter> findParameterHeader(String filter) {
.../...
The client application as:
#SpringBootApplication
#Configuration
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class
, HibernateJpaAutoConfiguration.class
, DataSourceTransactionManagerAutoConfiguration.class })
#ComponentScan(
basePackages= {
"org.associative.ui"
,"org.associative.service"
})
#Import({AssociativityConfiguration.class, AuthenticateConfiguration.class})
public class Application {
private final static Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
and configurations:
#Configuration
#EnableTransactionManagement
#EntityScan(basePackages= "org.associative.domain.associativity")
#EnableJpaRepositories(
basePackages = "org.associative.domain.associativity.repository"
, entityManagerFactoryRef = "associativityEntityManager"
, transactionManagerRef = "associativityTransactionManager"
)
#ConfigurationProperties(prefix = "db.associativity")
public class AssociativityConfiguration {
private final static Logger log = LoggerFactory.getLogger(AssociativityConfiguration.class);
#Autowired
private Environment env;
private final static String ASSOCIATIVITY_DRIVER_CLASS_NAME = "db.associativity.classname";
private final static String ASSOCIATIVITY_URL = "db.associativity.connectionUrl";
private final static String ASSOCIATIVITY_USERNAME = "db.associativity.username";
private final static String ASSOCIATIVITY_PASSWORD = "db.associativity.password";
private final static String HIBERNATE_DIALECT = "hibernate.dialect";
#Bean(name = "associativityDataSource")
public DataSource datasource() {
DataSource dataSource = DataSourceBuilder.create()
.driverClassName(env.getProperty(ASSOCIATIVITY_DRIVER_CLASS_NAME))
.url(env.getProperty(ASSOCIATIVITY_URL))
.username(env.getProperty(ASSOCIATIVITY_USERNAME))
.password(env.getProperty(ASSOCIATIVITY_PASSWORD)).build();
if (log.isTraceEnabled())
log.trace(String.format("associativityConfiguration datasource:%s", dataSource.toString()));
return dataSource;
}
#Bean(name = "associativityEntityManager")
#PersistenceContext(unitName = "associativity")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
#Qualifier("associativityDataSource") DataSource dataSource) {
Map<String, Object> jpaProperties = new HashMap<>();
jpaProperties.put(HIBERNATE_DIALECT, env.getProperty(HIBERNATE_DIALECT));
LocalContainerEntityManagerFactoryBean em = builder.dataSource(dataSource)
.packages("org.associative.domain.authenticate").persistenceUnit("pu_associativity").properties(jpaProperties)
.build();
em.setJpaPropertyMap(jpaProperties);
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(adapter); // not mandatory definition
return em;
}
#Bean(name = "associativityTransactionManager")
public PlatformTransactionManager associativityTransactionManager(
#Qualifier("associativityEntityManager") EntityManagerFactory entityManagerFactory) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
and
#Configuration
#EnableTransactionManagement
#EntityScan(basePackages= "org.associative.domain.authenticate")
#EnableJpaRepositories(
basePackages = "org.associative.domain.authenticate.repository"
, entityManagerFactoryRef = "authenticateEntityManager"
, transactionManagerRef = "authenticateTransactionManager"
)
#ConfigurationProperties(prefix="db.authenticate")
public class AuthenticateConfiguration {
private final static Logger log = LoggerFactory.getLogger(AuthenticateConfiguration.class);
#Autowired
private Environment env;
private final static String AUTHENTICATE_DRIVER_CLASS_NAME= "db.authenticate.classname";
private final static String AUTHENTICATE_URL = "db.authenticate.connectionUrl";
private final static String AUTHENTICATE_USERNAME = "db.authenticate.username";
private final static String AUTHENTICATE_PASSWORD = "db.authenticate.password";
private final static String HIBERNATE_DIALECT = "hibernate.dialect";
#Primary
#Bean(name = "authenticateDataSource")
public DataSource datasource() {
DataSource dataSource = DataSourceBuilder.create()
.driverClassName(env.getProperty(AUTHENTICATE_DRIVER_CLASS_NAME))
.url(env.getProperty(AUTHENTICATE_URL))
.username(env.getProperty(AUTHENTICATE_USERNAME))
.password(env.getProperty(AUTHENTICATE_PASSWORD))
.build();
if ( log.isTraceEnabled()) log.trace(String.format("authenticateDataSource datasource:%s", dataSource.toString()));
return dataSource;
}
#Primary
#Bean(name="authenticateEntityManager")
#PersistenceContext(unitName = "authenticate")
//https://raymondhlee.wordpress.com/tag/enablejparepositories/
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder, #Qualifier("authenticateDataSource")DataSource dataSource) {
Map<String,Object> jpaProperties = new HashMap<>();
jpaProperties.put(HIBERNATE_DIALECT, env.getProperty(HIBERNATE_DIALECT));
LocalContainerEntityManagerFactoryBean em = builder
.dataSource(dataSource)
.packages("org.associative.domain.authenticate")
.persistenceUnit("pu_authenticate")
.properties(jpaProperties)
.build();
em.setJpaPropertyMap(jpaProperties);
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(adapter); // not mandatory definition
return em;
}
#Primary
#Bean(name="authenticateTransactionManager")
public PlatformTransactionManager authenticateTransactionManager(
#Qualifier("authenticateEntityManager")EntityManagerFactory entityManagerFactory){
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory);
return transactionManager;
}
}
I'm facing an issue when a service is built by using autowiring in the construction of my client interface:
#SpringUI
public class ParameterListView extends CssLayout implements Serializable {
private final static Logger log = LoggerFactory.getLogger(ParameterListView.class);
#Autowired
private ParameterController controller;
#PostConstruct
private void initView() {
if ( log.isTraceEnabled() ) log.trace(String.format("initView:%s", "no param"));
Grid<Parameter> grid = new Grid<>();
this.addComponent(grid);
grid.setItems(controller.getParameterHeader(""));
grid.addColumn(Parameter::getParameterClass);
grid.addColumn(Parameter::getParameterValueShort);
grid.addColumn(Parameter::getParameterValueLong);
2017-12-01 14:20:07.151 ERROR o.s.b.SpringApplication Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterControllerImpl': Unsatisfied
dependency expressed through field 'serviceParameter'; nested
exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'serviceParameterImpl': Unsatisfied
dependency expressed through field 'parameterRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'parameterRepository': Invocation of
init method failed; nested exception is
java.lang.IllegalArgumentException: Not a managed type: class
org.associative.domain.associativity.Parameter
I already spent a lot of time in order to solve the multiple database connections because I was thinking this issue comes from a definition problem but I'm not sure now.
So, what should I look to in order to solve this.
Thank you very much.
The last line of your stack trace is a clue: Not a managed type: class org.associative.domain.associativity.Parameter. Hibernate doesn't know about your Parameter entity.
In the LocalContainerEntityManagerFactoryBean you set packages to scan to org.associative.domain.authenticate. Your Parameter entity is not under this package.
This should fix the problem:
.packages("org.associative.domain.authenticate", "org.associative.domain.associativity")
I'm trying to create my own RouteBuilder but I'm getting the following error:
java.lang.IllegalArgumentException: onException must be defined before any routes in the RouteBuilder
at org.apache.camel.builder.RouteBuilder.onException(RouteBuilder.java:214)
at com.mdw360.ttt.mongo.fab.route.ExceptionBuilder.configure(ExceptionBuilder.java:18)
at org.apache.camel.builder.RouteBuilder.checkInitialized(RouteBuilder.java:322)
at org.apache.camel.builder.RouteBuilder.configureRoutes(RouteBuilder.java:276)
at org.apache.camel.builder.RouteBuilder.addRoutesToCamelContext(RouteBuilder.java:262)
at org.apache.camel.impl.DefaultCamelContext.addRoutes(DefaultCamelContext.java:679)
at org.apache.camel.test.junit4.CamelTestSupport.doSetUp(CamelTestSupport.java:302)
at org.apache.camel.test.junit4.CamelTestSupport.setUp(CamelTestSupport.java:217)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.junit.runner.JUnitCore.run(JUnitCore.java:160)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:78)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:212)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
On my ExceptionBuilder I have this code:
public class ExceptionBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
ExceptionProcessor exceptionProcessor = new ExceptionProcessor();
onException(Exception.class).process(exceptionProcessor);
}
}
And on my test I have that:
#Test
public void testExceptionWhileRouting() throws Exception {
getMockEndpoint("mock:http").expectedBodiesReceived("Camel rocks");
getMockEndpoint("mock:http").whenAnyExchangeReceived(new Processor() {
public void process(Exchange exchange) throws Exception {
System.out.println("ERROR");
exchange.setException(new ConnectException("Simulated connection error"));
}
});
template.sendBody("direct:file", "Camel rocks");
assertMockEndpointsSatisfied();
}
#Override
protected RouteBuilder createRouteBuilder() {
ExceptionBuilder routeBuilder = new ExceptionBuilder();
routeBuilder.from("direct:file").to("mock:http");
return routeBuilder;
}
As I'm adding the onException into the configure, why it's saying that I must define it before any route?
You need to move this:
from("direct:file").to("mock:http");
to the configure() method, after you call onException(). So it looks like this:
public class ExceptionBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
onException(Exception.class).process(new ExceptionProcessor());
from("direct:file").to("mock:http");
}
}
Then your createRouteBuilder() method should look like this:
#Override
protected RouteBuilder createRouteBuilder() {
return new ExceptionBuilder();
}
I think the reason it's giving you an error is because routes are expected to contain the from() method call.
You might be able to do something like this if you're trying to create a common exception handling route:
public class ExceptionBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
from("direct:onException").process(new ExceptionProcessor());
}
}
public class TestRouteBuilder extends RouteBuilder{
#Override
public void configure() throws Exception {
onException(Exception.class).to("direct:onException");
from("direct:start").to("mock:end");
}
}
I am attempting to read values from MySQL database and display it in a table in JavaFX. I use netbeans IDE. When I run my code I got the exception mentioned in the title. I will post code below:
public class ViewSubject extends Application {
private final TableView<Subject> table = new TableView<>();
private final ObservableList<Subject> data
= FXCollections.observableArrayList();
final HBox hb = new HBox();
private Connection connect = null;
private Statement statement = null;
private final PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws ClassNotFoundException, SQLException {
Scene scene = new Scene(new Group());
stage.setTitle("Add Subject");
stage.setWidth(650);
stage.setHeight(550);
stage.setResizable(false);
final Label label = new Label("Subject Details");
label.setFont(new Font("Calibri", 20));
TableColumn sub = new TableColumn("Subject Name");
sub.setMinWidth(350);
sub.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subName"));
sub.setCellFactory(TextFieldTableCell.forTableColumn());
sub.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubName(t.getNewValue());
}
}
);
TableColumn code = new TableColumn("Subject Code");
code.setMinWidth(130);
code.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subCode"));
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
TableColumn rev = new TableColumn("Revision");
rev.setMinWidth(130);
rev.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subRev"));
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
table.setItems(data);
table.getColumns().addAll(sub, code, rev);
final VBox vbox = new VBox();
vbox.setSpacing(10);
vbox.setPadding(new Insets(20, 20, 20, 20));
vbox.getChildren().addAll(label, table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost:3306/project?"
+ "user=root&password=virus");
statement = connect.createStatement();
resultSet = statement
.executeQuery("select * from subject");
writeResultSet(resultSet);
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
String subname = resultSet.getString("subname");
String code = resultSet.getString("subcode");
String rev = resultSet.getString("subrev");
data.add(new Subject(subname, code, rev));
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (SQLException e) {
}
}
}
There is one more class in the package -
public class Subject {
private final SimpleStringProperty sub;
private final SimpleStringProperty code;
private final SimpleStringProperty rev;
Subject(String subName, String subCode, String subRev) {
this.sub = new SimpleStringProperty(subName);
this.code = new SimpleStringProperty(subCode);
this.rev = new SimpleStringProperty(subRev);
}
public String getSubName() {
return sub.get();
}
public void setSubName(String subName) {
sub.set(subName);
}
public String getSubCode() {
return code.get();
}
public void setSubCode(String subCode) {
code.set(subCode);
}
public String getSubRev() {
return rev.get();
}
public void setSubRev(String subRev) {
rev.set(subRev);
}
}
This is the exception details:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at viewsubject.ViewSubject.read(ViewSubject.java:119)
at viewsubject.ViewSubject.start(ViewSubject.java:113)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
... 1 more
When the code is ran, a window appears for a fraction of a second and then suddenly closes due to the occurrence of this exception. Why this exception occurs ? How can remove this exception?
You don't have the MySQL JDBC driver on your classpath.
Perform the Vogella tutorial on Java and JDBC with MySQL. Do the whole tutorial step by step, running code each step of the way. As part of the Vogella tutorial, it tells you how to setup 3rd party libraries (like the MySQL JDBC library) in Eclipse.
When posting code, try to post code which matches the stack trace. The StackTrace reports an error at viewsubject.ViewSubject.read(ViewSubject.java:119) but there is no such read function in your ViewSubject class.
I am attempting to read values from MySQL database and display it in a table in JavaFX. I use netbeans IDE. When I run my code I got the exception mentioned in the title. I will post code below:
public class ViewSubject extends Application {
private final TableView<Subject> table = new TableView<>();
private final ObservableList<Subject> data
= FXCollections.observableArrayList();
final HBox hb = new HBox();
private Connection connect = null;
private Statement statement = null;
private final PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws ClassNotFoundException, SQLException {
Scene scene = new Scene(new Group());
stage.setTitle("Add Subject");
stage.setWidth(650);
stage.setHeight(550);
stage.setResizable(false);
final Label label = new Label("Subject Details");
label.setFont(new Font("Calibri", 20));
TableColumn sub = new TableColumn("Subject Name");
sub.setMinWidth(350);
sub.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subName"));
sub.setCellFactory(TextFieldTableCell.forTableColumn());
sub.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubName(t.getNewValue());
}
}
);
TableColumn code = new TableColumn("Subject Code");
code.setMinWidth(130);
code.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subCode"));
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
TableColumn rev = new TableColumn("Revision");
rev.setMinWidth(130);
rev.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subRev"));
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
table.setItems(data);
table.getColumns().addAll(sub, code, rev);
final VBox vbox = new VBox();
vbox.setSpacing(10);
vbox.setPadding(new Insets(20, 20, 20, 20));
vbox.getChildren().addAll(label, table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost:3306/project?"
+ "user=root&password=virus");
statement = connect.createStatement();
resultSet = statement
.executeQuery("select * from subject");
writeResultSet(resultSet);
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
String subname = resultSet.getString("subname");
String code = resultSet.getString("subcode");
String rev = resultSet.getString("subrev");
data.add(new Subject(subname, code, rev));
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (SQLException e) {
}
}
}
There is one more class in the package -
public class Subject {
private final SimpleStringProperty sub;
private final SimpleStringProperty code;
private final SimpleStringProperty rev;
Subject(String subName, String subCode, String subRev) {
this.sub = new SimpleStringProperty(subName);
this.code = new SimpleStringProperty(subCode);
this.rev = new SimpleStringProperty(subRev);
}
public String getSubName() {
return sub.get();
}
public void setSubName(String subName) {
sub.set(subName);
}
public String getSubCode() {
return code.get();
}
public void setSubCode(String subCode) {
code.set(subCode);
}
public String getSubRev() {
return rev.get();
}
public void setSubRev(String subRev) {
rev.set(subRev);
}
}
This is the exception details:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at viewsubject.ViewSubject.read(ViewSubject.java:119)
at viewsubject.ViewSubject.start(ViewSubject.java:113)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
... 1 more
When the code is ran, a window appears for a fraction of a second and then suddenly closes due to the occurrence of this exception. Why this exception occurs ? How can remove this exception?
You don't have the MySQL JDBC driver on your classpath.
Perform the Vogella tutorial on Java and JDBC with MySQL. Do the whole tutorial step by step, running code each step of the way. As part of the Vogella tutorial, it tells you how to setup 3rd party libraries (like the MySQL JDBC library) in Eclipse.
When posting code, try to post code which matches the stack trace. The StackTrace reports an error at viewsubject.ViewSubject.read(ViewSubject.java:119) but there is no such read function in your ViewSubject class.