Example usage for org.dom4j.io XMLWriter write

List of usage examples for org.dom4j.io XMLWriter write

Introduction

In this page you can find the example usage for org.dom4j.io XMLWriter write.

Prototype

public void write(Object object) throws IOException 

Source Link

Document

Writes the given object which should be a String, a Node or a List of Nodes.

Usage

From source file:org.apache.isis.core.runtime.services.viewmodelsupport.Dom4jUtil.java

License:Apache License

static String asString(final Document doc) {
    XMLWriter writer = null;
    final StringWriter sw = new StringWriter();
    try {/*from  ww  w  . ja va2  s.c  o m*/
        OutputFormat outputFormat = OutputFormat.createPrettyPrint();
        writer = new XMLWriter(sw, outputFormat);
        writer.write(doc);
        return sw.toString();
    } catch (IOException e) {
        throw new IsisException(e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:org.apache.maven.archetype.common.DefaultPomManager.java

License:Apache License

public void addModule(File pom, String artifactId)
        throws IOException, XmlPullParserException, DocumentException, InvalidPackaging {
    boolean found = false;

    StringWriter writer = new StringWriter();
    Reader fileReader = null;/*from w  w  w  .ja va2  s .  c  o  m*/

    try {
        fileReader = ReaderFactory.newXmlReader(pom);

        SAXReader reader = new SAXReader();
        Document document = reader.read(fileReader);
        Element project = document.getRootElement();

        String packaging = null;
        Element packagingElement = project.element("packaging");
        if (packagingElement != null) {
            packaging = packagingElement.getStringValue();
        }
        if (!"pom".equals(packaging)) {
            throw new InvalidPackaging(
                    "Unable to add module to the current project as it is not of packaging type 'pom'");
        }

        Element modules = project.element("modules");
        if (modules == null) {
            modules = project.addText("  ").addElement("modules");
            modules.setText("\n  ");
            project.addText("\n");
        }
        // TODO: change to while loop
        for (@SuppressWarnings("unchecked")
        Iterator<Element> i = modules.elementIterator("module"); i.hasNext() && !found;) {
            Element module = i.next();
            if (module.getText().equals(artifactId)) {
                found = true;
            }
        }
        if (!found) {
            Node lastTextNode = null;
            for (@SuppressWarnings("unchecked")
            Iterator<Node> i = modules.nodeIterator(); i.hasNext();) {
                Node node = i.next();
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    lastTextNode = null;
                } else if (node.getNodeType() == Node.TEXT_NODE) {
                    lastTextNode = node;
                }
            }

            if (lastTextNode != null) {
                modules.remove(lastTextNode);
            }

            modules.addText("\n    ");
            modules.addElement("module").setText(artifactId);
            modules.addText("\n  ");

            XMLWriter xmlWriter = new XMLWriter(writer);
            xmlWriter.write(document);

            FileUtils.fileWrite(pom.getAbsolutePath(), writer.toString());
        } // end if
    } finally {
        IOUtil.close(fileReader);
    }
}

From source file:org.apache.maven.archetype.old.DefaultOldArchetype.java

License:Apache License

static boolean addModuleToParentPom(String artifactId, Reader fileReader, Writer fileWriter)
        throws DocumentException, IOException, ArchetypeTemplateProcessingException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(fileReader);
    Element project = document.getRootElement();

    String packaging = null;//from  w ww  .  j a  va  2s.  c  o m
    Element packagingElement = project.element("packaging");
    if (packagingElement != null) {
        packaging = packagingElement.getStringValue();
    }
    if (!"pom".equals(packaging)) {
        throw new ArchetypeTemplateProcessingException(
                "Unable to add module to the current project as it is not of packaging type 'pom'");
    }

    Element modules = project.element("modules");
    if (modules == null) {
        modules = project.addText("  ").addElement("modules");
        modules.setText("\n  ");
        project.addText("\n");
    }
    boolean found = false;
    for (Iterator<?> i = modules.elementIterator("module"); i.hasNext() && !found;) {
        Element module = (Element) i.next();
        if (module.getText().equals(artifactId)) {
            found = true;
        }
    }
    if (!found) {
        Node lastTextNode = null;
        for (Iterator<?> i = modules.nodeIterator(); i.hasNext();) {
            Node node = (Node) i.next();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                lastTextNode = null;
            } else if (node.getNodeType() == Node.TEXT_NODE) {
                lastTextNode = node;
            }
        }

        if (lastTextNode != null) {
            modules.remove(lastTextNode);
        }

        modules.addText("\n    ");
        modules.addElement("module").setText(artifactId);
        modules.addText("\n  ");

        XMLWriter writer = new XMLWriter(fileWriter);
        writer.write(document);
    }
    return !found;
}

