Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.lang.reflect.Constructor;

import java.util.HashMap;

import java.util.LinkedList;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {

    public static Map<String, Object> getProperties(Element root) {
        Map<String, Object> map = new HashMap<String, Object>();
        Element[] list = getChildrenByName(root, "property");
        for (int i = 0; i < list.length; i++) {
            String name = list[i].getAttribute("name");
            String type = list[i].getAttribute("type");
            String valueString = getText(list[i]);
            try {
                Class<?> cls = Class.forName(type);
                Constructor<?> con = cls.getConstructor(new Class<?>[] { String.class

                });
                Object value = con.newInstance(new Object[] { valueString

                });
                map.put(name, value);
            } catch (Exception e) {
                System.err.println("Unable to parse property '" + name +

                        "'='" + valueString + "': " + e.toString());
            }
        }
        return map;
    }

    public static Element[] getChildrenByName(Element e, String name) {
        NodeList nl = e.getChildNodes();
        int max = nl.getLength();
        LinkedList<Node> list = new LinkedList<Node>();
        for (int i = 0; i < max; i++) {
            Node n = nl.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name)) {
                list.add(n);
            }
        }
        return list.toArray(new Element[list.size()]);
    }

    public static String getAttribute(Element e, String name) {
        return e.getAttribute(name);
    }

    public static String getText(Element e) {
        NodeList nl = e.getChildNodes();
        int max = nl.getLength();
        for (int i = 0; i < max; i++) {
            Node n = nl.item(i);
            if (n.getNodeType() == Node.TEXT_NODE) {
                return n.getNodeValue();
            }
        }
        return "";
    }
}