Example usage for org.dom4j.tree DefaultElement add

List of usage examples for org.dom4j.tree DefaultElement add

Introduction

In this page you can find the example usage for org.dom4j.tree DefaultElement add.

Prototype

public void add(Attribute attribute) 

Source Link

Usage

From source file:com.mor.blogengine.model.BlogCategory.java

License:Open Source License

/**
 * a-like as {@link #toString() }/*  ww w .  j a  v  a 2s. c  o m*/
 *
 * @return an XML representation of element
 */
@Override
public DefaultElement toElement() {

    // QName lElementDecl = new QName("Category", mNamespace);
    DefaultElement lReturnElement = new DefaultElement("Category");

    // Attribute= a=new Attribute("", mCatName)
    lReturnElement.add(new DefaultAttribute("ID", getEntityID()));
    lReturnElement.add(new DefaultAttribute("name", getCatName()));
    lReturnElement.add(new DefaultAttribute("description", getDescription()));

    return lReturnElement;
}

From source file:com.mor.blogengine.model.BlogComment.java

License:Open Source License

@Override
public DefaultElement toElement() {

    // this is element Declaration in complete form.
    // QName lCommentTextDecl = new QName("CommentText", mNamespace);
    // QName lReturnelementdecl = new QName("Comment", mNamespace);
    DefaultElement lReturnElement = null;
    DefaultElement lCommentText = new DefaultElement("CommentText");

    lCommentText.addText(mCommentText);/*from www. j  av  a  2s .c om*/
    lReturnElement = new DefaultElement("Comment");

    // lReturnElement.add(mNamespace);
    lReturnElement.add(new DefaultAttribute("entryID", getEntryID()));
    lReturnElement.add(new DefaultAttribute("ID", getEntityID()));
    lReturnElement.add(new DefaultAttribute("date", mDate));
    lReturnElement.add(new DefaultAttribute("author", mAuthor));
    lReturnElement.add(new DefaultAttribute("webPage", mWebPage));
    lReturnElement.add(lCommentText);

    return lReturnElement;
}

From source file:com.mor.blogengine.model.BlogEntry.java

License:Open Source License

/**
 *
 * @return XML node representation of entry
 *//*from  w w w  .j a  v a  2s .  c  om*/
@Override
public DefaultElement toElement() {

    // this is element Declaration in complete form.
    // QName lElementDecl = new QName("Entry", mNamespace);
    DefaultElement lReturnElement = new DefaultElement("Entry");

    lReturnElement.add(new DefaultAttribute("date", getDate()));
    lReturnElement.add(new DefaultAttribute("categoryID", getCatID()));
    lReturnElement.add(new DefaultAttribute("allowComments", getAllowComments()));
    lReturnElement.add(new DefaultAttribute("ID", getEntityID()));

    //      this is element Declaration in complete form.
    // QName lEntryTextDecl = new QName("Text", mNamespace);
    DefaultElement lEntryText = new DefaultElement("Text");

    lEntryText.addText(mTexte);
    lReturnElement.add(lEntryText);

    // QName lResumeDecl = new QName("Resume", mNamespace);
    DefaultElement lEntryResume = new DefaultElement("Resume");

    lEntryResume.addText(mResume);
    lReturnElement.add(lEntryResume);

    return lReturnElement;
}

From source file:com.mor.blogengine.xml.XMLHandlerImpl.java

License:Open Source License

/**
 * Append a node to parent node/*from   w ww  . j av a  2 s.c  o m*/
 *
 * @param root The node to add under
 * @param content what to add to root node
 * @return appended or not
 */
@Override
public boolean append(DefaultElement root, DefaultElement content) {
    String elemID = root.valueOf("@ID");
    DefaultElement elemInDoc = (DefaultElement) mRootElement.elementByID(elemID);

    if (elemInDoc != null) {
        elemInDoc.add(content);

        int indexOfappended = elemInDoc.indexOf(content);

        return (indexOfappended != -1);
    }
    return false;
}

From source file:com.thoughtworks.cruise.ConfigureCruiseUsingApi.java

License:Apache License

@com.thoughtworks.gauge.Step("Create pipeline <pipelineName> using template <templateName>")
public void createPipelineUsingTemplate(final String pipelineName, final String templateName) throws Exception {
    editPipelineGroup(new PipelineGroupEditAction() {

        public void applyEdit(Document group) {
            Element pipelines = (Element) group.selectSingleNode("//pipelines");
            Element pipeline = new DefaultElement("pipeline");
            pipeline.addAttribute("name", pipelineName);
            pipeline.addAttribute("template", templateName);
            DefaultElement materials = new DefaultElement("materials");
            DefaultElement hg = new DefaultElement("hg");
            hg.addAttribute("url", "some-url");
            materials.add(hg);
            pipeline.add(materials);// ww  w .  j  av a 2s  .co  m
            pipelines.add(pipeline);
            scenarioState.pushPipeline(pipelineName, pipelineName);
        }
    });
}

From source file:de.tud.kom.p2psim.impl.network.gnp.topology.CountryLookup.java

License:Open Source License