From source file:org.apache.maven.plugin.idea.AbstractIdeaMojo.java

License:Apache License

protected void writeXmlDocument(File file, Document document) throws IOException {
    XMLWriter writer = new IdeaXmlWriter(file);
    writer.write(document);
    writer.close();//w w  w.j ava  2  s.c  o  m
}

From source file:org.apache.openmeetings.core.documents.CreateLibraryPresentation.java

License:Apache License

public static ConverterProcessResult generateXMLDocument(File targetDirectory, String originalDocument,
        String pdfDocument, String swfDocument) {
    ConverterProcessResult returnMap = new ConverterProcessResult();
    returnMap.setProcess("generateXMLDocument");
    try {//from w  w w. j  av a  2s  . c  om
        Document document = DocumentHelper.createDocument();
        Element root = document.addElement("presentation");

        File file = new File(targetDirectory, originalDocument);
        root.addElement("originalDocument").addAttribute("lastmod", (new Long(file.lastModified())).toString())
                .addAttribute("size", (new Long(file.length())).toString()).addText(originalDocument);

        if (pdfDocument != null) {
            File pdfDocumentFile = new File(targetDirectory, pdfDocument);
            root.addElement("pdfDocument")
                    .addAttribute("lastmod", (new Long(pdfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(pdfDocumentFile.length())).toString()).addText(pdfDocument);
        }

        if (swfDocument != null) {
            File swfDocumentFile = new File(targetDirectory, originalDocument);
            root.addElement("swfDocument")
                    .addAttribute("lastmod", (new Long(swfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(swfDocumentFile.length())).toString()).addText(swfDocument);
        }

        Element thumbs = root.addElement("thumbs");

        //Second get all Files of this Folder
        FilenameFilter ff = new FilenameFilter() {
            @Override
            public boolean accept(File b, String name) {
                File f = new File(b, name);
                return f.isFile();
            }
        };

        String[] allfiles = targetDirectory.list(ff);
        if (allfiles != null) {
            Arrays.sort(allfiles);
            for (int i = 0; i < allfiles.length; i++) {
                File thumbfile = new File(targetDirectory, allfiles[i]);
                if (allfiles[i].startsWith(thumbImagePrefix)) {
                    thumbs.addElement("thumb")
                            .addAttribute("lastmod", (new Long(thumbfile.lastModified())).toString())
                            .addAttribute("size", (new Long(thumbfile.length())).toString())
                            .addText(allfiles[i]);
                }
            }
        }

        // lets write to a file
        XMLWriter writer = new XMLWriter(
                new FileOutputStream(new File(targetDirectory, OmFileHelper.libraryFileName)));
        writer.write(document);
        writer.close();

        returnMap.setExitValue("0");

        return returnMap;
    } catch (Exception err) {
        log.error("Error while generateXMLDocument", err);
        returnMap.setError(err.getMessage());
        returnMap.setExitValue("-1");
        return returnMap;
    }
}

From source file:org.apache.openmeetings.documents.CreateLibraryPresentation.java

License:Apache License

public static ConverterProcessResult generateXMLDocument(File targetDirectory, String originalDocument,
        String pdfDocument, String swfDocument) {
    ConverterProcessResult returnMap = new ConverterProcessResult();
    returnMap.setProcess("generateXMLDocument");
    try {//from  w w w .  ja v  a  2s .com

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

        File file = new File(targetDirectory, originalDocument);
        root.addElement("originalDocument").addAttribute("lastmod", (new Long(file.lastModified())).toString())
                .addAttribute("size", (new Long(file.length())).toString()).addText(originalDocument);

        if (pdfDocument != null) {
            File pdfDocumentFile = new File(targetDirectory, pdfDocument);
            root.addElement("pdfDocument")
                    .addAttribute("lastmod", (new Long(pdfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(pdfDocumentFile.length())).toString()).addText(pdfDocument);
        }

        if (swfDocument != null) {
            File swfDocumentFile = new File(targetDirectory, originalDocument);
            root.addElement("swfDocument")
                    .addAttribute("lastmod", (new Long(swfDocumentFile.lastModified())).toString())
                    .addAttribute("size", (new Long(swfDocumentFile.length())).toString()).addText(swfDocument);
        }

        Element thumbs = root.addElement("thumbs");

        //Secoond get all Files of this Folder
        FilenameFilter ff = new FilenameFilter() {
            public boolean accept(File b, String name) {
                File f = new File(b, name);
                return f.isFile();
            }
        };

        String[] allfiles = targetDirectory.list(ff);
        if (allfiles != null) {
            Arrays.sort(allfiles);
            for (int i = 0; i < allfiles.length; i++) {
                File thumbfile = new File(targetDirectory, allfiles[i]);
                if (allfiles[i].startsWith("_thumb_")) {
                    thumbs.addElement("thumb")
                            .addAttribute("lastmod", (new Long(thumbfile.lastModified())).toString())
                            .addAttribute("size", (new Long(thumbfile.length())).toString())
                            .addText(allfiles[i]);
                }
            }
        }

        // lets write to a file
        XMLWriter writer = new XMLWriter(
                new FileOutputStream(new File(targetDirectory, OmFileHelper.libraryFileName)));
        writer.write(document);
        writer.close();

        returnMap.setExitValue("0");

        return returnMap;
    } catch (Exception err) {
        err.printStackTrace();
        returnMap.setError(err.getMessage());
        returnMap.setExitValue("-1");
        return returnMap;
    }
}

From source file:org.apache.openmeetings.documents.InstallationDocumentHandler.java

License:Apache License

public static void createDocument(Integer stepNo) throws Exception {

    Document document = DocumentHelper.createDocument();

    Element root = document.addElement("install");
    Element step = root.addElement("step");

    step.addElement("stepnumber").addText(stepNo.toString());
    step.addElement("stepname").addText("Step " + stepNo);

    XMLWriter writer = new XMLWriter(new FileWriter(OmFileHelper.getInstallFile()));
    writer.write(document);
    writer.close();//from  w  w  w.ja  va 2  s.  c om

}

From source file:org.apache.openmeetings.installation.InstallationDocumentHandler.java

License:Apache License

public static void createDocument(int stepNo) throws Exception {
    Document document = DocumentHelper.createDocument();

    Element root = document.addElement("install");
    Element step = root.addElement("step");

    step.addElement("stepnumber").addText("" + stepNo);
    step.addElement("stepname").addText("Step " + stepNo);

    try (OutputStream os = new FileOutputStream(OmFileHelper.getInstallFile())) {
        XMLWriter writer = new XMLWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
        writer.write(document);
        writer.close();//from  w  ww .j av a2  s .  c  o  m
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.CalendarServlet.java

License:Apache License

@Override
protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws ServletException, IOException {

    try {/*  w ww  .j  a  v  a2s .com*/
        String sid = httpServletRequest.getParameter("sid");

        if (sid == null) {
            sid = "default";
        }
        log.debug("sid: " + sid);

        Long users_id = getBean(SessiondataDao.class).checkSession(sid);
        Long user_level = getBean(UserManager.class).getUserLevelByID(users_id);

        if (user_level != null && user_level > 0) {

            String timeZoneIdAsStr = httpServletRequest.getParameter("timeZoneId");

            if (timeZoneIdAsStr == null) {
                log.error("No timeZoneIdAsStr given, using default");
                timeZoneIdAsStr = "";
            }

            TimeZone timezone = getBean(TimezoneUtil.class)
                    .getTimezoneByOmTimeZoneId(Long.valueOf(timeZoneIdAsStr).longValue());

            String yearStr = httpServletRequest.getParameter("year");
            String monthStr = httpServletRequest.getParameter("month");
            String userStr = httpServletRequest.getParameter("user");
            String contactUser = httpServletRequest.getParameter("contactUser");

            Calendar starttime = GregorianCalendar.getInstance(timezone);
            starttime.set(Calendar.DATE, 1);
            starttime.set(Calendar.MONTH, Integer.parseInt(monthStr) - 1);
            starttime.set(Calendar.MINUTE, 0);
            starttime.set(Calendar.SECOND, 0);
            starttime.set(Calendar.YEAR, Integer.parseInt(yearStr));

            Calendar endtime = GregorianCalendar.getInstance(timezone);
            endtime.set(Calendar.DATE, 1);
            endtime.set(Calendar.MONTH, Integer.parseInt(monthStr));
            endtime.set(Calendar.MINUTE, 0);
            endtime.set(Calendar.SECOND, 0);
            endtime.set(Calendar.YEAR, Integer.parseInt(yearStr));

            Long userToShowId = Long.parseLong(contactUser);
            if (userToShowId == 0) {
                userToShowId = Long.parseLong(userStr);
            }

            List<Appointment> appointements = getBean(AppointmentLogic.class).getAppointmentByRange(
                    userToShowId, new Date(starttime.getTimeInMillis()), new Date(endtime.getTimeInMillis()));

            Document document = DocumentHelper.createDocument();
            document.setXMLEncoding("UTF-8");
            document.addComment("###############################################\n"
                    + getServletContext().getServletContextName() + " Calendar \n"
                    + "###############################################");

            Element vcalendar = document.addElement("vcalendar");

            Element year = vcalendar.addElement("year" + yearStr);
            Element month = year.addElement("month" + monthStr);

            int previousDay = 0;
            Element day = null;

            for (Appointment appointment : appointements) {

                Calendar appStart = Calendar.getInstance(timezone);
                appStart.setTime(appointment.getAppointmentStarttime());

                int dayAsInt = appStart.get(Calendar.DATE);

                if (previousDay != dayAsInt) {

                    day = month.addElement("day" + dayAsInt);

                    previousDay = dayAsInt;

                }

                if (appStart.get(Calendar.MONTH) + 1 == Integer.parseInt(monthStr)) {

                    Element event = day.addElement("event");

                    Element appointementId = event.addElement("appointementId");
                    appointementId.addAttribute("value", "" + appointment.getAppointmentId());

                    Element isConnectedEvent = event.addElement("isConnectedEvent");
                    isConnectedEvent.addAttribute("value", "" + appointment.getIsConnectedEvent());

                    Element rooms_id = event.addElement("rooms_id");
                    Element roomtype = event.addElement("roomtype");
                    if (appointment.getRoom() != null) {
                        rooms_id.addAttribute("value", "" + appointment.getRoom().getRooms_id());
                        roomtype.addAttribute("value",
                                "" + appointment.getRoom().getRoomtype().getRoomtypes_id());
                    } else {
                        rooms_id.addAttribute("value", "0");
                        roomtype.addAttribute("value", "1");
                    }
                    Element remindType = event.addElement("remindtype");
                    remindType.addAttribute("value",
                            appointment.getRemind() != null ? "" + appointment.getRemind().getTypId() : "0");

                    Element summary = event.addElement("summary");
                    summary.addAttribute("value", appointment.getAppointmentName());

                    Element comment = event.addElement("comment");
                    comment.addAttribute("value", appointment.getAppointmentDescription());

                    Element start = event.addElement("start");

                    start.addAttribute("year", "" + appStart.get(Calendar.YEAR));
                    start.addAttribute("month", "" + (appStart.get(Calendar.MONTH) + 1));
                    start.addAttribute("day", "" + appStart.get(Calendar.DATE));
                    start.addAttribute("hour", "" + appStart.get(Calendar.HOUR_OF_DAY));
                    start.addAttribute("minute", "" + appStart.get(Calendar.MINUTE));

                    Calendar appEnd = Calendar.getInstance(timezone);
                    appEnd.setTime(appointment.getAppointmentEndtime());
                    Element end = event.addElement("end");
                    end.addAttribute("year", "" + appEnd.get(Calendar.YEAR));
                    end.addAttribute("month", "" + (appEnd.get(Calendar.MONTH) + 1));
                    end.addAttribute("day", "" + appEnd.get(Calendar.DATE));
                    end.addAttribute("hour", "" + appEnd.get(Calendar.HOUR_OF_DAY));
                    end.addAttribute("minute", "" + appEnd.get(Calendar.MINUTE));

                    Element category = event.addElement("category");
                    category.addAttribute("value", "" + appointment.getAppointmentCategory().getCategoryId());

                    Element uid = event.addElement("uid");
                    uid.addAttribute("value", "" + appointment.getAppointmentId());

                    Element attendees = event.addElement("attendees");

                    for (MeetingMember meetingMember : appointment.getMeetingMember()) {

                        Element attendee = attendees.addElement("attendee");

                        Element email = attendee.addElement("email");
                        email.addAttribute("value", meetingMember.getEmail());

                        Element userId = attendee.addElement("userId");
                        if (meetingMember.getUserid() != null) {
                            userId.addAttribute("value", "" + meetingMember.getUserid().getUser_id());
                        } else {
                            userId.addAttribute("value", "");
                        }

                        Element memberId = attendee.addElement("memberId");
                        memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId());

                        Element firstname = attendee.addElement("firstname");
                        memberId.addAttribute("value", "" + meetingMember.getMeetingMemberId());
                        firstname.addAttribute("value", meetingMember.getFirstname());

                        Element lastname = attendee.addElement("lastname");
                        lastname.addAttribute("value", meetingMember.getLastname());

                        Element jNameTimeZoneMember = attendee.addElement("jNameTimeZone");
                        if (meetingMember.getOmTimeZone() != null) {
                            jNameTimeZoneMember.addAttribute("value", meetingMember.getOmTimeZone().getJname());
                        } else {
                            jNameTimeZoneMember.addAttribute("value", "");
                        }

                    }

                }

            }

            httpServletResponse.reset();
            httpServletResponse.resetBuffer();
            OutputStream out = httpServletResponse.getOutputStream();
            httpServletResponse.setContentType("text/xml");

            // httpServletResponse.setHeader("Content-Length", ""+
            // rf.length());

            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setEncoding("UTF-8");
            XMLWriter writer = new XMLWriter(out, outformat);
            writer.write(document);
            writer.flush();

            out.flush();
            out.close();

        }
    } catch (ServerNotInitializedException e) {
        return;
    } catch (Exception er) {
        log.error("[Calendar :: service]", er);
    }
}

From source file:org.apache.openmeetings.servlet.outputhandler.LangExport.java

License:Apache License

public static void serializetoXML(OutputStream out, String aEncodingScheme, Document doc) throws Exception {
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding(aEncodingScheme);
    XMLWriter writer = new XMLWriter(out, outformat);
    writer.write(doc);
    writer.flush();//from  w  w w .ja  v  a 2s. c om
}