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

public Attribute(final String name, final String value) 

Source Link

Document

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

Usage

From source file:ac.simons.syndication.modules.atom.AtomModuleGenerator.java

License:BSD License

private void addLinks(final Element parent, final AtomContent content) {
    for (final Link link : content.getLinks()) {
        final Element e = new Element("link", ATOM_NS);

        if (!isBlank(link.getRel())) {
            e.setAttribute(new Attribute("rel", link.getRel()));
        }//from   w ww .  j  a v a 2 s .  co  m
        if (!isBlank(link.getType())) {
            e.setAttribute(new Attribute("type", link.getType()));
        }
        if (!isBlank(link.getHref())) {
            e.setAttribute(new Attribute("href", link.getHref()));
        }
        if (!isBlank(link.getHreflang())) {
            e.setAttribute(new Attribute("hreflang", link.getHreflang()));
        }
        if (!isBlank(link.getTitle())) {
            e.setAttribute(new Attribute("title", link.getTitle()));
        }
        if (link.getLength() != 0) {
            e.setAttribute(new Attribute("length", Long.toString(link.getLength())));
        }
        parent.addContent(e);
    }
}

From source file:arquivo.ArquivoF.java

public String add(String confSenha, String loing, String senha, String nome) {
    if (confSenha.equals(senha) && !loing.equals("") && !nome.equals("") && !senha.equals("")) {
        if (0 != busca(nome, true, "funcinario").size() && buscaLong(loing).size() != 0)
            return "erro nome ja cadastrado";
        SAXBuilder builder = new SAXBuilder();
        try {//w w  w.  java  2 s  .  c  om
            Document doc = builder.build(arquivo);
            Element root = (Element) doc.getRootElement();

            Element funcionario = new Element("funcinario");

            Attribute nomeE = new Attribute("nome", nome);
            funcionario.setAttribute(nomeE);

            Element loingE = new Element("loing");
            loingE.setText(loing);
            funcionario.addContent(loingE);

            Element senhaE = new Element("senha");
            senhaE.setText(senha);
            funcionario.addContent(senhaE);

            root.addContent(funcionario);

            XMLOutputter xout = new XMLOutputter();
            OutputStream out = new FileOutputStream(arquivo);
            xout.output(doc, out);
            System.out.println("Documento alterado com sucesso!");

            return "cadastrado com suceso";
        } catch (Exception e) {

        }
    } else
        return "preemcha os compos corretamente";
    return "erro cadastral";
}

From source file:arquivo.ArquivoFilme.java

