août

20

Posted by : admin | On : 20 août 2019

vimeo

https://vimeo.com/39796236

source code https://github.com/DoctusHartwald/ticket-monster

 

sample pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<!--
 Copyright 2016-2017 Red Hat, Inc, and individual contributors.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.example</groupId>
  <artifactId>fruits</artifactId>
  <version>15-SNAPSHOT</version>

  <name>Simple Fruits Application</name>
  <description>Spring Boot - CRUD Booster</description>

  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>

    <maven.min.version>3.3.9</maven.min.version>
    <postgresql.version>9.4.1212</postgresql.version>
    <openjdk18-openshift.version>1.3</openjdk18-openshift.version>

    <spring-boot.version>2.1.3.RELEASE</spring-boot.version>
    <spring-boot-bom.version>2.1.3.Final-redhat-00001</spring-boot-bom.version>
    <maven-surefire-plugin.version>2.20</maven-surefire-plugin.version>
    <fabric8-maven-plugin.version>3.5.40</fabric8-maven-plugin.version>
    <fabric8.openshift.trimImageInContainerSpec>true</fabric8.openshift.trimImageInContainerSpec>
    <fabric8.skip.build.pom>true</fabric8.skip.build.pom>
    <fabric8.generator.from>
      registry.access.redhat.com/redhat-openjdk-18/openjdk18-openshift:${openjdk18-openshift.version}
    </fabric8.generator.from>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>me.snowdrop</groupId>
        <artifactId>spring-boot-bom</artifactId>
        <version>${spring-boot-bom.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

<!-- TODO: ADD Actuator dependency here -->

    <!-- Testing -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

<!-- /actuator/health 
management.endpoints.web.exposure.include=*
/actuator/metrics

/acutuator/metrics/[metric-name]
/actuator/beans
Jaeger and Tracing
-->
<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
  <dependency>
          <groupId>org.postgresql</groupId>
          <artifactId>postgresql</artifactId>
          <version>${postgresql.version}</version>
          <scope>runtime</scope>
        </dependency>

</dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>${spring-boot.version}</version> <configuration> <profiles> <profile>local</profile> </profiles> <classifier>exec</classifier> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> <profiles> <profile> <id>local</id> <activation> <activeByDefault>true</activeByDefault> </activation> <dependencies> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> </dependency> </dependencies> </profile> <profile> <id>openshift</id> <dependencies> <!-- TODO: ADD PostgreSQL database dependency here --> </dependencies> <build> <plugins> <plugin> <groupId>io.fabric8</groupId> <artifactId>fabric8-maven-plugin</artifactId> <version>${fabric8-maven-plugin.version}</version> <executions> <execution> <id>fmp</id> <goals> <goal>resource</goal> <goal>build</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> </project>

test class sample

@RunWith(SpringRunner.class)

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class ApplicationTest {

    @Autowired
    private FruitRepository fruitRepository;

    @Before
    public void beforeTest() {
    }

    @Test
    public void testGetAll() {
      assertTrue(fruitRepository.findAll().spliterator().getExactSizeIfKnown()==3);
    }

    @Test
    public void getOne() {
      assertTrue(fruitRepository.findById(1).orElse(null)!=null);
    }


Spring REst services
package com.example.service;

import java.util.List;
import java.util.Objects;
import java.util.Spliterator;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Controller
@RequestMapping(value = "/api/fruits")
public class FruitController {

    private final FruitRepository repository;

    @Autowired
    public FruitController(FruitRepository repository) {
        this.repository = repository;
    }

    @ResponseBody
    @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public List getAll() {
        return StreamSupport
                .stream(repository.findAll().spliterator(), false)
                .collect(Collectors.toList());
    }
@ResponseBody
    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
    public Fruit post(@RequestBody(required = false) Fruit fruit) {
        verifyCorrectPayload(fruit);

        return repository.save(fruit);
    }

    @ResponseBody
    @GetMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public Fruit get(@PathVariable("id") Integer id) {
        verifyFruitExists(id);

        return repository.findById(id).orElse(null);
    }

}

exemple fabric 8

apiVersion: v1
kind: Deployment
metadata:
  name: ${project.artifactId}
spec:
  template:
    spec:
      containers:
        - env:
            - name: DB_USERNAME
              valueFrom:
                 secretKeyRef:
                   name: my-database-secret
                   key: user
            - name: DB_PASSWORD
              valueFrom:
                 secretKeyRef:
                   name: my-database-secret
                   key: password
            - name: JAVA_OPTIONS
              value: "-Dspring.profiles.active=openshift"
Properties openShift
spring.datasource.url=jdbc:postgresql://${MY_DATABASE_SERVICE_HOST}:${MY_DATABASE_SERVICE_PORT}/my_data
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.hibernate.ddl-auto=create

mai

11

Posted by : admin | On : 11 mai 2012

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

- 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

  • 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 )

 

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 .

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

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>
  • 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">
		<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 : admin | On : 11 mai 2012

 

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();
	      }

    }
}

jan

10

Posted by : admin | On : 10 janvier 2012

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();
		}
	}
}