Example usage for org.dom4j DocumentFactory getInstance

List of usage examples for org.dom4j DocumentFactory getInstance

Introduction

In this page you can find the example usage for org.dom4j DocumentFactory getInstance.

Prototype

public static synchronized DocumentFactory getInstance() 

Source Link

Document

Access to singleton implementation of DocumentFactory which is used if no DocumentFactory is specified when building using the standard builders.

Usage

From source file:no.ntnu.idi.freerider.xml.RequestSerializer.java

License:Apache License

/** Serialize this Request. */
public static String serialize(Request request) {
    if (request == null)
        return null;
    //Create and initialize the request's major structure.
    Document xmldocument = DocumentFactory.getInstance().createDocument();
    xmldocument.setXMLEncoding(ProtocolConstants.PREFERRED_CHARSET.displayName()); //Possible alternative: try ISO-8859-1
    Element root = xmldocument.addElement(ProtocolConstants.REQUEST);
    Element header = root.addElement(ProtocolConstants.REQUEST_HEADER);
    header.addAttribute(ProtocolConstants.REQUEST_TYPE_ATTRIBUTE, request.getType().toString());
    header.addAttribute(ProtocolConstants.PROTOCOL_VERSION_ATTRIBUTE, ProtocolConstants.PROTOCOL_VERSION);
    header.addAttribute(ProtocolConstants.PROTOCOL_ATTRIBUTE, ProtocolConstants.PROTOCOL);
    Element data = root.addElement(ProtocolConstants.DATA);

    //Add data unique to this request.
    header.addAttribute(ProtocolConstants.USER_ATTRIBUTE, request.getUser().getID());
    if (request instanceof RouteRequest) {
        data.add(SerializerUtils.serializeRoute(((RouteRequest) request).getRoute()));
    } else if (request instanceof SearchRequest) {
        SearchRequest req = (SearchRequest) request;
        data.add(SerializerUtils.serializeSearch(req.getStartPoint(), req.getEndPoint(), req.getStartTime(),
                req.getNumDays()));/*from w ww . jav  a  2  s. c  o m*/
    } else if (request instanceof UserRequest) {
        data.add(SerializerUtils.serializeUser(request.getUser()));
    } else if (request instanceof JourneyRequest) {
        data.add(SerializerUtils.serializeJourney(((JourneyRequest) request).getJourney()));
    } else if (request instanceof NotificationRequest) {
        data.add(SerializerUtils.serializeNotification(((NotificationRequest) request).getNotification()));
    } else if (request instanceof LoginRequest) {
        Element token = new DefaultElement(ProtocolConstants.ACCESS_TOKEN_ELEMENT);
        token.setText(((LoginRequest) request).getAccessToken());
        data.add(token);
    } else if (request instanceof PreferenceRequest) {
        data.add(SerializerUtils.serializePreference(((PreferenceRequest) request).getPreference()));
    } else if (request instanceof CarRequest) {
        data.add(SerializerUtils.serializeCar(((CarRequest) request).getCar()));
    } else if (request instanceof SingleJourneyRequest) {
        data.addAttribute(ProtocolConstants.SINGLE_JOURNEY_ID,
                Integer.toString(((SingleJourneyRequest) request).getJourneySerial()));
    }

    return xmldocument.asXML();
}

From source file:no.ntnu.idi.freerider.xml.ResponseSerializer.java

License:Apache License