public String add(String nome, String faixa, String tipo) {
    if (0 != busca(nome, true, "filme").size())
        return "erro nome ja cadastrado";
    SAXBuilder builder = new SAXBuilder();
    try {/*from ww  w . j  a va  2 s. co m*/
        Document doc = builder.build(arquivo);
        Element root = (Element) doc.getRootElement();

        Element filmeE = new Element("filme");

        Attribute nomeE = new Attribute("nome", nome);
        filmeE.setAttribute(nomeE);

        Attribute tipoE = new Attribute("tipo", tipo);
        filmeE.setAttribute(tipoE);

        Attribute faixaE = new Attribute("faixa", faixa);
        filmeE.setAttribute(faixaE);

        root.addContent(filmeE);

        XMLOutputter xout = new XMLOutputter();
        OutputStream out = new FileOutputStream(arquivo);
        xout.output(doc, out);
        System.out.println("Documento alterado com sucesso!");

        return "cadastrado com suceso";
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "erro cadastral";
}

From source file:arquivo.ArquivoFilme.java

public String addSesao(String nome, int numeroSala, int horaI, int mimI, int horaF, int mimF) {
    String retorno = "erro";
    if (!nome.equals("")) {
        if (this.confirnaSesao(numeroSala, horaI, mimI, horaF, mimF)) {
            SAXBuilder builder = new SAXBuilder();
            try {
                Document doc = builder.build(arquivo);
                Element root = (Element) doc.getRootElement();

                List<Element> filme = super.buscaInterna(root, true, nome, "filme");
                if (filme.size() == 0) {
                    return "erro filme n registrado";
                }//from  w ww . ja v  a 2 s  .  com
                List<Element> salas = filme.get(0).getChildren("sala");

                Element secao = new Element("secao");
                secao.setAttribute(new Attribute("horaI", "" + horaI));
                secao.setAttribute(new Attribute("mimI", "" + mimI));
                secao.setAttribute(new Attribute("horaF", "" + horaF));
                secao.setAttribute(new Attribute("mimF", "" + mimF));

                boolean confirna = false;
                for (int i = 0; i < salas.size(); i++) {
                    if (salas.get(i).getAttributeValue("numeroSala").equals("" + numeroSala)) {
                        confirna = true;
                        salas.get(i).addContent(secao);
                        break;
                    }
                }
                if (!confirna) {
                    Element sala = new Element("sala");
                    sala.addContent(secao);
                    filme.get(0).addContent(sala);
                }

                XMLOutputter xout = new XMLOutputter();
                OutputStream out = new FileOutputStream(arquivo);
                xout.output(doc, out);
                System.out.println("Documento alterado com sucesso!");

                retorno = "cadastrado com suceso";
            } catch (Exception e) {

            }
        } else
            retorno = "nesse horario a sala estara ocupada";
    }
    return retorno;
}

From source file:ca.mcgill.cs.swevo.jayfx.model.AbstractElement.java

License:Open Source License

@Override
public Element getXML() {
    Element ret = new Element(IElement.class.getSimpleName());
    ret.setAttribute(new Attribute(IElement.ID, this.getId()));
    ret.addContent(this.getCategory().getXML());
    return ret;//  w ww .jav a  2  s  .  co  m
}

From source file:ca.nrc.cadc.ac.xml.AbstractReaderWriter.java

License:Open Source License

/**
 * Get a JDOM element from a Group object.
 *
 * @param group The UserRequest./* w  ww. jav a 2s  . co  m*/
 * @param deepCopy Return all Group elements.
 * @return A JDOM Group representation.
 * @throws WriterException
 */
protected final Element getElement(Group group, boolean deepCopy) throws WriterException {
    if (group == null) {
        throw new WriterException("null Group");
    }

    // Create the root group element.
    Element groupElement = new Element(GROUP);
    String groupURI = group.getID().toString();
    groupElement.setAttribute(new Attribute(URI, groupURI));

    // Group owner
    if (group.getOwner() != null) {
        Element ownerElement = new Element(OWNER);
        Element userElement = getElement(group.getOwner());
        ownerElement.addContent(userElement);
        groupElement.addContent(ownerElement);
    }

    if (deepCopy) {
        // Group description
        if (group.description != null) {
            Element descriptionElement = new Element(DESCRIPTION);
            descriptionElement.setText(group.description);
            groupElement.addContent(descriptionElement);
        }

        // lastModified
        if (group.lastModified != null) {
            Element lastModifiedElement = new Element(LAST_MODIFIED);
            DateFormat df = DateUtil.getDateFormat(DateUtil.IVOA_DATE_FORMAT, DateUtil.UTC);
            lastModifiedElement.setText(df.format(group.lastModified));
            groupElement.addContent(lastModifiedElement);
        }

        // Group properties
        if (!group.getProperties().isEmpty()) {
            Element propertiesElement = new Element(PROPERTIES);
            for (GroupProperty property : group.getProperties()) {
                propertiesElement.addContent(getElement(property));
            }
            groupElement.addContent(propertiesElement);
        }

        // Group groupMembers.
        if ((group.getGroupMembers() != null) && (!group.getGroupMembers().isEmpty())) {
            Element groupMembersElement = new Element(GROUP_MEMBERS);
            for (Group groupMember : group.getGroupMembers()) {
                groupMembersElement.addContent(getElement(groupMember, false));
            }
            groupElement.addContent(groupMembersElement);
        }

        // Group userMembers
        if ((group.getUserMembers() != null) && (!group.getUserMembers().isEmpty())) {
            Element userMembersElement = new Element(USER_MEMBERS);
            for (User userMember : group.getUserMembers()) {
                userMembersElement.addContent(getElement(userMember));
            }
            groupElement.addContent(userMembersElement);
        }

        // Group groupAdmins.
        if ((group.getGroupAdmins() != null) && (!group.getGroupAdmins().isEmpty())) {
            Element groupAdminsElement = new Element(GROUP_ADMINS);
            for (Group groupMember : group.getGroupAdmins()) {
                groupAdminsElement.addContent(getElement(groupMember, false));
            }
            groupElement.addContent(groupAdminsElement);
        }

        // Group userAdmins
        if ((group.getUserAdmins() != null) && (!group.getUserAdmins().isEmpty())) {
            Element userAdminsElement = new Element(USER_ADMINS);
            for (User userMember : group.getUserAdmins()) {
                userAdminsElement.addContent(getElement(userMember));
            }
            groupElement.addContent(userAdminsElement);
        }
    }

    return groupElement;
}

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

License:Open Source License

public Document input(final String json) throws JSONException {
    JSONObject rootJson = new JSONObject(json);
    List<String> keys = Arrays.asList(JSONObject.getNames(rootJson));
    List<Namespace> namespaces = new ArrayList<Namespace>();
    Namespace namespace = getNamespace(namespaces, rootJson, keys);

    String rootKey = null;//  ww  w  .  ja va2s  .co  m
    List<Attribute> attributes = new ArrayList<Attribute>();
    for (String key : keys) {
        if (!key.startsWith("@xmlns")) {
            if (key.startsWith("@")) {
                String value;
                if (rootJson.isNull(key)) {
                    value = "";
                } else {
                    value = getStringValue(rootJson.get(key));
                }
                attributes.add(new Attribute(key.substring(1), value));
            } else {
                // DOM can only have one root element.
                if (rootKey != null) {
                    throw new IllegalStateException("Found multiple root entries");
                }
                rootKey = key;
            }
        }
    }

    Element rootElement = new Element(rootKey, namespace);
    for (Attribute attribute : attributes) {
        rootElement.setAttribute(attribute);
    }

    Object value = rootJson.get(rootKey);
    processObject(rootKey, value, rootElement, namespace, namespaces);

    Document document = new Document();
    document.setRootElement(rootElement);
    return document;
}

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

License:Open Source License

private void processJSONObject(JSONObject jsonObject, Element element, List<Namespace> namespaces)
        throws JSONException {
    List<String> keys = Arrays.asList(JSONObject.getNames(jsonObject));
    Namespace namespace = getNamespace(namespaces, jsonObject, keys);
    if (namespace == null) {
        namespace = element.getNamespace();
    }/*w w  w . ja  v  a2  s.  co m*/

    for (String key : keys) {
        if (jsonObject.isNull(key)) {
            continue;
        }

        // attribute
        if (key.startsWith("@")) {
            Object value = jsonObject.get(key);
            element.setAttribute(new Attribute(key.substring(1), getStringValue(value)));
            continue;
        }

        // text content
        Object value = jsonObject.get(key);
        if (key.equals("$")) {
            element.setText(getStringValue(value));
            continue;
        }

        Element child = new Element(key, namespace);
        if (listElementMap.containsKey(key)) {
            final String childKey = listElementMap.get(key);
            final Object childObject = ((JSONObject) value).get("$");
            Element grandChild = new Element(childKey, namespace);

            if (childObject instanceof JSONArray) {
                processJSONArray(key, (JSONArray) childObject, child, namespace, namespaces);
            } else if (childObject instanceof JSONObject) {
                processJSONObject((JSONObject) childObject, grandChild, namespaces);
                child.addContent(grandChild);
            }
        } else if (value instanceof JSONObject) {
            processJSONObject((JSONObject) value, child, namespaces);
        }

        element.addContent(child);
    }
}

From source file:codigoFonte.Sistema.java

public boolean addUser(User u) throws IOException {

    boolean success = false, matriculaExists = false;
    File file = new File("Sistema.xml");
    Document newDocument = null;//w w w .j  av a2s.co m
    Element root = null;
    Attribute matricula = null, nome = null, tipo = null, senha = null;
    Element user = null;

    if (u.getTipo().isEmpty() || u.getTipo().isEmpty() || u.getPassword().isEmpty()) {
        return success;
    }

    if (file.exists()) {
        SAXBuilder builder = new SAXBuilder();
        try {
            newDocument = builder.build(file);
        } catch (JDOMException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
        root = newDocument.getRootElement();
    } else {
        root = new Element("sistema");

        newDocument = new Document(root);
    }

    if (root.getChildren().size() > 0) {
        List<Element> listUsers = root.getChildren();
        for (Element a : listUsers) {
            if (a.getAttributeValue("matrcula").equals(u.getMatricula())) {
                matriculaExists = true;
            }
        }
    }

    if (!matriculaExists) {
        user = new Element("user");

        matricula = new Attribute("matrcula", this.newId());
        tipo = new Attribute("tipo", u.getTipo());
        nome = new Attribute("nome", u.getNome());
        senha = new Attribute("senha", u.getPassword());

        user.setAttribute(matricula);
        user.setAttribute(nome);
        user.setAttribute(tipo);
        user.setAttribute(senha);
        //user.setAttribute(divida);

        root.addContent(user);

        success = true;
    }
    //        

    XMLOutputter out = new XMLOutputter();

    try {
        FileWriter arquivo = new FileWriter(file);
        out.output(newDocument, arquivo);
    } catch (IOException ex) {
        Logger.getLogger(Sistema.class.getName()).log(Level.SEVERE, null, ex);
    }

    return success;
}

From source file:com.c4om.autoconf.ulysses.extra.svrlmultipathinterpreter.PartialNodeGenerator.java

License:Apache License

/**
 * Given a selectFromPath, it queries the runtime configuration to get the selectable values pointed by that path
 * and generates the met:possibleValues element that describes it.
 * @param selectFromPath the path to select from (including a document function, relative to the runtime configuration)
 * @param metamodelDoc the metamodel document, to extract probabilities from.
 * @param originalPath the path of the original element at the document
 * @return the desired met:possibleValues
 * @throws IOException If there are I/O errors while loading documents to select values from.
 * @throws JDOMException If there are problems at XML parsing while loading documents to select values from.
 *//* w  w w  .j  a v a 2  s. co  m*/
private Element getPossibleValuesElement(String selectFromPath, Document metamodelDoc, String originalPath)
        throws JDOMException, IOException {
    Element possibleValuesElement = new Element("possibleValues",
            AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA);

    List<String> gatheredPossibleValues = new ArrayList<>();

    if (selectFromPath.contains("|")) {
        String[] singlePaths = selectFromPath.split("\\|");
        for (int i = 0; i < singlePaths.length; i++) {
            String singlePath = singlePaths[i];
            gatheredPossibleValues.addAll(getSelectableValuesFromSinglePath(singlePath));
        }
    } else {
        gatheredPossibleValues = getSelectableValuesFromSinglePath(selectFromPath);
    }

    for (String possibleValue : gatheredPossibleValues) {
        Element currentPosibleValueElement = new Element("possibleValue",
                AutoconfXMLConstants.NAMESPACE_AUTOCONF_METADATA);
        String queryFrequencyStr = "sum(" + originalPath + "/" + metamodelAttributesPrefix + "Value[./@"
                + metamodelAttributesPrefix + "ValueAttr='" + possibleValue + "']/@" + metamodelAttributesPrefix
                + "Frequency)";
        String queryParentFrequencyStr = "sum(" + originalPath + "/@" + metamodelAttributesPrefix
                + "Frequency)";
        List<Double> queryFrequencyResults;
        List<Double> queryParentFrequencyResults;
        if (metamodelDoc != null) {
            queryFrequencyResults = performJAXENXPath(queryFrequencyStr, metamodelDoc, Filters.fdouble());
            queryParentFrequencyResults = performJAXENXPath(queryParentFrequencyStr, metamodelDoc,
                    Filters.fdouble());

        } else {
            queryFrequencyResults = Collections.emptyList();
            queryParentFrequencyResults = Collections.emptyList();
        }

        if (queryParentFrequencyResults.size() > 0 && queryFrequencyResults.size() > 0) {
            double myFrequency = queryFrequencyResults.get(0);
            double myParentFrequency = queryParentFrequencyResults.get(0);
            double probability = myFrequency / myParentFrequency;
            String formattedProbability = String.format(Locale.US, "%.2f", probability);
            if (!formattedProbability.equalsIgnoreCase("nan")) {
                Attribute probabilityAttribute = new Attribute("probability", formattedProbability);
                currentPosibleValueElement.setAttribute(probabilityAttribute);
            }
        }

        currentPosibleValueElement.setText(possibleValue);
        possibleValuesElement.addContent(currentPosibleValueElement);
    }

    return possibleValuesElement;
}