C# in eclipse
http://emonic.sourceforge.net/html/CSharpEditorWithErrors.html
Migration Visual studio to Eclipse Project :
http://www.ibm.com/developerworks/library/os-eclipse-migratenetvs/
Source http://www.careerride.com/Spring-bean-lifecycle-in-spring-framework.aspx Question/response JAVA Spring What is Spring? Spring is a framework that resolves common problems in JEE architecture. (JDBC ,integration later, presentation layer …) Spring is managing business objects and encouraging practices POJO model (vs programming model) It’s highly recommended to use a architectural tiers (presentation,business,dao Layer) ; the inejection of the different beans
Le Grand collisionneur de hadrons (LHC) est un gigantesque instrument scientifique situé près de Genève, à cheval sur la frontière franco-suisse, à environ 100 mètres sous terre. C’est un accélérateur de particules, avec lequel les physiciens étudient les plus petites particules connues : les composants fondamentaux de la matière. Le LHC va révolutionner notre compréhension du monde,
Rendre un Jar executable en Spring Nous allons voir dans cet article comment packager un executable jar avec Maven 2 . Ayant rencontrer quelque problème dans le chargement des Beans Spring . Pour cela il faut inclure dans le packaging du jar les fichiers spring.handlers et spring.schemas. Nous utiliserons ici le plugin shade plutot
Samba permet de partager des dossiers sous Linux avec des ordinateurs locaux sous Windows, très pratique, donc ! De plus, il permet d’établir un réseau relativement sécurisé grâce à ses nombreuses fonctions. Commencez d’abord par l’installer : loguez vous en root puis tapez : apt-get install samba Il faut ensuite configurer quelques lignes du fichier
juin
05
Posted by : 5 juin 2012
| On :
C# in eclipse
http://emonic.sourceforge.net/html/CSharpEditorWithErrors.html
Migration Visual studio to Eclipse Project :
http://www.ibm.com/developerworks/library/os-eclipse-migratenetvs/
mai
13
Posted by : 13 mai 2012
| On :mai
11
Posted by : 11 mai 2012
| On :This tutorial is inspired from (run under glassfish)
http://java.dzone.com/articles/ejb-30-and-spring-25
In this following page I modified the spring configuration and test the deployment on Jboss 4.2
- Java 5 or higher
- Spring Tools suite (or Eclipse )
- Jboss 4.2.x (tested on version jboss-4.2.3.GA)
- Spring 2.5.6
The data layer is using @Entity to define the Table (or pojo) that will correspond to our data model
Here we have a simple table called Customer with a series of fields
As in Facade design pattern we will expose an interface and the method that the client can attack on the server side
So here we define an interface call CustomerService that is annoted with @Remote
Then we’ve implement the CRUD operation and @PersistenceContext in CustomerServiceImpl class
Then in the second part of the tutorial we are viewing how to bind Spring with EJB 3
To do that you’ll need to investigate the name of jndi register in your server.
The tag jee:jndi-lookup will bind both EJB context and spring context
Once your project is set up you can easily use Spring test or more simply define a Java project that reference your Ejb project (write a main )
When Should I use EJB or Spring ?
Personnaly I go through EJB 2 or 3 for exposing the services that I want others to use . In this sample projet we have seen how simple it is to expose some operation on Customer .
I prefer to use EJB also for Datalayer (DAO Data access Object) , We only need a persistence configuration file and an EntityManager, whereas in Spring the configuration is quite verbose .
Meanwhile I will also use spring because it’s modular and scapable for integration process , feed of data …
It’s also well oriented on Framework integration , so the integration overhall remain less painful .
Recently Springsource team has also develop in spring source view module for spring batch and spring integration. As a consequence we can realize and spot out easily what is going on around all that mess.
What also we need to keep in mind is that main vendors IBM websphere, Weblogic, jboss and others are ease to respect J2EE specification standard; so you’re project in EJB will remain supported for a while
Finaly for large scale system where high volum, deman is need you will better use EJB standard to support the charge and the concurrency process.
Below you will find out the project code as well as the check you need to realize to ensure that the deployment part on application server has been realized successfully .
The server deployment can be a little touchy , you need to bump your head around for a certain time at the beginning but after searching on forum and reading vendor documentation it’s should be allright !!
In this other article , I expose how you can test out easily your project to see if you can make it work it out .
Basicaly there 3 method , you can right a main if your project is small , an other way is to write Junit for unit test . Finally you can use Spring Test and get the power of Ioc mechanism .
http://what-when-how.com/enterprise-javabeans-3/combining-the-power-of-ejb-3-and-spring/
Project look like
Setup Jboss
When you start your server you should have the following log
17:30:56,041 INFO [SessionFactoryObjectFactory] Factory name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 INFO [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,041 INFO [SessionFactoryObjectFactory] Bound factory to JNDI name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 WARN [SessionFactoryObjectFactory] InitialContext did not implement EventContext
17:30:56,041 INFO [SchemaUpdate] Running hbm2ddl schema update
17:30:56,041 INFO [SchemaUpdate] fetching database metadata
17:30:56,041 INFO [SchemaUpdate] updating schema
17:30:56,072 INFO [TableMetadata] table found: PUBLIC.CUSTOMER
17:30:56,072 INFO [TableMetadata] columns: [first_name, middle_name, last_name, email_id, customer_id]
17:30:56,072 INFO [TableMetadata] foreign keys: []
17:30:56,072 INFO [TableMetadata] indexes: [sys_idx_60]
17:30:56,072 INFO [SchemaUpdate] schema update complete
17:30:56,072 INFO [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,150 INFO [JmxKernelAbstraction] creating wrapper delegate for: org.jboss.ejb3.stateless.StatelessContainer
17:30:56,150 INFO [JmxKernelAbstraction] installing MBean: jboss.j2ee:jar=CustomerService.jar,name=CustomerServiceImpl,service=EJB3 with dependencies:
17:30:56,150 INFO [JmxKernelAbstraction] persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,182 INFO [EJBContainer] STARTED EJB: com.ejb.service.CustomerServiceImpl ejbName: CustomerServiceImpl
17:30:56,213 INFO [EJB3Deployer] Deployed: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/deploy/CustomerService.jar
17:30:56,229 INFO [DefaultEndpointRegistry] register: jboss.ws:context=CustomerService,endpoint=CustomerServiceImpl
17:30:56,338 INFO [TomcatDeployer] deploy, ctxPath=/CustomerService, warUrl=…/tmp/deploy/CustomerService.jar38776.war/
17:30:57,432 INFO [WSDLFilePublisher] WSDL published to: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/data/wsdl/CustomerService.jar/CustomerService38777.wsdl
17:30:57,744 INFO [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=…/deploy/jmx-console.war/
17:30:57,885 INFO [Http11Protocol] Démarrage de Coyote HTTP/1.1 sur http-127.0.0.1-8080
Compy spring.jar in the path
<Jboss_HOME>\server\default\lib
check the deployement of webservices
http://127.0.0.1:8080/CustomerService/CustomerServiceImpl?wsdl
Jmx console
check the deployement of EJB3
Check the JNDI view deployment you should view
Mbean database=localDB,service=Hypersonic call the Mbean Hypersonic and click start
package com.ejb.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity //@Table(name = "CUSTOMER", catalog = "", schema = "ADMIN") public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "CUSTOMER_ID") private Long customerId; @Column(name = "FIRST_NAME") private String firstName; @Column(name = "LAST_NAME") private String lastName; @Column(name = "MIDDLE_NAME") private String middleName; @Column(name = "EMAIL_ID") private String emailId; public Customer() { } public Customer(Long customerId) { this.customerId = customerId; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } } package com.ejb.service; import java.util.Collection; import javax.ejb.Remote; import com.ejb.domain.Customer; @Remote public interface CustomerService { Customer create(Customer info); Customer update(Customer info); void remove(Long customerId); Collection<Customer> findAll(); Customer[] findAllAsArray(); Customer findByPrimaryKey(Long customerId); } package com.ejb.service; import java.util.Collection; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.ejb.domain.Customer; @WebService(name = "CustomerService", serviceName = "CustomerService", targetNamespace = "urn:CustomerService") @SOAPBinding(style = SOAPBinding.Style.RPC) @Stateless(name = "CustomerServiceImpl") public class CustomerServiceImpl implements CustomerService { @PersistenceContext(name="Customer") private EntityManager manager; @WebMethod public Customer create(Customer info) { this.manager.persist(info); return info; } @WebMethod public Customer update(Customer info) { return this.manager.merge(info); } @WebMethod public void remove(Long customerId) { this.manager.remove(this.manager.getReference(Customer.class, customerId)); } public Collection<Customer> findAll() { Query query = this.manager.createQuery("SELECT c FROM Customer c"); return query.getResultList(); } @WebMethod public Customer[] findAllAsArray() { Collection<Customer> collection = findAll(); return (Customer[]) collection.toArray(new Customer[collection.size()]); } @WebMethod public Customer findByPrimaryKey(Long customerId) { return (Customer) this.manager.find(Customer.class, customerId); } } package com.spring.service; import com.ejb.domain.Customer; public interface CustomerManager { public void addCustomer(Customer customer); public void removeCustomer(Long customerId); public Customer[] listCustomers(); } package com.spring.service; import com.ejb.domain.Customer; import com.ejb.service.CustomerService; public class CustomerManagerImpl implements CustomerManager { CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } public void removeCustomer(Long customerId) { customerService.remove(customerId); } public Customer[] listCustomers() { return customerService.findAllAsArray(); } public void addCustomer(Customer customer) { customerService.create(customer); } }
Persistence Unit
here we use for the example HSQL , it’s embedded on Jboss Server
the configuration file will be as follow :
<persistence> <persistence-unit name="Customer"> <class>com.ejb.domain.Customer</class> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
<properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="" /> <!-- EclipseLink should create the database schema automatically --> <property name="eclipselink.ddl-generation" value="create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> </properties>
the Spring configuration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"> <!-- Use a custom JNDI bean factory configured not to prepend lookups with "java:comp/env" --> <bean id="jndiFactory"> <property name="resourceRef" value="false" /> </bean> <!-- Configure the CommonAnnotationBeanPostProcessor to always use JNDI lookup (for EJBs) and use the custom JNDI bean factory above. --> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"> <property name="alwaysUseJndiLookup" value="true" /> <property name="jndiFactory" ref="jndiFactory" /> </bean> <!-- <jee:jndi-lookup id="customerService" jndi-name="com.ejb.service.CustomerServiceImpl"> </jee:jndi-lookup> --> <jee:jndi-lookup id="customerService" jndi-name="CustomerServiceImpl/remote" lookup-on-startup="false" proxy-interface="com.ejb.service.CustomerService"></jee:jndi-lookup> <bean id="manageCustomer"> <property name="customerService" ref="customerService" /> </bean> </beans>
The client test configuration project
you’re project should like like this
*in the classpath create a jndi.propertiesand java class client
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
package com.spring.client; import javax.naming.Context; import javax.naming.InitialContext; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ejb.domain.Customer; import com.ejb.service.CustomerService; import com.spring.service.CustomerManager; public class SpringAndEJBMain { public static void main(String[] args) { try { Context context = new InitialContext(); CustomerService stock = (CustomerService) context.lookup("CustomerService/remote"); ApplicationContext contextSpring =new ClassPathXmlApplicationContext("SpringXMLConfig.xml"); CustomerManager service = (CustomerManager) contextSpring.getBean("manageCustomer"); Customer customer = new Customer(); customer.setFirstName("Meera"); customer.setLastName("Subbarao"); customer.setMiddleName("B"); customer.setEmailId("meera@springandejb.com"); customer.setCustomerId(new Long(1)); service.addCustomer(customer); for (Customer cust : service.listCustomers()) { System.out.println(cust.getFirstName()); System.out.println(cust.getLastName()); System.out.println(cust.getMiddleName()); System.out.println(cust.getEmailId()); } // service.removeCustomer(new Long(1)); } catch (Exception e) { e.printStackTrace(); } } }
mai
11
Posted by : 11 mai 2012
| On :
The client test configuration project
you’re project should like like this
*in the classpath create a jndi.propertiesand java class client
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
package com.spring.client; import javax.naming.Context; import javax.naming.InitialContext; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ejb.domain.Customer; import com.ejb.service.CustomerService; import com.spring.service.CustomerManager; public class SpringAndEJBMain { public static void main(String[] args) { try { Context context = new InitialContext(); CustomerService stock = (CustomerService) context.lookup("CustomerService/remote"); ApplicationContext contextSpring =new ClassPathXmlApplicationContext("SpringXMLConfig.xml"); CustomerManager service = (CustomerManager) contextSpring.getBean("manageCustomer"); Customer customer = new Customer(); customer.setFirstName("Meera"); customer.setLastName("Subbarao"); customer.setMiddleName("B"); customer.setEmailId("meera@springandejb.com"); customer.setCustomerId(new Long(1)); service.addCustomer(customer); for (Customer cust : service.listCustomers()) { System.out.println(cust.getFirstName()); System.out.println(cust.getLastName()); System.out.println(cust.getMiddleName()); System.out.println(cust.getEmailId()); } // service.removeCustomer(new Long(1)); } catch (Exception e) { e.printStackTrace(); } } }
mai
11
Posted by : 11 mai 2012
| On :This tutorial is inspired from (run under glassfish)
http://java.dzone.com/articles/ejb-30-and-spring-25
In this following page I modified the spring configuration and test the deployment on Jboss 4.2
Environnement tool requirement
- Spring Tools suite or Eclipse
- Jboss 4.2.x (tested on version jboss-4.2.3.GA)
- Spring 2.5.6
The data layer is using @Entity to define the Table (or pojo) that will correspond to our data model
Here we have a simple table called Customer with a series of fields
then we need to ask ourself which services do we want to expose to others ?
As in Facade design pattern we will expose an interface and the method that the client can attack on the server side
So here we define an interface call CustomerService that is annoted with @Remote
Then we’ve implement the CRUD operation and @PersistenceContext in CustomerServiceImpl class
Then in the second part of the tutorial we are viewing how to bind Spring with EJB 3
To do that you’ll need to investigate the name of jndi register in your server.
The tag jee:jndi-lookup will bind both EJB context and spring context
Once your project is set up you can easily use Spring test or more simply define a Java project that reference your Ejb project (write a main )
Go further
http://what-when-how.com/enterprise-javabeans-3/combining-the-power-of-ejb-3-and-spring/
Project look like
Setup Jboss
When you start your server you should have the following log
17:30:56,041 INFO [SessionFactoryObjectFactory] Factory name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 INFO [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,041 INFO [SessionFactoryObjectFactory] Bound factory to JNDI name: persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,041 WARN [SessionFactoryObjectFactory] InitialContext did not implement EventContext
17:30:56,041 INFO [SchemaUpdate] Running hbm2ddl schema update
17:30:56,041 INFO [SchemaUpdate] fetching database metadata
17:30:56,041 INFO [SchemaUpdate] updating schema
17:30:56,072 INFO [TableMetadata] table found: PUBLIC.CUSTOMER
17:30:56,072 INFO [TableMetadata] columns: [first_name, middle_name, last_name, email_id, customer_id]
17:30:56,072 INFO [TableMetadata] foreign keys: []
17:30:56,072 INFO [TableMetadata] indexes: [sys_idx_60]
17:30:56,072 INFO [SchemaUpdate] schema update complete
17:30:56,072 INFO [NamingHelper] JNDI InitialContext properties:{java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory, java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces}
17:30:56,150 INFO [JmxKernelAbstraction] creating wrapper delegate for: org.jboss.ejb3.stateless.StatelessContainer
17:30:56,150 INFO [JmxKernelAbstraction] installing MBean: jboss.j2ee:jar=CustomerService.jar,name=CustomerServiceImpl,service=EJB3 with dependencies:
17:30:56,150 INFO [JmxKernelAbstraction] persistence.units:jar=CustomerService.jar,unitName=Customer
17:30:56,182 INFO [EJBContainer] STARTED EJB: com.ejb.service.CustomerServiceImpl ejbName: CustomerServiceImpl
17:30:56,213 INFO [EJB3Deployer] Deployed: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/deploy/CustomerService.jar
17:30:56,229 INFO [DefaultEndpointRegistry] register: jboss.ws:context=CustomerService,endpoint=CustomerServiceImpl
17:30:56,338 INFO [TomcatDeployer] deploy, ctxPath=/CustomerService, warUrl=…/tmp/deploy/CustomerService.jar38776.war/
17:30:57,432 INFO [WSDLFilePublisher] WSDL published to: file:/C:/jboss-4.2.3.GA-jdk6/jboss-4.2.3.GA/server/default/data/wsdl/CustomerService.jar/CustomerService38777.wsdl
17:30:57,744 INFO [TomcatDeployer] deploy, ctxPath=/jmx-console, warUrl=…/deploy/jmx-console.war/
17:30:57,885 INFO [Http11Protocol] Démarrage de Coyote HTTP/1.1 sur http-127.0.0.1-8080
Compy spring.jar in the path
<Jboss_HOME>\server\default\lib
check the deployement of webservices
http://127.0.0.1:8080/CustomerService/CustomerServiceImpl?wsdl
Jmx console
check the deployement of EJB3
Check the JNDI view deployment you should view
Mbean database=localDB,service=Hypersonic call the Mbean Hypersonic and click start
package com.ejb.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity //@Table(name = "CUSTOMER", catalog = "", schema = "ADMIN") public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "CUSTOMER_ID") private Long customerId; @Column(name = "FIRST_NAME") private String firstName; @Column(name = "LAST_NAME") private String lastName; @Column(name = "MIDDLE_NAME") private String middleName; @Column(name = "EMAIL_ID") private String emailId; public Customer() { } public Customer(Long customerId) { this.customerId = customerId; } public Long getCustomerId() { return customerId; } public void setCustomerId(Long customerId) { this.customerId = customerId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this.middleName = middleName; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } } package com.ejb.service; import java.util.Collection; import javax.ejb.Remote; import com.ejb.domain.Customer; @Remote public interface CustomerService { Customer create(Customer info); Customer update(Customer info); void remove(Long customerId); Collection<Customer> findAll(); Customer[] findAllAsArray(); Customer findByPrimaryKey(Long customerId); } package com.ejb.service; import java.util.Collection; import javax.ejb.Stateless; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import com.ejb.domain.Customer; @WebService(name = "CustomerService", serviceName = "CustomerService", targetNamespace = "urn:CustomerService") @SOAPBinding(style = SOAPBinding.Style.RPC) @Stateless(name = "CustomerServiceImpl") public class CustomerServiceImpl implements CustomerService { @PersistenceContext(name="Customer") private EntityManager manager; @WebMethod public Customer create(Customer info) { this.manager.persist(info); return info; } @WebMethod public Customer update(Customer info) { return this.manager.merge(info); } @WebMethod public void remove(Long customerId) { this.manager.remove(this.manager.getReference(Customer.class, customerId)); } public Collection<Customer> findAll() { Query query = this.manager.createQuery("SELECT c FROM Customer c"); return query.getResultList(); } @WebMethod public Customer[] findAllAsArray() { Collection<Customer> collection = findAll(); return (Customer[]) collection.toArray(new Customer[collection.size()]); } @WebMethod public Customer findByPrimaryKey(Long customerId) { return (Customer) this.manager.find(Customer.class, customerId); } } package com.spring.service; import com.ejb.domain.Customer; public interface CustomerManager { public void addCustomer(Customer customer); public void removeCustomer(Long customerId); public Customer[] listCustomers(); } package com.spring.service; import com.ejb.domain.Customer; import com.ejb.service.CustomerService; public class CustomerManagerImpl implements CustomerManager { CustomerService customerService; public void setCustomerService(CustomerService customerService) { this.customerService = customerService; } public void removeCustomer(Long customerId) { customerService.remove(customerId); } public Customer[] listCustomers() { return customerService.findAllAsArray(); } public void addCustomer(Customer customer) { customerService.create(customer); } }
Persistence Unit
in HSQL embein Jboss the configuration will be
<persistence> <persistence-unit name="Customer"> <class>com.ejb.domain.Customer</class> <jta-data-source>java:/DefaultDS</jta-data-source> <properties> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> </properties> </persistence-unit> </persistence>
in MySQL the configuration will be
<properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="" /> <!-- EclipseLink should create the database schema automatically --> <property name="eclipselink.ddl-generation" value="create-tables" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> </properties>
the Spring configuration
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd"> <!-- Use a custom JNDI bean factory configured not to prepend lookups with "java:comp/env" --> <bean id="jndiFactory" class="org.springframework.jndi.support.SimpleJndiBeanFactory"> <property name="resourceRef" value="false" /> </bean> <!-- Configure the CommonAnnotationBeanPostProcessor to always use JNDI lookup (for EJBs) and use the custom JNDI bean factory above. --> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"> <property name="alwaysUseJndiLookup" value="true" /> <property name="jndiFactory" ref="jndiFactory" /> </bean> <!-- <jee:jndi-lookup id="customerService" jndi-name="com.ejb.service.CustomerServiceImpl"> </jee:jndi-lookup> --> <jee:jndi-lookup id="customerService" jndi-name="CustomerServiceImpl/remote" lookup-on-startup="false" proxy-interface="com.ejb.service.CustomerService"></jee:jndi-lookup> <bean id="manageCustomer" class="com.spring.service.CustomerManagerImpl"> <property name="customerService" ref="customerService" /> </bean> </beans>
The client test configuration project
you’re project should like like this
*in the classpath create a jndi.propertiesand java class client
java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces java.naming.provider.url=localhost:1099
package com.spring.client; import javax.naming.Context; import javax.naming.InitialContext; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.ejb.domain.Customer; import com.ejb.service.CustomerService; import com.spring.service.CustomerManager; public class SpringAndEJBMain { public static void main(String[] args) { try { Context context = new InitialContext(); CustomerService stock = (CustomerService) context.lookup("CustomerService/remote"); ApplicationContext contextSpring =new ClassPathXmlApplicationContext("SpringXMLConfig.xml"); CustomerManager service = (CustomerManager) contextSpring.getBean("manageCustomer"); Customer customer = new Customer(); customer.setFirstName("Meera"); customer.setLastName("Subbarao"); customer.setMiddleName("B"); customer.setEmailId("meera@springandejb.com"); customer.setCustomerId(new Long(1)); service.addCustomer(customer); for (Customer cust : service.listCustomers()) { System.out.println(cust.getFirstName()); System.out.println(cust.getLastName()); System.out.println(cust.getMiddleName()); System.out.println(cust.getEmailId()); } // service.removeCustomer(new Long(1)); } catch (Exception e) { e.printStackTrace(); } } }
mai
05
Posted by : 5 mai 2012
| On :1: Débrancher le cable d’alimentation, maintenir les touche « Aide« & « OK« puis rebrancher le cable d’alimentation tout en maintenant les deux touches jusqu’à l’xtinction complète de l’imprimante.
2: Débrancher à nouveau le cable d’alimentation reliés à la HP C6180
3: Attendre environ 30 à 60 secondes avant de reconnecter l’alimentation
4 : Appuyer sur le bonton ON/OFF. En principe l’imprimante effectue un reboot complet de son système comme le premier.
Si cela ne fonctionne dès le premier coup, réessayer à nouveau…
avr
28
Posted by : 28 avril 2012
| On :Spring batch is a module of Spring Framework that focus more specifically on Batch processing .
The current real time processing (au fils de l’eau) can be used when we want our data to be refresh or treated rapidly by our system.
Meanwhile, when we have huge amount of opertaion to realize or not priorize treatement to be done we will prefer to have a batch processing .
In this article we’ll try to have an overview on how spring batch is working
Basically we need data in entrance of our feed and output this data in a different format regarding the rule defined in our processor
-> reader -> proccessor -> Writer (see example M1)
Spring batch overlay this cycle with a step.
Note that a subtask of that step can be realized by a tasklet (see example M2)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns:batch="http://www.springframework.org/schema/batch" xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/batch http://www.springframework.org/schema/batch/spring-batch-2.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd"> <!-- Define and declare your steps to realize by spring batch --> <!--Example step M1 --> <batch:step id="step1"> <batch:tasklet> <batch:chunk reader="flatReader" processor="customProcessor" writer="LineWriter" commit-interval="10" /> </batch:tasklet> </batch:step> <!--Define a custom tasklet to execute during the step of batch processing --> <batch:step id="step2"> <batch:tasklet ref="getCacheTasklet" /> </batch:step> <!--Example step M2--> <util:map id="cacheReferenceItemMap" /> <bean id="getCacheTasklet" class="org.example.tasklet.GetReferenceItemTasklet" p:cacheReferenceItemMap-ref="cacheReferenceItemMap" /> </beans>
Java code of the tasklet
package org.example.tasklet; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.springframework.batch.core.StepContribution; import org.springframework.batch.core.scope.context.ChunkContext; import org.springframework.batch.core.step.tasklet.Tasklet; import org.springframework.batch.repeat.RepeatStatus; public class GetReferenceItemTasklet implements Tasklet { Map<String, String> cacheReferenceItemMap; String fileName; /** * @param cacheReferenceItemMap * the cacheReferenceItemMap represents our cache structure. */ public void setCobDateMap(final Map<String, String> cacheReferenceItemMap) { this.cacheReferenceItemMap = cacheReferenceItemMap; } /** * @param fileName * */ public void setScratchFiles(final String fileName) { this.fileName = fileName; } /* * (non-Javadoc) * example : we have our name file : 0411Myfile405480.csv * we are retrieving 0411 number with this method . * @seeorg.springframework.batch.core.step.tasklet.Tasklet#execute(org. * springframework.batch.core.StepContribution, * org.springframework.batch.core.scope.context.ChunkContext) */ public RepeatStatus execute(final StepContribution contribution, final ChunkContext chunkContext) throws Exception { Pattern pattern = Pattern.compile("(\\d{4})MyFile\\d+\\.csv"); Matcher matcher = pattern.matcher(fileName); if (matcher.find()) { this.cacheReferenceItemMap.put(fileName, matcher.group(1)); } else { throw new Exception("ERROR: Can't get file name error " + fileName); } } return RepeatStatus.FINISHED; } }
ezez
avr
23
Posted by : 23 avril 2012
| On :Source
http://www.careerride.com/Spring-bean-lifecycle-in-spring-framework.aspx
Question/response JAVA
Spring is a framework that resolves common problems in JEE architecture. (JDBC ,integration later, presentation layer …)
Spring is managing business objects and encouraging practices POJO model (vs programming model)
It’s highly recommended to use a architectural tiers (presentation,business,dao Layer) ; the inejection of the different beans is realized by utilizing IoC.
Spring is both comprehensive and modular. Spring has a layered architecture, meaning that you can choose to use just about any part of it in isolation. Spring is also an ideal framework for test driven projects.
The bean’s definition is found by the spring container from the XML file and instantiates the bean.
All the properties specified in the bean definition are populated by spring using dependency injection.
The bean’s Id is passed to setBeanName() method by the factory, and the factory calls setBeanFactory() is passed to itself, incase the bean implements the BeanFactoryAware interface.
The init() method is invoked if specified. If any BeanPostProcessors are associated with the bean, the methods postProcessAfterInitialization() are invoked.
http://www.careerride.com/Interview-Questions-Java-Threading.aspx
2 type of process are being execute in a PC
les multitache par processus + long pour le CPU de réaliser le swap entre les différents applicatif .
Le multitache par thread
class MonThread implements Runnable { Thread t ; MonThread("Mon thread "){ t = new Thread("Mon thread"); t.start(); } public void run(){ System.out.println("Thread enfant démarré"); } public static void main(String args[]){ new MonThread(); System.out.println("Thread principale démarré "); System.out.println("Thread principale terminé "); } }
l’instruction join() permet d’attendre le thread enfant se termine et qu’il rejoinne le thread principale . (exemple le thread du main)
permettre à deux thread de ne pas accéder à la même ressource en même temps on utilise pour cela le mot clé synchronized dans le prototype de la méthode.Souvent cela arrive lorsque 1 thread => appel 1 methode d’une autre classe Exemple :
class MonThread implements Runnable (){ String s1 ; Parenthese p1; Thread t ; public MonThread(Parenthese p2 , String s2){ p1 = p2 ; s1 = s2 ; t = new Thread(this); t.start(); } public void run(){ p1.afficher(); // La méthode affficher doit être nécessairement en synchronized } }
Une méthode peut etre appellé à l’intérieur d’un bloc synchronizé ( les objets et les methodes sont synchronisés ) Les appels aux méthodes contenues dans le bloc synchronisé n’ont lieu qu’après que le threade a activé le moniteur sur objet L’instruction synchronized
public void run(){ synchronized(p1){ p1.afficher(); } }
Communication entre les threads wait() demande à un thread de libérer un moniteur et de se placer en suspens .notify() demande au thread suspendu de se remettre en marche et de reprendre le contrôle du moniteur
class MonThread implements Runnable { Thread t; MonThread(String threadName) { // t = new Thread(threadName); // t.start(); } public void run() { System.out.println("RUN Child thread :" + Thread.currentThread()); } public static void main(String args[]) throws InterruptedException { Thread thread1 = new Thread(new MonThread("thread1"), "thread1"); Thread thread2 = new Thread(new MonThread("thread2"), "thread2"); thread1.start(); thread2.start(); thread1.join(); if (!thread1.isAlive()) { System.out.println("Thread T1 is not alive."); } thread2.join(); if (!thread2.isAlive()) System.out.println("Thread T2 is not alive."); Thread.currentThread().sleep(2000); System.out.println(Thread.currentThread()); } }
RUN Child thread :Thread[thread1,5,main]
RUN Child thread :Thread[thread2,5,main]
Thread T1 is not alive.Thread T2 is not alive.
Thread[main,5,main]
package coordination; public class AutoBus extends Thread { int total = 0; public void run() { synchronized (this) { System.out.println("wait ..."); for (int i = 0; i < 100; i++) total = +i; System.out.println("passenger is given notification call "); notify(); } } public static void main(String[] args) throws InterruptedException { AutoBus bus = new AutoBus(); bus.start(); synchronized (bus) { System.out.println(" passenger is waiting for the bus"); bus.wait(); System.out.println("passenger go notification"); } System.out.println(" total=" + bus.total); } }
passenger is waiting for the buswait …
passenger is given notification call passenger go notification total=99
Example questions :
how to create a thread and start it running
Example 1 : Extending Thread Class
Example 2 : implentation Runnable
Explain how do we allow one thread to wait while other to finish.
When a thread is created and started, what is its initial state?
Ready for execution (Create + started )
A thread is in “Ready” state after it has been created and started.
This state signifies that the thread is ready for execution. From here, it can be in the running state.
explain monitor in java
mot clé synchronization
If we want to transfer data over a network then it needs to be serialized. Objects cannot be transferred as they are. Hence, we need to declare that a class implements serializable so that a compiler knows that the data needs to be serialized.
EJB is a standard for developing server side in JAVA. It specifies agreement between components and application servers that allows components to run on server. They are mainly for complex serer side operations like executing complex algorithm or high volume business. EJB provides the application layer logic, also called as middle tier. It provides a standard specifications-based way to develop and deploy enterprise-class system.
There are 3 kinds of EJB’s -
Sessions beans represent business logic of an application. Session beans can be of 2 types namely stateless and stateful beans
Entity beans represent persistent data in an EJB application.
This type of beans is used implement asynchronous communication in the system.
The state of the conversation can be maintained using a stateful session bean.
It implements ‘javax.ejb.SessionBean’ interface and is deployed with the declarative attribute ‘stateful’.
The instance variables contain a state only during the invocation by a client method.
The bean can use the conversational states as its business process methods.
Main cons: Resources that is needed to be substain to maintain connection between server and client
Other discussion pro/cons :
http://blog.xebia.fr/2007/07/24/service-stateful-vs-service-stateless/
We dont maintain conversational state specific to client session.
It is an EJB component that implements ‘javax.ejb.SessionBean’ interface.
The stateless session bens carry equal value for all the instances due to which a container can assign a bean to any client making it very scalable.
There is no instance state. The business methods on a stateless session bean are like procedural applications or static methods, so all the data needed to execute the method is provided by the method arguments.
Stateless session beans are very lightweight and fast.Typically an application requires less number of stateless beans compared to stateful beans.
Heavy weight application consume a lot of time while loading the plug-ins. In lazy loading approach, the plug-ins that are needed at that particular time are loaded and instantiated. This boosts up the performance as only the plug-ins that are used are loaded. This also ensures the efficiency and speeds up the initial load time of the applications. Applications like Eclipse use this approach. In other words, the goal of lazy loading is to dedicate memory only when it is absolutely necessary.
-A server is an application that responds to the requests made by client(s) and manages system resources like network connections, threads, processes, memory, database connections, etc
E.g.: Websphere,Jonas,BEA WebLogic …
-A server can contain N number of containers. An EJB container runs inside an EJB server. The Container shields the EJB server through an API between the bean and its container.
-A connector is used to resolve the issue with the legacy systems. A connector is an architecture defined by Sun. Since the applications running on the legacy systems cannot be discarded due to the business logic and other reasons, the connectors were used to serve the purpose.
(exemple connector : Oracle, Mysql,Postgre …)
What is the difference between EAR, JAR and WAR file?
Modules are packaged based on their functionality as EAR, JAR and WAR files.
• JAR files (.jar):Modules which contain EJB class files and EJB deployment descriptor are packed as JAR files.
WAR Files (.war):Web modules which contain Servlet class files, JSP Files, supporting files, GIF and HTML files are packaged as JAR file.
EAR Files (.ear):‘.jar’ & ‘.war’ files are packaged as JAR files. ‘Ear’ stands for enterprise archive. These files are deployed in the application server.
Java.io
Flux entrée System.in .
Remarque : Depuis Java 5 la classe Scanner permet de lire les entrées clavier facilement
Scanner scanner = new Scanner(System.in);
String choix = scanner.next();
Flux de sortie : System.out
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
nom = br.readLine();
on peut appeler la méthode d’un objet sans avoir à instancier celui ci
On l’utilise le plus souvent lorsque l’objet n’a pas de rapport à proprement dit avec la classe
disposer d’information collectives (exemple : comptage instance de classe )
ou bien disposer de fonction indépendante
n’ont accès qu’au champs static de la classe
utilise surtout pour initialiser des champs static
=> Conseil mieux vaut avoir un private static methode pour avoir la main sur nos variables facilement
recopie les références de l’objet mais ne provoquue pas la recopie des valeur des objets .
== et !=
ne compare les objets que sur les reférences , peut être utilisé pour comparer des références null , 2 énum values …
a.compareTo(b) compare les values des champs a et b et retourne un int issu de la comparaison
=> penser aussi au pattern Iterator et à la classe Comparator<T>
Lors un objet ne possède plus de référence sur cet objet on dit qu’il est candidat au gargage collector
finalize() est appellé par le garbage collector quand la condition précédente est vérifié
permet de définir une classe sans lui donner de nom
pas de référence possible
classe anonyme peut dériver d’une autre classe (exemple de la classe JpaTemplate )
classe anonyme implémentant une interface
le constructeur dérivée (fille) doit prendre en charge l’intégralité de la contruction du père.
ou bien utiliser le mot clé super() pour ne pas avoir à redéfinir les fonctionnalités et disposé de celle défini dans la classe mère.
complète l’héritage , peut prendre plusieurs formes ou comportement suivant les situations .
différentes formes de polymorphisme
méthode
classe
polymorphisme via heritage (on spécialise un comportement )
String … elements <=> String [] elements
interdit la modification de la valeur (variable )
méthode final ne peuvent être redéfini par une classe dérivée
classe final idem
pas instancation objet possible
contient les méthodes et champs dont héritera toutes les classes dérivées
des erreur peuvent se produire on les gère… gestion des exceptions
Java.lang.Throwable
|
exception java.lang.error
Runtime SQLException/IOException
NPE
SeccurityException
StringBuffer
StringTokenizer
matcher
List
doublon autorisé
récupération via index
LinkedList (liste doublement chainée )
ArrayList (tableau redimensionnable)
Vector ( la différence avec ArrayList est qu’elle est synchronisé durant l’appel de la méthode de cette classe par un thread autre et ne peut être modifier )
Map
clé /valeur
unicité de la clé
HashTable va recherche ses éléments avec hashCode
HashTable est ThreadSafe et n’accepte pas null
HashMap n’est poas ThreadSafe
Set
n’accepte pas les doublons
HahsSet permet de stocker des objets sans doublons , n’accepte pas d’objet null (sinon NPE) => Iterator
TreeSet utilise un arbre de recherche
SortedSet
Pile
pop/push
Iterator
List<String> maListe = new ArrayList<String>();
maListe.add(« Bonkour »);
Iterator<String> it= maListe.iterator();
while(it.hasNext()){
sysout(it.next());
}
parcours HashMap
for(Key key : map.keySet()){}
inner join
relation 1-1 entre 2 tables
exemple :
Select * from Employee inner join departement on employee.DepartementID=departement.DepartementID
natural join : jointure faites sur les tables de même nom
Left / right join (favoriser une ou autre des tables)
Toutes les valeur de A et les valeurs de B qui matche avec A
cela se traduit en clair quelquesoit ….. who is in