Case study IBM
http://www.ibm.com/developerworks/websphere/techjournal/0909_blythe/0909_blythe.html
http://db.apache.org/ojb/docu/guides/objectcache.html#Why+a+cache+and+how+it+works%3F
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
nov
16
Posted by : 16 novembre 2013
| On :
Case study IBM
http://www.ibm.com/developerworks/websphere/techjournal/0909_blythe/0909_blythe.html
http://db.apache.org/ojb/docu/guides/objectcache.html#Why+a+cache+and+how+it+works%3F
nov
11
Posted by : 11 novembre 2013
| On :
Processus concerne une application, un programme
Un programme peut gérer plusieurs petits procesus appelé threads et partagés ses ressources au niveau de la JVM du cluster issu du serveur applicatif
Les sémaphores: utiliser beaucoup dans la gestion des ressources dans son système exploitation .
Le problemes du diner des philosophes: algorithme de Dijkstra
L’algorithme du banquier.
uniquement utilisé dans le cas de variable primitive, unique que plusieurs thread peuvent attaquées cette meme variable
Attention ce mot clé ne garanti pas l’atomicité de l’opération
Pas de lock associé dessus
Attention au NPE si la valeur est à null
(Cela indique que la memoire est partagé entre les threads pour cette variable)
Difference entre volatile et synchronized
Synchronized s’applique à un objet et volatile s’applique à la référence de objet
Pour garantir qu’une variable primitive est atomique CF classe AtomiInteger / AtomicReference
Exemple Simple : utilisation des mots clé : notify , wait…
Dans cet exemple nous voyons qu’en faites nous appliqueons de manière intuitive le pattern observateur . Dans lexemple suivant nous allons approfondir cette notion
public class AutoBus extends Thread { int total = 0; public void run() { synchronized (this) { System.out.println("wait ..."); for (int i = 0; i < 10; i++){ total = +i; try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } 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); } }
Préferer les block synchronized au méthode synchronized .
Ne crée pas de lock au niveau de objet équivalent à synchronized(this) cela veut dire que l’on utilise le monitor of the « this » objet in order to help keeping the object safe . C’est une erreur !!
La bonne pratique est de créer un objet privé qui serviera de monitoring de l’objet et nous garantiera que celui ci nest pas modifié par deux threads concurents :
exemple ligne :
private final Object myMonitor = new Object();
package observerpattern; /** * * @author Hugo */ public interface ISubject { void registerObserver(IObserver o); void unregisterObserver(IObserver o); void NotifyObservers(String s); } public class Subject implements ISubject { private final HashSet<IObserver> subscribers; public Subject() { // Eliminates the possibility of duplicated objects - subscribers. this.subscribers = new HashSet<IObserver>(); } // // 1) Using the "this" object's monitor // @Override // Registering subscriber. // public synchronized void registerObserver(IObserver o) { // System.out.println("Inside register observer method"); // this.subscribers.add(o); // } // // @Override // Unregistering subscriber. // public synchronized void unregisterObserver(IObserver o) { // this.subscribers.remove(o); // } // // @Override // public void NotifyObservers(final String s) { // // Equivalent to --> public synchronized void NotifyObservers(final String s) // synchronized(this){ // for (IObserver o : this.subscribers) { // o.Update(s); // } // } // } // 2) Using a private object's monitor! private final Object myMonitor = new Object(); @Override // Registering subscriber. public void registerObserver(IObserver o) { synchronized ( myMonitor ){ System.out.println("Inside register observer method"); this.subscribers.add(o); } } @Override // Unregistering subscriber. public void unregisterObserver(IObserver o) { synchronized ( myMonitor ){ this.subscribers.remove(o); } } @Override public void NotifyObservers(final String s) { synchronized ( myMonitor ){ for (IObserver o : this.subscribers) { o.Update(s); } } } } package observerpattern; /** * * @author Hugo */ public interface IObserver { void Update(String s); void SubscribeTo(ISubject subject); void UnsubscribeTo(ISubject subject); } public class Observer implements IObserver{ private final String _name; public Observer(String name){ _name = name; } @Override public void Update(String s){ System.out.println(String.format("%s has received a new message from magazine: %s",_name,s)); } @Override public void SubscribeTo(ISubject subject) { subject.registerObserver(this); } @Override public void UnsubscribeTo(ISubject subject) { subject.unregisterObserver(this); } }
Java 5 introduced java.util.concurrent.Callable interface in concurrency package that is similar to Runnable interface but it can return any Object and able to throw Exception.
Callable interface use Generic to define the return type of Object. Executors class provide useful methods to execute Callable in a thread pool. Since callable tasks run in parallel, we have to wait for the returned Object. Callable tasks return java.util.concurrent.Future object. Using Future we can find out the status of the Callable task and get the returned Object. It provides get() method that can wait for the Callable to finish and then return the result.
package callable; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class MyCallable implements Callable<String> { @Override public String call() throws Exception { Thread.sleep(1000); //return the thread name executing this callable task return Thread.currentThread().getName(); } public static void main(String args[]){ //Get ExecutorService from Executors utility class, thread pool size is 10 ExecutorService executor = Executors.newFixedThreadPool(10); //create a list to hold the Future object associated with Callable List<Future<String>> list = new ArrayList<Future<String>>(); //Create MyCallable instance Callable<String> callable = new MyCallable(); for(int i=0; i< 100; i++){ //submit Callable tasks to be executed by thread pool Future<String> future = executor.submit(callable); //add Future to the list, we can get return value using Future list.add(future); } for(Future<String> fut : list){ try { //print the return value of Future, notice the output delay in console // because Future.get() waits for task to get completed System.out.println(new Date()+ "::"+fut.get()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } } //shut down the executor service now executor.shutdown(); } }
public class ExecutorServiceExample { private static class MyTask implements Callable<Double> { private final int index; private MyTask(Integer idx) { index = idx; } public Double call() throws InterruptedException { System.out.println("Working on index " + index + "..."); // pretend we're doing something long and complex here... Thread.sleep(2000); System.out.println("Completed index " + index); // pretend this is the net result of the long, complex thing we did: return index * .001; } } public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService execs = Executors.newFixedThreadPool(10); List<Future<Double>> results = new ArrayList<Future<Double>>(); for (int i = 0; i < 100; i++) { Future<Double> result = execs.submit(new MyTask(i)); results.add(result); } // this is just a signal; it won't terminate until all tasks are completed execs.shutdown(); System.out.println("Sent shutdown signal"); execs.awaitTermination(60, TimeUnit.MINUTES); System.out.println("Results: "); int index = 0; for (Future<Double> result : results) { System.out.println(index++ + ":\t" + result.get()); } } }
Autre resources
http://www.journaldev.com/1034/java-blockingqueue-example-implementing-producer-consumer-problem
http://doanduyhai.wordpress.com/2012/08/04/design-pattern-the-asynchronous-dispatcher/
http://www.journaldev.com/1162/
août
17
Posted by : 17 août 2013
| On :juil
26
Posted by : 26 juillet 2013
| On :source : http://dottech.org/105407/how-to-root-lg-optimus-3d-p920-on-ice-cream-sandwich-or-gingerbread-guide/
Disclaimer: This guide is intended as a helpful “how to”. dotTech and its writers are not responsible for any gain or loss (including but not limited to bricked devices) incurred as a result of following this guide. Root your device at your own risk. Rooting may void your warranty.
This root guide is for LG Optimus 3D running either Android 2.2 Froyo, Android 2.3 Gingerbread or Android 4.04 Ice Cream Sandwich. It is specifically for the P920.
Enjoy a rooted LG Optimus 3D P920.
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
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(); } } }
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
jan
10
Posted by : 10 janvier 2012
| On :Rss Reader
Bellow a Simple code about how to make a simple Rss Reader handle by SAX handler.
package mapping.rss; public class Item { private String title ; private String description; private String link; private String pubDate; private String source; private String mediaContent; private String mediaText; /** * @return the title */ public String getTitle() { return title; } /** * @param title the title to set */ public void setTitle(String title) { this.title = title; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the link */ public String getLink() { return link; } /** * @param link the link to set */ public void setLink(String link) { this.link = link; } /** * @return the pubDate */ public String getPubDate() { return pubDate; } /** * @param pubDate the pubDate to set */ public void setPubDate(String pubDate) { this.pubDate = pubDate; } /** * @return the source */ public String getSource() { return source; } /** * @param source the source to set */ public void setSource(String source) { this.source = source; } /** * @return the mediaContent */ public String getMediaContent() { return mediaContent; } /** * @param mediaContent the mediaContent to set */ public void setMediaContent(String mediaContent) { this.mediaContent = mediaContent; } /** * @return the mediaText */ public String getMediaText() { return mediaText; } /** * @param mediaText the mediaText to set */ public void setMediaText(String mediaText) { this.mediaText = mediaText; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Item [title="); builder.append(title); builder.append(", description="); builder.append(description); builder.append(", link="); builder.append(link); builder.append(", pubDate="); builder.append(pubDate); builder.append(", source="); builder.append(source); builder.append(", mediaContent="); builder.append(mediaContent); builder.append(", mediaText="); builder.append(mediaText); builder.append("]"); return builder.toString(); } } package xml; import java.util.ArrayList; import java.util.List; import mapping.rss.Item; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class SearchItemRssHandler extends DefaultHandler { private final static String CHANNEL="channel"; private final static String ITEM="item"; private final static String TITLE="title"; private final static String LINK="link"; private final static String DESCRIPTION="description"; private final static String SOURCE="source"; private final static String PUBDATE="PUBDATE"; private boolean bfChannel = false; private boolean bfItem = false; private boolean bfTitle = false; private boolean bflink = false ; private boolean bfDescription = false ; private boolean bfSource = false ; private boolean bfPubdate = false; private Item item ; private List<Item> items ; public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { if(qName.equalsIgnoreCase(CHANNEL)){ items = new ArrayList<Item>(); bfChannel = true; } if(qName.equalsIgnoreCase(ITEM)){ item = new Item(); bfItem = true ; } if(qName.equalsIgnoreCase(TITLE)){ bfTitle = true ; } if(qName.equalsIgnoreCase(LINK)){ bflink = true ; } if(qName.equalsIgnoreCase(PUBDATE)){ bfPubdate = true ; } if(qName.equalsIgnoreCase(SOURCE)){ bfSource = true ; } if(qName.equalsIgnoreCase(DESCRIPTION)){ bfDescription = true ; } } public void endElement(String uri, String localName, String qName) throws SAXException { if(qName.equalsIgnoreCase(ITEM)){ items.add(item); bfItem = false; } if(qName.equalsIgnoreCase(CHANNEL)){ setItems(items); bfChannel = false ; } } public void characters(char ch[], int start, int length) throws SAXException { String resu= new String(ch, start, length); if(bfItem){ bfItem = false; } if(bfDescription){ if(item!=null) item.setDescription(resu); bfDescription = false; } if(bfTitle){ if(item!=null) item.setTitle(resu); bfTitle = false; } if(bflink){ if(item!=null) item.setLink(resu); bflink = false ; } if(bfPubdate){ if(item!=null) item.setPubDate(resu); bfPubdate = false; } if(bfSource){ if(item!=null) item.setSource(resu); } } /** * @return the items */ public List<Item> getItems() { return items; } /** * @param items the items to set */ public void setItems(List<Item> items) { this.items = items; } } ///TEST Main package xml.test; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.List; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import mapping.rss.Item; import org.xml.sax.InputSource; import xml.SearchItemRssHandler; public class ReadRssXmlFile { public static void main(String argv[]) { try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); File file = new File("C:\\workspace\src\\rss-test-fr.xml"); InputStream inputStream= new FileInputStream(file); Reader reader = new InputStreamReader(inputStream,"UTF-8"); InputSource is = new InputSource(reader); is.setEncoding("UTF-8"); SearchItemRssHandler handler = new SearchItemRssHandler(); saxParser.parse(is, handler); List<Item> items = handler.getItems(); for (Item item : items) { System.out.println(item); } } catch (Exception e) { e.printStackTrace(); } } }