Why service classes are not autowired? - spring-mvc

I'll try to develop simple web service.
In order to make test data, i create test class.
However, in this class, there is error that service classes are not autowired.
help me.
Why it is not autoried?
This is error message.
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:117)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:83)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:228)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:230)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:291)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:249)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultServletHandlerMapping' defined in class org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:125)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:109)
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:261)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.web.servlet.HandlerMapping]: Factory method 'defaultServletHandlerMapping' threw exception; nested exception is java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
... 42 more
Caused by: java.lang.IllegalArgumentException: A ServletContext is required to configure default servlet handling
at org.springframework.util.Assert.notNull(Assert.java:115)
at org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer.<init>(DefaultServletHandlerConfigurer.java:53)
at org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport.defaultServletHandlerMapping(WebMvcConfigurationSupport.java:451)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$c4ca4a4e.CGLIB$defaultServletHandlerMapping$26(<generated>)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$c4ca4a4e$$FastClassBySpringCGLIB$$3fa44495.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:355)
at org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration$$EnhancerBySpringCGLIB$$c4ca4a4e.defaultServletHandlerMapping(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
... 43 more
This is my test class.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = AppInitializer.class)
public class createTestData {
#Autowired
private UserService userService;
#Autowired
private ReadabilityService readabilityService;
#Test
#Transactional
public void createTestData()
{
.....
testData.setUser(userService.findByUsername("test1"));
.....
}
}
This is configuration class.
package com.websystique.springmvc.configuration;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import com.websystique.springmvc.service.UserService;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.websystique.springmvc")
public class AppConfig extends WebMvcConfigurerAdapter{
/**
* Configure ViewResolvers to deliver preferred views.
*/
#Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
/**
* Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
*/
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
/**
* Configure Converter to be used.
* In our example, we need a converter to convert string values[Roles] to UserProfiles in newUser.jsp
*/
#Override
public void addFormatters(FormatterRegistry registry) {
}
/**
* Configure MessageSource to lookup any validation/error message in internationalized property files
*/
#Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("messages");
return messageSource;
}
#Order(Ordered.HIGHEST_PRECEDENCE)
#Bean
CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
filter.setForceEncoding(true);
return filter;
}
/**Optional. It's only required when handling '.' in #PathVariables which otherwise ignore everything after last '.' in #PathVaidables argument.
* It's a known bug in Spring [https://jira.spring.io/browse/SPR-6164], still present in Spring 4.1.7.
* This is a workaround for this issue.
*/
#Override
public void configurePathMatch(PathMatchConfigurer matcher) {
matcher.setUseRegisteredSuffixPatternMatch(true);
}
}
help me

Have you read the stacktrace? Which indicates you are trying to load web based classes in a now web based test. Read the documentation on how to be able to test web based things

Related

javaFX Obfuscate error at java.lang.Thread.run(Unknown Source)

