Example usage for org.jdom2 Document getRootElement

List of usage examples for org.jdom2 Document getRootElement

Introduction

In this page you can find the example usage for org.jdom2 Document getRootElement.

Prototype

public Element getRootElement() 

Source Link

Document

This will return the root Element for this Document

Usage

From source file:com.novell.ldapchai.impl.edir.value.nspmComplexityRules.java

License:Open Source License

private static List<Policy> readComplexityPoliciesFromXML(final String input) {
    final List<Policy> returnList = new ArrayList<Policy>();
    try {//ww  w.  jav  a2 s .  c  o m
        final SAXBuilder builder = new SAXBuilder();
        final Document doc = builder.build(new StringReader(input));
        final Element rootElement = doc.getRootElement();

        final List policyElements = rootElement.getChildren("Policy");
        for (final Object policyNode : policyElements) {
            final Element policyElement = (Element) policyNode;
            final List<RuleSet> returnRuleSets = new ArrayList<RuleSet>();
            for (final Object ruleSetObjects : policyElement.getChildren("RuleSet")) {
                final Element loopRuleSet = (Element) ruleSetObjects;
                final Map<Rule, String> returnRules = new HashMap<Rule, String>();
                int violationsAllowed = 0;

                final org.jdom2.Attribute violationsAttribute = loopRuleSet.getAttribute("ViolationsAllowed");
                if (violationsAttribute != null && violationsAttribute.getValue().length() > 0) {
                    violationsAllowed = Integer.parseInt(violationsAttribute.getValue());
                }

                for (final Object ruleObject : loopRuleSet.getChildren("Rule")) {
                    final Element loopRuleElement = (Element) ruleObject;

                    final List ruleAttributes = loopRuleElement.getAttributes();
                    for (final Object attributeObject : ruleAttributes) {
                        final org.jdom2.Attribute loopAttribute = (org.jdom2.Attribute) attributeObject;

                        final Rule rule = Rule.valueOf(loopAttribute.getName());
                        final String value = loopAttribute.getValue();
                        returnRules.put(rule, value);
                    }
                }
                returnRuleSets.add(new RuleSet(violationsAllowed, returnRules));
            }
            returnList.add(new Policy(returnRuleSets));
        }
    } catch (JDOMException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    } catch (IOException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    } catch (NullPointerException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    } catch (IllegalArgumentException e) {
        LOGGER.debug("error parsing stored response record: " + e.getMessage());
    }
    return returnList;
}

From source file:com.oagsoft.grafo.util.XMLLoader.java

public static Grafo leerArchivoXml(String nomArch) {
    SAXBuilder builder = new SAXBuilder();
    Grafo g = null;/*  w w  w . ja va 2 s  .  co  m*/
    try {
        Document document = (Document) builder.build(new File(nomArch));
        Element rootNode = document.getRootElement();
        Element nV = rootNode.getChild("numero-vertices");
        int numVertices = Integer.parseInt(nV.getValue().trim());
        g = new Grafo(numVertices);
        Element ad = rootNode.getChild("adyacencias");
        List<Element> hijos = ad.getChildren("adyacencia");
        for (Element hijo : hijos) {
            int nIni = Integer.parseInt(hijo.getChildTextTrim("nodo-inicial"));
            int nFin = Integer.parseInt(hijo.getChildTextTrim("nodo-final"));
            g.adyacencia(nIni, nFin);
        }
        //            System.out.println("Hay " + hijos.size()+ " adyacencias");
    } catch (JDOMException | IOException ex) {
        System.out.println(ex.getMessage());
    }
    return g;
}

From source file:com.oagsoft.wazgle.tools.XMLLoader.java

