Example usage for org.jdom2 Attribute getName

List of usage examples for org.jdom2 Attribute getName

Introduction

In this page you can find the example usage for org.jdom2 Attribute getName.

Prototype

public String getName() 

Source Link

Document

This will retrieve the local name of the Attribute.

Usage

From source file:ca.nrc.cadc.xml.JsonOutputter.java

License:Open Source License

private boolean writeAttributes(Element e, PrintWriter w, int i) throws IOException {
    boolean ret = writeSchemaAttributes(e, w, i);

    Iterator<Attribute> iter = e.getAttributes().iterator();
    if (ret && iter.hasNext())
        w.print(",");
    while (iter.hasNext()) {
        ret = true;//w  ww . j a  v a2 s  .  co  m
        Attribute a = iter.next();
        indent(w, i);
        w.print(QUOTE);
        w.print("@");
        if (StringUtil.hasText(a.getNamespacePrefix())) {
            w.print(a.getNamespacePrefix());
            w.print(":");
        }
        w.print(a.getName());
        w.print(QUOTE);
        w.print(" : ");
        if (isBoolean(e.getName(), a.getValue()) || isNumeric(e.getName(), a.getValue())) {
            w.print(a.getValue());
        } else {
            w.print(QUOTE);
            w.print(a.getValue());
            w.print(QUOTE);
        }
        if (iter.hasNext())
            w.print(",");
    }

    return ret;
}

From source file:cager.parser.test.SimpleTest2.java

License:Open Source License

