如何在Java中监听任何Messaging队列并将XML转换为XSD?

时间:2021-07-21 21:49:06

i want to listen to a any queue & retrieve XML messages from that Queue. Say active MQ.

我想收听任何队列并从该队列中检索XML消息。说活跃的MQ。

Once I receive , the XML , I want to convert it into secondary format. Please tell me how ? Sample XML i will receive in the queue looks like this :

收到XML后,我想将其转换为二级格式。请告诉我怎么样?我将在队列中收到的示例XML如下所示:

<customer id="87866">
<age>55</age>
<name>Peter</name>
</customer>

2 个解决方案

#1


0  

I'd suggest you're trying to solve two different problems here.

我建议你在这里尝试解决两个不同的问题。

First, the conversion part: This answer shows a nice way to convert XML into JSON without any need to know the structure.

首先,转换部分:这个答案显示了一种很好的方法,可以将XML转换为JSON,而无需了解结构。

Another approach would be to use JAXB to unmarshal the XML into Java objects, which can then be serialized into JSON, for example by GSON. (This approach would be a bit more work, and is more brittle but would give you more control over the incoming format, and allow you to perform business logic and transformation in between, if required.

另一种方法是使用JAXB将XML解组为Java对象,然后可以将其序列化为JSON,例如通过GSON。 (这种方法会更加有效,并且更加脆弱,但可以让您更好地控制传入格式,并允许您在需要时执行业务逻辑和转换。

Second, listening to a JMS queue - this will depend on your library, but I've found ActiveMQ very easy to get going with. A quickstart guide should give you detailed explanations of how to write a quick consumer.

第二,听JMS队列 - 这将取决于你的库,但我发现ActiveMQ非常容易使用。快速入门指南应该为您提供有关如何编写快速消费者的详细说明。

Is this what you were looking for? Need more/different detail?

这是你在寻找什么?需要更多/不同的细节?

#2


0  

For JMS Listner:

对于JMS Listner:

Customer

package com.jms;


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Customer [name=" + name + ", age=" + age + ", id=" + id + "]";
    }

}

MyMessageListener

  package com.jms;
    import java.io.StringReader;
    import java.io.StringWriter;

    import javax.jms.Message;  
import javax.jms.MessageListener;  
import javax.jms.TextMessage;  
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;


public class MyMessageListener implements MessageListener{  
        @Override  
        public void onMessage(Message m) {  
            TextMessage message=(TextMessage)m;  
            try{  
                String xml = message.getText();

                //Get customer POJO
                Customer customer = generateEntity(xml);
                System.out.println(customer);

                //Convert POJO to json and update in mongodb
                convertEntityToJsonAndUpdateDB(customer);

            }catch (Exception e) {e.printStackTrace();  }  
        }  

   private static   Customer generateEntity(String xml){
       Customer customer = null;
       try{ 
        StringReader reader = new StringReader(xml);
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        customer = (Customer) jaxbUnmarshaller.unmarshal(reader);
      }catch(Exception ex){
          ex.printStackTrace();
      }
    return customer;
   }


   private static void convertEntityToJsonAndUpdateDB(Customer customer){
    try{  
      StringWriter writer = new StringWriter();
      ObjectMapper mapper = new ObjectMapper();
      mapper.writeValue(writer, customer);
      System.out.println("Json:"+writer.toString());
      // To connect to mongodb server
      MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
      // connect to database
       DB db = mongoClient.getDB( "test" );
         System.out.println("Connect to database successfully");
         //Insert the json
         DBCollection collection = db.getCollection("mycollection");
         DBObject dbObject = (DBObject) JSON.parse(writer.toString());
          collection.insert(dbObject);
         System.out.println("DB Insertion Successful"); 
     }catch(Exception ex){
         ex.printStackTrace();
     }

    }
}  

TestListener

package com.jms;
import org.springframework.context.support.GenericXmlApplicationContext;  

public class TestListener {  
 public static void main(String[] args) {  
    GenericXmlApplicationContext ctx=new GenericXmlApplicationContext();  
    ctx.load("classpath:applicationContext.xml");  
    ctx.refresh();  

    while(true){}  
 }  
}

mdb

package com.jms;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;


