Example usage for org.dom4j.io XMLWriter flush

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

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the underlying Writer

Usage

From source file:org.apache.directory.studio.ldapbrowser.core.BrowserConnectionIO.java

License:Apache License

/**
 * Saves the browser connections using the output stream.
 *
 * @param stream//w w w. jav a 2  s  .co  m
 *      the OutputStream
 * @param browserConnectionMap
 *      the map of browser connections
 * @throws IOException
 *      if an I/O error occurs
 */
public static void save(OutputStream stream, Map<String, IBrowserConnection> browserConnectionMap)
        throws IOException {
    // Creating the Document
    Document document = DocumentHelper.createDocument();

    // Creating the root element
    Element root = document.addElement(BROWSER_CONNECTIONS_TAG);

    if (browserConnectionMap != null) {
        for (IBrowserConnection browserConnection : browserConnectionMap.values()) {
            writeBrowserConnection(root, browserConnection);
        }
    }

    // Writing the file to disk
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$
    XMLWriter writer = new XMLWriter(stream, outformat);
    writer.write(document);
    writer.flush();
}

From source file:org.apache.directory.studio.ldapservers.LdapServersManagerIO.java

License:Apache License

/**
 * Writes the list of servers to the given stream.
 *
 * @param servers/* www . j a  v  a 2 s . c o  m*/
 *      the servers
 * @param outputStream
 *      the output stream
 * @throws IOException
 *      if an error occurs when writing to the stream
 */
