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.waarp.openr66.database.data.DbTaskRunner.java

License:Open Source License

/**
 * Write selected TaskRunners to an XML file using an XMLWriter
 * //from   w ww  .j  a  v  a  2s.c  o  m
 * @param preparedStatement
 * @param filename
 * @return the NbAndSpecialId for the number of transfer and higher rank found
 * @throws WaarpDatabaseNoConnectionException
 * @throws WaarpDatabaseSqlException
 * @throws OpenR66ProtocolBusinessException
 */
public static NbAndSpecialId writeXMLWriter(DbPreparedStatement preparedStatement, String filename)
        throws WaarpDatabaseNoConnectionException, WaarpDatabaseSqlException, OpenR66ProtocolBusinessException {
    NbAndSpecialId nbAndSpecialId = null;
    OutputStream outputStream = null;
    XMLWriter xmlWriter = null;
    try {
        outputStream = new FileOutputStream(filename);
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("ISO-8859-1");
        xmlWriter = new XMLWriter(outputStream, format);
        preparedStatement.executeQuery();
        nbAndSpecialId = writeXML(preparedStatement, xmlWriter);
    } catch (FileNotFoundException e) {
        logger.error("Cannot write XML file", e);
        throw new OpenR66ProtocolBusinessException("File not found");
    } catch (UnsupportedEncodingException e) {
        logger.error("Cannot write XML file", e);
        throw new OpenR66ProtocolBusinessException("Unsupported Encoding");
    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.endDocument();
                xmlWriter.flush();
                xmlWriter.close();
            } catch (SAXException e) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                File file = new File(filename);
                file.delete();
                logger.error("Cannot write XML file", e);
                throw new OpenR66ProtocolBusinessException("Unsupported Encoding");
            } catch (IOException e) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                File file = new File(filename);
                file.delete();
                logger.error("Cannot write XML file", e);
                throw new OpenR66ProtocolBusinessException("Unsupported Encoding");
            }
        } else if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
            }
            File file = new File(filename);
            file.delete();
        }
    }
    return nbAndSpecialId;
}

From source file:org.waarp.openr66.database.data.DbTaskRunner.java

License:Open Source License

/**
 * Method to write the current DbTaskRunner for NoDb client instead of updating DB. 'setToArray'
 * must be called priorly to be able to store the values.
 * /*w w w .  j a v  a 2s  .c om*/
 * @throws OpenR66ProtocolBusinessException
 */
public void writeXmlWorkNoDb() throws OpenR66ProtocolBusinessException {
    String filename = backendXmlFilename();
    OutputStream outputStream = null;
    XMLWriter xmlWriter = null;
    try {
        outputStream = new FileOutputStream(filename);
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("ISO-8859-1");
        xmlWriter = new XMLWriter(outputStream, format);
        Element root = new DefaultElement(XMLRUNNERS);
        try {
            xmlWriter.writeOpen(root);
            Element node;
            node = DbTaskRunner.getElementFromRunner(this);
            xmlWriter.write(node);
            xmlWriter.flush();
            xmlWriter.writeClose(root);
        } catch (IOException e) {
            logger.error("Cannot write XML file", e);
            throw new OpenR66ProtocolBusinessException("Cannot write file: " + e.getMessage());
        } catch (WaarpDatabaseSqlException e) {
            logger.error("Cannot write Data", e);
            throw new OpenR66ProtocolBusinessException("Cannot write Data: " + e.getMessage());
        }
    } catch (FileNotFoundException e) {
        logger.error("Cannot write XML file", e);
        throw new OpenR66ProtocolBusinessException("File not found");
    } catch (UnsupportedEncodingException e) {
        logger.error("Cannot write XML file", e);
        throw new OpenR66ProtocolBusinessException("Unsupported Encoding");
    } finally {
        if (xmlWriter != null) {
            try {
                xmlWriter.endDocument();
                xmlWriter.flush();
                xmlWriter.close();
            } catch (SAXException e) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                File file = new File(filename);
                file.delete();
                logger.error("Cannot write XML file", e);
                throw new OpenR66ProtocolBusinessException("Unsupported Encoding");
            } catch (IOException e) {
                try {
                    outputStream.close();
                } catch (IOException e2) {
                }
                File file = new File(filename);
                file.delete();
                logger.error("Cannot write XML file", e);
                throw new OpenR66ProtocolBusinessException("Unsupported Encoding");
            }
        } else if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
            }
            File file = new File(filename);
            file.delete();
        }
    }
}

