Example usage for org.dom4j Document setXMLEncoding

List of usage examples for org.dom4j Document setXMLEncoding

Introduction

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

Prototype

void setXMLEncoding(String encoding);

Source Link

Document

Sets the encoding of this document as it will appear in the XML declaration part of the document.

Usage

From source file:dk.nsi.stamdata.replication.webservice.AtomFeedWriter.java

License:Mozilla Public License

public <T extends View> org.w3c.dom.Document write(Class<T> viewClass, List<T> records) throws IOException {
    checkNotNull(viewClass);/*  w ww .  j a v  a 2  s.c  om*/
    checkNotNull(records);

    String entityName = Views.getViewPath(viewClass);

    try {
        Document document = DocumentHelper.createDocument();
        document.setXMLEncoding("utf-8");

        // Start the feed.

        Element feed = document.addElement("atom:feed", ATOM_NS);

        // Get the namespace of the view class.

        String viewNS = viewClass.getPackage().getAnnotation(XmlSchema.class).namespace();
        Namespace namespace = new Namespace(null, viewNS);
        document.getRootElement().add(namespace);

        writeFeedMetadata(entityName, feed);

        // Write each record as an ATOM entry.

        Marshaller marshaller = viewXmlHelper.createMarshaller(viewClass);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, STREAM_ENCODING);

        for (Object record : records) {
            View view = (View) record;
            writeEntry(feed, entityName, view, marshaller);
        }

        return convertToW3C(document);
    } catch (Exception e) {
        throw new IOException("Failed while writing ATOM feed.", e);
    }
}

From source file:dk.nsi.stamdata.replication.webservice.RecordXmlGenerator.java

License:Mozilla Public License

public org.w3c.dom.Document generateXml(List<RecordMetadata> records, String register, String datatype,
        DateTime updated) throws TransformerException {
    String stamdataNamespaceUri = STAMDATA_NAMESPACE_URI_PREFIX + register;

    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding("utf-8");

    Element root = document.addElement("atom:feed", ATOM_NAMESPACE_URI);

    addElement(root, ATOM_NAMESPACE_URI, "atom:id",
            String.format("tag:nsi.dk,2011:%s/%s/v1", register, datatype));
    addElement(root, ATOM_NAMESPACE_URI, "atom:updated", AtomDate.toString(updated.toDate()));
    addElement(root, ATOM_NAMESPACE_URI, "atom:title", "Stamdata Registry Feed");
    Element author = addElement(root, ATOM_NAMESPACE_URI, "atom:author", null);
    addElement(author, ATOM_NAMESPACE_URI, "atom:name", "National Sundheds IT");

    for (RecordMetadata metadata : records) {
        Element entry = addElement(root, ATOM_NAMESPACE_URI, "atom:entry", null);
        String atomId = String.format("tag:nsi.dk,2011:%s/%s/v1/%d%07d", register, datatype,
                metadata.getModifiedDate().getMillis(), metadata.getPid());
        addElement(entry, ATOM_NAMESPACE_URI, "atom:id", atomId);
        addElement(entry, ATOM_NAMESPACE_URI, "atom:title", null);

        addElement(entry, ATOM_NAMESPACE_URI, "atom:updated",
                AtomDate.toString(metadata.getModifiedDate().toDate()));

        Element content = addElement(entry, ATOM_NAMESPACE_URI, "atom:content", null);
        content.addAttribute("type", "application/xml");

        Element recordElement = addElement(content, stamdataNamespaceUri, datatype, null);
        for (FieldSpecification fieldSpecification : recordSpecification.getFieldSpecs()) {
            addElement(recordElement, stamdataNamespaceUri, fieldSpecification.name,
                    valueAsString(metadata.getRecord(), fieldSpecification));
        }//from   ww w.ja  v  a2s .  c o  m
        DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
        addElement(recordElement, stamdataNamespaceUri, "ValidFrom",
                metadata.getValidFrom().toString(formatter));
        if (metadata.getValidTo() == null) {
            addElement(recordElement, stamdataNamespaceUri, "ValidTo", END_OF_TIME.toString(formatter));
        } else {
            addElement(recordElement, stamdataNamespaceUri, "ValidTo",
                    metadata.getValidTo().toString(formatter));
        }
        addElement(recordElement, stamdataNamespaceUri, "ModifiedDate",
                metadata.getModifiedDate().toString(formatter));
    }

    return convertToW3C(document);
}

From source file:eu.scape_project.planning.criteria.bean.CriteriaHierarchyHelperBean.java

License:Apache License

/**
 * A function which exports all current criteria into a freemind xml string.
 * Used to ease creation of criteria-hierarchies (manual this is a hard
 * job)./*from   ww  w.j a  v a  2 s  .c o m*/
 * 
 * @return the criteria as XML string
 */