public static String serialize(Response responseObject) {
    //Initialize empty Response document.
    Document xmlResponse = DocumentFactory.getInstance().createDocument();
    xmlResponse.setXMLEncoding(ProtocolConstants.PREFERRED_CHARSET.displayName()); //Possible alternative: try ISO-8859-1
    Element responseRoot = xmlResponse.addElement(ProtocolConstants.RESPONSE);
    Element responseHeader = responseRoot.addElement(ProtocolConstants.RESPONSE_HEADER);
    responseHeader.addAttribute(ProtocolConstants.PROTOCOL_ATTRIBUTE, ProtocolConstants.PROTOCOL);
    //      responseHeader.addAttribute("xmlns:tns", ProtocolConstants.XMLNS_RESPONSE);
    //      responseHeader.addAttribute("xmlns:xsi", ProtocolConstants.XMLNS_XSI);
    //      responseHeader.addAttribute("xsi:schemalocation", ProtocolConstants.XSI_SCHEMALOCATION_RESPONSE);
    responseHeader.addAttribute(ProtocolConstants.PROTOCOL_VERSION_ATTRIBUTE,
            ProtocolConstants.PROTOCOL_VERSION);

    //Handle null request errors.
    if (responseObject == null) {
        responseHeader.addAttribute(ProtocolConstants.RESPONSE_STATUS_ATTRIBUTE,
                ResponseStatus.FAILED.toString());
        return xmlResponse.asXML();
    }/*  w  w w . jav  a  2 s.c o m*/

    //Complete initialization.
    responseHeader.addAttribute(ProtocolConstants.REQUEST_TYPE_ATTRIBUTE, responseObject.getType().toString());
    if (responseObject.getErrorMessage() != null) {
        responseHeader.addAttribute(ProtocolConstants.ERROR_MESSAGE_ATTRIBUTE,
                responseObject.getErrorMessage());
    }
    Element responseData = responseRoot.addElement(ProtocolConstants.DATA);

    //Add header data.
    responseHeader.addAttribute(ProtocolConstants.RESPONSE_STATUS_ATTRIBUTE,
            responseObject.getStatus().toString());
    //Insert other data.
    if (responseObject instanceof JourneyResponse && ((JourneyResponse) responseObject).getJourneys() != null) {
        for (Journey journey : ((JourneyResponse) responseObject).getJourneys()) {
            Element journeyElement = SerializerUtils.serializeJourney(journey);
            if (journeyElement != null) {
                responseData.add(journeyElement);
            }
        }
    }
    if (responseObject instanceof RouteResponse && ((RouteResponse) responseObject).getRoutes() != null) {
        for (Route route : ((RouteResponse) responseObject).getRoutes()) {
            Element routeElement = SerializerUtils.serializeRoute(route);
            if (routeElement != null) {
                responseData.add(routeElement);
            }
        }
    }
    if (responseObject instanceof NotificationResponse
            && ((NotificationResponse) responseObject).getNotifications() != null)
        for (Notification note : ((NotificationResponse) responseObject).getNotifications()) {
            Element noteElement = SerializerUtils.serializeNotification(note);
            if (noteElement != null)
                responseData.add(noteElement);
        }
    if (responseObject instanceof PreferenceResponse
            && ((PreferenceResponse) responseObject).getPreferences() != null) {
        Element prefElement = SerializerUtils
                .serializePreference(((PreferenceResponse) responseObject).getPreferences());
        if (prefElement != null) {
            responseData.add(prefElement);
        }
    }
    if (responseObject instanceof CarResponse && ((CarResponse) responseObject).getCar() != null) {
        Element carElement = SerializerUtils.serializeCar(((CarResponse) responseObject).getCar());
        if (carElement != null) {
            responseData.add(carElement);
        }
    }
    if (responseObject instanceof UserResponse && ((UserResponse) responseObject).getUser() != null) {
        Element userElement = SerializerUtils.serializeUser(((UserResponse) responseObject).getUser());
        if (userElement != null) {
            responseData.add(userElement);
        }
    }
    return xmlResponse.asXML();
}

From source file:nz.govt.natlib.ndha.common.dublincore.DublinCore.java

License:Open Source License

private void createNew() {

    m_document = DocumentFactory.getInstance().createDocument();

    m_record = m_document.addElement("record");
    m_record.add(dcNamespace);/*  w  w w  .  ja  va2 s.c  o  m*/
    m_record.add(dctermsNamespace);
    m_record.add(xsiNamespace);
}

From source file:org.apache.ddlutils.task.DumpMetadataTask.java

License:Apache License

/**
 * {@inheritDoc}//from   w  ww . j av a  2  s .c  om
 */
public void execute() throws BuildException {
    if (_dataSource == null) {
        log("No data source specified, so there is nothing to do.", Project.MSG_INFO);
        return;
    }

    Connection connection = null;
    try {
        Document document = DocumentFactory.getInstance().createDocument();
        Element root = document.addElement("metadata");

        root.addAttribute("driverClassName", _dataSource.getDriverClassName());

        connection = _dataSource.getConnection();

        dumpMetaData(root, connection.getMetaData());

        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        XMLWriter xmlWriter = null;

        outputFormat.setEncoding(_outputEncoding);
        if (_outputFile == null) {
            xmlWriter = new XMLWriter(System.out, outputFormat);
        } else {
            xmlWriter = new XMLWriter(new FileOutputStream(_outputFile), outputFormat);
        }
        xmlWriter.write(document);
        xmlWriter.close();
    } catch (Exception ex) {
        throw new BuildException(ex);
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
            }
        }
    }
}

From source file:org.apache.taglibs.xtags.xpath.AbstractTag.java

License:Apache License

