poniedziałek, 22 lipca 2013

Apache Camel - Wczytanie XML / JAXB

 [Apache Camel 2.8.0, JAXB, Jboss 6]
Przykład zaczytanie pliku XML do obiektu JAVA, z walidacją względem pliku XSD.

Wymagane dependency:
        <dependency>
            <groupId>org.apache.camel</groupId>
            <artifactId>camel-jaxb</artifactId>
            <version>${camel-version}</version>
        </dependency>

//W serwisie dodajemy metodę do uruchomienia pobierania danych z XML:
    public void getBookXML() {
        log.info("Import z XML BEGIN");   
        BookXML bookXML = null;
        Exchange exchFile;
        List<BookDTO> books = new ArrayList<BookDTO>();
        ProducerTemplate producer = camelContext.createProducerTemplate();
        ConsumerTemplate consumer = camelContext.createConsumerTemplate();
        try {
            String endpoint = MyUtils.getParameterOrNull("endpoint.file");
            log.info("endpoint: "+endpoint);
            exchFile = consumer.receive(endpoint, 2000L);
            if (exchFile != null && exchFile.getIn() != null
                    && exchFile.getIn().getBody() != null) {
                log.info("Pobrano z: "
                        + exchFile.getIn().getBody().getClass().toString());
                log.info("ret: " + exchFile.getIn().getBody().toString());

               
                Object validRet = producer.sendBody("direct:unmarshal",
                        ExchangePattern.InOut, exchFile.getIn().getBody());
                if(validRet instanceof Boolean
                        && (Boolean)validRet){
                    bookXML = (BookXML) producer.sendBody("direct:readXmlBook",
                            ExchangePattern.InOut, exchFile.getIn().getBody());
                }else{
                    throw new MyException("B\u0142\u0105d walidacji XML");
                }               
                books = prepareHashMapBooks(bookXML);
                consumer.doneUoW(exchFile);
            } else {
                log.info("Brak pliku do importu");
            }
            log.info("Pobrano: "+books.size());
        } catch (Exception e) {
            e.printStackTrace();
        }   
        log.info("Import z XML END");
    }

//BUILDER TRAS APACHE CAMEL
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.model.dataformat.JaxbDataFormat;

public class MyRouteBuilderFile extends RouteBuilder{

    @Override
    public void configure() throws Exception {       
        JaxbDataFormat dataFormat = new JaxbDataFormat(false);
        dataFormat.setContextPath("com.bloger.programmingmt.example");
        //przeksztalcenie na z XML na DTO
        from("direct:unmarshalFile")
        .unmarshal(dataFormat)
        .to("log: IN ==>");

        //Parsowania XML na podstawie XSD
        from("direct:unmarshal")
        .convertBodyTo(org.w3c.dom.Document.class)
        .bean(ParserXMLFileProcessor .class, "process")
        .end();
    }

}

//PROCESOR WALIDUJACY STRUKTURE PLIKU XML NA PODSTAWIE XSD
public class ParserXMLFileProcessor implements Processor {
   
    private static final Logger log = Logger.getLogger(ParserXMLFileProcessor.class);
   
    @Autowired
    private CamelContext camelContext;

   
    @Override
    public void process(Exchange exchange) throws Exception {
        Exchange exchFile = null;
        try {
            SchemaFactory factory = SchemaFactory
                    .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
           
            ConsumerTemplate consumer = camelContext.createConsumerTemplate();
            //Wskazanie pliku XSD do walidacji
            String schemaFileEndpoint = Utils.getParameterOrNull("endpoint.book.file.validator");
            log.info("schemaFileEndpoint: "+schemaFileEndpoint);
            try {
                if(schemaFileEndpoint!=null
                        && schemaFileEndpoint.length()>0){
                exchFile = consumer.receive(schemaFileEndpoint, 2000L);
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new MyException("Wystąpił wyjątek podczas pobierania pliku XSD dla walidacji: "+e.getMessage());
            }
            if (exchFile != null && exchFile.getIn() != null
                    && exchFile.getIn().getBody() != null) {
                log.info("Pobrano z: "
                        + exchFile.getIn().getBody().getClass().toString());
                log.info("ret: " + exchFile.getIn().getBody().toString());
                Schema schema = factory.newSchema((File)((GenericFile)exchFile.getIn().getBody()).getFile());
   
                Validator validator = schema.newValidator();
                validator.validate(new DOMSource((Document)exchange.getIn().getBody()));
                System.out.println("...passed...");
                consumer.doneUoW(exchFile);
            } else {
                log.info("Brak pliku do walidacji struktury");
            }
            exchange.getIn().setBody(Boolean.TRUE);
            exchange.getOut().setBody(Boolean.TRUE);
        } catch (Exception e) {
            e.printStackTrace();
            exchange.getIn().setBody(Boolean.FALSE);
            exchange.getOut().setBody(Boolean.FALSE);
        }
    }
   
    public void setCamelContext(
            CamelContext camelContext) {
        this.camelContext = camelContext;
    }
}

Brak komentarzy:

Prześlij komentarz