public class TestMongoDB {
   public static void main(String[] args) {
     try{     
       // To connect to mongodb server
          MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
          // connect to database
           DB db = mongoClient.getDB( "test" );
             System.out.println("Connect to database successfully");
             //Insert the json
             DBCollection collection = db.getCollection("mycollection");
             //For querying mondo db
             DBCursor cursor = collection.find();
                while(cursor.hasNext()) {
                    System.out.println(cursor.next());
                }
         }catch(Exception ex){
             ex.printStackTrace();
         }
   }
}

#1


0  

I'd suggest you're trying to solve two different problems here.

我建议你在这里尝试解决两个不同的问题。

First, the conversion part: This answer shows a nice way to convert XML into JSON without any need to know the structure.

首先,转换部分:这个答案显示了一种很好的方法,可以将XML转换为JSON,而无需了解结构。

Another approach would be to use JAXB to unmarshal the XML into Java objects, which can then be serialized into JSON, for example by GSON. (This approach would be a bit more work, and is more brittle but would give you more control over the incoming format, and allow you to perform business logic and transformation in between, if required.

另一种方法是使用JAXB将XML解组为Java对象,然后可以将其序列化为JSON,例如通过GSON。 (这种方法会更加有效,并且更加脆弱,但可以让您更好地控制传入格式,并允许您在需要时执行业务逻辑和转换。

Second, listening to a JMS queue - this will depend on your library, but I've found ActiveMQ very easy to get going with. A quickstart guide should give you detailed explanations of how to write a quick consumer.

第二,听JMS队列 - 这将取决于你的库,但我发现ActiveMQ非常容易使用。快速入门指南应该为您提供有关如何编写快速消费者的详细说明。

Is this what you were looking for? Need more/different detail?

这是你在寻找什么?需要更多/不同的细节?

#2


0  

For JMS Listner:

对于JMS Listner:

Customer

package com.jms;


import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

    @XmlElement
    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "Customer [name=" + name + ", age=" + age + ", id=" + id + "]";
    }

}

MyMessageListener

  package com.jms;
    import java.io.StringReader;
    import java.io.StringWriter;

    import javax.jms.Message;  
import javax.jms.MessageListener;  
import javax.jms.TextMessage;  
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.util.JSON;


public class MyMessageListener implements MessageListener{  
        @Override  
        public void onMessage(Message m) {  
            TextMessage message=(TextMessage)m;  
            try{  
                String xml = message.getText();

                //Get customer POJO
                Customer customer = generateEntity(xml);
                System.out.println(customer);

                //Convert POJO to json and update in mongodb
                convertEntityToJsonAndUpdateDB(customer);

            }catch (Exception e) {e.printStackTrace();  }  
        }  

   private static   Customer generateEntity(String xml){
       Customer customer = null;
       try{ 
        StringReader reader = new StringReader(xml);
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);

        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();

        customer = (Customer) jaxbUnmarshaller.unmarshal(reader);
      }catch(Exception ex){
          ex.printStackTrace();
      }
    return customer;
   }


   private static void convertEntityToJsonAndUpdateDB(Customer customer){
    try{  
      StringWriter writer = new StringWriter();
      ObjectMapper mapper = new ObjectMapper();
      mapper.writeValue(writer, customer);
      System.out.println("Json:"+writer.toString());
      // To connect to mongodb server
      MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
      // connect to database
       DB db = mongoClient.getDB( "test" );
         System.out.println("Connect to database successfully");
         //Insert the json
         DBCollection collection = db.getCollection("mycollection");
         DBObject dbObject = (DBObject) JSON.parse(writer.toString());
          collection.insert(dbObject);
         System.out.println("DB Insertion Successful"); 
     }catch(Exception ex){
         ex.printStackTrace();
     }

    }
}  

TestListener

package com.jms;
import org.springframework.context.support.GenericXmlApplicationContext;  

public class TestListener {  
 public static void main(String[] args) {  
    GenericXmlApplicationContext ctx=new GenericXmlApplicationContext();  
    ctx.load("classpath:applicationContext.xml");  
    ctx.refresh();  

    while(true){}  
 }  
}

mdb

package com.jms;

import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;


public class TestMongoDB {
   public static void main(String[] args) {
     try{     
       // To connect to mongodb server
          MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
          // connect to database
           DB db = mongoClient.getDB( "test" );
             System.out.println("Connect to database successfully");
             //Insert the json
             DBCollection collection = db.getCollection("mycollection");
             //For querying mondo db
             DBCursor cursor = collection.find();
                while(cursor.hasNext()) {
                    System.out.println(cursor.next());
                }
         }catch(Exception ex){
             ex.printStackTrace();
         }
   }
}