Example usage for org.dom4j Document addElement

List of usage examples for org.dom4j Document addElement

Introduction

In this page you can find the example usage for org.dom4j Document addElement.

Prototype

Element addElement(String name);

Source Link

Document

Adds a new Element node with the given name to this branch and returns a reference to the new node.

Usage

From source file:org.codehaus.mojo.dita.DitaEclipseMojo.java

License:Apache License

private void generateBrandNewEclipseProjectFile(File eclipseProjectFile) throws MojoExecutionException {
    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement("projectDescription");
    root.addElement("name").setText(projectName);
    root.addElement("comment");
    root.addElement("projects");

    addDitaBuildCommand(root.addElement("buildSpec"));
    addDitaBuildNature(root.addElement("natures"));

    writeOutEclipseProject(doc, eclipseProjectFile);

}

From source file:org.codehaus.mojo.hibernate2.MappingsAggregatorMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    try {//from  w w  w. j a  v a 2s . co m
        String version = null;

        if (getBasedir() == null) {
            throw new MojoExecutionException("Required configuration missing: basedir");
        }

        File files[] = getIncludeFiles();
        if (files == null || files.length <= 0) {
            return;
        }
        File f = new File(getOutputFile());
        if (!f.exists()) {
            f.getParentFile().mkdirs();
            f.createNewFile();
        }
        OutputFormat format = OutputFormat.createPrettyPrint();
        XMLWriter writer = new XMLWriter(new FileWriter(f), format);
        writer.setEntityResolver(new HibernateEntityResolver());
        //writer.setResolveEntityRefs(false);
        Document finalDoc = DocumentHelper.createDocument();
        Element rootHM = null;
        for (int i = 0; i < files.length; i++) {
            print("Parsing: " + files[i].getAbsolutePath());
            SAXReader reader = new SAXReader(false);
            reader.setEntityResolver(new HibernateEntityResolver());
            //reader.setIncludeExternalDTDDeclarations(false);
            //reader.setIncludeExternalDTDDeclarations(false);
            Document current = reader.read(files[i]);
            String currentVersion = getVersion(current);
            if (version == null) {
                version = currentVersion;
                finalDoc.setProcessingInstructions(current.processingInstructions());
                finalDoc.setDocType(current.getDocType());
                rootHM = finalDoc.addElement("hibernate-mapping");
            } else if (!version.equals(currentVersion)) {
                //LOG.warn("Mapping in " + files[i].getName() + " is not of the same mapping version as " + files[0].getName() + " mapping, so merge is impossible. Skipping");
                continue;
            }
            for (Iterator iter = current.selectSingleNode("hibernate-mapping").selectNodes("class")
                    .iterator(); iter.hasNext(); rootHM.add((Element) ((Element) iter.next()).clone())) {
            }
        }

        print("Writing aggregate file: " + f.getAbsolutePath());
        writer.write(finalDoc);
        writer.close();
    } catch (Exception ex) {
        throw new MojoExecutionException("Error in executing MappingsAgrregatorBean", ex);
    }
}

From source file:org.collectionspace.chain.csp.persistence.services.connection.MultipartRequestDataSource.java

License:Educational Community License

public MultipartRequestDataSource(Map<String, Document> body) throws ConnectionException {

    Document document = DocumentHelper.createDocument();
    Element root = document.addElement("document");

    if (body != null) {
        for (String mapkey : body.keySet()) {
            if (body.containsKey(mapkey) && body.get(mapkey) != null) {
                Element rooted = body.get(mapkey).getRootElement();
                root.add(rooted);/*from   w ww .ja  v  a2  s.c  o m*/
            }
        }
        data = ConnectionUtils.documentToStream(document);
    }

}

From source file:org.collectionspace.chain.csp.persistence.services.GenericStorage.java

License:Educational Community License