public static Grafo<GraphicNode> leerArchivoXml(String nomArch) {
    SAXBuilder builder = new SAXBuilder();
    Grafo<GraphicNode> g = null;//w  w  w  . j  a  va 2  s.c  o  m
    try {
        Document document = (Document) builder.build(new File(nomArch));
        Element rootNode = document.getRootElement();
        Element nV = rootNode.getChild("numero-vertices");
        int numVertices = Integer.parseInt(nV.getValue().trim());
        g = new Grafo(numVertices);
        Element nodos = rootNode.getChild("nodos");
        List<Element> hijos = nodos.getChildren("nodo");
        for (Element hijo : hijos) {
            int id = Integer.parseInt(hijo.getChildTextTrim("id"));
            int coorX = Integer.parseInt(hijo.getChildTextTrim("coor-x"));
            int coorY = Integer.parseInt(hijo.getChildTextTrim("coor-y"));
            GraphicNode nodo = new GraphicNode(id, new Point(coorX, coorY), 10, false);
            g.adVertice(nodo);
        }
        Element adyacencias = rootNode.getChild("adyacencias");
        List<Element> ad = adyacencias.getChildren("adyacencia");
        for (Element hijo : ad) {
            int vIni = Integer.parseInt(hijo.getChildTextTrim("nodo-inicial"));
            int vFinal = Integer.parseInt(hijo.getChildTextTrim("nodo-final"));
            GraphicNode nIni = g.getVertice(vIni);
            GraphicNode nFin = g.getVertice(vFinal);

            g.adyacencia(nIni, nFin);

        }
        //            System.out.println("Hay " + hijos.size()+ " adyacencias");
    } catch (JDOMException | IOException ex) {
        System.out.println(ex.getMessage());
    }
    return g;
}

From source file:com.ohnosequences.xml.model.go.GoTermXML.java

License:Open Source License

public static GoTermXML getGoTerm(String id) throws Exception {

    GoTermXML temp = new GoTermXML();

    URL url = new URL(GO_TERM_SERVICE_URL + id);
    // Connect//from w  w w  .  ja v  a  2 s .  c  o  m
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    // Get data
    SAXBuilder saxBuilder = new SAXBuilder();
    Document doc = saxBuilder.build(urlConnection.getInputStream());

    Element termElement = doc.getRootElement().getChild("term");

    String idString, nameString, defString;
    idString = termElement.getChildText("id");
    nameString = termElement.getChildText("name");
    defString = termElement.getChild("def").getChildText("defstr");

    if (!id.equals(idString)) {
        throw new Exception(
                "El id proporcionado y el encontrado en el xml proporcionado por el servicio no son el mismo");
    } else {
        temp.setId(idString);
        temp.setGoName(nameString);
        temp.setDefinition(defString);
    }

    return temp;
}

From source file:com.rhythm.louie.server.LouieProperties.java

License:Apache License

public static void processProperties(URL configs, String contextGateway) throws Exception {
    loadInternals(); //this code organization is weird but it's from iterations of design

    if (contextGateway != null) {
        //Overrides a default set by internal properties
        Server.setDefaultGateway(contextGateway);
    }//from  w  ww  . jav a 2  s. c  o  m

    Document properties = loadDocument(configs);
    if (properties == null) {
        return;
    }

    Element louie = properties.getRootElement();

    //Check for alternate loading point 
    boolean resetRoot = false;
    for (Element elem : louie.getChildren()) {
        if (ALT_PATH.equalsIgnoreCase(elem.getName())) {
            String altPath = elem.getTextTrim();
            LoggerFactory.getLogger(LouieProperties.class).info("Loading Louie configs from alternate file: {}",
                    altPath);
            //overwrite document with values from alternate config 
            properties = loadDocument(new File(altPath).toURI().toURL());
            if (properties == null)
                return;
            resetRoot = true;
        }
    }
    if (resetRoot) {
        //reset root to new properties obj root
        louie = properties.getRootElement();
    }

    Element groups = louie.getChild(GROUPS);
    if (groups != null) {
        AccessManager.loadGroups(groups);
    }

    boolean serversConfigured = false;
    for (Element elem : louie.getChildren()) {
        String elemName = elem.getName().toLowerCase();

        if (null != elemName)
            switch (elemName) {
            case ALT_PATH:
                LoggerFactory.getLogger(LouieProperties.class)
                        .warn("Extra config_path alternate loading point specified. "
                                + "Only one file-switch can be performed.\n"
                                + "  Please verify what is specified in the embedded xml file.\n"
                                + "  Found: {}", elem.getText());
                break;
            case SERVER_PARENT:
                processServers(elem);
                serversConfigured = true;
                break;
            case SERVICE_PARENT:
                processServices(elem, false);
                break;
            case MESSAGING:
                MessagingProperties.processMessaging(elem);
                break;
            case MAIL:
                MailProperties.processProperties(elem);
                break;
            case SCHEDULER:
                TaskSchedulerProperties.processProperties(elem);
                break;
            case ALERTS:
                AlertProperties.processProperties(elem);
                break;
            case CUSTOM:
                processCustomProperties(elem);
                break;
            case GROUPS:
                break;
            default:
                LoggerFactory.getLogger(LouieProperties.class).warn("Unexpected top level property  {}",
                        elemName);
                break;
            }
    }
    if (!serversConfigured)
        processServers(null); //ugly bootstrapping workflow
}