I'm new to JavaFX. I get this error when I try to run my JavaFX app
Exception in Application start method
java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$1(LauncherImpl.java:182)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.AbstractMethodError: javafx.application.Application.start(Ljavafx/stage/Stage;)V
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$8(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$7(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$5(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$6(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$4(WinApplication.java:186)
... 1 more
My main class is main.mainpage
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.stage.WindowEvent;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class mainpage extends Application {
public static Stage STAGE;
public static Scene SCENE;
#Override
public void start(Stage stage) throws Exception {
STAGE = stage;
Parent root = FXMLLoader.load(getClass().getResource("login.fxml"));
SCENE = new Scene(root);
STAGE.setScene(SCENE);
STAGE.show();
STAGE.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
Platform.exit();
System.exit(0);
}
});
}
public static void main(String args[]) {
launch(args);
}
}
Proguard config file:
-injars '************************************************************.jar'
-outjars '************************************************************-obf.jar'
-libraryjars 'C:\Program Files\Java\jre1.8.0_251\lib\rt.jar'
-dontshrink
-obfuscationdictionary OBF.txt
-classobfuscationdictionary OBF.txt
-packageobfuscationdictionary OBF.txt
-dontnote
-dontwarn
-ignorewarnings
# Keep - Applications. Keep all application classes, along with their 'main'
# methods.
-keepclasseswithmembers public class com.javafx.main.Main, main.mainpage {
public static void main(java.lang.String[]);
}
# Rename FXML files together with related views
-adaptresourcefilenames **.fxml,**.png,**.css
-adaptresourcefilecontents **.fxml
-adaptclassstrings
# Save meta-data for stack traces
-renamesourcefileattribute SourceFile
-keepattributes SourceFile,LineNumberTable
# Keep all annotations and meta-data
-keepattributes *Annotation*,Signature,EnclosingMethod
# Keep names of fields marked with #FXML attribute
-keepclassmembers class * {
#javafx.fxml.FXML *;
}
# Also keep - Enumerations. Keep the special static methods that are required in
# enumeration classes.
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
# Also keep - Database drivers. Keep all implementations of java.sql.Driver.
-keep class * extends java.sql.Driver
# Keep names - Native method names. Keep all native class/method names.
-keepclasseswithmembers,includedescriptorclasses,allowshrinking class * {
native <methods>;
}
I use exe4j to make exe file. When I run without obfuscating then the app is working. But it doesn't work after obfuscating.

EJB persistence not working

I have a example EJB persistence with EJB module run on Jboss 5GA , JDK 6 . Default package have 3 file :
Book.java :
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="books")
public class Book implements Serializable{
private int id;
private String name;
public Book(){
}
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(name="id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
LibraryPersistentBean.java
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class LibraryPersistentBean implements LibraryPersistentBeanRemote {
#PersistenceContext(unitName="EJBModule1PU")
private EntityManager entityManager;
#Override
public void addBook(Book book) {
entityManager.persist(book);
}
#Override
public List<Book> getBooks() {
return entityManager.createQuery("From books").getResultList();
}
}
LibraryPersistentBeanRemote.java:
import java.util.List;
import javax.ejb.Remote;
#Remote
public interface LibraryPersistentBeanRemote {
void addBook(Book bookName);
List<Book> getBooks();
}
And configure files are persistence.xml and jboss-ds.xml that have lines of code :
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="EJBModule1PU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/MysqlDS</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
<?xml version="1.0" encoding="UTF-8"?>
<datasources>
<local-tx-datasource>
<jndi-name>MysqlDS</jndi-name>
<connection-url>jdbc:mysql://localhost:3306/ejb_books?zeroDateTimeBehavior=convertToNull</connection-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<user-name>root</user-name>
<password/>
<min-pool-size>5</min-pool-size>
<max-pool-size>20</max-pool-size>
<idle-timeout-minutes>5</idle-timeout-minutes>
</local-tx-datasource>
</datasources>
Client's application consist of :
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
public class JavaApplication1 {
public static void main(String[] args) throws NamingException {
try {
Book b = new Book();
b.setName("AI");
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
env.put(Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
env.put(Context.PROVIDER_URL, "jnp://localhost:1099");
Context ctx = new InitialContext(env);
LibraryPersistentBeanRemote libraryBean = (LibraryPersistentBeanRemote)ctx.lookup("LibraryPersistentBean/remote");
libraryBean.addBook(b);
} catch (NamingException ex) {
Logger.getLogger(JavaApplication1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and jboss-client.jar, EJB Module was imported
when run, errors were occured :
Mar 7, 2017 10:30:23 AM JavaApplication1 main
SEVERE: null
javax.naming.NoInitialContextException: Cannot instantiate class: org.jnp.interfaces.NamingContextFactory [Root exception is java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory]
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:657)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.init(InitialContext.java:223)
at javax.naming.InitialContext.<init>(InitialContext.java:197)
at JavaApplication1.main(JavaApplication1.java:25)
Caused by: java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:247)
at com.sun.naming.internal.VersionHelper12.loadClass(VersionHelper12.java:46)
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:654)
... 4 more
How to resolve these error ? thanks you so much !
"$JBOSS_HOME/jboss-as/client/jnp-client.jar" contains the missing class "org.jnp.interfaces.NamingContextFactory" , The "jnp-client.jar" is referred internally using the MANIFEST.MF file "class-path" entry of the "$JBOSS_HOME/client/jbossall-client.jar" file.
So the JBoss Client code users/developers need to make sure that in order to avoid the "[Caused by: java.lang.ClassNotFoundException: org.jnp.interfaces.NamingContextFactory]" exception users must include the "$JBOSS_HOME/client/jbossall-client.jar" in client's classpath.

How configure spring multiple profiles databases javaconfig

How to start a project with spring MVC with profiles, multiple connections to the database .. and run tests with gradle?
Some time ago I'm trying to make these settings and I'm not getting what I'm doing wrong?
(Sorry for my english I'm using google translate.)
Here are my settings
Dev Settings
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost:5432/nextinfoerp
db.username=myuser
db.password=mypass
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.format_sql =true
entitymanager.packages.to.scan=br.com.nextinfo.erp
Test Settings
#Test properties:
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost:5432/nextinfoerptestdb
db.username=myuser
db.password=mypass
#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
hibernate.show_sql=true
hibernate.format_sql =true
entitymanager.packages.to.scan=br.com.nextinfo.erp
Gradle Settings
apply plugin: 'java'
apply plugin: 'war'
apply plugin: 'eclipse-wtp'
apply plugin: 'jetty'
sourceCompatibility = 1.8
targetCompatibility = 1.8
ext.springVersion= '4.1.7.RELEASE'
ext.jacksondataTypeHibernate4 ='2.5.3'
ext.easycriteriaVersion ='3.0.0'
ext.hibernateCoreVersion ='4.3.10.Final'
ext.hibernateValidadeVersion ='5.1.3.Final'
ext.springDataVersion ='1.8.0.RELEASE'
ext.mysqlConnectionVersion= '5.1.6'
ext.servletApiVersion ='2.5'
dependencies {
testCompile 'junit:junit:4.12'
compile project(':utils')
compile"javax.servlet:jstl:1.2"
compile "org.thymeleaf:thymeleaf-spring4:2.1.2.RELEASE"
compile group: 'javax.servlet', name: 'servlet-api', version: servletApiVersion
compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '1.2.9'
compile group: 'org.springframework.security', name: 'spring-security-web', version: '4.0.2.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-core', version: '4.0.2.RELEASE'
compile group: 'org.springframework.security', name: 'spring-security-config', version: '4.0.2.RELEASE'
compile 'org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE'
compile group: 'org.springframework', name: 'spring-context', version: springVersion
compile group: 'org.springframework', name: 'spring-web', version: springVersion
compile group: 'org.springframework', name: 'spring-test', version: springVersion
compile group: 'org.springframework', name: 'spring-webmvc', version: springVersion
compile group: 'org.springframework.data', name: 'spring-data-jpa', version:springDataVersion
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-hibernate4', version: jacksondataTypeHibernate4
compile "org.postgresql:postgresql:9.3-1100-jdbc4"
compile group: 'uaihebert.com', name: 'EasyCriteria', version: easycriteriaVersion
compile group: 'org.hibernate', name: 'hibernate-validator', version: hibernateValidadeVersion
compile group: 'org.hibernate', name: 'hibernate-core', version: hibernateCoreVersion
compile group: 'org.hibernate', name: 'hibernate-entitymanager', version: hibernateCoreVersion
}
class for database configuration
package br.com.nextinfo.erp.web.config;
import java.util.Properties;
import javax.annotation.Resource;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#Profile("dev")
#EnableJpaRepositories("br.com.nextinfo.erp.web.dao")
#PropertySource("classpath:dev.properties")
public class DevProfileDatabase extends AbstractDatabaseConfig implements PerfilDataBase {
private static final Logger log = LoggerFactory.getLogger(DevProfileDatabase.class);
#Resource
private Environment env;
#Bean
public DataSource dataSource() {
log.warn("settings data Source "+this.getClass().getCanonicalName());
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
return dataSource;
}
#Bean
protected Properties hibProperties() {
Properties properties = new Properties();
properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
properties.put(PROPERTY_NAME_HIBERNATE_FORMAT_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_FORMAT_SQL));
return properties;
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
txManager.getEntityManagerFactory().getMetamodel().getEntities();
return txManager;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
log.warn("settings data entity manager "+this.getClass().getCanonicalName());
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(true);
vendorAdapter.setShowSql(true);
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setJpaVendorAdapter(vendorAdapter);
factory.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
factory.setDataSource(dataSource());
factory.afterPropertiesSet();
return factory.getObject();
}
}
My class incializer
import javax.servlet.Filter;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
#Order(1)
public class Inicializer extends AbstractAnnotationConfigDispatcherServletInitializer implements WebApplicationInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {ThymeleafConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ThymeleafConfig.class,ProdProfileDatabase.class,DevProfileDatabase.class,TestProfileDatabase.class};
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
#Override
protected Filter[] getServletFilters() {
return new Filter[] { };
}
#Override
protected WebApplicationContext createRootApplicationContext() {
WebApplicationContext context =
(WebApplicationContext)super.createRootApplicationContext();
((ConfigurableEnvironment)context.getEnvironment()).setActiveProfiles("dev");
return context;
}
I'm using spring-data
the error
Servlet.init() for servlet dispatcher threw exception
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in class path resource [br/com/nextinfo/erp/web/config/ProdProfileDatabase.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.transaction.PlatformTransactionManager]: Factory method 'transactionManager' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [br/com/nextinfo/erp/web/config/ProdProfileDatabase.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManagerFactory]: Factory method 'entityManagerFactory' threw exception; nested exception is org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:664)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:536)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:490)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)
If I remove the annotation profiles and classes that use the annotation inicializer function normally,
How do I solve this?
I solved the problem by moving the database configuration classes to load along with the root settings
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {ThymeleafConfig.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ThymeleafConfig.class,ProdProfileDatabase.class,DevProfileDatabase.class,TestPr ofileDatabase.class};
}
I did this exchange
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {ProdProfileDatabase.class,DevProfileDatabase.class,TestPr ofileDatabase.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] {ThymeleafConfig.class};
}