From source file:org.xwiki.tool.xar.XARMojo.java

License:Open Source License

private void performTransformations() throws Exception {
    if (this.transformations == null) {
        return;/*from  ww  w  . ja v a 2s  .  c  om*/
    }

    // Copy XML pages from dependent XAR if we modify them.
    unpackTransformedXARs();

    SAXReader reader = new SAXReader();

    // For each defined file, perform the transformation asked
    for (Transformation transformation : this.transformations) {
        File file = new File(this.project.getBuild().getOutputDirectory(), transformation.getFile());
        Document document = reader.read(file);
        Node node = document.selectSingleNode(transformation.getXpath());
        String value = transformation.getValue();
        if (!StringUtils.isEmpty(value)) {
            // Get the current value at node and replace $1 with it (if any)
            String currentValue = node.getText();
            node.setText(value.replace("$1", currentValue));
        }
        // Write the modified file to disk
        XMLWriter writer = new XMLWriter(new FileOutputStream(file));
        writer.write(document);
        writer.flush();
        writer.close();
    }
}

From source file:org.zmail.bp.GenerateBulkProvisionFileFromLDAP.java

License:Open Source License

public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZmailSoapContext zsc = getZmailSoapContext(context);
    Map<String, Object> attrs = AdminService.getAttrs(request, true);
    String password = null;/*  w ww. j a v  a  2 s  .c  o m*/
    Element elPassword = request.getOptionalElement(AdminExtConstants.A_password);
    if (elPassword != null) {
        password = elPassword.getTextTrim();
    }
    String generatePwd = request.getElement(AdminExtConstants.A_generatePassword).getTextTrim();
    Element elPasswordLength = request.getOptionalElement(AdminExtConstants.A_genPasswordLength);
    String fileFormat = request.getElement(AdminExtConstants.A_fileFormat).getTextTrim();
    String mustChangePassword = request.getElement(AdminExtConstants.E_mustChangePassword).getTextTrim();

    int genPwdLength = 0;
    if (generatePwd == null) {
        generatePwd = "false";
    } else if (generatePwd.equalsIgnoreCase("true")) {
        if (elPasswordLength != null) {
            genPwdLength = Integer.valueOf(elPasswordLength.getTextTrim());
        } else {
            genPwdLength = DEFAULT_PWD_LENGTH;
        }
        if (genPwdLength < 1) {
            genPwdLength = DEFAULT_PWD_LENGTH;
        }
    }
    int maxResults = 0;
    Element elMaxResults = request.getOptionalElement(AdminExtConstants.A_maxResults);
    if (elMaxResults != null) {
        maxResults = Integer.parseInt(elMaxResults.getTextTrim());
    }
    GalParams.ExternalGalParams galParams = new GalParams.ExternalGalParams(attrs, GalOp.search);
    Element response = zsc.createElement(AdminExtConstants.GENERATE_BULK_PROV_FROM_LDAP_RESPONSE);
    String fileToken = Double.toString(Math.random() * 100);
    LdapGalMapRules rules = new LdapGalMapRules(Provisioning.getInstance().getConfig(), true);
    try {
        SearchGalResult result = LdapGalSearch.searchLdapGal(galParams, GalOp.search, "*", maxResults, rules,
                null, null);

        List<GalContact> entries = result.getMatches();
        int totalAccounts = 0;
        int totalDomains = 0;
        int totalExistingDomains = 0;
        int totalExistingAccounts = 0;
        List<String> domainList = new ArrayList<String>();
        if (entries != null) {
            String outFileName = null;
            if (FILE_FORMAT_PREVIEW.equalsIgnoreCase(fileFormat)) {
                String SMTPHost = "";
                String SMTPPort = "";

                Element eSMTPHost = request.getOptionalElement(AdminExtConstants.E_SMTPHost);
                if (eSMTPHost != null) {
                    SMTPHost = eSMTPHost.getTextTrim();
                }
                Element eSMTPPort = request.getOptionalElement(AdminExtConstants.E_SMTPPort);
                if (eSMTPPort != null) {
                    SMTPPort = eSMTPPort.getTextTrim();
                }
                for (GalContact entry : entries) {
                    String mail = entry.getSingleAttr(ContactConstants.A_email);
                    if (mail == null)
                        continue;

                    String parts[] = EmailUtil.getLocalPartAndDomain(mail);
                    if (parts == null)
                        continue;

                    if (!domainList.contains(parts[1])) {
                        totalDomains++;
                        //Check if this domain is in Zmail
                        Domain domain = Provisioning.getInstance().getDomainByName(parts[1]);
                        if (domain != null) {
                            totalExistingDomains++;
                        }
                        domainList.add(parts[1]);
                    }
                    totalAccounts++;
                    Account acct = Provisioning.getInstance().getAccountByName(mail);
                    if (acct != null) {
                        totalExistingAccounts++;
                    }
                }
                response.addElement(AdminExtConstants.E_totalCount).setText(Integer.toString(totalAccounts));
                response.addElement(AdminExtConstants.E_domainCount).setText(Integer.toString(totalDomains));
                response.addElement(AdminExtConstants.E_skippedAccountCount)
                        .setText(Integer.toString(totalExistingAccounts));
                response.addElement(AdminExtConstants.E_skippedDomainCount)
                        .setText(Integer.toString(totalExistingDomains));
                response.addElement(AdminExtConstants.E_SMTPHost).setText(SMTPHost);
                response.addElement(AdminExtConstants.E_SMTPPort).setText(SMTPPort);
                return response;
            } else if (AdminFileDownload.FILE_FORMAT_BULK_CSV.equalsIgnoreCase(fileFormat)) {
                outFileName = String.format("%s%s_bulk_%s_%s.csv", LC.zmail_tmp_directory.value(),
                        File.separator, zsc.getAuthtokenAccountId(), fileToken);
                FileOutputStream out = null;
                CSVWriter writer = null;
                try {
                    out = new FileOutputStream(outFileName);
                    writer = new CSVWriter(new OutputStreamWriter(out));
                    for (GalContact entry : entries) {
                        String mail = entry.getSingleAttr(ContactConstants.A_email);
                        if (mail == null)
                            continue;

                        String[] line = new String[6];
                        line[0] = mail;
                        line[1] = entry.getSingleAttr(ContactConstants.A_fullName);
                        line[2] = entry.getSingleAttr(ContactConstants.A_firstName);
                        line[3] = entry.getSingleAttr(ContactConstants.A_lastName);
                        if (password != null) {
                            line[4] = password;
                        } else if (generatePwd.equalsIgnoreCase("true")) {
                            line[4] = String.valueOf(BulkImportAccounts.generateStrongPassword(genPwdLength));
                        }

                        line[5] = mustChangePassword;
                        writer.writeNext(line);
                    }
                    writer.close();
                } catch (IOException e) {
                    throw ServiceException.FAILURE(e.getMessage(), e);
                } finally {
                    if (writer != null) {
                        try {
                            writer.close();
                        } catch (IOException ignore) {
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else if (AdminFileDownload.FILE_FORMAT_BULK_XML.equalsIgnoreCase(fileFormat)) {
                outFileName = String.format("%s%s_bulk_%s_%s.xml", LC.zmail_tmp_directory.value(),
                        File.separator, zsc.getAuthtokenAccountId(), fileToken);
                FileWriter fileWriter = null;
                XMLWriter xw = null;
                try {
                    fileWriter = new FileWriter(outFileName);
                    xw = new XMLWriter(fileWriter, org.dom4j.io.OutputFormat.createPrettyPrint());
                    Document doc = DocumentHelper.createDocument();
                    org.dom4j.Element rootEl = DocumentHelper.createElement(AdminExtConstants.E_ZCSImport);
                    org.dom4j.Element usersEl = DocumentHelper.createElement(AdminExtConstants.E_ImportUsers);
                    doc.add(rootEl);
                    rootEl.add(usersEl);
                    for (GalContact entry : entries) {
                        String email = entry.getSingleAttr(ContactConstants.A_email);
                        if (email == null)
                            continue;

                        org.dom4j.Element eUser = DocumentHelper.createElement(AdminExtConstants.E_User);
                        org.dom4j.Element eName = DocumentHelper
                                .createElement(AdminExtConstants.E_ExchangeMail);

                        if (email != null) {
                            eName.setText(email);
                        }
                        eUser.add(eName);

                        org.dom4j.Element eDisplayName = DocumentHelper
                                .createElement(Provisioning.A_displayName);
                        String fullName = entry.getSingleAttr(ContactConstants.A_fullName);
                        if (fullName != null) {
                            eDisplayName.setText(fullName);
                        }
                        eUser.add(eDisplayName);

                        org.dom4j.Element eGivenName = DocumentHelper.createElement(Provisioning.A_givenName);
                        String firstName = entry.getSingleAttr(ContactConstants.A_firstName);
                        if (firstName != null) {
                            eGivenName.setText(firstName);
                        }
                        eUser.add(eGivenName);

                        org.dom4j.Element eLastName = DocumentHelper.createElement(Provisioning.A_sn);
                        String lastName = entry.getSingleAttr(ContactConstants.A_lastName);
                        if (lastName != null) {
                            eLastName.setText(lastName);
                        }
                        eUser.add(eLastName);
                        org.dom4j.Element ePassword = DocumentHelper
                                .createElement(AdminExtConstants.A_password);
                        if (password != null) {
                            ePassword.setText(password);
                        } else if (generatePwd.equalsIgnoreCase("true")) {
                            ePassword.setText(
                                    String.valueOf(BulkImportAccounts.generateStrongPassword(genPwdLength)));
                        }
                        eUser.add(ePassword);

                        org.dom4j.Element elMustChangePassword = DocumentHelper
                                .createElement(Provisioning.A_zmailPasswordMustChange);
                        elMustChangePassword.setText(mustChangePassword);
                        eUser.add(elMustChangePassword);

                        usersEl.add(eUser);
                    }
                    xw.write(doc);
                    xw.flush();
                } catch (IOException e) {
                    throw ServiceException.FAILURE(e.getMessage(), e);
                } finally {
                    if (xw != null) {
                        try {
                            xw.close();
                        } catch (IOException ignore) {
                        }
                    }
                    if (fileWriter != null) {
                        try {
                            fileWriter.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else if (AdminFileDownload.FILE_FORMAT_MIGRATION_XML.equalsIgnoreCase(fileFormat)) {
                outFileName = String.format("%s%s_migration_%s_%s.xml", LC.zmail_tmp_directory.value(),
                        File.separator, zsc.getAuthtokenAccountId(), fileToken);
                FileWriter fileWriter = null;
                XMLWriter xw = null;
                try {
                    fileWriter = new FileWriter(outFileName);
                    xw = new XMLWriter(fileWriter, org.dom4j.io.OutputFormat.createPrettyPrint());
                    Document doc = DocumentHelper.createDocument();
                    org.dom4j.Element rootEl = DocumentHelper.createElement(AdminExtConstants.E_ZCSImport);
                    doc.add(rootEl);
                    /**
                     * set Options section
                     */
                    org.dom4j.Element optionsEl = DocumentHelper.createElement(E_Options);
                    org.dom4j.Element importMailsEl = DocumentHelper
                            .createElement(AdminExtConstants.E_importMails);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_importMails).getTextTrim())) {
                        importMailsEl.setText("1");
                    } else {
                        importMailsEl.setText("0");
                    }
                    optionsEl.add(importMailsEl);
                    rootEl.add(optionsEl);
                    org.dom4j.Element importContactsEl = DocumentHelper
                            .createElement(AdminExtConstants.E_importContacts);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_importContacts).getTextTrim())) {
                        importContactsEl.setText("1");
                    } else {
                        importContactsEl.setText("0");
                    }
                    optionsEl.add(importContactsEl);
                    org.dom4j.Element importCalendarEl = DocumentHelper
                            .createElement(AdminExtConstants.E_importCalendar);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_importCalendar).getTextTrim())) {
                        importCalendarEl.setText("1");
                    } else {
                        importCalendarEl.setText("0");
                    }
                    optionsEl.add(importCalendarEl);
                    org.dom4j.Element importTasksEl = DocumentHelper
                            .createElement(AdminExtConstants.E_importTasks);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_importTasks).getTextTrim())) {
                        importTasksEl.setText("1");
                    } else {
                        importTasksEl.setText("0");
                    }
                    optionsEl.add(importTasksEl);
                    org.dom4j.Element importJunkEl = DocumentHelper
                            .createElement(AdminExtConstants.E_importJunk);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_importJunk).getTextTrim())) {
                        importJunkEl.setText("1");
                    } else {
                        importJunkEl.setText("0");
                    }
                    optionsEl.add(importJunkEl);
                    org.dom4j.Element importDeletedItemsEl = DocumentHelper
                            .createElement(AdminExtConstants.E_importDeletedItems);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_importDeletedItems).getTextTrim())) {
                        importDeletedItemsEl.setText("1");
                    } else {
                        importDeletedItemsEl.setText("0");
                    }
                    optionsEl.add(importDeletedItemsEl);
                    org.dom4j.Element ignorePreviouslyImportedEl = DocumentHelper
                            .createElement(AdminExtConstants.E_ignorePreviouslyImported);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_ignorePreviouslyImported).getTextTrim())) {
                        ignorePreviouslyImportedEl.setText("1");
                    } else {
                        ignorePreviouslyImportedEl.setText("0");
                    }
                    optionsEl.add(ignorePreviouslyImportedEl);
                    org.dom4j.Element InvalidSSLOkEl = DocumentHelper
                            .createElement(AdminExtConstants.E_InvalidSSLOk);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_InvalidSSLOk).getTextTrim())) {
                        InvalidSSLOkEl.setText("1");
                    } else {
                        InvalidSSLOkEl.setText("0");
                    }
                    optionsEl.add(InvalidSSLOkEl);

                    /**
                     * set MapiProfile section
                     */
                    org.dom4j.Element mapiProfileEl = DocumentHelper
                            .createElement(AdminExtConstants.E_MapiProfile);
                    rootEl.add(mapiProfileEl);
                    org.dom4j.Element profileEl = DocumentHelper.createElement(E_profile);
                    profileEl.setText(request.getElement(AdminExtConstants.E_MapiProfile).getTextTrim());
                    mapiProfileEl.add(profileEl);

                    org.dom4j.Element serverEl = DocumentHelper.createElement(E_server);
                    serverEl.setText(request.getElement(AdminExtConstants.E_MapiServer).getTextTrim());
                    mapiProfileEl.add(serverEl);

                    org.dom4j.Element logonUserDNEl = DocumentHelper.createElement(E_logonUserDN);
                    logonUserDNEl
                            .setText(request.getElement(AdminExtConstants.E_MapiLogonUserDN).getTextTrim());
                    mapiProfileEl.add(logonUserDNEl);

                    /**
                     * set ZmailServer section
                     */
                    org.dom4j.Element zmailSererEl = DocumentHelper.createElement(E_ZmailServer);
                    rootEl.add(zmailSererEl);

                    org.dom4j.Element serverNameEl = DocumentHelper
                            .createElement(AdminExtConstants.E_serverName);
                    serverNameEl.setText(Provisioning.getInstance().getLocalServer().getName());
                    zmailSererEl.add(serverNameEl);

                    org.dom4j.Element adminUserNameEl = DocumentHelper
                            .createElement(AdminExtConstants.E_adminUserName);
                    adminUserNameEl
                            .setText(request.getElement(AdminExtConstants.E_ZmailAdminLogin).getTextTrim());
                    zmailSererEl.add(adminUserNameEl);

                    org.dom4j.Element adminUserPasswordEl = DocumentHelper.createElement(E_password);
                    adminUserPasswordEl
                            .setText(request.getElement(AdminExtConstants.E_ZmailAdminPassword).getTextTrim());
                    zmailSererEl.add(adminUserPasswordEl);

                    org.dom4j.Element domaindEl = DocumentHelper.createElement(E_domain);
                    domaindEl.setText(request.getElement(AdminExtConstants.E_TargetDomainName).getTextTrim());
                    zmailSererEl.add(domaindEl);

                    /**
                     * set UserProvision section
                     */
                    org.dom4j.Element userProvisionEl = DocumentHelper.createElement(E_UserProvision);
                    rootEl.add(userProvisionEl);
                    org.dom4j.Element provisionUsersEl = DocumentHelper
                            .createElement(AdminExtConstants.E_provisionUsers);
                    if ("TRUE".equalsIgnoreCase(
                            request.getElement(AdminExtConstants.E_provisionUsers).getTextTrim())) {
                        provisionUsersEl.setText("1");
                    } else {
                        provisionUsersEl.setText("0");
                    }
                    userProvisionEl.add(provisionUsersEl);

                    /**
                     * set ImportUsers section
                     */
                    org.dom4j.Element usersEl = DocumentHelper.createElement(AdminExtConstants.E_ImportUsers);

                    rootEl.add(usersEl);
                    for (GalContact entry : entries) {
                        String email = entry.getSingleAttr(ContactConstants.A_email);
                        if (email == null)
                            continue;

                        org.dom4j.Element eUser = DocumentHelper.createElement(AdminExtConstants.E_User);
                        org.dom4j.Element eExchangeMail = DocumentHelper
                                .createElement(AdminExtConstants.E_ExchangeMail);
                        eExchangeMail.setText(email);
                        eUser.add(eExchangeMail);

                        org.dom4j.Element ePassword = DocumentHelper
                                .createElement(AdminExtConstants.A_password);
                        if (password != null) {
                            ePassword.setText(password);
                        } else if (generatePwd.equalsIgnoreCase("true")) {
                            ePassword.setText(
                                    String.valueOf(BulkImportAccounts.generateStrongPassword(genPwdLength)));
                        }
                        eUser.add(ePassword);
                        org.dom4j.Element elMustChangePassword = DocumentHelper
                                .createElement(Provisioning.A_zmailPasswordMustChange);
                        elMustChangePassword.setText(mustChangePassword);
                        eUser.add(elMustChangePassword);
                        usersEl.add(eUser);
                    }
                    xw.write(doc);
                    xw.flush();
                } catch (IOException e) {
                    throw ServiceException.FAILURE(e.getMessage(), e);
                } finally {
                    if (xw != null) {
                        try {
                            xw.close();
                        } catch (IOException ignore) {
                        }
                    }
                    if (fileWriter != null) {
                        try {
                            fileWriter.close();
                        } catch (IOException ignore) {
                        }
                    }
                }
            } else {
                throw (ServiceException.INVALID_REQUEST("Wrong value for fileFormat parameter", null));
            }
            response.addElement(AdminExtConstants.E_fileToken).setText(fileToken);
        }
    } catch (ServiceException e) {
        if (LdapException.INVALID_SEARCH_FILTER.equals(e.getCode())
                || e.getCause() instanceof LdapException.LdapInvalidSearchFilterException) {
            throw BulkProvisionException.BP_INVALID_SEARCH_FILTER(e);
        } else {
            throw e;
        }
    }
    return response;
}