From source file:com.rhythm.louie.server.LouieProperties.java

License:Apache License

private static void loadInternals() throws JDOMException, IOException {
    Document internals;
    SAXBuilder docBuilder = new SAXBuilder();

    URL xmlURL = LouieProperties.class.getResource("/config/louie-internal.xml");
    internals = docBuilder.build(xmlURL);

    Element louie = internals.getRootElement();

    //Load internal defaults into Server
    Element serverDef = louie.getChild("server_defaults");

    Server.setDefaultHost(serverDef.getChildText(HOST));
    Server.setDefaultGateway(serverDef.getChildText(GATEWAY));
    Server.setDefaultDisplay(serverDef.getChildText(DISPLAY));
    Server.setDefaultIP(serverDef.getChildText(IP));
    Server.setDefaultTimezone(serverDef.getChildText(TIMEZONE));
    Server.setDefaultLocation(serverDef.getChildText(LOCATION));
    Server.setDefaultPort(Integer.parseInt(serverDef.getChildText(PORT)));
    Server.setDefaultSecure(Boolean.parseBoolean(serverDef.getChildText(SECURE)));

    //Load internal defaults into ServiceProperties
    Element serviceDef = louie.getChild("service_defaults");

    ServiceProperties.setDefaultCaching(Boolean.parseBoolean(serviceDef.getChildText(CACHING)));
    ServiceProperties.setDefaultEnable(Boolean.parseBoolean(serviceDef.getChildText(ENABLE)));
    ServiceProperties.setDefaultReadOnly(Boolean.parseBoolean(serviceDef.getChildText(READ_ONLY)));

    //Load internal services into ServiceProperties
    Element coreServices = louie.getChild("core_services");
    processServices(coreServices, true);

    Element schedDef = louie.getChild("scheduler_defaults");
    TaskSchedulerProperties.setThreadPoolSize(Integer.parseInt(schedDef.getChildText(POOL_SIZE)));

    Element accessDef = louie.getChild("group_defaults");
    AccessManager.loadGroups(accessDef);

}

From source file:com.rometools.modules.mediarss.io.RSS20YahooParser.java

License:Open Source License

/**
 * Indicates if a JDom document is an RSS instance that can be parsed with the parser.
 * <p/>//from  www. ja  va  2  s . c  om
 * It checks for RDF ("http://www.w3.org/1999/02/22-rdf-syntax-ns#") and RSS
 * ("http://purl.org/rss/1.0/") namespaces being defined in the root element.
 *
 * @param document document to check if it can be parsed with this parser implementation.
 * @return <b>true</b> if the document is RSS1., <b>false</b> otherwise.
 */
@Override
public boolean isMyType(final Document document) {
    boolean ok = false;

    final Element rssRoot = document.getRootElement();
    final Namespace defaultNS = rssRoot.getNamespace();

    ok = defaultNS != null && defaultNS.equals(getRSSNamespace());

    return ok;
}

From source file:com.rometools.opml.io.impl.OPML10Parser.java

License:Apache License

/**
 * Inspects an XML Document (JDOM) to check if it can parse it.
 * <p>/*from   www.  j  a  v a 2 s .c  o  m*/
 * It checks if the given document if the type of feeds the parser understands.
 * <p>
 *
 * @param document XML Document (JDOM) to check if it can be parsed by this parser.
 * @return <b>true</b> if the parser know how to parser this feed, <b>false</b> otherwise.
 */
@Override
public boolean isMyType(final Document document) {
    final Element e = document.getRootElement();

    if (e.getName().equals("opml")
            && (e.getChild("head") == null || e.getChild("head").getChild("docs") == null)
            && (e.getAttributeValue("version") == null || e.getAttributeValue("version").equals("1.0"))) {
        return true;
    }

    return false;
}