/**
 * /*ww  w .  j a  va  2  s.  c  om*/
 * @return xml-element containing current lookup data
 */
public Element exportToXML() {
    DefaultElement country = new DefaultElement("CountryLookup");
    Set<String> codeKeys = countryLookup.keySet();
    for (String code : codeKeys) {
        DefaultElement countryXml = new DefaultElement("CountryKey");
        countryXml.addAttribute("code", code);
        countryXml.addAttribute("countryGeoIP", getGeoIpCountryName(code));
        countryXml.addAttribute("countryPingEr", getPingErCountryName(code));
        countryXml.addAttribute("regionPingEr", getPingErRegionName(code));
        country.add(countryXml);
    }
    return country;
}

From source file:de.tud.kom.p2psim.impl.network.gnp.topology.HostMap.java

License:Open Source License

/**
 * /*from   ww w.  ja v a2s  . c  om*/
 * @return xml Document Object of relevant Class Attributes
 */
private Document getDocument() {
    Set<Host> hosts = new HashSet<Host>();

    // "GroupLookup" Element
    log.debug("Generate XML-Element \"GroupLookup\"");
    DefaultElement groups = new DefaultElement("GroupLookup");
    for (String group : this.groups.keySet()) {
        log.debug("  - Export Group: " + group);
        hosts.addAll(this.groups.get(group));
        DefaultElement peerXml = new DefaultElement("Group");
        peerXml.addAttribute("id", group);
        peerXml.addAttribute("maxsize", String.valueOf(this.groups.get(group).size()));
        String ip = "";
        int x = 0;
        int blockSize = 1000;
        // IP Block of 1000, too long blocks leads to hangUp ??
        for (Host host : this.groups.get(group)) {
            x++;
            ip += "," + host.getIpAddress();
            if (x % blockSize == 0) {
                ip = ip.substring(1);
                DefaultElement ips = new DefaultElement("IPs");
                ips.addAttribute("value", ip);
                peerXml.add(ips);
                ip = "";
            }
        }
        if (ip.length() > 0) {
            ip = ip.substring(1);
            DefaultElement ips = new DefaultElement("IPs");
            ips.addAttribute("value", ip);
            peerXml.add(ips);
        }
        groups.add(peerXml);
    }

    // "Hosts" Element
    log.debug("Generate XML-Element \"Hosts\"");
    DefaultElement peers = new DefaultElement("Hosts");
    for (Host host : hosts) {
        DefaultElement peer = new DefaultElement("Host");
        peer.addAttribute("ip", String.valueOf(host.getIpAddress()));

        String area = (host.getArea() != null) ? host.getArea() : "--";
        peer.addAttribute("continentalArea", area);

        String countryCode = (host.getCountryCode() != null) ? host.getCountryCode() : "--";
        peer.addAttribute("countryCode", countryCode);

        String region = (host.getRegion() != null) ? host.getRegion() : "--";
        peer.addAttribute("region", region);

        String city = (host.getCity() != null) ? host.getCity() : "--";
        peer.addAttribute("city", city);

        String isp = (host.getISP() != null) ? host.getISP() : "--";
        peer.addAttribute("isp", isp);

        peer.addAttribute("longitude", String.valueOf(host.getLongitude()));
        peer.addAttribute("latitude", String.valueOf(host.getLatitude()));
        String coordinates = (host.getGnpPositionReference() != null)
                ? host.getGnpPositionReference().getCoordinateString()
                : "0";
        peer.addAttribute("coordinates", coordinates);
        peers.add(peer);
    }

    // "PingErLookup" Elements
    log.debug("Generate XML-Element \"PingErLookup\"");
    Element pingEr = pingErLookup.exportToXML();

    // "CountryLookup" Element
    log.debug("Generate XML-Element \"CountryLookup\"");
    Element country = countryLookup.exportToXML();

    DefaultDocument document = new DefaultDocument(new DefaultElement("gnp"));
    document.getRootElement().add(groups);
    document.getRootElement().add(peers);
    document.getRootElement().add(pingEr);
    document.getRootElement().add(country);
    return document;

}

From source file:de.tud.kom.p2psim.impl.network.gnp.topology.PingErLookup.java

License:Open Source License

/**
 * Export the Class Attributes to an XML Element
 * /*from w w  w  .  j  a va2s . c om*/
 * @param element
 */
public Element exportToXML() {
    DefaultElement pingEr = new DefaultElement("PingErLookup");
    Set<String> fromKeys = data.keySet();
    for (String from : fromKeys) {
        Set<String> toKeys = data.get(from).keySet();
        for (String to : toKeys) {
            DefaultElement pingErXml = new DefaultElement("SummaryReport");
            pingErXml.addAttribute("from", from);
            pingErXml.addAttribute("to", to);
            pingErXml.addAttribute("minimumRtt", String.valueOf(getMinimumRtt(from, to)));
            pingErXml.addAttribute("averageRtt", String.valueOf(getAverageRtt(from, to)));
            pingErXml.addAttribute("delayVariation", String.valueOf(getRttVariation(from, to)));
            pingErXml.addAttribute("packetLoss", String.valueOf(getPacktLossRate(from, to)));
            pingEr.add(pingErXml);
        }
    }
    return pingEr;
}