/** @return the factory used to create XPath instances */
protected DocumentFactory getDocumentFactory() {
    return DocumentFactory.getInstance();
}

From source file:org.b5chat.crossfire.plugin.admin.AdminConsole.java

License:Open Source License

/**
 * Rebuilds the generated model.//from  w  w w .ja  va 2  s . c  om
 */
private static synchronized void rebuildModel() {
    Document doc = DocumentFactory.getInstance().createDocument();
    generatedModel = coreModel.createCopy();
    doc.add(generatedModel);

    // Add in all overrides.
    for (Element element : overrideModels.values()) {
        // See if global settings are overriden.
        Element appName = (Element) element.selectSingleNode("//adminconsole/global/appname");
        if (appName != null) {
            Element existingAppName = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/appname");
            existingAppName.setText(appName.getText());
            if (appName.attributeValue("plugin") != null) {
                existingAppName.addAttribute("plugin", appName.attributeValue("plugin"));
            }
        }
        Element appLogoImage = (Element) element.selectSingleNode("//adminconsole/global/logo-image");
        if (appLogoImage != null) {
            Element existingLogoImage = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/logo-image");
            existingLogoImage.setText(appLogoImage.getText());
            if (appLogoImage.attributeValue("plugin") != null) {
                existingLogoImage.addAttribute("plugin", appLogoImage.attributeValue("plugin"));
            }
        }
        Element appLoginImage = (Element) element.selectSingleNode("//adminconsole/global/login-image");
        if (appLoginImage != null) {
            Element existingLoginImage = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/login-image");
            existingLoginImage.setText(appLoginImage.getText());
            if (appLoginImage.attributeValue("plugin") != null) {
                existingLoginImage.addAttribute("plugin", appLoginImage.attributeValue("plugin"));
            }
        }
        Element appVersion = (Element) element.selectSingleNode("//adminconsole/global/version");
        if (appVersion != null) {
            Element existingVersion = (Element) generatedModel
                    .selectSingleNode("//adminconsole/global/version");
            if (existingVersion != null) {
                existingVersion.setText(appVersion.getText());
                if (appVersion.attributeValue("plugin") != null) {
                    existingVersion.addAttribute("plugin", appVersion.attributeValue("plugin"));
                }
            } else {
                ((Element) generatedModel.selectSingleNode("//adminconsole/global"))
                        .add(appVersion.createCopy());
            }
        }
        // Tabs
        for (Object o : element.selectNodes("//tab")) {
            Element tab = (Element) o;
            String id = tab.attributeValue("id");
            Element existingTab = getElemnetByID(id);
            // Simple case, there is no existing tab with the same id.
            if (existingTab == null) {
                // Make sure that the URL on the tab is set. If not, default to the
                // url of the first item.
                if (tab.attributeValue("url") == null) {
                    Element firstItem = (Element) tab.selectSingleNode("//item[@url]");
                    if (firstItem != null) {
                        tab.addAttribute("url", firstItem.attributeValue("url"));
                    }
                }
                generatedModel.add(tab.createCopy());
            }
            // More complex case -- a tab with the same id already exists.
            // In this case, we have to overrite only the difference between
            // the two elements.
            else {
                overrideTab(existingTab, tab);
            }
        }
    }
}

From source file:org.b5chat.crossfire.xmpp.privacy.PrivacyList.java

License:Open Source License

/**
 * Returns an Element with the privacy list XML representation.
 *
 * @return an Element with the privacy list XML representation.
 */// www. java  2 s.  c o  m
public Element asElement() {
    //Element listElement = DocumentFactory.getInstance().createDocument().addElement("list");
    Element listElement = DocumentFactory.getInstance().createDocument().addElement("list",
            "jabber:iq:privacy");
    listElement.addAttribute("name", getName());
    // Add the list items to the result
    for (PrivacyItem item : items) {
        listElement.add(item.asElement());
    }
    return listElement;
}

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

License:Apache License

private void addDitaOpenPlatformToCurrentEclipseProject(File eclipseProjectFile) throws MojoExecutionException {
    Document doc = DocumentFactory.getInstance().createDocument();

    try {/*ww  w  .  jav  a2  s . co  m*/
        SAXReader saxReader = new SAXReader();
        doc = saxReader.read(eclipseProjectFile);

        this.addDitaBuildCommand(doc);

        this.addDitaBuildNature(doc);

    } catch (DocumentException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

    this.writeOutEclipseProject(doc, eclipseProjectFile);

}

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.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);/*from   w w w .j av a  2s  . 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;
}