private String exportAllCriteriaToFreeMindXml() {
    Document doc = DocumentHelper.createDocument();
    doc.setXMLEncoding("UTF-8");

    Element root = doc.addElement("map");
    Namespace xsi = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

    root.add(xsi);
    root.addAttribute("version", "0.8.1");

    root.addComment(
            "To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net");

    Element baseNode = root.addElement("node");
    baseNode.addAttribute("TEXT", "allCriteria");

    Collection<Measure> allCriteria = criteriaManager.getAllMeasures();
    ArrayList<Measure> allCriteriaSortable = new ArrayList<Measure>(allCriteria);
    Collections.sort(allCriteriaSortable);
    allCriteria = allCriteriaSortable;

    // each criterion should be added as simple node
    for (Measure measure : allCriteria) {
        // construct node text
        String nodeText = measure.getAttribute().getName() + "#" + measure.getName() + "|" + measure.getUri();

        // add node
        Element node = baseNode.addElement("node");
        node.addAttribute("TEXT", nodeText);
    }

    String xml = doc.asXML();
    return xml;
}

From source file:eu.scape_project.planning.criteria.xml.CriteriaHierarchyExporter.java

License:Apache License

/**
 * Method responsible for exporting a CriteriaHierarchy-TreeNode to freemind-xml format.
 * // w  w w  . j  a  v a  2  s .  c om
 * @param criteriaTreeNode CriteriaHierarchy-Treenode to export
 * @return freemind-xml String.
 */
private String exportToFreemindXml(CriteriaTreeNode criteriaTreeNode) {
    Document doc = DocumentHelper.createDocument();
    doc.setXMLEncoding("UTF-8");

    Element root = doc.addElement("map");
    Namespace xsi = new Namespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");

    root.add(xsi);
    root.addAttribute("version", "0.8.1");

    root.addComment(
            "To view this file, download free mind mapping software FreeMind from http://freemind.sourceforge.net");
    addSubTreeFreemind(root, criteriaTreeNode);

    String xml = doc.asXML();

    return xml;
}

From source file:io.selendroid.util.JsonXmlUtil.java

License:Apache License

private static Document buildXmlDoc(JSONObject tree) {
    Document document = DocumentHelper.createDocument();
    document.setXMLEncoding("UTF-8");
    Element root = document.addElement("views");
    buildXmlNode(tree, root);//from w  ww.jav a 2s .c o m
    return document;
}

From source file:nc.noumea.mairie.organigramme.services.exportGraphML.impl.ExportGraphMLServiceOrgaEntitesImpl.java

License:Open Source License

private byte[] exportGraphML(EntiteDto entiteDto, FiltreStatut filtreStatut, Map<String, Boolean> mapIdLiOuvert)
        throws IOException {

    DocumentFactory factory = DocumentFactory.getInstance();
    Element root = factory.createElement("graphml");
    Document document = factory.createDocument(root);
    document.setXMLEncoding("utf-8");

    Element graph = initRoot(root);
    initHeader(root);/*  w  w w. j  a  v a  2  s .com*/
    construitTableauStats(graph, entiteDto);
    buildGraphMlTree(graph, entiteDto, mapIdLiOuvert, filtreStatut);
    ajoutLogoMairie(graph);

    ByteArrayOutputStream os_writer = new ByteArrayOutputStream();
    try {
        BufferedWriter wtr = new BufferedWriter(new OutputStreamWriter(os_writer, "UTF-8"));
        document.write(wtr);
        wtr.flush();
        wtr.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return os_writer.toByteArray();
}

From source file:nc.noumea.mairie.organigramme.services.exportGraphML.impl.ExportGraphMLServiceOrgaFichesPosteImpl.java

License:Open Source License

private byte[] exportGraphML(FichePosteTreeNodeDto node, boolean isAfficheAgent,
        Map<String, Boolean> mapIdLiOuvert) throws IOException {

    DocumentFactory factory = DocumentFactory.getInstance();
    Element root = factory.createElement("graphml");
    Document document = factory.createDocument(root);
    document.setXMLEncoding("utf-8");

    Element graph = initRoot(root);
    initHeader(root);/*from ww  w.  ja  v  a  2 s  .  c o  m*/
    construitTableauStats(graph, this.entiteDto);

    mapFichesPosteSuperieureByService = EntityUtils.getFichesPosteChefDeService(node);
    buildGraphMlTree(graph, node, mapIdLiOuvert, isAfficheAgent, null);

    ByteArrayOutputStream os_writer = new ByteArrayOutputStream();
    try {
        BufferedWriter wtr = new BufferedWriter(new OutputStreamWriter(os_writer, "UTF-8"));
        document.write(wtr);
        wtr.flush();
        wtr.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return os_writer.toByteArray();
}

From source file:nc.noumea.mairie.organigramme.services.impl.ExportGraphMLServiceImpl.java

License:Open Source License

private byte[] exportGraphML(EntiteDto entiteDto, Map<String, Boolean> mapIdLiOuvert) {

    DocumentFactory factory = DocumentFactory.getInstance();
    Element root = factory.createElement("graphml");
    Document document = factory.createDocument(root);
    document.setXMLEncoding("utf-8");

    initHeader(root);//from w w w  .  j  a  v  a  2  s  .  c o  m
    Element graph = initRoot(root);
    buildGraphMlTree(graph, entiteDto, mapIdLiOuvert);

    ByteArrayOutputStream os_writer = new ByteArrayOutputStream();
    try {
        BufferedWriter wtr = new BufferedWriter(new OutputStreamWriter(os_writer, "UTF-8"));
        document.write(wtr);
        wtr.flush();
        wtr.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return os_writer.toByteArray();
}

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()));/*w w w.j  a v a2  s.  c om*/
    } 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();
    }/*from ww w . j  ava2 s  . com*/

    //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();
}