Example usage for org.jdom2 Attribute Attribute

List of usage examples for org.jdom2 Attribute Attribute

Introduction

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

Prototype

@Deprecated
public Attribute(final String name, final String value, final int type) 

Source Link

Document

This will create a new Attribute with the specified (local) name, value and type, and does not place the attribute in a Namespace .

Usage

From source file:AL_gui.java

License:Apache License

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    // TODO add your handling code here:
    try {//from w ww  .  ja  va 2  s .  c om
        String nnetName = JOptionPane.showInputDialog(jButton3, "Enter a filename, excluding extention.",
                "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
        if (nnetName == " ") {
            JOptionPane.showMessageDialog(null, "An input value must be entered.");
        }

        Element nnet = new Element("NNETWORK");
        nnet.setAttribute(new Attribute("noNamespaceSchemaLocation", "ANNeML.xsd",
                Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance")));
        nnet.setAttribute(new Attribute("NNET_NAME", nnetName));
        Document doc = new Document(nnet);

        String subnnets = JOptionPane.showInputDialog(jButton3, "How many SUBNET(s)?", "ANNeML Wizard",
                JOptionPane.QUESTION_MESSAGE);
        if (subnnets == " ") {
            JOptionPane.showMessageDialog(null, "An input value must be entered.");
        }
        int numSubs = java.lang.Integer.parseInt(subnnets);
        int i = 0;
        do {
            Element subnet = new Element("SUBNET");
            String learningRate = JOptionPane.showInputDialog(jButton3, "SUBNET learning rate(eta)?",
                    "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
            if (learningRate == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            subnet.setAttribute(new Attribute("NNET_V2", learningRate));
            subnet.setAttribute(new Attribute("SNET_NAME", nnetName + "-subnet" + String.valueOf(i + 1)));
            subnet.setAttribute(new Attribute("ADJUST_LOCK", "0"));

            String input_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<INPUT>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (input_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numInLayers = java.lang.Integer.parseInt(input_layers);
            int x = 0;
            do {
                Element inLayer = new Element("LAYER");
                inLayer.setAttribute(new Attribute("LAYER_NAME", "INPUT"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                inLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String inNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<INPUT>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (inNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numInNodes = java.lang.Integer.parseInt(inNodes);
                int y = 0;
                do {
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "IN" + String.valueOf(x + 1) + String.valueOf(y + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", "0.0"));
                    node.setAttribute(new Attribute("CNAME", "Input node#" + String.valueOf(y + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    Element inSynapse = new Element("SYNAPSE");
                    inSynapse.setAttribute(new Attribute("WEIGHT", "1.00"));
                    inSynapse.setAttribute(new Attribute("ORG_NEURODE", "INPUT"));
                    node.addContent(inSynapse);
                    inLayer.addContent(node);
                    y++;
                } while (y < numInNodes);
                subnet.addContent(inLayer);
                x++;
            } while (x < numInLayers);

            String hidden_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<HIDDEN>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (hidden_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numHLayers = java.lang.Integer.parseInt(hidden_layers);
            int z = 0;
            do {
                Element hLayer = new Element("LAYER");
                hLayer.setAttribute(new Attribute("LAYER_NAME", "HIDDEN"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                hLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String hNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<HIDDEN>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (hNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numhNodes = java.lang.Integer.parseInt(hNodes);
                int a = 0;
                do {
                    Random rnd = new Random();
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "N" + String.valueOf(z + 1) + String.valueOf(a + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", getRandomValue(rnd, low, high, decpl)));
                    node.setAttribute(new Attribute("CNAME", "Hidden node#" + String.valueOf(a + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    hLayer.addContent(node);
                    a++;
                } while (a < numhNodes);
                subnet.addContent(hLayer);
                z++;
            } while (z < numHLayers);

            String output_layers = JOptionPane.showInputDialog(jButton3,
                    "How many <<OUTPUT>> LAYERS(s) in this subnet?", "ANNeML Wizard",
                    JOptionPane.QUESTION_MESSAGE);
            if (hidden_layers == " ") {
                JOptionPane.showMessageDialog(null, "An input value must be entered.");
            }
            int numOLayers = java.lang.Integer.parseInt(output_layers);
            int b = 0;
            do {
                Element oLayer = new Element("LAYER");
                oLayer.setAttribute(new Attribute("LAYER_NAME", "OUTPUT"));
                String transferFunc = JOptionPane.showInputDialog(jButton3,
                        "Which transfer function for this LAYER? 1(hyberbolic tangent) or 2(logarithmic sigmoid)",
                        "ANNeML Wizard", JOptionPane.QUESTION_MESSAGE);
                if (transferFunc == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                oLayer.setAttribute(new Attribute("TRANSFER_FUNCTION", transferFunc));
                String oNodes = JOptionPane.showInputDialog(jButton3,
                        "How many NEURODE(s) in this <<OUTPUT>> LAYER?", "ANNeML Wizard",
                        JOptionPane.QUESTION_MESSAGE);
                if (oNodes == " ") {
                    JOptionPane.showMessageDialog(null, "An input value must be entered.");
                }
                int numoNodes = java.lang.Integer.parseInt(oNodes);
                int d = 0;
                do {
                    Random rnd = new Random();
                    Element node = new Element("NEURODE");
                    node.setAttribute(
                            new Attribute("N_ID", "ON" + String.valueOf(b + 1) + String.valueOf(d + 1)));
                    node.setAttribute(new Attribute("ACTIVE", "-1"));
                    node.setAttribute(new Attribute("ACTIVITY", "0.0"));
                    node.setAttribute(new Attribute("BIAS", getRandomValue(rnd, low, high, decpl)));
                    node.setAttribute(new Attribute("CNAME", "Output node#" + String.valueOf(d + 1)));
                    node.setAttribute(new Attribute("NNET_V4", "0.0"));
                    oLayer.addContent(node);
                    d++;
                } while (d < numoNodes);
                subnet.addContent(oLayer);
                b++;
            } while (b < numOLayers);

            doc.getRootElement().addContent(subnet);
            i++;
        } while (i < numSubs);

        //generate fully interconnected SYNAPSE(s) for all NEURODE(s) within each SUBNET

        java.util.List subnets = XPath.newInstance("//SUBNET").selectNodes(doc);
        Iterator itSubslist = subnets.iterator();
        do {
            Element currentSnet = (Element) itSubslist.next();
            String snetName = currentSnet.getAttributeValue("SNET_NAME");
            //System.out.println(snetName);

            java.util.List Hnodes = XPath
                    .newInstance("//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                    .selectNodes(doc);
            Iterator itHNodelist = Hnodes.iterator();
            do {
                Element node = (Element) itHNodelist.next();
                //System.out.println(node.getAttributeValue("N_ID"));
                java.util.List Inodes = XPath
                        .newInstance(
                                "//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='INPUT']/NEURODE")
                        .selectNodes(doc);
                Iterator itNodelist = Inodes.iterator();
                do {
                    Element currentNode = (Element) itNodelist.next();
                    //System.out.println(currentNode.getAttributeValue("N_ID"));
                    Element hSynapse = new Element("SYNAPSE");
                    Random rnd = new Random();
                    hSynapse.setAttribute(new Attribute("WEIGHT", getRandomValue(rnd, low, high, decpl)));
                    hSynapse.setAttribute(new Attribute("ORG_NEURODE", currentNode.getAttributeValue("N_ID")));
                    node.addContent(hSynapse);
                } while (itNodelist.hasNext());
            } while (itHNodelist.hasNext());

            java.util.List Onodes = XPath
                    .newInstance("//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='OUTPUT']/NEURODE")
                    .selectNodes(doc);
            Iterator itONodelist = Onodes.iterator();
            do {
                Element node = (Element) itONodelist.next();
                //System.out.println(node.getAttributeValue("N_ID"));
                java.util.List hnodes = XPath
                        .newInstance(
                                "//SUBNET[@SNET_NAME='" + snetName + "']/LAYER[@LAYER_NAME='HIDDEN']/NEURODE")
                        .selectNodes(doc);
                Iterator itNodelist = hnodes.iterator();
                do {
                    Element currentNode = (Element) itNodelist.next();
                    //System.out.println(currentNode.getAttributeValue("N_ID"));
                    Element hSynapse = new Element("SYNAPSE");
                    Random rnd = new Random();
                    hSynapse.setAttribute(new Attribute("WEIGHT", getRandomValue(rnd, low, high, decpl)));
                    hSynapse.setAttribute(new Attribute("ORG_NEURODE", currentNode.getAttributeValue("N_ID")));
                    node.addContent(hSynapse);
                } while (itNodelist.hasNext());
            } while (itONodelist.hasNext());

        } while (itSubslist.hasNext());

        // new XMLOutputter().output(doc, System.out);
        XMLOutputter xmlOutput = new XMLOutputter();

        // display nice nice
        xmlOutput.setFormat(Format.getPrettyFormat());
        xmlOutput.output(doc, System.out);
        xmlOutput.output(doc, new FileWriter(nnetName + ".xml"));

        System.out.println("File Saved!");

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}

From source file:by.epam.lw05.xml.ListToXml.java

private static Document listToDocument(List<Gun> guns) {
    Element root = new Element("arsenal", "tns", "http://www.example.com/Tarifes");
    root.addNamespaceDeclaration(Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    Attribute attr = new Attribute("schemaLocation", "http://www.example.com/Tarifes myschema.xsd",
            Namespace.getNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"));
    root.setAttribute(attr);/*from  ww  w.  j  ava  2  s. c  o m*/
    for (Gun gun : guns) {
        Element combatUnit = new Element("combatunit");

        combatUnit.setAttribute("serial", String.valueOf(gun.getSerial()));

        Element model = new Element("model");
        model.setText(gun.getModel());
        combatUnit.addContent(model);

        Element handy = new Element("handy");
        handy.setText(gun.getHandy());
        combatUnit.addContent(handy);

        Element origin = new Element("origin");
        origin.setText(String.valueOf(gun.getOrigin()));
        combatUnit.addContent(origin);

        Element ttx = new Element("ttx");

        Element distance = new Element("distance");
        distance.setText(String.valueOf(gun.getDistance()));
        ttx.addContent(distance);

        Element optics = new Element("optics");
        optics.setText(String.valueOf(gun.isOptics()));
        ttx.addContent(optics);
        combatUnit.addContent(ttx);

        root.addContent(combatUnit);
    }
    return new Document(root);
}

From source file:ca.nrc.cadc.vos.NodeWriter.java

License:Open Source License

/**
 * Build the properties Element of a Node.
 *
 * @param node Node.// w w  w .j a  v  a2 s .c o  m
 * @return properties Element.
 */
protected Element getPropertiesElement(Node node) {
    Element ret = new Element("properties", vosNamespace);
    for (NodeProperty nodeProperty : node.getProperties()) {
        Element property = new Element("property", vosNamespace);
        if (nodeProperty.isMarkedForDeletion())
            property.setAttribute(new Attribute("nil", "true", xsiNamespace));
        else
            property.setText(nodeProperty.getPropertyValue());
        property.setAttribute("uri", nodeProperty.getPropertyURI());
        property.setAttribute("readOnly", (nodeProperty.isReadOnly() ? "true" : "false"));
        ret.addContent(property);
    }
    return ret;
}

From source file:ca.nrc.cadc.vosi.Capability.java

License:Open Source License

public Element toXmlElement(Namespace xsi, Namespace cap, Namespace vor) {
    Element eleCapability = new Element("capability");
    eleCapability.setAttribute("standardID", _standardID);

    Element eleInterface = new Element("interface");
    eleCapability.addContent(eleInterface);

    Attribute attType = new Attribute("type", vor.getPrefix() + ":ParamHTTP", xsi);
    eleInterface.setAttribute(attType);//from   w  w  w .j  a v  a  2  s .  co m
    if (_role != null)
        eleInterface.setAttribute("role", _role);

    Element eleAccessURL = new Element("accessURL");
    eleInterface.addContent(eleAccessURL);

    eleAccessURL.setAttribute("use", "full");
    eleAccessURL.setText(_hostContext + _resourceName);

    return eleCapability;
}

From source file:ca.nrc.cadc.vosi.TableSet.java

License:Open Source License

/**
 * @param cd//from w  w  w  .  j a v  a2 s. co  m
 * @return
 */
private Element toXmlElement(ColumnDesc cd) {
    Element eleColumn = new Element("column");
    addChild(eleColumn, "name", cd.getColumnName());
    addChild(eleColumn, "description", cd.description);
    addChild(eleColumn, "unit", cd.unit);
    addChild(eleColumn, "ucd", cd.ucd);
    addChild(eleColumn, "utype", cd.utype);

    String datatype = cd.getDatatype();
    String[] parts = datatype.split(":");
    if (isTapType(parts)) {
        Element eleDt = addChild(eleColumn, "dataType", parts[1]);
        if (eleDt != null) {
            Attribute attType = new Attribute("type", vod.getPrefix() + ":TAPType", xsi);
            eleDt.setAttribute(attType);
            if (cd.getArraysize() != null && cd.getArraysize() > 0)
                eleDt.setAttribute("size", cd.getArraysize().toString());
        }
    } else if (isVOTableType(parts)) {
        Element eleDt = addChild(eleColumn, "dataType", parts[1]);
        if (eleDt != null) {
            Attribute attType = new Attribute("type", vod.getPrefix() + ":VOTableType", xsi);
            eleDt.setAttribute(attType);
            if (cd.getArraysize() != null && cd.getArraysize() > 0)
                eleDt.setAttribute("arraysize", cd.getArraysize().toString());
        }
    } else // custom type
    {
        log.warn("cannot convert " + cd + " to a legal VODataService column element, skipping");
        return null;
    }
    if (cd.indexed)
        addChild(eleColumn, "flag", "indexed");
    // TODO: flag=primary for primary keys? 

    return eleColumn;
}

From source file:com.c4om.autoconf.ulysses.extra.svinchangesetgenerator.SVINChangesetGenerator.java

License:Apache License

/**
 * This method generates a changeset document, which describes what nodes
 * must be added and replaced. It generates it from the SVRLInterpreter
 * report passed at constructor./*from   ww w. j ava  2  s  . c  o  m*/
 * 
 * @param pathToConfiguration path to the runtime configuration.
 * 
 * @param reportDocument the report document (objective solution description).
 * 
 * @return The generated changeset document.
 * 
 * @throws JDOMException
 *             If there are problems at JDOM2 XML parsings
 * @throws IOException
 *             I/O problems
 * @throws SaxonApiException
 *             problems with Saxon API while transforming metamodel
 *             suggestions into partial autocomplete nodes
 * @throws ParserConfigurationException
 *             problems with javax.xml APIs while transforming metamodel
 *             suggestions into partial autocomplete nodes
 */
public Document getSingleChangesetDocument(String pathToConfiguration, Document reportDocument)
        throws JDOMException, IOException, SaxonApiException, ParserConfigurationException {
    Element resultRoot = new Element("changeset", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
    resultRoot.addNamespaceDeclaration(NAMESPACE_AUTOCONF_METADATA); // To
    // prevent
    // several
    // "xmlns:*****"
    // attributes
    // to
    // appear
    // everywhere
    Document result = new Document(resultRoot);
    Element reportElement = reportDocument.getRootElement();
    for (Element currentDiscrepancyElement : reportElement.getChildren()) {
        boolean isCreate = false;
        Element interestingPathsElement = currentDiscrepancyElement.getChild("interestingPaths",
                NAMESPACE_SVRL_INTERPETER_REPORT);
        String searchPathText = interestingPathsElement.getAttributeValue("search-path");
        String basePathText = interestingPathsElement.getAttributeValue("base-path");
        String keySubpathText = interestingPathsElement.getAttributeValue("key-subpath");
        // First, we look for a path to search the element where discrepancy
        // took place (if it exists)
        String[] docAndPath;
        String searchPathInternal;
        if (searchPathText == null) {
            docAndPath = divideDocAndPath(basePathText);
            searchPathInternal = docAndPath[1] + "[" + keySubpathText + "]";
        } else {
            docAndPath = divideDocAndPath(searchPathText);
            searchPathInternal = docAndPath[1];
        }
        if (!documentCache.containsKey(docAndPath[0])) {
            documentCache.put(docAndPath[0],
                    loadJDOMDocumentFromFile(new File(pathToConfiguration + "/" + docAndPath[0])));
        }
        Document currentDoc = documentCache.get(docAndPath[0]);
        List<Element> discordingElementAtDocList = performJAXENXPath(searchPathInternal, currentDoc,
                Filters.element(), xpathNamespaces);
        if (discordingElementAtDocList.size() == 0) {
            isCreate = true;
        }
        if (isCreate) {
            Element nodeToCreate = currentDiscrepancyElement
                    .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                    .clone();
            //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it.
            nodeToCreate.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT);
            boolean thereAreMetamodelSuggestions = currentDiscrepancyElement
                    .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren()
                    .size() > 0;
            if (thereAreMetamodelSuggestions) {
                Element metamodelSuggestionUntransformed = currentDiscrepancyElement
                        .getChild("metamodelSuggestions", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                        .clone();
                Document suggestionMiniDocument = new Document(metamodelSuggestionUntransformed);
                Document suggestionMiniDocumentTransformed = performXSLT(suggestionMiniDocument,
                        xsltTransformMetamodelDocument);
                Element metamodelSuggestion = suggestionMiniDocumentTransformed.getRootElement();
                Attribute metadataAttribute = new Attribute("autogen-from", "metamodel",
                        NAMESPACE_AUTOCONF_METADATA);
                mixTreesRecursive(metamodelSuggestion, nodeToCreate, metadataAttribute,
                        NAMESPACE_AUTOCONF_METADATA.getURI());
            } else {
                Attribute mayNeedManualCompletion = new Attribute("may-need-completion", "true",
                        NAMESPACE_AUTOCONF_METADATA);
                nodeToCreate.setAttribute(mayNeedManualCompletion);
            }
            Element createNodeElement = new Element("add-node", AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
            final String REGEXP_TO_GET_PARENT_PATH = "(.+)(/[^\\[\\]/]+(\\[.+\\])?)$";
            Pattern patternToGetParentPath = Pattern.compile(REGEXP_TO_GET_PARENT_PATH);
            Matcher matcherToGetParentPath = patternToGetParentPath.matcher(searchPathInternal);
            matcherToGetParentPath.matches();
            String pathToParent = matcherToGetParentPath.group(1);
            Attribute pathToParentAttr = new Attribute("underParentAtPath", pathToParent);
            Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]);
            createNodeElement.setAttribute(documentToChangeAttr);
            createNodeElement.setAttribute(pathToParentAttr);
            createNodeElement.addContent(nodeToCreate);
            resultRoot.addContent(createNodeElement);

        } else {
            for (int i = 0; i < discordingElementAtDocList.size(); i++) {
                Element nodeToModify = currentDiscrepancyElement
                        .getChild("suggestedPartialNode", NAMESPACE_SVRL_INTERPETER_REPORT).getChildren().get(0)
                        .clone();
                //Sometimes, svinrep namespace is declared here (it is not clear why). We must remove it.
                nodeToModify.removeNamespaceDeclaration(NAMESPACE_SVRL_INTERPETER_REPORT);
                Element discordingElementAtDoc = discordingElementAtDocList.get(i);
                mixTreesRecursive(discordingElementAtDoc, nodeToModify, null,
                        NAMESPACE_AUTOCONF_METADATA.getURI());
                Element replaceNodeElement = new Element("replace-node",
                        AutoconfXMLConstants.NAMESPACE_SVINAPPLIER);
                Attribute pathToElementAttr = new Attribute("atPath",
                        generateAttributeBasedPath(discordingElementAtDoc));
                Attribute documentToChangeAttr = new Attribute("atResource", docAndPath[0]);
                replaceNodeElement.setAttribute(documentToChangeAttr);
                replaceNodeElement.setAttribute(pathToElementAttr);
                replaceNodeElement.addContent(nodeToModify);
                resultRoot.addContent(replaceNodeElement);
            }
        }
    }
    return result;
}

From source file:com.c4om.utils.xmlutils.JDOMUtils.java

License:Apache License

/**
 * This method converts a XPath attribute filter into an {@link Attribute} {@link List}. 
 * Count tokens are optional. However, if a count token is present, the number of attributes must match its count value.
 * @param filter the filter to convert (without initial '[' and final ']')
 * @param namespaces the {@link Namespace} objects with the uri-prefix mappings used at attributes
 * @return the list of attributes, as described
 * @throws IllegalArgumentException if one of the "and"-separated tokens is neither a count token nor an attribute token
 * @throws IndexOutOfBoundsException if the count token is present and does not match the number of attributes
 *///from   w w  w  . ja  v a 2  s. c  om
public static List<Attribute> generateAttributeListFromFilter(String filter, Collection<Namespace> namespaces) {
    String filterTrimmed = filter.trim();
    String[] attributeTokens = filterTrimmed.split(" +and +");
    List<Attribute> attributeList = new ArrayList<Attribute>(attributeTokens.length);
    Pattern attributeTokenPattern = Pattern.compile(REGEXP_ATTRIBUTES_FILTER_ATTRIBUTE_TOKEN);
    Pattern countTokenPattern = Pattern.compile(REGEXP_ATTRIBUTES_FILTER_COUNT_TOKEN);
    int knownCount = -1; //-1 means unknown
    for (int i = 0; i < attributeTokens.length; i++) {
        String currentToken = attributeTokens[i].trim();
        Matcher countMatcher = countTokenPattern.matcher(currentToken);
        if (countMatcher.matches()) {
            //It is a count token
            knownCount = Integer.parseInt(countMatcher.group("value"));
        } else {
            Matcher attributeMatcher = attributeTokenPattern.matcher(currentToken);
            if (!attributeMatcher.matches()) {
                throw new IllegalArgumentException("Invalid filter '" + filterTrimmed + "' since token '"
                        + currentToken + "' is neither a count token nor an attribute token.");
            }
            String attrName = attributeMatcher.group("name");
            String attrPref = attributeMatcher.group("pref");
            String attrValue = attributeMatcher.group("value");
            Namespace attrNamespace = solveNamespaceForPrefix(attrPref, namespaces);
            //Namespace not found
            if (attrNamespace == null) {
                throw new IllegalArgumentException("Namespace prefix '" + attrPref
                        + "' at path token is not defined at namespaces parameter.");
            }

            Attribute currentAttribute = new Attribute(attrName, attrValue, attrNamespace);
            attributeList.add(currentAttribute);
        }
    }
    if (knownCount >= 0 && attributeList.size() != knownCount) {
        throw new IndexOutOfBoundsException("Count value '" + knownCount
                + "' does not match attribute list size '" + attributeList.size() + "'");
    }
    return attributeList;
}

From source file:com.cybernostics.jsp2thymeleaf.api.elements.JspTagElementConverter.java

public JspTagElementConverter renamesAttribute(String oldName, String newName, Namespace namespace) {
    removesAttributes(oldName);/*from  w  w  w .  j  av  a2 s.  c om*/

    addsAttributes((currentValues) -> currentValues.containsKey(oldName)
            ? Arrays.asList(new Attribute(newName, currentValues.get(oldName).toString(), namespace))
            : ListUtils.EMPTY_LIST);
    return this;
}

From source file:com.cybernostics.jsp2thymeleaf.converters.jstl.core.CChooseJspConverter.java

public CChooseJspConverter() {
    super("choose", "block");
    removesAtributes("test");
    addsAttributes(/*  w  ww .j  a  va2  s. c  o  m*/
            (currentValues) -> Arrays.asList(new Attribute("if", currentValues.get("test"), thymeleafCN)));

}

From source file:com.rometools.modules.content.io.ContentModuleGenerator.java

License:Open Source License

@Override
public void generate(final com.rometools.rome.feed.module.Module module, final org.jdom2.Element element) {
    // this is not necessary, it is done to avoid the namespace definition in every item.
    Element root = element;//from   w w  w  .jav a2 s .  c  o  m

    while (root.getParent() != null && root.getParent() instanceof Element) {
        root = (Element) root.getParent();
    }

    root.addNamespaceDeclaration(CONTENT_NS);

    if (!(module instanceof ContentModule)) {
        return;
    }

    final ContentModule cm = (ContentModule) module;

    final List<String> encodeds = cm.getEncodeds();

    if (encodeds != null) {
        LOG.debug("{}", cm.getEncodeds().size());
        for (int i = 0; i < encodeds.size(); i++) {
            element.addContent(generateCDATAElement("encoded", encodeds.get(i).toString()));
        }
    }

    final List<ContentItem> contentItems = cm.getContentItems();

    if (contentItems != null && !contentItems.isEmpty()) {
        final Element items = new Element("items", CONTENT_NS);
        final Element bag = new Element("Bag", RDF_NS);
        items.addContent(bag);

        for (int i = 0; i < contentItems.size(); i++) {
            final ContentItem contentItem = contentItems.get(i);
            final Element li = new Element("li", RDF_NS);
            final Element item = new Element("item", CONTENT_NS);

            if (contentItem.getContentAbout() != null) {
                final Attribute about = new Attribute("about", contentItem.getContentAbout(), RDF_NS);
                item.setAttribute(about);
            }

            if (contentItem.getContentFormat() != null) {
                // LOG.debug( "Format");
                final Element format = new Element("format", CONTENT_NS);
                final Attribute formatResource = new Attribute("resource", contentItem.getContentFormat(),
                        RDF_NS);
                format.setAttribute(formatResource);

                item.addContent(format);
            }

            if (contentItem.getContentEncoding() != null) {
                // LOG.debug( "Encoding");
                final Element encoding = new Element("encoding", CONTENT_NS);
                final Attribute encodingResource = new Attribute("resource", contentItem.getContentEncoding(),
                        RDF_NS);
                encoding.setAttribute(encodingResource);
                item.addContent(encoding);
            }

            if (contentItem.getContentValue() != null) {
                final Element value = new Element("value", RDF_NS);

                if (contentItem.getContentValueParseType() != null) {
                    final Attribute parseType = new Attribute("parseType",
                            contentItem.getContentValueParseType(), RDF_NS);
                    value.setAttribute(parseType);
                }

                if (contentItem.getContentValueNamespaces() != null) {
                    final List<Namespace> namespaces = contentItem.getContentValueNamespaces();

                    for (int ni = 0; ni < namespaces.size(); ni++) {
                        value.addNamespaceDeclaration(namespaces.get(ni));
                    }
                }

                final List<Content> detached = new ArrayList<Content>();

                for (int c = 0; c < contentItem.getContentValueDOM().size(); c++) {
                    detached.add(contentItem.getContentValueDOM().get(c).clone().detach());
                }

                value.setContent(detached);
                item.addContent(value);
            } // end value

            li.addContent(item);
            bag.addContent(li);
        } // end contentItems loop

        element.addContent(items);
    }
}