working on it ...

Filters

Explore Public Snippets

Sort by

Found 96 snippets matching: jaxb

    public by lbottaro  356017  1  7  3

    Vendor class - Java example for marshalling/unmarshalling, using JAX-B XmlID annotation

    This is the Vendor class, where the XmlElement annotation sets the vendorID attribute as XmlID. Such key will match the reference set in Card class, using annotation XmlIDREF.
    package com.test.jaxb;
    
    import java.io.Serializable;
    
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlID;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Vendor implements Serializable {
    	
    	 @XmlElement(name = "vendor-ID")
    	 @XmlID
    	private String vendorID;
    	 @XmlElement(name = "vendor-Name")
    	private String vendorName;
    	/**
    	 * @param vendorID
    	 * @param vendorName
    	 */
    	public Vendor(String vendorID, String vendorName) {
    		super();
    		this.vendorID = vendorID;
    		this.vendorName = vendorName;
    	}
    	/**
    	 * 
    	 */
    	public Vendor() {
    		super();
    		// TODO Auto-generated constructor stub
    	}
    	/**
    	 * @return the vendorID
    	 */
    	public String getVendorID() {
    		return vendorID;
    	}
    	/**
    	 * @param vendorID the vendorID to set
    	 */
    	public void setVendorID(String vendorID) {
    		this.vendorID = vendorID;
    	}
    	/**
    	 * @return the vendorName
    	 */
    	public String getVendorName() {
    		return vendorName;
    	}
    	/**
    	 * @param vendorName the vendorName to set
    	 */
    	public void setVendorName(String vendorName) {
    		this.vendorName = vendorName;
    	}
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "Vendor [vendorID=" + vendorID + ", vendorName=" + vendorName
    				+ "]";
    	}
    }
    

    public by lbottaro  5437  1  9  4

    How to marshal and unmarshal java class to xml file using JAX-B

    This java code shows how to marshal and unmarshal class data to xml using JAX-B library, contained in javax.xml.bind.JAXB package. MyNetwork object contains two lists, one for Vendor objects and one for Equipment objects. Each Equipment has a list of Cards and each card refers to a specific Vendor. Marshalling and unmarshalling operation is dele
    package com.test.jaxb;
    
    import java.io.File;
    import javax.xml.bind.JAXB;
    
    public class MarshallingExamples {
    
        public MarshallingExamples() {
            MyNetwork network = new MyNetwork();
            Vendor v1 = new Vendor("123", "NameVVV");
            Vendor v2 = new Vendor("567", "NameZZZ");
            Vendor v3 = new Vendor("345", "NameXXX");
            Equipment eqp1 = new Equipment("112233", "TYPE_ABC", "00-14-22-01-23-45");
            eqp1.addCard(new Card(CardType.DWDM, "AABBCC", 2, v1));
            network.addEquipments(eqp1);
            Equipment eqp2 = new Equipment("222333", "TYPE_ZZZ", "00-C4-22-C1-23-C5");
            eqp2.addCard(new Card(CardType.SDH, "AA1234", 1, v2));
            eqp2.addCard(new Card(CardType.ETH, "AACCDD", 4, v1));
            network.addEquipments(eqp2);
            Equipment eqp3 = new Equipment("445566", "TYPE_CDE", "01-C3-2A-C1-AA-C5");
            eqp3.addCard(new Card(CardType.DWDM, "AAFF44", 1, v3));
            eqp3.addCard(new Card(CardType.DWDM, "AABF33", 1, v3));
            eqp3.addCard(new Card(CardType.ETH, "AA33DD", 2, v2));
            network.addEquipments(eqp3);
            network.addVendor(v1);
            network.addVendor(v2);
            network.addVendor(v3);
            JAXB.marshal(network, new File("out.xml"));        
            network = JAXB.unmarshal(new File("out.xml"), MyNetwork.class);
            for(Equipment eqp : network.getEquipments()) {
                System.out.println(eqp);
            }
            for(Vendor vend : network.getVendors()) {
                System.out.println(vend);
            }
        }
    
        public static void main(String[] args) {
            new MarshallingExamples();
        }
    }
    

    public by lbottaro  2481  5  6  0

    Equipment class - Integration of JPA and JAXB Java classes

    The class models an Equipment, referencing its own Network class via ManyToOne and XmlIDREF annotations. It has many Card objects and refers to unique EquipmentController, using annotation OneToOne.
    package com.examples.jpa;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    import javax.persistence.OneToMany;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;
    import javax.xml.bind.annotation.*;
    
    @XmlType(propOrder = {"id", "network", "label", "cards", "equipmentController"})
    @XmlAccessorType(XmlAccessType.FIELD)
    @Entity
    @Table(name = "EQUIPMENT")
    public class Equipment implements Serializable {
    
    	@XmlElement(name = "equipment-ID")
    	@XmlID
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private String id;
    	
    	@ManyToOne
    	@XmlIDREF
    	private Network network;
    	
    	@XmlElement(name = "equipment-label")
        @Column(name = "LABEL", length = 125)
        private String label;
    	
    	@XmlElementWrapper(name = "cards")
    	@XmlElement(name = "equipment-cards")
        @OneToMany(mappedBy = "equipment", cascade = CascadeType.ALL, orphanRemoval = true)
        private List<Card> cards;
    	
    	@XmlElement(name = "equipment-controller")
        @OneToOne(cascade = CascadeType.ALL)
        private EquipmentController equipmentController;
    
        public Equipment() {
        }
    
        public Equipment(String label) {
            this.label = label;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public void addCard(Card card) {
            if (cards == null) {
                this.cards = new ArrayList();
            }
            card.setEquipment(this);
            cards.add(card);
        }
    
        public List<Card> getCards() {
            return cards;
        }
    
        public void setCards(List<Card> cards) {
            this.cards = cards;
        }
    
        public String getLabel() {
            return label;
        }
    
        public void setLabel(String label) {
            this.label = label;
        }
    
        public EquipmentController getEquipmentController() {
            return equipmentController;
        }
    
        public void setEquipmentController(EquipmentController equipmentController) {
            this.equipmentController = equipmentController;
            equipmentController.setEquipment(this);
        }
    
        @Override
        public String toString() {
            return "Equipment{" + "id=" + id + ", label=" + label + ", equipmentController=" + equipmentController + '}';
        }
    
    	/**
    	 * @return the network
    	 */
    	public Network getNetwork() {
    		return network;
    	}
    
    	/**
    	 * @param network the network to set
    	 */
    	public void setNetwork(Network network) {
    		this.network = network;
    	}
    
    	
        
    }
    

    public by lbottaro  2140  6  6  1

    Network class - How to integrate JPA and JAXB java objects

    Network class contains a list of Equipment objects. Note the OneToMany annotation, used to mark the relationship link between the two classes. FetchType EAGER is set to load all the structures once the object is referenced.
    package com.examples.jpa;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToMany;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlElementWrapper;
    import javax.xml.bind.annotation.XmlID;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
     
    @Entity
    @XmlRootElement(name = "network-topology")
    @XmlType(propOrder={"equipments", "id"})
    @XmlAccessorType(XmlAccessType.FIELD) 
    public class Network {
     
    	@XmlElement(name = "id")
    	@XmlID
    	@Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private String id;
    	
    	@XmlElementWrapper(name = "equipments-list")
        @XmlElement(name = "equipment")
    	@OneToMany(mappedBy = "network", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
        private List<Equipment> equipments;
    	
    	/**
    	 * @return the equipments
    	 */
    	public List<Equipment> getEquipments() {
    		return equipments;
    	}
     
    	/**
    	 * @param equipments the equipments to set
    	 */
    	public void setEquipments(List<Equipment> equipments) {
    		this.equipments = equipments;
    	}
     
    	/**
    	 * @param eqp the equipment to add 
    	 */
    	public void addEquipments(Equipment eqp) {
            if (equipments == null) {
                this.equipments = new ArrayList();
            }
            eqp.setNetwork(this);;
            equipments.add(eqp);
        }
    
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "Network [id=" + id + ", equipments=" + equipments + "]";
    	}
    
    	/**
    	 * @return the id
    	 */
    	public String getId() {
    		return id;
    	}
    
    	/**
    	 * @param id the id to set
    	 */
    	public void setId(String id) {
    		this.id = id;
    	}
    	
    	
    }
     

    public by lbottaro  2685  1  6  0

    Ethernet java class - Integration of JPA and JAXB Java classes

    The class extends the abstract Port class, integratin both JPA and JAX-B java api.
    package com.examples.jpa;
    
    import javax.persistence.Column;
    import javax.persistence.DiscriminatorValue;
    import javax.persistence.Entity;
    import javax.persistence.Table;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    
    @Entity
    @Table(name = "ETHERNET_PORT")
    @DiscriminatorValue("ETHERNET")
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlRootElement(name="eth-port")
    public class EthernetPort extends Port {
    
    	@XmlElement(name = "mtu")
        @Column(name = "MTU_SIZE")
        private int mtuSize;
    	
        @Column(name = "SPEED")
    	@XmlElement(name = "speed")
        private int speed;
        
    	@XmlElement(name = "auton")
        @Column(name = "AUTONEGOTATION")
        private boolean autonegotiation;
    
        public EthernetPort() {
        }
    
        public EthernetPort(String label) {
            super(label);
        }
    
        public EthernetPort(String label, int mtuSize, int speed, boolean autonegotiation) {
            super(label);
            this.mtuSize = mtuSize;
            this.speed = speed;
            this.autonegotiation = autonegotiation;
        }
    
        public int getMtuSize() {
            return mtuSize;
        }
    
        public void setMtuSize(int mtuSize) {
            this.mtuSize = mtuSize;
        }
    
        public int getSpeed() {
            return speed;
        }
    
        public void setSpeed(int speed) {
            this.speed = speed;
        }
    
        public boolean isAutonegotiation() {
            return autonegotiation;
        }
    
        public void setAutonegotiation(boolean autonegotiation) {
            this.autonegotiation = autonegotiation;
        }
    
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "EthernetPort [mtuSize=" + mtuSize + ", speed=" + speed
    				+ ", autonegotiation=" + autonegotiation + "]";
    	}
        
        
    
    }
    

    public by lbottaro  2294  2  6  1

    Card class - Integration of java JPA and JAXB API

    The Card class contains a list of Port objects, using OneToMany annotation for its relation. Many Card objects may refer to the same Equipment, with annotation ManyToOne and XmlIDREF.
    package com.examples.jpa;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.ManyToOne;
    import javax.persistence.OneToMany;
    import javax.persistence.Table;
    import javax.persistence.Transient;
    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    @Entity
    @Table(name = "CARD")
    public class Card implements Serializable {
    
    	@XmlElement(name = "id")
    	@XmlID
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private String id;
    	
    	@XmlElement(name = "label")
        @Column(name = "LABEL", length = 125)
        private String label;
    	
    	@XmlElementRef
    	@XmlElementWrapper(name = "ports")
        @OneToMany(mappedBy = "card", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER) 
        private List<Port> ports;
    	
        @ManyToOne
        @XmlIDREF
        private Equipment equipment;
    
        public Card() {
        }
    
        public Card(String label) {
            this.label = label;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public void addPort(Port port) {
            if (ports == null) {
                this.ports = new ArrayList<Port>();
            }
            port.setCard(this);
            ports.add(port);
        }
    
        public List<Port> getPorts() {
            return ports;
        }
    
        public void setPorts(List<Port> ports) {
            this.ports = ports;
        }
    
        public String getLabel() {
            return label;
        }
    
        public void setLabel(String label) {
            this.label = label;
        }
    
        public Equipment getEquipment() {
            return equipment;
        }
    
        public void setEquipment(Equipment equipment) {
            this.equipment = equipment;
        }
    
        @Override
        public String toString() {
            return "Card{" + "id=" + id + ", label=" + label + ", ports=" + ports + ", equipment=" + equipment + '}';
        }
    }
    

    public by lbottaro  2299  0  6  1

    EquipmentController java class - Integration of JPA and JAXB Java classes

    This class refers to a unique Equipment class, using OneToOne annotation.
    package com.examples.jpa;
    
    import java.io.Serializable;
    
    import javax.persistence.Column;
    import javax.persistence.Embedded;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;
    import javax.xml.bind.annotation.*;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    @Entity
    @Table(name = "EQUIPMENT_CONTROLLER")
    public class EquipmentController implements Serializable {
    
    	@XmlElement(name = "id")
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    	
    	@XmlElement(name = "label")
        @Column(name = "LABEL", length = 125)
        private String label;
    	
    	@XmlTransient
        @OneToOne
        private Equipment equipment;
    	
    	@XmlElement(name = "controllerAddress")
        @Embedded
        private ControllerAddress controllerAddress;
    
        public EquipmentController() {
        }
    
        public EquipmentController(String label) {
            this.label = label;
        }
    
        public Long getId() {
            return id;
        }
    
        public void setId(Long id) {
            this.id = id;
        }
    
        public String getLabel() {
            return label;
        }
    
        public void setLabel(String label) {
            this.label = label;
        }
    
        public Equipment getEquipment() {
            return equipment;
        }
    
        public void setEquipment(Equipment equipment) {
            this.equipment = equipment;
        }
    
        public ControllerAddress getControllerAddress() {
            return controllerAddress;
        }
    
        public void setControllerAddress(ControllerAddress controllerAddress) {
            this.controllerAddress = controllerAddress;
        }
    
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "EquipmentController [id=" + id + ", label=" + label
    				+ ", controllerAddress="
    				+ controllerAddress + "]";
    	}
        
        
    
    }
    

    public by lbottaro  2229  0  6  1

    How to integrate JAXB and JPA annotations in java

    This example shows how to integrate JAX-B and JPA annotations and methods to marshal/unmarshal java objects from xml and persist and access data on database.
    package com.examples.jpa.tests;
    
    import com.examples.jpa.*;
    
    import java.io.File;
    import java.util.Iterator;
    import java.util.List;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.EntityTransaction;
    import javax.persistence.LockModeType;
    import javax.persistence.Persistence;
    import javax.persistence.TypedQuery;
    import javax.persistence.criteria.CriteriaBuilder;
    import javax.persistence.criteria.CriteriaQuery;
    import javax.persistence.criteria.Path;
    import javax.persistence.criteria.Predicate;
    import javax.persistence.criteria.Root;
    import javax.persistence.criteria.Selection;
    import javax.xml.bind.JAXB;
    
    public class EntityTests {
    
        private final static EntityManagerFactory entityManagerFactory;
    
        static {
            entityManagerFactory = Persistence.createEntityManagerFactory("MyNativeJPAProject");
        }
    
        public EntityTests() {
    //        createNetwork();
    //        testOptimisticLock();
    //        printEquipment();
    //        testDeleteOrphan();
    //        printEquipment();
    //        testCriteria();
        	Network network = createNetwork();
        	JAXB.marshal(network, new File("out.xml"));
        	network = null;
        	network = JAXB.unmarshal(new File("out.xml"), Network.class);
        	
        	if (network != null)
            {
        		System.out.println(network);
        		String id = network.getId();
            	network = null;
            	network = selectNetwork(id);
            	
            	if (network != null)
                {
                	System.out.println(network);
                }
                else
                {
                	System.out.println("Select Null!");
                }
            }
        	else
            {
            	System.out.println("Unmarshal Null!");
            }
        	
        }
    
        public static void main(String[] args) {
            new EntityTests();
        }
        
        private Network selectNetwork(String networkId)
        {    	        
        	Network network = null;
            network = findNetwork(networkId);
            return network;
        }
        
        public Network findNetwork(String id)
        {
        	Network network = null;
        	EntityManager entityManager = entityManagerFactory.createEntityManager();
            try {
            	String jpql = "SELECT n FROM Network n WHERE n.id = :id";
            	
            	TypedQuery<Network> query = entityManager.createQuery(jpql, Network.class);
            	query.setParameter("id", id);
            	network = query.getSingleResult();
                
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                entityManager.close();
            }
            return network;
        }
        
        
        private Network createNetwork()
        {
            Network network = new Network();
            Equipment e1 = new Equipment("Eqt 1");
            EquipmentController ctrl1 = new EquipmentController("Ctrl 1");
            ctrl1.setControllerAddress(new ControllerAddress("194.23.4.1", 4447));
            e1.setEquipmentController(ctrl1);
            Card c1 = new Card("Crd:1.1");
            Port p11 = new EthernetPort("Prt:1.1.1", 1526, 1000, true);
            c1.addPort(p11);
            Port p12 = new EthernetPort("Prt:1.1.2", 1024, 100, true);;
            c1.addPort(p12);
            e1.addCard(c1);
            Card c2 = new Card("Crd:1.2");
            Port p21 = new SdhPort("Prt:1.2.1", true, 2488, VirtualContainer.VC12);
            p21.setCard(c2);
            c2.addPort(p21);
            Port p22 = new EthernetPort("Prt:1.2.2", 1526, 1000, true);
            c2.addPort(p22);
            Port p32 = new EthernetPort("Prt:1.2.3", 1024, 2048, true);
            c2.addPort(p32);
            e1.addCard(c2);
            
            
            Equipment e2 = new Equipment("Eqt 2");
            EquipmentController ctrl2 = new EquipmentController("Ctrl 2");
            ctrl2.setControllerAddress(new ControllerAddress("194.23.4.222", 1122));
            e2.setEquipmentController(ctrl2);
            Card c22 = new Card("Crd:1.2");
            Port p212 = new EthernetPort("Prt:1.1.2", 1526, 1000, true);
            c22.addPort(p212);
            Port p2123 = new EthernetPort("Prt:1.1.3", 1024, 100, true);;
            c22.addPort(p2123);
            e2.addCard(c22);
            
            network.addEquipments(e1);
            network.addEquipments(e2);
            
            save(network);
            
            return network;
            
        }
    
        private void printEquipment() {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            try {
                TypedQuery<Equipment> query = entityManager.createQuery("SELECT e FROM Equipment e", Equipment.class);
                List<Equipment> equipments = query.getResultList();
                for (Equipment equipment : equipments) {
                    NetworkUtils.print(equipment, System.out);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                entityManager.close();
            }
        }
    
        public void deleteEquipment() {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                TypedQuery<Equipment> query = entityManager.createQuery("SELECT e FROM Equipment e", Equipment.class);
                List<Equipment> equipments = query.getResultList();
                for (Equipment equipment : equipments) {
                    transaction.begin();
                    entityManager.detach(equipment);
                    transaction.commit();
                }
    
            } catch (Exception e) {
                e.printStackTrace();
                transaction.rollback();
            } finally {
                entityManager.close();
            }
        }
    
        private void testDeleteOrphan() {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                TypedQuery<Equipment> query = entityManager.createQuery("SELECT e FROM Equipment e", Equipment.class);
                List<Equipment> equipments = query.getResultList();
                transaction.begin();
                for (Equipment equipment : equipments) {
                    List<Card> cards = equipment.getCards();
                    for (Iterator<Card> i = cards.iterator(); i.hasNext();) {
                        Card card = i.next();
                        if ("Crd:1.1".equals(card.getLabel())) {
                            i.remove();
                        }
                        card.setEquipment(null);
                    }
                    entityManager.merge(equipment);
                }
                transaction.commit();
            } catch (Exception e) {
                e.printStackTrace();
                transaction.rollback();
            } finally {
                entityManager.close();
            }
        }
    
        private void createEquipment() {
            Equipment e1 = new Equipment("Eqt 1");
            EquipmentController ctrl1 = new EquipmentController("Ctrl 1");
            ctrl1.setControllerAddress(new ControllerAddress("194.23.4.1", 4447));
            e1.setEquipmentController(ctrl1);
            Card c1 = new Card("Crd:1.1");
            Port p11 = new EthernetPort("Prt:1.1.1", 1526, 1000, true);
            c1.addPort(p11);
            Port p12 = new EthernetPort("Prt:1.1.2", 1024, 100, true);;
            c1.addPort(p12);
            e1.addCard(c1);
            Card c2 = new Card("Crd:1.2");
            Port p21 = new SdhPort("Prt:1.2.1", true, 2488, VirtualContainer.VC12);
            p21.setCard(c2);
            c2.addPort(p21);
            Port p22 = new EthernetPort("Prt:1.2.2", 1526, 1000, true);
            c2.addPort(p22);
            Port p32 = new EthernetPort("Prt:1.2.3", 1024, 2048, true);
            c2.addPort(p32);
            e1.addCard(c2);
            save(e1);
        }
    
        private Card findCardByLabel(String label) {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            try {
                TypedQuery<Card> query = entityManager.createQuery("SELECT c FROM Card c WHERE c.label = :label", Card.class);
                query.setParameter("label", label);
                Card card = query.getSingleResult();
                return card;
            } finally {
                entityManager.close();
            }
        }
    
        private void save(Equipment e1) {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();
                entityManager.persist(e1);
                transaction.commit();
            } catch (Exception e) {
                e.printStackTrace();
                transaction.rollback();
            } finally {
                entityManager.close();
            }
        }
    
        private void save(Network n) {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();
                entityManager.persist(n);
                transaction.commit();
            } catch (Exception e) {
                e.printStackTrace();
                transaction.rollback();
            } finally {
                entityManager.close();
            }
        }
        private void testCriteria() {
            EntityManager entityManager = entityManagerFactory.createEntityManager();
            try {
                CriteriaBuilder builder = entityManager.getCriteriaBuilder();
                CriteriaQuery<String> criteria = builder.createQuery(String.class);
                Root portRoot = criteria.from(Port.class);
                criteria.select(portRoot.get("label"));
                Path<Object> cardLabelPath = portRoot.get("card").get("label");
                Predicate whereCondition = builder.equal(cardLabelPath, "Crd:1.1");
                criteria.where(whereCondition);
                List<String> portLabels = entityManager.createQuery(criteria).getResultList();
                for (String portLabel : portLabels) {
                    System.out.println("Port label: " + portLabel);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                entityManager.close();
            }
        }
    
        private void testOptimisticLock() {
    
            Thread t1 = new Thread() {
    
                @Override
                public void run() {
                    EntityManager entityManager = entityManagerFactory.createEntityManager();
                    EntityTransaction transaction = entityManager.getTransaction();
                    try {
                        transaction.begin();
                        TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class);
                        query.setLockMode(LockModeType.OPTIMISTIC);
                        query.setParameter("portLabel", "Prt:1.2.1");
                        Port port = query.getSingleResult();
                        System.out.println("Thread 1: Lock obtained");
                        this.sleep(10000);
                        port.setDescription("Changed");
                        entityManager.merge(port);
                        transaction.commit();
                        System.out.println("Thread 1: Transaction commited and lock released");
                    } catch (Exception e) {
                        e.printStackTrace();
                        transaction.rollback();
                    } finally {
                        entityManager.close();
                    }
                }
    
            };
            t1.start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(EntityTests.class.getName()).log(Level.SEVERE, null, ex);
            }
            Thread t2 = new Thread() {
    
                @Override
                public void run() {
                    EntityManager entityManager = entityManagerFactory.createEntityManager();
                    EntityTransaction transaction = entityManager.getTransaction();
                    try {
                        transaction.begin();
                        TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class);
                        query.setLockMode(LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                        query.setParameter("portLabel", "Prt:1.2.1");
                        System.out.println("Thread 2: Waiting for read Port");
                        Port port = query.getSingleResult();
                        System.out.println("Thread 2: Port is: "+port); 
                        port.setDescription("SDH port");
                        entityManager.merge(port);
                        transaction.commit();
                        System.out.println("Thread 2: Transaction commited");
                    } catch (Exception e) {
                        e.printStackTrace();
                        transaction.rollback();
                    } finally {
                        entityManager.close();
                    }
                }
            };
            t2.start();
        }
    
        
        private void testPessimisticLock() {
    
            Thread t1 = new Thread() {
    
                @Override
                public void run() {
                    EntityManager entityManager = entityManagerFactory.createEntityManager();
                    EntityTransaction transaction = entityManager.getTransaction();
                    try {
                        transaction.begin();
                        TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class);
                        query.setLockMode(LockModeType.PESSIMISTIC_WRITE);
                        query.setParameter("portLabel", "Prt:1.2.1");
                        Port port = query.getSingleResult();
                        System.out.println("Thread 1: Lock obtained");
                        this.sleep(10000);
                        transaction.commit();
                        System.out.println("Thread 1: Transaction commited and lock released");
                    } catch (Exception e) {
                        e.printStackTrace();
                        transaction.rollback();
                    } finally {
                        entityManager.close();
                    }
                }
    
            };
            t1.start();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(EntityTests.class.getName()).log(Level.SEVERE, null, ex);
            }
            Thread t2 = new Thread() {
    
                @Override
                public void run() {
                    EntityManager entityManager = entityManagerFactory.createEntityManager();
                    EntityTransaction transaction = entityManager.getTransaction();
                    try {
                        transaction.begin();
                        TypedQuery<Port> query = entityManager.createQuery("SELECT p FROM Port p WHERE p.label = :portLabel", Port.class);
                        query.setLockMode(LockModeType.PESSIMISTIC_READ);
                        query.setParameter("portLabel", "Prt:1.2.1");
                        System.out.println("Thread 2: Waiting for read Port");
                        Port port = query.getSingleResult();
                        System.out.println("Thread 2: Port is: "+port); 
                        transaction.commit();
                        System.out.println("Thread 2: Transaction commited");
                    } catch (Exception e) {
                        e.printStackTrace();
                        transaction.rollback();
                    } finally {
                        entityManager.close();
                    }
                }
            };
            t2.start();
        }
    }
    

    public by lbottaro  1915  1  6  0

    Port class - Integration of java JPA and JAXB

    This is a generic abstract Port class, managed by a Card class.
    package com.examples.jpa;
    
    import java.io.Serializable;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.DiscriminatorColumn;
    import javax.persistence.Entity;
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Inheritance;
    import javax.persistence.InheritanceType;
    import javax.persistence.ManyToOne;
    import javax.persistence.Transient;
    import javax.persistence.Version;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlIDREF;
    import javax.xml.bind.annotation.XmlSeeAlso;
    import javax.xml.bind.annotation.XmlTransient;
    import javax.xml.bind.annotation.XmlType;
    
    @Entity
    @Inheritance(strategy = InheritanceType.JOINED)
    @XmlAccessorType(XmlAccessType.FIELD)
    @XmlSeeAlso(value={SdhPort.class, EthernetPort.class})
    @XmlType(name="Port")
    public abstract class Port implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
    	@XmlElement(name = "id")
        private String id;
        
        @Column(name = "LABEL", length = 125)
        @XmlElement(name = "label")
        private String label;
        
        @ManyToOne
        @XmlIDREF
        private Card card;
        
        @Column(name = "DESCRIPTION", length = 125)
        @XmlElement(name = "description")
        private String description;
        
        @Version
        @XmlTransient
        private int version;
    
        public Port() {
        }
    
        public Port(String label) {
            this.label = label;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public Card getCard() {
            return card;
        }
    
        public void setCard(Card card) {
            this.card = card;
        }
    
        public String getLabel() {
            return label;
        }
    
        public void setLabel(String label) {
            this.label = label;
        }
    
        public int getVersion() {
            return version;
        }
    
        public void setVersion(int version) {
            this.version = version;
        }
    
        public String getDescription() {
            return description;
        }
    
        public void setDescription(String description) {
            this.description = description;
        }
    
        @Override
        public String toString() {
            return "Port{" + "id=" + id + ", label=" + label + '}';
        }
    
    }
    

    public by lbottaro  1969  0  6  0

    ControllerAddress java class - Integration of JPA and JAXB Java classes

    This class is embedded into EquipmentController class, using annotation Embeddable
    package com.examples.jpa;
    
    import java.io.Serializable;
    
    import javax.persistence.Embeddable;
    import javax.xml.bind.annotation.XmlAccessType;
    import javax.xml.bind.annotation.XmlAccessorType;
    import javax.xml.bind.annotation.XmlElement;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    @Embeddable
    public class ControllerAddress implements Serializable {
    
    	@XmlElement(name = "host")
        private String host;
    	@XmlElement(name = "port")
        private int port;
    
        public ControllerAddress() {
        }
    
        public ControllerAddress(String host, int port) {
            this.host = host;
            this.port = port;
        }
    
        public String getHost() {
            return host;
        }
    
        public void setHost(String host) {
            this.host = host;
        }
    
        public int getPort() {
            return port;
        }
    
        public void setPort(int port) {
            this.port = port;
        }
    
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "ControllerAddress [host=" + host + ", port=" + port + "]";
    	}
        
        
    
    }
    
    • Public Snippets
    • Channels Snippets