protected static Element createRelationship(Relationship rel, Object data, String csid, String subjtype,
        String metaType, Boolean reverseIt, Spec spec)
        throws ExistException, UnderlyingStorageException, JSONException {

    Document doc = DocumentFactory.getInstance().createDocument();
    Element subroot = doc.addElement("relation-list-item");

    Element predicate = subroot.addElement("predicate");
    predicate.addText(rel.getPredicate());
    Element relMetaType = subroot.addElement("relationshipMetaType");
    relMetaType.addText(metaType);/* w  w w  .  j  a v a 2  s.  c  o m*/
    String subjectName = "subject";
    String objectName = "object";
    if (reverseIt) {
        subjectName = "object";
        objectName = "subject";
    }
    Element subject = subroot.addElement(subjectName);
    Element subjcsid = subject.addElement("csid");
    if (csid != null) {
        subjcsid.addText(csid);
    } else {
        subjcsid.addText("${itemCSID}");
    }

    //find out record type from urn 
    String refName = (String) data;
    Element object = subroot.addElement(objectName);

    // We may or may not be dealing with a sub-resource like AuthItems.
    // TODO - this may all be unneccessary, as the services should fill in
    // doc types, etc. now automatically.
    // OTOH, not a bad idea to validate the refName...
    RefName.AuthorityItem itemParsed = RefName.AuthorityItem.parse(refName);
    if (itemParsed != null) {
        String serviceurl = itemParsed.inAuthority.resource;
        Record myr = spec.getRecordByServicesUrl(serviceurl);
        if (myr.isType("authority")) {

            Element objRefName = object.addElement("refName");
            objRefName.addText(refName);
        } else {
            throw new JSONException(
                    "Relation object refName is for sub-resources other than authority item - NYI!");
        }
    } else {
        RefName.Authority resourceParsed = RefName.Authority.parse(refName);
        if (resourceParsed != null) {
            Element objRefName = object.addElement("refName");
            objRefName.addText(refName);
        } else {
            throw new JSONException("Relation object refName does not appear to be valid!");
        }
    }

    //log.info(subroot.asXML());
    return subroot;
}

From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

License:Educational Community License

public static Document getXMLRelationship(Element[] listItems) {
    Document doc = DocumentFactory.getInstance().createDocument();
    Element root = doc.addElement(new QName("relations-common-list",
            new Namespace("ns3", "http://collectionspace.org/services/relation")));
    root.addNamespace("ns2", "http://collectionspace.org/services/jaxb");
    //<ns3:relations-common-list xmlns:ns3="http://collectionspace.org/services/relation" xmlns:ns2="http://collectionspace.org/services/jaxb">

    if (listItems != null) {
        for (Element bitdoc : listItems) {
            root.add(bitdoc);//from  w w  w  .  j a v  a2  s  .c  om
        }
    }

    return doc;

}

From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

License:Educational Community License

public static Document convertToXml(Record r, JSONObject in, String section, String permtype,
        Boolean useInstance) throws JSONException, UnderlyingStorageException {
    if (!useInstance) {
        return convertToXml(r, in, section, permtype);
    }//w  w w. j av a 2s .c  om

    Document doc = DocumentFactory.getInstance().createDocument();
    String[] parts = r.getServicesRecordPath(section).split(":", 2);
    if (useInstance) {
        parts = r.getServicesInstancesPath(section).split(":", 2);
    }
    String[] rootel = parts[1].split(",");
    Element root = doc.addElement(new QName(rootel[1], new Namespace("ns2", rootel[0])));

    Element element = root.addElement("displayName");
    element.addText(in.getString("displayName"));
    Element element2 = root.addElement("shortIdentifier");
    element2.addText(in.getString("shortIdentifier"));
    if (in.has("vocabType")) {
        Element element3 = root.addElement("vocabType");
        element3.addText(in.getString("vocabType"));
    }

    return doc;
    //yes I know hardcode is bad - but I need this out of the door today
    /*
    <ns2:personauthorities_common xmlns:ns2="http://collectionspace.org/services/person">
    <displayName>PAHMA Person Authority</displayName>
    <vocabType>PersonAuthority</vocabType>
    <shortIdentifier>pamha</shortIdentifier>
    </ns2:personauthorities_common>
     */

}

From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

License:Educational Community License

public static Document convertToXml(Record r, JSONObject in, String section, String operation)
        throws JSONException, UnderlyingStorageException {
    Document doc = DocumentFactory.getInstance().createDocument();
    try {/* www  .  ja va  2  s .  co  m*/
        String path = r.getServicesRecordPath(section);
        if (path != null) {
            String[] parts = path.split(":", 2);
            String[] rootel = parts[1].split(",");
            Element root = doc.addElement(new QName(rootel[1], new Namespace("ns2", rootel[0])));
            if (r.getAllServiceFieldTopLevel(operation, section).length > 0) {
                for (FieldSet f : r.getAllServiceFieldTopLevel(operation, section)) {
                    addFieldSetToXml(root, f, in, section, operation);
                }
                return doc;
            }
        } else {
            // Revert to DEBUG after v4.0 testing
            log.warn(String.format("Record %s lacks expected section %s", r.getRecordName(), section));
        }
    } catch (Exception ex) {
        log.debug("Error in XmlJsonConversion.convertToXml", ex);
        throw ex;
    }
    return null;
}