public static void write(List<LdapServer> servers, OutputStream outputStream) throws IOException {
    // Creating the Document
    Document document = DocumentHelper.createDocument();

    // Creating the root element
    Element root = document.addElement(LDAP_SERVERS_TAG);

    if (servers != null) {
        for (LdapServer server : servers) {
            addLdapServer(server, root);
        }
    }

    // Writing the file to the stream
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$
    XMLWriter writer = new XMLWriter(outputStream, outformat);
    writer.write(document);
    writer.flush();
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileExporter.java

License:Apache License

/**
 * Converts the given schema to its source code representation
 * in XML file format./*from  w ww  .ja v a 2s. com*/
 *
 * @param schema
 *      the schema to convert
 * @return
 *      the corresponding source code representation
 * @throws IOException
 */
public static String toXml(Schema schema) throws IOException {
    // Creating the Document
    Document document = DocumentHelper.createDocument();

    // Adding the schema
    addSchema(schema, document);

    // Creating the output stream we're going to put the XML in
    OutputStream os = new ByteArrayOutputStream();
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$

    // Writing the XML.
    XMLWriter writer = new XMLWriter(os, outformat);
    writer.write(document);
    writer.flush();
    writer.close();

    return os.toString();
}

From source file:org.apache.directory.studio.schemaeditor.model.io.XMLSchemaFileExporter.java

License:Apache License

/**
 * Converts the given schemas to their source code representation
 * in one XML file format./*from   w w  w .  ja va2 s. com*/
 *
 * @param schemas
 *      the array of schemas to convert
 * @return
 *      the corresponding source code representation
 * @throws IOException
 */
public static String toXml(Schema[] schemas) throws IOException {
    // Creating the Document and the 'root' Element
    Document document = DocumentHelper.createDocument();

    addSchemas(schemas, document);

    // Creating the output stream we're going to put the XML in
    OutputStream os = new ByteArrayOutputStream();
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$

    // Writing the XML.
    XMLWriter writer = new XMLWriter(os, outformat);
    writer.write(document);
    writer.flush();
    writer.close();

    return os.toString();
}

From source file:org.apache.directory.studio.schemaeditor.PluginUtils.java

License:Apache License

/**
 * Saves the projects in the Projects File.
 */// w  w w  . j a  va 2 s.  c  o  m
public static void saveProjects() {
    try {
        // Saving the projects to the temp projects file
        OutputFormat outformat = OutputFormat.createPrettyPrint();
        outformat.setEncoding("UTF-8"); //$NON-NLS-1$
        XMLWriter writer = new XMLWriter(new FileOutputStream(getTempProjectsFile()), outformat);
        writer.write(ProjectsExporter
                .toDocument(Activator.getDefault().getProjectsHandler().getProjects().toArray(new Project[0])));
        writer.flush();

        // Copying the temp projects file to the final location
        String content = FileUtils.readFileToString(getTempProjectsFile(), "UTF-8"); //$NON-NLS-1$
        FileUtils.writeStringToFile(getProjectsFile(), content, "UTF-8"); //$NON-NLS-1$
    } catch (IOException e) {
        // If an error occurs when saving to the temp projects file or
        // when copying the temp projects file to the final location,
        // we try to save the projects directly to the final location.
        try {
            OutputFormat outformat = OutputFormat.createPrettyPrint();
            outformat.setEncoding("UTF-8"); //$NON-NLS-1$
            XMLWriter writer = new XMLWriter(new FileOutputStream(getProjectsFile()), outformat);
            writer.write(ProjectsExporter.toDocument(
                    Activator.getDefault().getProjectsHandler().getProjects().toArray(new Project[0])));
            writer.flush();
        } catch (IOException e2) {
            // If another error occur, we display an error
            reportError(Messages.getString("PluginUtils.ErrorSavingProject"), e2, Messages //$NON-NLS-1$
                    .getString("PluginUtils.ProjectsSavingError"), //$NON-NLS-1$
                    Messages.getString("PluginUtils.ErrorSavingProject")); //$NON-NLS-1$
        }
    }
}

From source file:org.apache.directory.studio.schemaeditor.view.wizards.ExportProjectsWizard.java

License:Apache License

/**
 * {@inheritDoc}/* w  ww .j  av a 2 s  . c o m*/
 */
public boolean performFinish() {
    // Saving the dialog settings
    page.saveDialogSettings();

    // Getting the projects to be exported and where to export them
    final Project[] selectedProjects = page.getSelectedProjects();
    final String exportDirectory = page.getExportDirectory();
    try {
        getContainer().run(false, false, new IRunnableWithProgress() {
            public void run(IProgressMonitor monitor) {
                monitor.beginTask(Messages.getString("ExportProjectsWizard.ExportingProject"), //$NON-NLS-1$
                        selectedProjects.length);
                for (Project project : selectedProjects) {
                    monitor.subTask(project.getName());

                    try {
                        OutputFormat outformat = OutputFormat.createPrettyPrint();
                        outformat.setEncoding("UTF-8"); //$NON-NLS-1$
                        XMLWriter writer = new XMLWriter(new FileOutputStream(exportDirectory + "/" //$NON-NLS-1$
                                + project.getName() + ".schemaproject"), outformat); //$NON-NLS-1$
                        writer.write(ProjectsExporter.toDocument(project));
                        writer.flush();
                    } catch (UnsupportedEncodingException e) {
                        PluginUtils.logError(
                                NLS.bind(Messages.getString("ExportProjectsWizard.ErrorWhenSavingProject"), //$NON-NLS-1$
                                        new String[] { project.getName() }),
                                e);
                        ViewUtils.displayErrorMessageDialog(Messages.getString("ExportProjectsWizard.Error"), //$NON-NLS-1$
                                NLS.bind(Messages.getString("ExportProjectsWizard.ErrorWhenSavingProject"), //$NON-NLS-1$
                                        new String[] { project.getName() }));
                    } catch (FileNotFoundException e) {
                        PluginUtils.logError(
                                NLS.bind(Messages.getString("ExportProjectsWizard.ErrorWhenSavingProject"), //$NON-NLS-1$
                                        new String[] { project.getName() }),
                                e);
                        ViewUtils.displayErrorMessageDialog(Messages.getString("ExportProjectsWizard.Error"), //$NON-NLS-1$
                                NLS.bind(Messages.getString("ExportProjectsWizard.ErrorWhenSavingProject"), //$NON-NLS-1$
                                        new String[] { project.getName() }));
                    } catch (IOException e) {
                        PluginUtils.logError(
                                NLS.bind(Messages.getString("ExportProjectsWizard.ErrorWhenSavingProject"), //$NON-NLS-1$
                                        new String[] { project.getName() }),
                                e);
                        ViewUtils.displayErrorMessageDialog(Messages.getString("ExportProjectsWizard.Error"), //$NON-NLS-1$
                                NLS.bind(Messages.getString("ExportProjectsWizard.ErrorWhenSavingProject"), //$NON-NLS-1$
                                        new String[] { project.getName() }));
                    }
                    monitor.worked(1);
                }
                monitor.done();
            }
        });
    } catch (InvocationTargetException e) {
        // Nothing to do (it will never occur)
    } catch (InterruptedException e) {
        // Nothing to do.
    }

    return true;
}

From source file:org.apache.directory.studio.templateeditor.model.parser.TemplateIO.java

License:Apache License

/**
 * Saves the template using the writer./*from  w w  w  .j  a v  a  2s .  c  o  m*/
 *
 * @param template
 *      the connections
 * @param stream
 *      the OutputStream
 * @throws IOException
 *      if an I/O error occurs
 */
public static void save(Template template, OutputStream stream) throws IOException {
    // Creating the Document
    Document document = DocumentHelper.createDocument();

    writeTemplate(document, template);

    // Writing the file to disk
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding("UTF-8"); //$NON-NLS-1$
    XMLWriter writer = new XMLWriter(stream, outformat);
    writer.write(document);
    writer.flush();
    writer.close();
}

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 {//from ww w.j a va2 s .co m
        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);/*from w  w  w. j  ava  2 s  .co  m*/
    writer.flush();
}

From source file:org.apache.openmeetings.util.LangExport.java

License:Apache License

public static void serializetoXML(Writer out, String aEncodingScheme, Document doc) throws Exception {
    OutputFormat outformat = OutputFormat.createPrettyPrint();
    outformat.setEncoding(aEncodingScheme);
    XMLWriter writer = new XMLWriter(out, outformat);
    writer.write(doc);/*w  w  w  .j  a  v  a2s .  co m*/
    writer.flush();
}