From source file:pt.webdetails.cda.exporter.HtmlExporter.java

License:Open Source License

@Override
public void export(OutputStream out, TableModel tableModel) throws ExporterException {
    final Document document = DocumentHelper.createDocument();
    Element table = null;/*from  w  w  w  .j a  v  a 2  s. c  om*/

    if (fullHtml) {
        final Element html = document.addElement("html");
        final Element head = html.addElement("head");
        head.addElement("title").addText(title);
        table = html.addElement("body").addElement("table");
    } else {
        table = document.addElement("table");
    }

    final int columnCount = tableModel.getColumnCount();

    //table headers
    final Element headerRow = table.addElement("tr");
    for (int i = 0; i < columnCount; i++) {
        String colName = tableModel.getColumnName(i);
        headerRow.addElement("th").addText(colName);
    }

    //table body
    for (int i = 0; i < tableModel.getRowCount(); i++) {
        Element row = table.addElement("tr");

        for (int j = 0; j < columnCount; j++) {
            Element tableCell = row.addElement("td");
            Object value = tableModel.getValueAt(i, j);
            tableCell.setText(valueToText(value));

            if (value instanceof Date) {
                tableCell.setText(format.format(value));
            } else if (value != null) {
                // numbers can be safely converted via toString, as they use a well-defined format there
                tableCell.setText(value.toString());
            }

        }
    }

    try {
        document.setXMLEncoding("UTF-8");

        OutputFormat outFormat = new OutputFormat();
        outFormat.setOmitEncoding(true);
        outFormat.setSuppressDeclaration(true);//otherwise msexcel/oocalc may not recognize content
        outFormat.setNewlines(true);
        outFormat.setIndentSize(columnCount);
        final Writer writer = new BufferedWriter(new OutputStreamWriter(out));
        XMLWriter xmlWriter = new XMLWriter(writer, outFormat);
        xmlWriter.write(document);
        xmlWriter.flush();
    } catch (IOException e) {
        throw new ExporterException("IO Exception converting to utf-8", e);
    }
}

