working on it ...

Filters

Explore Public Snippets

Sort by

Found 333 snippets matching: annotations

    public by dave83  223923  8  7  0

    How to run methods in class marked with specific Java annotation

    The snippet shows how to invoke only methods of a class marked with specific annotation. The list of methods class (MyTest) is returned using reflection. Annotations are returned via getAnnotation() method. The method is executed via invoke() method.
    import java.lang.reflect.Method;
    
    public class MyTest {
    
        @MyAnnotation
        public void method1() {
          System.out.println("method1");
        }
    
        public void method2() {
          System.out.println("method2");
        }
        
        @MyAnnotation
        public void method3() {
          System.out.println("method3");
        }
        
        public static void main(String[] args) {
    
            MyTest runner = new MyTest();
            Method[] methods = runner.getClass().getMethods();
    
            for (Method method : methods) {
                MyAnnotation annos = method.getAnnotation(MyAnnotation.class);
                if (annos != null) {
                    try {
                        method.invoke(runner);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    } 
                            

    public by lbottaro  2240  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  5452  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  4305  0  8  5

    Card class - Example for marshalling/unmarshalling java object using JAX-B

    Finally this is the Card class. It's used the standard JAX-B annotations for specifying the XmlElement and the XmlAccessorType. Note the usage of XmlAttribute annotation to specify the Vendor ID as attribute of element Card. Moreover the XmlIDREF annotation will link the attribute vendor with the ID of Vendor class. In this way once the xml will b
    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.XmlAttribute;
    import javax.xml.bind.annotation.XmlElement;
    import javax.xml.bind.annotation.XmlIDREF;
    import javax.xml.bind.annotation.XmlType;
    
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Card implements Serializable {
    
    	@XmlElement
        private CardType type;
    	@XmlElement
        private String number;
    	@XmlElement
        private int numOfSlots;
    	@XmlAttribute
        @XmlIDREF
        private Vendor vendor;
    
        /**
    	 * @return the vendor
    	 */
    	public Vendor getVendor() {
    		return vendor;
    	}
    
    	/**
    	 * @param vendor the vendor to set
    	 */
    	public void setVendor(Vendor vendor) {
    		this.vendor = vendor;
    	}
    
    	public Card() {
        }
    
    	/**
    	 * @return the type
    	 */
    	public CardType getType() {
    		return type;
    	}
    
    	/**
    	 * @param type the type to set
    	 */
    	public void setType(CardType type) {
    		this.type = type;
    	}
    
    	/**
    	 * @return the number
    	 */
    	public String getNumber() {
    		return number;
    	}
    
    	/**
    	 * @param number the number to set
    	 */
    	public void setNumber(String number) {
    		this.number = number;
    	}
    
    	/**
    	 * @return the numOfSlots
    	 */
    	public int getNumOfSlots() {
    		return numOfSlots;
    	}
    
    	/**
    	 * @param numOfSlots the numOfSlots to set
    	 */
    	public void setNumOfSlots(int numOfSlots) {
    		this.numOfSlots = numOfSlots;
    	}
    
    	/**
    	 * @param type
    	 * @param number
    	 * @param numOfSlots
    	 */
    	public Card(CardType type, String number, int numOfSlots, Vendor vendor) {
    		super();
    		this.type = type;
    		this.number = number;
    		this.numOfSlots = numOfSlots;
    		this.vendor=vendor;
    	}
    
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "Card [type=" + type + ", number=" + number + ", numOfSlots="
    				+ numOfSlots + ", vendor=" +vendor+"]";
    	}
    }
    

    public by lbottaro  3966  0  7  2

    MyNetwork class - Java example for marshalling/unmarshalling object to xml using JAX-B

    This is the main class of the previous example. MyNetwork contains two lists, one for Equipment class and one for Vendor class. Since it's the main root of the xml, I set the annotation XmlRootElement, with value = network-topology. Such name will be displayed in the xml. @XmlType annotation sets the order of the attributes in the xml, using prop
    package com.test.jaxb;
    
    import java.util.ArrayList;
    import java.util.List;
    
    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.XmlRootElement;
    import javax.xml.bind.annotation.XmlType;
    
    @XmlRootElement(name = "network-topology")
    @XmlType(propOrder={"vendors", "equipments"})
    @XmlAccessorType(XmlAccessType.FIELD) 
    public class MyNetwork {
    
    	@XmlElementWrapper(name = "equipments-list")
        @XmlElement(name = "equipment")
        private List<Equipment> equipments;
    	
        @XmlElementWrapper(name = "vendors-list")
        @XmlElement(name = "vendor")
        private List<Vendor> vendors;
    
        /**
    	 * @return the vendors
    	 */
    	public List<Vendor> getVendors() {
    		return vendors;
    	}
    
    	/**
    	 * @param vendors the vendors to set
    	 */
    	public void setVendors(List<Vendor> vendors) {
    		this.vendors = vendors;
    	}
    
    	/**
    	 * @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();
            }
            equipments.add(eqp);
        }
    	
    	/**
    	 * @param vendor the equipment to add 
    	 */
    	public void addVendor(Vendor vendor) {
            if (vendors == null) {
                this.vendors = new ArrayList();
            }
            vendors.add(vendor);
        }
    }
    
    

    public by lbottaro  3246  1  7  2

    Equipment class - Example for marshalling/unmarshalling java object using JAX-B

    This is the Equipment class. You can see the usage of Jax-B XmlElement and XmlElementWrapper annotations to define xml attributes and wrapper attribute.
    package com.test.jaxb;
    
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.List;
    
    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.XmlType;
    
    @XmlType(propOrder = {"eqpID", "macAddress", "type", "cards"})
    @XmlAccessorType(XmlAccessType.FIELD)
    public class Equipment implements Serializable {
    
        @XmlElement(name = "equipment-ID")
        private String eqpID;
        @XmlElement(name = "equipment-type")
        private String type;
        @XmlElement(name = "equipment-mac-address")
        private String macAddress;
        @XmlElementWrapper(name = "cards")
        @XmlElement(name = "traffic-card")
        private List<Card> cards; 
    
        public Equipment() {
        }
        
    	/**
    	 * @param eqpID
    	 * @param type
    	 * @param macAddress
    	 */
    	public Equipment(String eqpID, String type, String macAddress) {
    		super();
    		this.eqpID = eqpID;
    		this.type = type;
    		this.macAddress = macAddress;
    	}    
    
    	/**
    	 * @param eqpID
    	 * @param type
    	 * @param macAddress
    	 * @param cards
    	 */
    	public Equipment(String eqpID, String type, String macAddress,
    			List<Card> cards) {
    		super();
    		this.eqpID = eqpID;
    		this.type = type;
    		this.macAddress = macAddress;
    		this.cards = cards;
    	}
    	
    	/**
    	 * @return the eqpID
    	 */
    	public String getEqpID() {
    		return eqpID;
    	}
    
    	/**
    	 * @param eqpID the eqpID to set
    	 */
    	public void setEqpID(String eqpID) {
    		this.eqpID = eqpID;
    	}
    
    	/**
    	 * @return the type
    	 */
    	public String getType() {
    		return type;
    	}
    
    	/**
    	 * @param type the type to set
    	 */
    	public void setType(String type) {
    		this.type = type;
    	}
    
    	/**
    	 * @return the macAddress
    	 */
    	public String getMacAddress() {
    		return macAddress;
    	}
    
    	/**
    	 * @param macAddress the macAddress to set
    	 */
    	public void setMacAddress(String macAddress) {
    		this.macAddress = macAddress;
    	}
    
    	/**
    	 * @return the cards
    	 */
    	public List<Card> getCards() {
    		return cards;
    	}
    
    	/**
    	 * @param cards the cards to set
    	 */
    	public void setCards(List<Card> cards) {
    		this.cards = cards;
    	}
        
    	/**
    	 * @param card the equipment to add 
    	 */
    	public void addCard(Card card) {
            if (cards == null) {
                this.cards = new ArrayList();
            }
            cards.add(card);
        }
    
    	/* (non-Javadoc)
    	 * @see java.lang.Object#toString()
    	 */
    	@Override
    	public String toString() {
    		return "Equipment [eqpID=" + eqpID + ", type=" + type + ", macAddress="
    				+ macAddress + ", cards=" + cards + "]";
    	}
    }
    

    public by sherazam  2786  3  6  0

    How to Extract Text from PDF Documents Based on Columns inside .NET Apps

    // Enter here the actual content of the snippet.            //The following code snippet shows the steps to reduce text size and then try extracting text from PDF document.
    
    //[C# Code Sample]
     
    
    string path = "D:\\Temp\\";
    InitLicense();
    Document pdfDocument = new Document(path + "net_New-age NED's.pdf");
    
    TextFragmentAbsorber tfa = new TextFragmentAbsorber();
    pdfDocument.Pages.Accept(tfa);
    TextFragmentCollection tfc = tfa.TextFragments;
    foreach (TextFragment tf in tfc)
    {
        //need to reduce font size at least for 70%
        tf.TextState.FontSize = tf.TextState.FontSize * 0.7f;
    }
    Stream st = new MemoryStream();
    pdfDocument.Save(st);
    pdfDocument = new Document(st);
    
    TextAbsorber textAbsorber = new TextAbsorber();
    pdfDocument.Pages.Accept(textAbsorber);
    String extractedText = textAbsorber.Text;
    textAbsorber.Visit(pdfDocument);
    
    System.IO.File.WriteAllText(path + "Extracted.txt", extractedText);
    
    // [VB.NET Code Sample]
     
    
    Dim path As String = "D:\\Temp\\"
    ' instantiate Document object 
    Dim pdfDocument As Document = New Document(path + "net_New-age NED's.pdf")
    
    Dim tfa As Aspose.Pdf.Text.TextFragmentAbsorber = New Aspose.Pdf.Text.TextFragmentAbsorber()
    pdfDocument.Pages.Accept(tfa)
    Dim tfc As Aspose.Pdf.Text.TextFragmentCollection = tfa.TextFragments
    For Each tf As Aspose.Pdf.Text.TextFragment In tfc
    
        ' need to reduce font size at least for 70%
        tf.TextState.FontSize = tf.TextState.FontSize * 0.7F
    Next
    ' create temporary stream object
    Dim st As Stream = New MemoryStream()
    ' save PDF file with reduced font size
    pdfDocument.Save(st)
    ' Instantiate Document object with stream instance
    pdfDocument = New Document(st)
    
    Dim textAbsorber As Aspose.Pdf.Text.TextAbsorber = New Aspose.Pdf.Text.TextAbsorber()
    pdfDocument.Pages.Accept(textAbsorber)
    Dim extractedText As String = textAbsorber.Text
    textAbsorber.Visit(pdfDocument)
    
    System.IO.File.WriteAllText(path + "Extracted.txt", extractedText)
     
    //Second approach - Using ScaleFactor
    
    //[C# Code Sample]
     
    
    Document pdfDocument = new Document(inputFile);
    
    TextAbsorber textAbsorber = new TextAbsorber();
    textAbsorber.ExtractionOptions = new TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure);
    //Setting scale factor to 0.5 is enough to split columns in the majority of documents
    //Setting of zero allows to algorithm choose scale factor automatically
    textAbsorber.ExtractionOptions.ScaleFactor = 0.5; /* 0; */
    pdfDocument.Pages.Accept(textAbsorber);
    String extractedText = textAbsorber.Text;
    
    System.IO.File.WriteAllText(outFile, extractedText);
     
    // [VB.NET Code Sample]
     
    
    Dim pdfDocument As Document = New Document(inputFile)
    
    Dim textAbsorber As Aspose.Pdf.Text.TextAbsorber = New Aspose.Pdf.Text.TextAbsorber()
    textAbsorber.ExtractionOptions = New TextExtractionOptions(TextExtractionOptions.TextFormattingMode.Pure)
    'Setting scale factor to 0.5 is enough to split columns in the majority of documents
    'Setting of zero allows to algorithm choose scale factor automatically
    textAbsorber.ExtractionOptions.ScaleFactor = 0.5 ' 0;
    pdfDocument.Pages.Accept(textAbsorber)
    Dim extractedText As String = textAbsorber.Text
    
    System.IO.File.WriteAllText(outFile, extractedText)
    

    public by lbottaro  2499  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 msdn  1246  0  6  0

    CloseStreamAndStore: Gets the MemoryStream byte array and closes the stream and the store This is called by serializing functions to get byte representation of the annotations in the store.

    Gets the MemoryStream byte array and closes the stream and the store This is called by serializing functions to get byte representation of the annotations in the store. Store MemoryStream AnnotationStore
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Windows.Annotations;
    using System.Windows.Annotations.Storage;
    
    /// <summary>
    /// Gets the MemoryStream byte array and closes the stream and the store
    /// This is called by serializing functions to get byte representation of 
    /// the annotations in the store.
    /// </summary>
    /// <param name="stream">Store MemoryStream</param>
    /// <param name="store">AnnotationStore</param>
    /// <returns></returns>
    private static byte[] CloseStreamAndStore(MemoryStream stream, AnnotationStore store)
    {
        //close the store and get underlying array
        store.Flush();
        byte [] res = stream.ToArray();
        store.Dispose();
        stream.Close();
        return res;
    }

    public by msdn  960  0  6  0

    Deserialize: Deserialize a byte array to Annotations list

    Deserialize a byte array to Annotations list the input array created annotations
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Xml;
    using System.Xml.Serialization;
    using System.Windows.Annotations;
    using System.Windows.Annotations.Storage;
    
    /// <summary>
    /// Deserialize a byte array to Annotations list
    /// </summary>
    /// <param name="data">the input array</param>
    /// <returns>created annotations</returns>
    public static IList<Annotation> Deserialize(byte[] data)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }
        //create a MemoryStream based XmlStreamStore
        MemoryStream stream = new MemoryStream(data);
        XmlStreamStore store = new XmlStreamStore(stream);
        IList<Annotation> res = store.GetAnnotations();
        store.Dispose();
        stream.Close();
        return res;
    }
    • Public Snippets
    • Channels Snippets