From source file:org.collectionspace.chain.csp.webui.nuispec.ServicesXsd.java

License:Educational Community License

private String serviceschema(Storage s, String path) throws UIException {
    if (path != null) {
        section = path;//from  w  w  w. j av  a 2 s.co m
    }

    Document doc = DocumentFactory.getInstance().createDocument();
    Namespace ns = new Namespace("xs", "http://www.w3.org/2001/XMLSchema");
    String[] parts = record.getServicesRecordPath(section).split(":", 2);
    String[] rootel = parts[1].split(",");
    Element root = doc.addElement(new QName("schema", new Namespace("xs", "http://www.w3.org/2001/XMLSchema")));
    root.addAttribute("xmlns:ns", rootel[0]);
    root.addAttribute("xmlns", rootel[0]);
    root.addAttribute("targetNamespace", rootel[0]);
    root.addAttribute("version", "0.1");

    //      Element ele = root.addElement(new QName("element", ns));
    //      ele.addAttribute("name", rootel[1]);
    //      Element cele = ele.addElement(new QName("complexType", ns));

    // add toplevel items

    for (FieldSet fs : record.getAllFieldTopLevel("")) {
        generateDataEntry(root, fs, ns, root, false);
    }

    generateSearchList(root, ns);
    // log.info(doc.asXML());
    // return doc.asXML();

    return doc.asXML();

}

From source file:org.collectionspace.services.id.IDResource.java

License:Educational Community License

/**
 * Returns a representation of a single ID generator instance resource.
 *
 * @param    csid  An identifier for an ID generator instance.
 *
 * @return  A representation of an ID generator instance resource.
 *//*from www .  j ava  2 s  . c  o m*/
@GET
@Path("/{csid}")
@Produces(MediaType.APPLICATION_XML)
public Response readIDGenerator(@PathParam("csid") String csid) {

    ResponseBuilder builder = Response.ok();
    Response response = builder.build();

    String resourceRepresentation = "";
    try {
        ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = createServiceContext();
        IDGeneratorInstance instance = service.readIDGenerator(ctx, csid);

        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement(ID_GENERATOR_NAME);
        Namespace namespace = new Namespace(ID_SERVICE_NAMESPACE_PREFIX, ID_SERVICE_NAMESPACE);
        doc.getRootElement().add(namespace);

        // Make new elements for each of the components of this ID generator
        // instance, and attach them to the root element.

        // Append display name information for this ID generator instance.
        String displayname = instance.getDisplayName();
        root = appendDisplayNameIDGeneratorInformation(root, displayname);
        // Append detailed information for this ID generator instance.
        root = appendDetailedIDGeneratorInformation(root, instance);

        resourceRepresentation = XmlTools.prettyPrintXML(doc);
        response = Response.status(Response.Status.OK).entity(resourceRepresentation)
                .type(MediaType.APPLICATION_XML).build();

        // @TODO Return an XML-based error results format with the
        // responses below.

    } catch (DocumentNotFoundException dnfe) {
        response = Response.status(Response.Status.NOT_FOUND).entity(dnfe.getMessage())
                .type(MediaType.TEXT_PLAIN).build();

    } catch (IllegalStateException ise) {
        response = Response.status(Response.Status.BAD_REQUEST).entity(ise.getMessage())
                .type(MediaType.TEXT_PLAIN).build();

        // This is guard code that should never be reached.
    } catch (Exception e) {
        response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage())
                .type(MediaType.TEXT_PLAIN).build();
    }

    return response;
}

From source file:org.collectionspace.services.id.IDResource.java

License:Educational Community License

/**
 * Returns a base XML document representing a list of
 * ID generator instances.//from  w ww  .  ja  v a  2  s . c o m
 *
 * @return  A base XML document representing a list
 *          of ID generator instances.
 */
private Document baseListDocument() {

    Document doc = DocumentHelper.createDocument();
    Element root = doc.addElement(ID_GENERATOR_LIST_NAME);
    Namespace namespace = new Namespace(ID_SERVICE_NAMESPACE_PREFIX, ID_SERVICE_NAMESPACE);
    doc.getRootElement().add(namespace);

    return doc;
}