private void XMLtoJavaParser() {

    // Creamos el builder basado en SAX  
    SAXBuilder builder = new SAXBuilder();

    try {//from w  w w.  java  2 s .c o  m

        String nombreMetodo = null;
        List<String> atributos = new ArrayList<String>();
        String tipoRetorno = null;
        String nombreArchivo = null;
        String exportValue = "";
        String codigoFuente = "";
        HashMap<String, String> tipos = new HashMap<String, String>();

        // Construimos el arbol DOM a partir del fichero xml  
        Document doc = builder.build(new FileInputStream(ruta + "VBParser\\ejemplosKDM\\archivo.kdm"));
        //Document doc = builder.build(new FileInputStream("E:\\WorkspaceParser\\VBParser\\ejemplosKDM\\archivo.kdm"));    

        Namespace xmi = Namespace.getNamespace("xmi", "http://www.omg.org/XMI");

        XPathExpression<Element> xpath = XPathFactory.instance().compile("//codeElement", Filters.element());

        List<Element> elements = xpath.evaluate(doc);

        for (Element emt : elements) {

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:CompilationUnit") == 0) {

                nombreArchivo = emt.getAttributeValue("name").substring(0,
                        emt.getAttributeValue("name").indexOf('.'));

            }

            if (emt.getAttribute("type", xmi).getValue().compareTo("code:LanguageUnit") == 0) {

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    tipos.put(hijo.getAttributeValue("id", xmi), hijo.getAttributeValue("name"));

                }

            }
        }

        FileOutputStream fout;

        fout = new FileOutputStream(ruta + "VBParser\\src\\cager\\parser\\test\\" + nombreArchivo + ".java");
        //fout = new FileOutputStream("E:\\WorkspaceParser\\VBParser\\src\\cager\\parser\\test\\"+nombreArchivo+".java");           
        // get the content in bytes
        byte[] contentInBytes = null;

        contentInBytes = ("package cager.parser.test;\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        contentInBytes = ("public class " + nombreArchivo + "{\n\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();

        for (Element emt : elements) {
            // System.out.println("XPath has result: " + emt.getName()+" "+emt.getAttribute("type",xmi));
            if (emt.getAttribute("type", xmi).getValue().compareTo("code:MethodUnit") == 0) {

                nombreMetodo = emt.getAttribute("name").getValue();

                if (emt.getAttribute("export") != null)
                    exportValue = emt.getAttribute("export").getValue();

                atributos = new ArrayList<String>();

                List<Element> hijos = emt.getChildren();

                for (Element hijo : hijos) {

                    if (hijo.getAttribute("type", xmi) != null) {

                        if (hijo.getAttribute("type", xmi).getValue().compareTo("code:Signature") == 0) {

                            List<Element> parametros = hijo.getChildren();

                            for (Element parametro : parametros) {

                                if (parametro.getAttribute("kind") == null
                                        || parametro.getAttribute("kind").getValue().compareTo("return") != 0) {
                                    atributos.add(tipos.get(parametro.getAttribute("type").getValue()) + " "
                                            + parametro.getAttributeValue("name"));
                                } else {
                                    tipoRetorno = tipos.get(parametro.getAttribute("type").getValue());
                                }

                            }

                        }
                    } else if (hijo.getAttribute("snippet") != null) {

                        codigoFuente = hijo.getAttribute("snippet").getValue();

                    }

                }

                //System.out.println("MethodUnit!! " + emt.getName()+" "+emt.getAttribute("type",xmi)+" "+emt.getAttribute("name").getValue());
                //System.out.println(emt.getAttribute("name").getValue());

                if (tipoRetorno.compareTo("Void") == 0) {
                    tipoRetorno = "void";
                }

                contentInBytes = ("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (")
                        .getBytes();

                fout.write(contentInBytes);
                fout.flush();
                int n = 0;
                for (String parametro : atributos) {

                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        contentInBytes = (" " + parametro + ",").getBytes();
                    } else {
                        contentInBytes = (" " + parametro).getBytes();
                    }

                    fout.write(contentInBytes);
                    fout.flush();
                    n++;
                }

                contentInBytes = (" ) {\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\n/* \n " + codigoFuente + " \n */\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                contentInBytes = ("\t}\n\n").getBytes();

                fout.write(contentInBytes);
                fout.flush();

                System.out.print("\t" + exportValue + " " + tipoRetorno + " " + nombreMetodo + " (");
                n = 0;
                for (String parametro : atributos) {
                    if (atributos.size() > 0 && n < atributos.size() - 1) {
                        System.out.print(" " + parametro + ", ");
                    } else {
                        System.out.print(" " + parametro);
                    }
                    n++;

                }
                System.out.println(" ) {");
                System.out.println("/* \n " + codigoFuente + " \n */");
                System.out.println("\t}\n");
            }

        }

        contentInBytes = ("}\n").getBytes();

        fout.write(contentInBytes);
        fout.flush();
        fout.close();

        XPathExpression<Attribute> xp = XPathFactory.instance().compile("//@*", Filters.attribute(xmi));
        for (Attribute a : xp.evaluate(doc)) {
            a.setName(a.getName().toLowerCase());
        }

        xpath = XPathFactory.instance().compile("//codeElement/@name='testvb.cls'", Filters.element());
        Element emt = xpath.evaluateFirst(doc);
        if (emt != null) {
            System.out.println("XPath has result: " + emt.getName());
        }

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JDOMException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.abyala.decisiontree.SimpleDecisionTreeParser.java

License:Open Source License

/**
 * Creates a result specification for this node. Does not create the actual result object,
 * since there's no guarantee that that object will be immutable.
 *//*w  ww.ja  v a2s  .co  m*/
private ResultNode parseResult(final Element element, final ResultSpec resultSpec)
        throws DecisionTreeParserException {
    final ResultNode.Builder builder = new ResultNode.Builder(resultSpec);
    for (final Attribute attribute : element.getAttributes()) {
        final String name = attribute.getName();
        final String value = attribute.getValue();
        builder.addAttribute(name, value);
    }

    return builder.build();
}

From source file:com.ardor3d.extension.model.collada.jdom.ColladaAnimUtils.java

License:Open Source License

@SuppressWarnings("unchecked")
private static void getElementString(final Element e, final StringBuilder str, final int depth,
        final int maxDepth, final boolean showDots) {
    addSpacing(str, depth);/*from w  w w  .  j  a va  2s  .  com*/
    str.append('<');
    str.append(e.getName());
    str.append(' ');
    final List<Attribute> attrs = e.getAttributes();
    for (int i = 0; i < attrs.size(); i++) {
        final Attribute attr = attrs.get(i);
        str.append(attr.getName());
        str.append("=\"");
        str.append(attr.getValue());
        str.append('"');
        if (i < attrs.size() - 1) {
            str.append(' ');
        }
    }
    if (!e.getChildren().isEmpty() || !"".equals(e.getText())) {
        str.append('>');
        if (depth < maxDepth) {
            str.append('\n');
            for (final Element child : (List<Element>) e.getChildren()) {
                getElementString(child, str, depth + 1, maxDepth, showDots);
            }
            if (!"".equals(e.getText())) {
                addSpacing(str, depth + 1);
                str.append(e.getText());
                str.append('\n');
            }
        } else if (showDots) {
            str.append('\n');
            addSpacing(str, depth + 1);
            str.append("...");
            str.append('\n');
        }
        addSpacing(str, depth);
        str.append("</");
        str.append(e.getName());
        str.append('>');
    } else {
        str.append("/>");
    }
    str.append('\n');
}

From source file:com.googlesource.gerrit.plugins.manifest.CustomOutputter.java

License:Apache License

@Override
protected void printAttribute(java.io.Writer out, FormatStack fstack, Attribute attribute)
        throws java.io.IOException {
    // Do not print attributes that use default values
    for (DTDAttribute dtdAttribute : dtdAttributes) {
        if (attribute.getName().equals(dtdAttribute.getAttributeName())
                && attribute.getParent().getName().equals(dtdAttribute.getElementName())
                && attribute.getAttributeType().toString().equals(dtdAttribute.getType())
                && attribute.getValue().equals(dtdAttribute.getValue())) {
            return;
        }//from   w ww . j  a  va 2  s . c  om
    }

    out.append(fstack.getLineSeparator());
    String indent = fstack.getIndent();
    out.append(fstack.getLevelIndent());
    out.append(indent);
    // super.printAttribute() indents with an extra space, this will offset that
    out.append(indent.substring(0, indent.length() - 1));
    super.printAttribute(out, fstack, attribute);
}

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.  j  a v a 2 s .  c om*/
        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.rhythm.louie.server.LouieProperties.java

License:Apache License

private static void processServers(Element servers) {
    List<Server> serverList = new ArrayList<>();

    if (servers == null) {
        List<Server> empty = Collections.emptyList();
        Server.processServers(empty);/*from   ww w.java 2s . c  om*/
        return;
    }

    for (Element server : servers.getChildren()) {
        if (!SERVER.equals(server.getName().toLowerCase()))
            continue;

        String name = null;
        for (Attribute attr : server.getAttributes()) {
            if (NAME.equals(attr.getName().toLowerCase()))
                name = attr.getValue();
        }
        if (name == null) {
            LoggerFactory.getLogger(LouieProperties.class)
                    .error("A server was missing it's 'name' attribute and will be skipped!");
            continue;
        }
        Server prop = new Server(name);

        for (Element serverProp : server.getChildren()) {
            String propName = serverProp.getName().toLowerCase();
            String propValue = serverProp.getTextTrim();
            if (null != propName)
                switch (propName) {
                case HOST:
                    prop.setHost(propValue);
                    break;
                case DISPLAY:
                    prop.setDisplay(propValue);
                    break;
                case LOCATION:
                    prop.setLocation(propValue);
                    break;
                case GATEWAY:
                    prop.setGateway(propValue);
                    break;
                case IP:
                    prop.setIp(propValue);
                    break;
                case EXTERNAL_IP:
                    prop.setExternalIp(propValue);
                    break;
                case CENTRAL_AUTH:
                    prop.setCentralAuth(Boolean.parseBoolean(propValue));
                    break;
                case PORT:
                    prop.setPort(Integer.parseInt(propValue));
                    break;
                case SECURE:
                    prop.setSecure(Boolean.parseBoolean(propValue));
                    break;
                case TIMEZONE:
                    prop.setTimezone(propValue);
                    break;
                case CUSTOM:
                    for (Element child : serverProp.getChildren()) {
                        prop.addCustomProperty(child.getName(), child.getTextTrim());
                    }
                    break;
                default:
                    LoggerFactory.getLogger(LouieProperties.class).warn("Unexpected server property  {}:{}",
                            propName, propValue);
                    break;
                }
        }
        serverList.add(prop);
    }
    Server.processServers(serverList);
}

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

License:Apache License

private static void processServices(Element services, boolean internal) {
    if (services == null)
        return;/*from ww  w  .  j  av  a2 s  . c o m*/

    for (Element elem : services.getChildren()) {
        if (DEFAULT.equalsIgnoreCase(elem.getName())) {
            processServiceDefaults(elem);
            break;
        }
    }

    List<ServiceProperties> servicesList = new ArrayList<>();
    for (Element service : services.getChildren()) {
        String elementName = service.getName();
        if (!SERVICE.equalsIgnoreCase(elementName)) {
            if (!DEFAULT.equalsIgnoreCase(elementName)) {
                LoggerFactory.getLogger(LouieProperties.class).warn("Unknown {} element: {}", SERVICE_PARENT,
                        elementName);
            }
            continue;
        }

        String serviceName = null;
        Boolean enable = null;
        for (Attribute attr : service.getAttributes()) {
            String propName = attr.getName().toLowerCase();
            String propValue = attr.getValue();
            if (null != propName)
                switch (propName) {
                case NAME:
                    serviceName = propValue;
                    break;
                case ENABLE:
                    enable = Boolean.valueOf(propValue);
                    break;
                default:
                    LoggerFactory.getLogger(LouieProperties.class).warn("Unexpected service attribute {}:{}",
                            propName, propValue);
                    break;
                }
        }

        if (serviceName == null) {
            LoggerFactory.getLogger(LouieProperties.class)
                    .error("A service was missing it's 'name' attribute and will be skipped");
            continue;
        }

        ServiceProperties prop = new ServiceProperties(serviceName);
        if (enable != null) {
            prop.setEnable(enable);
        }

        for (Element serviceProp : service.getChildren()) {
            String propName = serviceProp.getName().toLowerCase();
            String propValue = serviceProp.getTextTrim();
            if (null != propName)
                switch (propName) {
                case CACHING:
                    prop.setCaching(Boolean.valueOf(propValue));
                    break;
                case READ_ONLY:
                    prop.setReadOnly(Boolean.valueOf(propValue));
                    break;
                case PROVIDER_CL:
                    prop.setProviderClass(propValue);
                    break;
                case RESPECTED_GROUPS:
                    AccessManager.loadServiceAccess(serviceName, serviceProp);
                    break;
                case RESERVED:
                    if (internal)
                        prop.setReserved(Boolean.valueOf(propValue));
                    break;
                case LAYERS:
                    processServiceLayers(serviceProp, prop);
                    break;
                case CUSTOM:
                    for (Element child : serviceProp.getChildren()) {
                        prop.addCustomProp(child.getName(), child.getTextTrim());
                    }
                    break;
                default:
                    LoggerFactory.getLogger(LouieProperties.class).warn("Unexpected server property  {}:{}",
                            propName, propValue);
                }
        }
        servicesList.add(prop);
    }
    ServiceProperties.processServices(servicesList);
}

From source file:com.swordlord.gozer.builder.Parser.java

License:Open Source License

@SuppressWarnings("unchecked")
private void parseElement(Element element, ObjectBase parent) {
    if (!_objectTags.containsKey(element.getName())) {
        String msg = MessageFormat.format("Element {0} unknown, parsing aborted.", element.getName());
        LOG.error(msg);/* ww  w.j ava2s . c  o  m*/
        return;
    }

    ObjectBase ob = instantiateClass(_objectTags.get(element.getName()));
    if (ob == null) {
        String msg = MessageFormat.format("Class for {0} could not be instantiated, parsing aborted.", element);
        LOG.error(msg);
        return;
    }

    if (element.getText() != null) {
        ob.setContent(element.getText());
    }
    List attributes = element.getAttributes();
    Iterator itAttributes = attributes.iterator();
    while (itAttributes.hasNext()) {
        Attribute attr = (Attribute) itAttributes.next();

        ob.putAttribute(attr.getName(), attr.getValue());
    }

    if (parent != null) {
        ob.inheritParent(parent);
        parent.putChild(ob);
    } else {
        _objectTree.setRoot(ob);
    }

    List children = element.getChildren();
    Iterator itChildren = children.iterator();
    while (itChildren.hasNext()) {
        parseElement((Element) itChildren.next(), ob);
    }
}

From source file:Contabilidad.CodeBase64.java

public void limpia(String ruta) {
    try {//  w  w w .j av a  2s  .  c  o m
        org.jdom2.Document doc = new SAXBuilder().build(ruta);
        Element rootNode = doc.getRootElement();
        List list = rootNode.getContent();
        for (int i = 0; i < list.size(); i++) {
            Content elementos = (Content) list.get(i);
            if (elementos.getCType() == Content.CType.Element) {
                Element aux = (Element) elementos;
                if (aux.getName().compareToIgnoreCase("Addenda") == 0) {
                    List list2 = aux.getContent();
                    for (int j = 0; j < list2.size(); j++) {
                        Content elementos2 = (Content) list2.get(j);
                        if (elementos2.getCType() == Content.CType.Element) {
                            Element aux2 = (Element) elementos2;
                            if (aux2.getName().compareToIgnoreCase("FactDocMX") == 0) {
                                list2.remove(aux2);
                            }
                            if (aux2.getName().compareToIgnoreCase("ECFD") == 0) {
                                Namespace NP = Namespace.getNamespace("", "");
                                aux2.setNamespace(NP);
                                List list3 = aux2.getContent();
                                for (int k = 0; k < list3.size(); k++) {
                                    Content elementos3 = (Content) list3.get(k);
                                    if (elementos3.getCType() == Content.CType.Element) {
                                        Element aux3 = (Element) elementos3;
                                        aux3.setNamespace(NP);
                                        List list4 = aux3.getContent();
                                        for (int l = 0; l < list4.size(); l++) {
                                            Content elementos4 = (Content) list4.get(l);
                                            if (elementos4.getCType() == Content.CType.Element) {
                                                Element aux4 = (Element) elementos4;
                                                aux4.setNamespace(NP);
                                                List list5 = aux4.getContent();
                                                for (int m = 0; m < list5.size(); m++) {
                                                    Content elementos5 = (Content) list5.get(m);
                                                    if (elementos5.getCType() == Content.CType.Element) {
                                                        Element aux5 = (Element) elementos5;
                                                        aux5.setNamespace(NP);
                                                        List list6 = aux5.getContent();
                                                        for (int n = 0; n < list6.size(); n++) {
                                                            Content elementos6 = (Content) list6.get(n);
                                                            if (elementos6
                                                                    .getCType() == Content.CType.Element) {
                                                                Element aux6 = (Element) elementos6;
                                                                aux6.setNamespace(NP);
                                                                List list7 = aux6.getContent();
                                                                for (int p = 0; p < list7.size(); p++) {
                                                                    Content elementos7 = (Content) list7.get(p);
                                                                    if (elementos7
                                                                            .getCType() == Content.CType.Element) {
                                                                        Element aux7 = (Element) elementos7;
                                                                        aux7.setNamespace(NP);
                                                                        List list8 = aux7.getContent();
                                                                        for (int q = 0; q < list8.size(); q++) {
                                                                            Content elementos8 = (Content) list8
                                                                                    .get(q);
                                                                            if (elementos8
                                                                                    .getCType() == Content.CType.Element) {
                                                                                Element aux8 = (Element) elementos8;
                                                                                aux8.setNamespace(NP);
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                List atributos = aux2.getAttributes();
                                for (int a = 0; a < atributos.size(); a++) {
                                    Attribute at = (Attribute) atributos.get(a);
                                    if (at.getName().compareToIgnoreCase("schemaLocation") == 0)
                                        aux2.removeAttribute(at);
                                }
                            }
                        }
                    }
                }
            }
        }
        XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
        try {
            outputter.output(doc, new FileOutputStream(ruta));
        } catch (IOException e) {
            System.out.println(e);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}