From source file:se.kb.xml.XmlSerializer.java

License:Apache License

/**
 * Writes the XML contained in the <code>Element</code> to the specified <code>OutputStream</code>.
 *
 * @param element the XML element to write
 * @param stream the stream to write to//from   ww w .  j  av  a  2 s.  c o m
 * @throws IOException
 */
public static void writeXmlTo(Element element, OutputStream stream) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(stream, Charsets.UTF_8);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(ENCODING);

    XMLWriter xmlwriter = new XMLWriter(writer, format);
    xmlwriter.write(element);
    xmlwriter.flush();
    writer.flush();
}

From source file:se.kb.xml.XMLUtils.java

License:Apache License

/**
 * Writes the XML contained in the <code>Element</code> to the specified
 * <code>OutputStream</code>.
 * /*from  ww w . ja  v  a2  s.  co m*/
 * @param element the XML element to write
 * @param stream the stream to write to
 * 
 * @throws IOException
 */
public static void writeXmlTo(Element element, OutputStream stream) throws IOException {
    OutputStreamWriter writer = new OutputStreamWriter(stream, ENCODING);
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setEncoding(ENCODING);

    XMLWriter xmlwriter = new XMLWriter(writer, format);
    xmlwriter.write(element);
    xmlwriter.flush();
    writer.flush();
}