Exception in Application start method java.lang.reflect.InvocationTargetException javafx

I write program with java8, JAVAFX, spring, hibernate, jpa, mysql.
I've to problem with connecting server part of program with javafx.
When I click on class with main→run as java aplication, this problems occurs:
log4j:WARN No appenders could be found for logger (org.jboss.resteasy.plugins.providers.DocumentProvider).
log4j:WARN Please initialize the log4j system properly.
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/Users/Sylwia/.m2/repository/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/Sylwia/.m2/repository/org/slf4j/slf4j-log4j12/1.7.5/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/Users/Sylwia/.m2/repository/org/slf4j/slf4j-simple/1.5.8/slf4j-simple-1.5.8.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(Unknown Source)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$147(Unknown Source)
at com.sun.javafx.application.LauncherImpl$$Lambda$48/1732398722.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: javafx.fxml.LoadException:
/C:/Users/Sylwia/git/Praca%20inzynierska%203/Praca%20inzynierska%202/target/classes/fxml/productComponent.fxml
at javafx.fxml.FXMLLoader.constructLoadException(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.loadImpl(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at pl.ftims.praca.restClientJavafx.RestClient.start(RestClient.java:17)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$153(Unknown Source)
at com.sun.javafx.application.LauncherImpl$$Lambda$51/1441419654.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$166(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$45/1051754451.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$164(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$47/742445343.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$165(Unknown Source)
at com.sun.javafx.application.PlatformImpl$$Lambda$46/1775282465.run(Unknown Source)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$141(Unknown Source)
at com.sun.glass.ui.win.WinApplication$$Lambda$37/1109371569.run(Unknown Source)
... 1 more
Caused by: java.lang.NullPointerException
at pl.ftims.praca.restClientJavafx.FXMLController.initialize(FXMLController.java:140)
... 23 more
Exception running application pl.ftims.praca.restClientJavafx.RestClient
//////////////////////////////////////////////////////////////////////
Should I first focus on problem:
at pl.ftims.praca.restClientJavafx.RestClient.start(RestClient.java:17)
or:
Caused by: java.lang.NullPointerException
at pl.ftims.praca.restClientJavafx.FXMLController.initialize(FXMLController.java:140)
... 23 more
my RestClient class:
package pl.ftims.praca.restClientJavafx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class RestClient extends Application {
#Override
public void start(Stage stage) throws Exception {
//When using the Class.getResource method,
//you must provide a local path from the location of the class on which is called the method.
//Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/components.fxml"));
Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/productComponent.fxml"));
//I also had to use Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));
/*FXMLLoader loader = new FXMLLoadergetClass().getResource("main.fxml");
loader.setController(new MainController(path));
Pane mainPane = loader.load();*/
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
/**
* The main() method is ignored in correctly deployed JavaFX application.
* main() serves only as fallback in case the application can not be
* launched through deployment artifacts, e.g., in IDEs with limited FX
* support. NetBeans ignores main().
*
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
FXMLController class
package pl.ftims.praca.restClientJavafx;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import pl.ftims.praca.model.ProductWrapper;
import pl.ftims.praca.model.Products;
public class FXMLController implements Initializable {
#FXML
private TableView productTable;
#FXML
private TableColumn idColumn;
#FXML
private TableColumn nameColumn;
#FXML
private TableColumn sellingPriceColumn;
#FXML
private TableColumn purchasePriceColumn;
#FXML
private TextField idField;//tego nie bylo chyba, bo nie mozna przeciez zmieniac id
#FXML
private TextField nameField;
#FXML
private TextField sellingPriceField;
#FXML
private TextField purchasePriceField;
/*private Long id;
private String name;
private Double sellingPrice;
private Double purchasePrice; //cena zakupu
#ManyToOne
private Storages storage; */
private List<Products> listOfProducts = null;
private List<Fxproduct> listOfFxProducts = null;
private ObservableList<Fxproduct> listOfObservableList = null;
private final static String REST_ROOT_URL = "http://localhost:8080/rest/";
private final Client client = ClientBuilder.newClient();
#FXML
private void remove(ActionEvent event) { //ok rozumiem
Fxproduct fxproduct = (Fxproduct) productTable.getSelectionModel().getSelectedItem();
listOfObservableList.remove(fxproduct);
Response response = client.target(REST_ROOT_URL).
// path("publisher").
path("products").
path("deleteProductWithId").
path(String.valueOf(fxproduct.getId())).
request().delete();
}
#FXML
private void save(ActionEvent event) {
Products product = new Products();
product.setName(nameField.getText());
product.setPurchasePrice(Double.parseDouble(purchasePriceField.getText()));
product.setSellingPrice(Double.parseDouble(sellingPriceField.getText()));
Entity<Products> kitapEntity = Entity.entity(product, MediaType.APPLICATION_XML);
Response response = client.target(REST_ROOT_URL).
path("product").
path("createProductWithData").
request().
post(kitapEntity);
list(null);
nameField.setText("");
purchasePriceField.setText("");
sellingPriceField.setText("");
}
#FXML
private void list(ActionEvent event) { //NIE WIEM JAK TO ZROBIC
Response response = client.target("http://localhost:8080/rest/").
path("products").
path("products").
request(MediaType.APPLICATION_XML).
get();
ProductWrapper productWrapper = response.readEntity(ProductWrapper.class); //nie mam tego
listOfProducts = (productWrapper.getProductList()==null)?new ArrayList<Products>(): productWrapper.getProductList();
// listOfFxProducts = new ArrayList<>();
// listOfFxProducts = new ArrayList<>(); //tak bylo, ale to jest java 1.7 i sie nie kompilowalo
for (Products k : listOfProducts) {
listOfFxProducts.add(new Fxproduct(k));
}
listOfObservableList = FXCollections.observableList(listOfFxProducts);
System.out.println(listOfObservableList);
productTable.setItems(listOfObservableList);
System.out.println(productTable);
}
public void kitapDuzenle(Products product) {
Entity<Products> kitapEntity = Entity.entity(product, MediaType.APPLICATION_XML);
Response response = client.target(REST_ROOT_URL).
path("product").
path("saveProduct2").
request().
put(kitapEntity);
}
// #SuppressWarnings("restriction")
#Override
public void initialize(URL url, ResourceBundle rb) {
productTable.setEditable(true); //tu jest blad, nullpointer
//NAME
nameColumn.setCellFactory(TextFieldTableCell.forTableColumn());
nameColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Fxproduct, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Fxproduct, String> t) {
ObservableList<Fxproduct> kitapListesi = t.getTableView().getItems();
Fxproduct kitap = kitapListesi.get(t.getTablePosition().getRow());
kitap.setName(t.getNewValue());
kitapDuzenle(kitap.getproduct());
}
}
);
//SELLINGPRICE
sellingPriceColumn.setCellFactory(TextFieldTableCell.forTableColumn(new DoubleToStringConverter()));//tu jest blad
sellingPriceColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Fxproduct, Double>>() {
#Override
public void handle(TableColumn.CellEditEvent<Fxproduct, Double> t) {
ObservableList<Fxproduct> kitapListesi = t.getTableView().getItems();
Fxproduct kitap = kitapListesi.get(t.getTablePosition().getRow());
kitap.setSellingPrice(t.getNewValue()); //tu ejst problem z double i siple double
kitapDuzenle(kitap.getproduct());
}
}
);
//PURCHASEPRICE
purchasePriceColumn.setCellFactory(TextFieldTableCell.forTableColumn(new DoubleToStringConverter()));
purchasePriceColumn.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Fxproduct, Double>>() {
#Override
public void handle(TableColumn.CellEditEvent<Fxproduct, Double> t) {
ObservableList<Fxproduct> kitapListesi = t.getTableView().getItems();
Fxproduct kitap = kitapListesi.get(t.getTablePosition().getRow());
kitap.setPurchasePrice(t.getNewValue());//tu ejst problem z double i siple double
kitapDuzenle(kitap.getproduct());
}
}
);
idColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, Long>("id"));
nameColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, String>("name"));
purchasePriceColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, Double>("price"));
sellingPriceColumn.setCellValueFactory(
new PropertyValueFactory<Fxproduct, Double>("price"));
list(null);
}
}
I thought that the problems is the path:
Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/productComponent.fxml"));
but I read this:
How to reference javafx fxml files in resource folder?
JavaFX "Location is required." even though it is in the same package
Referencing class resource in FXML
Error loading fxml files from a folder other than the bin folder
JavaFX: load resource from other package - NetBeans
How to reference javafx fxml files in resource folder?
https://stackexchange.com/search?q=How+to+reference+javafx+fxml+files+in+resource+folder%3F
JavaFX - Exception in Application start method?
and I didnt find the answer.
/////////////////////////////EDIT///////////////////
line 17 in RestClient:
Parent root = FXMLLoader.load(RestClient.class.getResource("/fxml/productComponent.fxml"));
line 139, 140 in FXMLController:
public void initialize(URL url, ResourceBundle rb) { productTable.setEditable(true); // nullpointer

Not able to call ejb on same machine using client class

I am new to EJB. I tried an example from java_for_web_with_servlets_jsp_and_ejb book. The following code creates an session been called Adder which adds two integers:
Adder.java:
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
public interface Adder extends EJBObject{
public int add(int a,int b) throws RemoteException;
}
AdderBean.java
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
public class AdderBean implements SessionBean{
public int add(int a, int b){
System.out.println("From AdderBean");
return (a+b);
}
#Override
public void ejbActivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbPassivate() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void ejbRemove() throws EJBException, RemoteException {
// TODO Auto-generated method stub
}
#Override
public void setSessionContext(SessionContext arg0) throws EJBException,
RemoteException {
// TODO Auto-generated method stub
}
}
AdderHome.java
package com.brainysoftware.ejb;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
public interface AdderHome extends EJBHome{
Adder create() throws RemoteException, CreateException;
}
The deployment descriptor is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar version="3.1" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd">
<description>Your first EJB application</description>
<display-name>Adder Application</display-name>
<enterprise-beans>
<session>
<ejb-name>Adder</ejb-name>
<home>com.brainysoftware.ejb.AdderHome</home>
<remote>com.brainysoftware.ejb.Adder</remote>
<ejb-class>com.brainysoftware.ejb.AdderBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Bean</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
I created a jar file of this project and placed the jar in the tomcat's lib.
Now, for the client I created a dynamic web project having the class BeanClient.java that uses the Adder bean:
import java.rmi.RemoteException;
import java.util.Properties;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.brainysoftware.ejb.Adder;
import com.brainysoftware.ejb.AdderHome;
import javax.rmi.PortableRemoteObject;
public class BeanClient {
public static void main(String[] args){
Properties props = new Properties();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
props.put(Context.PROVIDER_URL, "localhost:1099");
try{
InitialContext jnic = new InitialContext(props);
System.out.println("Get context");
Object ref = jnic.lookup("Adder");
System.out.println("Got reference");
AdderHome home = (AdderHome) PortableRemoteObject.narrow(ref,AdderHome.class);
Adder adder = home.create();
System.out.println("Adding 2 and 5:"+adder.add(2,5));
} catch(NamingException e){
System.out.println(e.toString());
} catch(CreateException e){
System.out.println(e.toString());
} catch (RemoteException e) {
System.out.println(e.toString());
}
}
}
On executing this class in eclipse, I get the following error:
Get context
javax.naming.CommunicationException: Could not obtain connection to any of these urls: localhost:1099 and discovery failed with error: javax.naming.CommunicationException: Receive timed out [Root exception is java.net.SocketTimeoutException: Receive timed out] [Root exception is javax.naming.CommunicationException: Failed to connect to server localhost:1099 [Root exception is javax.naming.ServiceUnavailableException: Failed to connect to server localhost:1099 [Root exception is java.net.ConnectException: Connection refused: connect]]]
Could you please help me out with this?
to look up and ejb firstbale :
you must have an interface and it's implementation.
you have to annotate your interface (#Local ou #Remote)
The implementation must be annotated #statless ou #statful
You have to add on you project a jndi.properties.
your ejb project must be deployed on your server to be easy to look up it.
i have for you an example with jboss here :
https://www.youtube.com/watch?v=mBwgHuBg96g
i hope that my answer is useful pour you

Resources