From source file:delphsim.model.Resultado.java

License:Open Source License

/**
 * Mtodo esttico que exporta los valores obtenidos tras la simulacin al
 * formato XML./*from  w w  w .j av  a2  s.  c  om*/
 * @param destino El archivo de destino.
 * @param nombres Los nombres de las distintas columnas/funciones.
 * @param definiciones La definicin de cada columna/funcin.
 * @param temps Array con los archivos temporales de los cuales obtener los
 *              datos a exportar.
 * @param numPuntosTotal El nmero de puntos total que contienen los
 *                       archivos temporales.
 * @param numPuntosExportar El nmero de puntos que quiere obtener el usuario.
 * @throws java.io.IOException Si hubiera algn problema al crear el archivo en disco.
 */
public static void exportarComoXML(File destino, String[] nombres, String[] definiciones, File[] temps,
        long numPuntosTotal, long numPuntosExportar) throws IOException {
    // Crear el documento, el elemento 'raiz' y asignarlo
    org.dom4j.Document documento = DocumentHelper.createDocument();
    DefaultElement elementoResultado = new DefaultElement("resultado");
    documento.setRootElement(elementoResultado);

    // Creamos los bfers de lectura para leer los temporales
    BufferedReader[] buffers = new BufferedReader[temps.length];
    for (int i = 0; i < temps.length; i++) {
        buffers[i] = new BufferedReader(new FileReader(temps[i]));
    }
    // Calculamos cada cuanto tenemos que guardar un punto
    double cadaCuanto;
    if (numPuntosTotal == numPuntosExportar) {
        cadaCuanto = 1.0d;
    } else {
        cadaCuanto = new Double(numPuntosTotal) / new Double(numPuntosExportar - 1);
    }
    long siguientePuntoExportar = 0;
    long contadorNumPuntoLeido = 0;
    long contadorNumPuntosExportados = 0;
    // Comenzamos a leer los temporales aadiendo elementos al documento
    String[] valores = new String[buffers.length];
    for (int i = 0; i < buffers.length; i++) {
        valores[i] = buffers[i].readLine();
    }
    // En el momento en que se lee un null, se termina
    while (valores[0] != null) {
        // Para cada punto que haya que exportar
        if (siguientePuntoExportar == contadorNumPuntoLeido) {
            DefaultElement nuevaFila = new DefaultElement("fila");
            // Para el tiempo, nuevo elemento, su valor y aadirlo a la fila
            DefaultElement elementoTiempo = new DefaultElement("Tiempo");
            elementoTiempo.setText(valores[0]);
            nuevaFila.add(elementoTiempo);
            // Lo mismo para cada linea, pero ademas con nombre y definicin
            for (int i = 1; i < valores.length; i++) {
                DefaultElement elementoLinea = new DefaultElement("Lnea" + i);
                elementoLinea.add(new DefaultAttribute("nombre", nombres[i]));
                elementoLinea.add(new DefaultAttribute("definicion", definiciones[i]));
                elementoLinea.setText(valores[i]);
                nuevaFila.add(elementoLinea);
            }
            // Y aadimos la nueva fila
            elementoResultado.add(nuevaFila);
            // Calculamos el siguiente punto a exportar
            contadorNumPuntosExportados++;
            siguientePuntoExportar = Math.round(cadaCuanto * contadorNumPuntosExportados);
            if (siguientePuntoExportar >= numPuntosTotal) {
                siguientePuntoExportar = numPuntosTotal - 1;
            }
        }
        // Leemos la siguiente lnea de los ficheros
        for (int i = 0; i < buffers.length; i++) {
            valores[i] = buffers[i].readLine();
        }
        contadorNumPuntoLeido++;
    }
    // Cerramos los bfers y el archivo de salida
    for (int i = 0; i < buffers.length; i++) {
        buffers[i].close();
    }
    // Imprimimos el documento como XML
    OutputFormat formato = OutputFormat.createPrettyPrint();
    formato.setEncoding("UTF-16");
    formato.setIndent("\t");
    formato.setNewLineAfterDeclaration(false);
    formato.setPadText(false);
    formato.setTrimText(true);
    formato.setXHTML(true);
    OutputStreamWriter salida = new OutputStreamWriter(new FileOutputStream(destino), "UTF-16");
    XMLWriter escritor = new XMLWriter(salida, formato);
    escritor.write(documento);
    escritor.flush();
    escritor.close();
}

From source file:gjset.data.Card.java

License:Open Source License

/**
 * //from   w  w w  .  ja  va  2  s. c  o  m
 * Returns a representation of the card as a {@link String}.  This representation is a unique parsable string that 
 * can be transformed back into a {@link Card} object using the static {@link #parseCard} method.
 *
 * @return The representation of this Card
 */
public Element getXMLRepresentation() {
    DefaultElement cardElement = new DefaultElement("card");

    cardElement.add(createElement("number", number));
    cardElement.add(createElement("color", color));
    cardElement.add(createElement("shape", shape));
    cardElement.add(createElement("shading", shading));

    return cardElement;
}