From source file:us.mn.state.health.lims.audittrail.daoimpl.AuditTrailDAOImpl.java

License:Mozilla Public License

/**
 * Convert to xml format by reading the table bases on it's id (dom4j)
 * @param table the table name/* w w  w  .  j a va 2 s  .  co  m*/
 * @param id the primary id
 * @return xml string
 */
public String getXML(String table, String id) throws LIMSRuntimeException {
    org.hibernate.Session session = HibernateUtil.getSession();
    org.hibernate.Session dom4jSession = session.getSession(org.hibernate.EntityMode.DOM4J);

    Element elem = (Element) dom4jSession.createQuery("from " + table + " where id=" + id).uniqueResult();
    java.io.StringWriter sw = new java.io.StringWriter();
    if (elem != null) {
        try {
            Document doc = DocumentHelper.createDocument();
            doc.add(elem);
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(sw, format);
            writer.write(doc);
            writer.flush();
            writer.close();

            return sw.toString();
        } catch (Exception e) {
            //buzilla 2154
            LogEvent.logError("AuditTrailDAOImpl", "getXML()", e.toString());
            throw new LIMSRuntimeException("Error in AuditTrail getXML()", e);
        }
    }
    return null;
}

From source file:zutil.parser.wsdl.WSDLWriter.java

License:Open Source License

private String generate() {
    if (cache == null) {
        try {//from   w w w.  j a  v  a 2  s .c  o m
            OutputFormat outformat = OutputFormat.createPrettyPrint();
            StringOutputStream out = new StringOutputStream();
            XMLWriter writer = new XMLWriter(out, outformat);

            Document docroot = generateDefinition();
            writer.write(docroot);

            writer.flush();
            this.cache = out.toString();
            out.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return cache;
}