From source file:com.rometools.opml.io.impl.OPML10Parser.java

License:Apache License

/**
 * Parses an XML document (JDOM Document) into a feed bean.
 * <p>/*from   w  ww.  ja va2  s  .  co m*/
 *
 * @param document XML document (JDOM) to parse.
 * @param validate indicates if the feed should be strictly validated (NOT YET IMPLEMENTED).
 * @return the resulting feed bean.
 * @throws IllegalArgumentException thrown if the parser cannot handle the given feed type.
 * @throws FeedException thrown if a feed bean cannot be created out of the XML document (JDOM).
 */
@Override
public WireFeed parse(final Document document, final boolean validate, final Locale locale)
        throws IllegalArgumentException, FeedException {
    final Opml opml = new Opml();
    opml.setFeedType("opml_1.0");

    final Element root = document.getRootElement();
    final Element head = root.getChild("head");

    if (head != null) {
        opml.setTitle(head.getChildText("title"));

        if (head.getChildText("dateCreated") != null) {
            opml.setCreated(DateParser.parseRFC822(head.getChildText("dateCreated"), Locale.US));
        }

        if (head.getChildText("dateModified") != null) {
            opml.setModified(DateParser.parseRFC822(head.getChildText("dateModified"), Locale.US));
        }

        opml.setOwnerName(head.getChildTextTrim("ownerName"));
        opml.setOwnerEmail(head.getChildTextTrim("ownerEmail"));
        opml.setVerticalScrollState(readInteger(head.getChildText("vertScrollState")));

        try {
            opml.setWindowBottom(readInteger(head.getChildText("windowBottom")));
        } catch (final NumberFormatException nfe) {
            LOG.warn("Unable to parse windowBottom", nfe);
            if (validate) {
                throw new FeedException("Unable to parse windowBottom", nfe);
            }
        }

        try {
            opml.setWindowLeft(readInteger(head.getChildText("windowLeft")));
        } catch (final NumberFormatException nfe) {
            LOG.warn("Unable to parse windowLeft", nfe);
            if (validate) {
                throw new FeedException("Unable to parse windowLeft", nfe);
            }
        }

        try {
            opml.setWindowRight(readInteger(head.getChildText("windowRight")));
        } catch (final NumberFormatException nfe) {
            LOG.warn("Unable to parse windowRight", nfe);
            if (validate) {
                throw new FeedException("Unable to parse windowRight", nfe);
            }
        }

        try {
            opml.setWindowLeft(readInteger(head.getChildText("windowLeft")));
        } catch (final NumberFormatException nfe) {
            LOG.warn("Unable to parse windowLeft", nfe);
            if (validate) {
                throw new FeedException("Unable to parse windowLeft", nfe);
            }
        }

        try {
            opml.setWindowTop(readInteger(head.getChildText("windowTop")));
        } catch (final NumberFormatException nfe) {
            LOG.warn("Unable to parse windowTop", nfe);
            if (validate) {
                throw new FeedException("Unable to parse windowTop", nfe);
            }
        }

        try {
            opml.setExpansionState(readIntArray(head.getChildText("expansionState")));
        } catch (final NumberFormatException nfe) {
            LOG.warn("Unable to parse expansionState", nfe);
            if (validate) {
                throw new FeedException("Unable to parse expansionState", nfe);
            }
        }
    }

    opml.setOutlines(parseOutlines(root.getChild("body").getChildren("outline"), validate, locale));
    opml.setModules(parseFeedModules(root, locale));

    return opml;
}

From source file:com.rometools.opml.io.impl.OPML20Generator.java

License:Apache License

/**
 * Creates an XML document (JDOM) for the given feed bean.
 *
 * @param feed the feed bean to generate the XML document from.
 * @return the generated XML document (JDOM).
 * @throws IllegalArgumentException thrown if the type of the given feed bean does not match with the type of the
 *             WireFeedGenerator./*  w ww  . ja v a2 s . c  o m*/
 * @throws FeedException thrown if the XML Document could not be created.
 */
@Override
public Document generate(final WireFeed feed) throws IllegalArgumentException, FeedException {
    final Document document = super.generate(feed);
    document.getRootElement().setAttribute("version", "2.0");
    return document;
}