Example usage for org.dom4j Document add

List of usage examples for org.dom4j Document add

Introduction

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

Prototype

void add(Node node);

Source Link

Document

Adds the given Node or throws IllegalAddException if the given node is not of a valid type.

Usage

From source file:org.orbeon.oxf.transformer.xupdate.statement.Utils.java

License:Open Source License

/**
 * Evaluates an XPath expression//from   ww w.jav a2s.  c  o m
 */
public static Object evaluate(final URIResolver uriResolver, Object context,
        final VariableContextImpl variableContext, final DocumentContext documentContext,
        final LocationData locationData, String select, NamespaceContext namespaceContext) {
    FunctionContext functionContext = new FunctionContext() {
        public org.jaxen.Function getFunction(final String namespaceURI, final String prefix,
                final String localName) {

            // Override document() and doc()
            if (/*namespaceURI == null &&*/ ("document".equals(localName) || "doc".equals(localName))) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            String url = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                            Document result = documentContext.getDocument(url);
                            if (result == null) {
                                Source source = uriResolver.resolve(url, locationData.getSystemID());
                                if (!(source instanceof SAXSource))
                                    throw new ValidationException("Unsupported source type", locationData);
                                XMLReader xmlReader = ((SAXSource) source).getXMLReader();
                                LocationSAXContentHandler contentHandler = new LocationSAXContentHandler();
                                xmlReader.setContentHandler(contentHandler);
                                xmlReader.parse(new InputSource());
                                result = contentHandler.getDocument();
                                documentContext.addDocument(url, result);
                            }
                            return result;
                        } catch (Exception e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "get-namespace-uri-for-prefix".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        String prefix = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                        Element element = null;
                        if (args.get(1) instanceof List) {
                            List list = (List) args.get(1);
                            if (list.size() == 1)
                                element = (Element) list.get(0);
                        } else if (args.get(1) instanceof Element) {
                            element = (Element) args.get(1);
                        }
                        if (element == null)
                            throw new ValidationException("An element is expected as the second argument "
                                    + "in get-namespace-uri-for-prefix()", locationData);
                        return element.getNamespaceForPrefix(prefix);
                    }
                };
            } else if (/*namespaceURI == null &&*/ "distinct-values".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        List originalList = args.get(0) instanceof List ? (List) args.get(0)
                                : Collections.singletonList(args.get(0));
                        List resultList = new ArrayList();
                        XPath stringXPath = Dom4jUtils.createXPath("string(.)");
                        for (Iterator i = originalList.iterator(); i.hasNext();) {
                            Object item = (Object) i.next();
                            String itemString = (String) stringXPath.evaluate(item);
                            if (!resultList.contains(itemString))
                                resultList.add(itemString);
                        }
                        return resultList;
                    }
                };
            } else if (/*namespaceURI == null &&*/ "evaluate".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            if (args.size() != 3) {
                                try {
                                    return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix,
                                            localName);
                                } catch (UnresolvableException e) {
                                    throw new ValidationException(e, locationData);
                                }
                            } else {
                                String xpathString = (String) Dom4jUtils.createXPath("string(.)")
                                        .evaluate(args.get(0));
                                XPath xpath = Dom4jUtils.createXPath(xpathString);
                                Map namespaceURIs = new HashMap();
                                List namespaces = (List) args.get(1);
                                for (Iterator i = namespaces.iterator(); i.hasNext();) {
                                    org.dom4j.Namespace namespace = (org.dom4j.Namespace) i.next();
                                    namespaceURIs.put(namespace.getPrefix(), namespace.getURI());
                                }
                                xpath.setNamespaceURIs(namespaceURIs);
                                return xpath.evaluate(args.get(2));
                            }
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "tokenize".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            String input = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(0));
                            String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1));
                            List result = new ArrayList();
                            while (input.length() != 0) {
                                int position = input.indexOf(pattern);
                                if (position != -1) {
                                    result.add(input.substring(0, position));
                                    input = input.substring(position + 1);
                                } else {
                                    result.add(input);
                                    input = "";
                                }
                            }
                            return result;
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "string-join".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            List strings = (List) args.get(0);
                            String pattern = (String) Dom4jUtils.createXPath("string(.)").evaluate(args.get(1));
                            StringBuilder result = new StringBuilder();
                            boolean isFirst = true;
                            for (Iterator i = strings.iterator(); i.hasNext();) {
                                if (!isFirst)
                                    result.append(pattern);
                                else
                                    isFirst = false;
                                String item = (String) (String) Dom4jUtils.createXPath("string(.)")
                                        .evaluate(i.next());
                                result.append(item);
                            }
                            return result.toString();
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else if (/*namespaceURI == null &&*/ "reverse".equals(localName)) {
                return new org.jaxen.Function() {
                    public Object call(Context jaxenContext, List args) {
                        try {
                            List result = new ArrayList((List) args.get(0));
                            Collections.reverse(result);
                            return result;
                        } catch (InvalidXPathException e) {
                            throw new ValidationException(e, locationData);
                        }
                    }
                };
            } else {
                try {
                    // Go through standard XPath functions
                    return XPathFunctionContext.getInstance().getFunction(namespaceURI, prefix, localName);
                } catch (UnresolvableException e) {
                    // User-defined function
                    try {
                        final Closure closure = findClosure(
                                variableContext.getVariableValue(namespaceURI, prefix, localName));
                        if (closure == null)
                            throw new ValidationException(
                                    "'" + qualifiedName(prefix, localName) + "' is not a function",
                                    locationData);
                        return new org.jaxen.Function() {
                            public Object call(Context context, List args) {
                                return closure.execute(args);
                            }
                        };
                    } catch (UnresolvableException e2) {
                        throw new ValidationException("Cannot invoke function '"
                                + qualifiedName(prefix, localName) + "', no such function", locationData);
                    }
                }
            }
        }

        private Closure findClosure(Object xpathObject) {
            if (xpathObject instanceof Closure) {
                return (Closure) xpathObject;
            } else if (xpathObject instanceof List) {
                for (Iterator i = ((List) xpathObject).iterator(); i.hasNext();) {
                    Closure closure = findClosure(i.next());
                    if (closure != null)
                        return closure;
                }
                return null;
            } else {
                return null;
            }
        }
    };

    try {
        // Create XPath
        XPath xpath = Dom4jUtils.createXPath(select);

        // Set variable, namespace, and function context
        if (context instanceof Context) {
            // Create a new context, as Jaxen may modify the current node in the context (is this a bug?)
            Context currentContext = (Context) context;
            Context newContext = new Context(new ContextSupport(namespaceContext, functionContext,
                    variableContext, DocumentNavigator.getInstance()));
            newContext.setNodeSet(currentContext.getNodeSet());
            newContext.setSize(currentContext.getSize());
            newContext.setPosition(currentContext.getPosition());
            context = newContext;
        } else {
            xpath.setVariableContext(variableContext);
            xpath.setNamespaceContext(namespaceContext);
            xpath.setFunctionContext(functionContext);
        }

        // Execute XPath
        return xpath.evaluate(context);
    } catch (Exception e) {
        throw new ValidationException(e, locationData);
    }
}

From source file:org.pentaho.aggdes.model.ssas.ConversionUtil.java

License:Open Source License

public static List<Document> generateMondrianDocsFromSSASSchema(final InputStream input)
        throws DocumentException, IOException, AggDesignerException {

    Document ssasDocument = parseAssl(input);

    // issue: if we have multi-line text, there is a problem with identing names / etc
    // solution: clean up the dom before traversal
    List allElements = ssasDocument.selectNodes("//*");
    for (int i = 0; i < allElements.size(); i++) {
        Element element = (Element) allElements.get(i);
        element.setText(element.getText().replaceAll("[\\s]+", " ").trim());
    }// ww  w  . ja v a  2 s  .com

    List ssasDatabases = ssasDocument.selectNodes("//assl:Database");
    List<Document> mondrianDocs = new ArrayList<Document>(ssasDatabases.size());
    for (int i = 0; i < ssasDatabases.size(); i++) {
        Document mondrianDoc = DocumentFactory.getInstance().createDocument();
        Element mondrianSchema = DocumentFactory.getInstance().createElement("Schema");
        mondrianDoc.add(mondrianSchema);
        Element ssasDatabase = (Element) ssasDatabases.get(i);
        mondrianSchema.add(DocumentFactory.getInstance().createAttribute(mondrianSchema, "name",
                getXPathNodeText(ssasDatabase, "assl:Name")));
        populateCubes(mondrianSchema, ssasDatabase);

        mondrianDocs.add(mondrianDoc);
    }

    return mondrianDocs;
}

From source file:org.pentaho.platform.dataaccess.client.ConnectionServiceClient.java

License:Open Source License

/**
 * Generates a SOAP request for an Axis service.
 * @param params// w  w  w .  java2 s  . c  o  m
 * @return
 */
protected String getRequestXml(Parameter... params) {

    Document doc = DocumentHelper.createDocument();

    Element envelopeNode = DocumentHelper.createElement("soapenv:Envelope"); //$NON-NLS-1$
    envelopeNode.addAttribute("xmlns:soapenv", "http://www.w3.org/2003/05/soap-envelope"); //$NON-NLS-1$ //$NON-NLS-2$
    envelopeNode.addAttribute("xmlns:wsa", "http://www.w3.org/2005/08/addressing"); //$NON-NLS-1$ //$NON-NLS-2$
    envelopeNode.addAttribute("xmlns:pho", //$NON-NLS-1$
            "http://impl.service.wizard.datasource.dataaccess.platform.pentaho.org"); //$NON-NLS-1$
    doc.add(envelopeNode);
    // create a Body node
    Element bodyNode = DocumentHelper.createElement("soapenv:Body"); //$NON-NLS-1$
    envelopeNode.add(bodyNode);

    if (params == null || params.length == 0) {
        return doc.asXML();
    }

    // create a parameter called 'parameters'
    Element parametersNode = DocumentHelper.createElement("pho:parameters"); //$NON-NLS-1$
    bodyNode.add(parametersNode);

    for (Parameter param : params) {
        // create a parameter called 'name'
        Element nameNode = DocumentHelper.createElement("pho:" + param.getName()); //$NON-NLS-1$
        parametersNode.add(nameNode);
        nameNode.setText(param.getValue().toString());
        nameNode.addAttribute("type", param.getValue().getClass().getCanonicalName()); //$NON-NLS-1$
    }

    return doc.asXML();
}

From source file:org.pentaho.platform.dataaccess.client.ConnectionServiceClient.java

License:Open Source License

/**
 * Returns XML for a connection object suitable for submitting to the connection web service
 * @param connection Connection object to be encoded as XML
 * @return XML serialization of the connection object
 *//*from  w  w w.  ja  v  a 2s. c  o  m*/
protected String getConnectionXml(IConnection connection) {
    Document doc = DocumentHelper.createDocument();

    // create a SOAP envelope and specify namespaces
    Element envelopeNode = DocumentHelper.createElement("soapenv:Envelope"); //$NON-NLS-1$
    envelopeNode.addAttribute("xmlns:soapenv", "http://www.w3.org/2003/05/soap-envelope"); //$NON-NLS-1$ //$NON-NLS-2$
    envelopeNode.addAttribute("xmlns:wsa", "http://www.w3.org/2005/08/addressing"); //$NON-NLS-1$ //$NON-NLS-2$
    envelopeNode.addAttribute("xmlns:pho", //$NON-NLS-1$
            "http://impl.service.wizard.datasource.dataaccess.platform.pentaho.org"); //$NON-NLS-1$
    doc.add(envelopeNode);
    // create a Body node
    Element bodyNode = DocumentHelper.createElement("soapenv:Body"); //$NON-NLS-1$
    envelopeNode.add(bodyNode);
    // create a parameter called 'connection'
    Element parameterNode = DocumentHelper.createElement("pho:connection"); //$NON-NLS-1$
    bodyNode.add(parameterNode);
    // create a Connection node with a type of org.pentaho.platform.dataaccess.datasource.beans.Connection
    Element connectionNode = DocumentHelper.createElement("pho:Connection"); //$NON-NLS-1$
    connectionNode.addAttribute("type", "org.pentaho.platform.dataaccess.datasource.beans.Connection"); //$NON-NLS-1$ //$NON-NLS-2$
    parameterNode.add(connectionNode);
    // add the driver class of the connection
    Element node = DocumentHelper.createElement("driverClass"); //$NON-NLS-1$
    node.setText(connection.getDriverClass());
    connectionNode.add(node);
    // add the name of the connection
    node = DocumentHelper.createElement("name"); //$NON-NLS-1$
    node.setText(connection.getName());
    connectionNode.add(node);
    // add the password for the connection
    node = DocumentHelper.createElement("password"); //$NON-NLS-1$
    node.setText(connection.getPassword());
    connectionNode.add(node);
    // add the url of the connection
    node = DocumentHelper.createElement("url"); //$NON-NLS-1$
    node.setText(connection.getUrl());
    connectionNode.add(node);
    // add the user name for the connection
    node = DocumentHelper.createElement("username"); //$NON-NLS-1$
    node.setText(connection.getUsername());
    connectionNode.add(node);

    // return the XML
    return doc.asXML();
}

From source file:org.pentaho.platform.repository.subscription.SubscriptionPublisher.java

License:Open Source License

@Override
public String publish(IPentahoSession session) {
    String publishSrcPath = PentahoSystem.getApplicationContext().getSolutionPath("") //$NON-NLS-1$
            + "system/ScheduleAndContentImport.xml"; //$NON-NLS-1$
    Document document = DocumentHelper.createDocument();
    Element root = DocumentHelper.createElement("importContentResults"); //$NON-NLS-1$
    document.add(root);
    try {/*from w ww .j  a v a 2s .c o  m*/
        ISubscriptionRepository subscriptionRepository = PentahoSystem.get(ISubscriptionRepository.class,
                session);
        File file = new File(publishSrcPath);
        if (!file.canRead()) {
            throw new FileNotFoundException("SubscriptionPublisher.publish() requires the file \""
                    + publishSrcPath + "\" to exist. The file does not exist.");
        }
        Document importDoc = XmlDom4JHelper.getDocFromFile(file, null);

        root.add(subscriptionRepository.importSchedules(importDoc));
        root.add(subscriptionRepository.importContent(importDoc));
    } catch (FileNotFoundException e) {
        getLogger().error(Messages.getString("SubscriptionPublisher.ERROR_0001", publishSrcPath), e); //$NON-NLS-1$
        return Messages.getString("SubscriptionPublisher.ERROR_0002", publishSrcPath); //$NON-NLS-1$
    } catch (DocumentException e) {
        getLogger().error(Messages.getString("SubscriptionPublisher.ERROR_0003", publishSrcPath), e); //$NON-NLS-1$
        return Messages.getString("SubscriptionPublisher.ERROR_0004") + publishSrcPath; //$NON-NLS-1$
    } catch (IOException e) {
        getLogger().error(Messages.getString("SubscriptionPublisher.ERROR_0005", publishSrcPath), e); //$NON-NLS-1$
        return Messages.getString("SubscriptionPublisher.ERROR_0006", publishSrcPath); //$NON-NLS-1$
    }

    List resultNodes = document.selectNodes("//@result"); //$NON-NLS-1$
    for (Iterator iter = resultNodes.iterator(); iter.hasNext();) {
        Attribute attribute = (Attribute) iter.next();
        if ("ERROR".equalsIgnoreCase(attribute.getValue())) { //$NON-NLS-1$
            return Messages.getString("SubscriptionPublisher.ERROR_0007"); //$NON-NLS-1$
        }
    }

    return Messages.getString("SubscriptionPublisher.INFO_0001"); //$NON-NLS-1$
}

From source file:org.pentaho.platform.web.http.api.resources.services.SystemService.java

License:Open Source License

private Document mergeAllDocument(Document[] documents) {
    Document document = DocumentHelper.createDocument();
    Element element = new DefaultElement("content"); //$NON-NLS-1$
    document.add(element);
    for (Document contentDocument : documents) {
        if ((contentDocument != null) && (contentDocument.getRootElement() != null)) {
            element.add(contentDocument.getRootElement());
        }/*from   ww w  .java 2 s.co m*/
    }
    return document;
}

From source file:org.pentaho.platform.web.http.api.resources.SystemResourceUtil.java

License:Open Source License

private static Document mergeAllDocument(Document[] documents) {
    Document document = DocumentHelper.createDocument();
    Element element = new DefaultElement("content"); //$NON-NLS-1$
    document.add(element);
    for (Document contentDocument : documents) {
        if ((contentDocument != null) && (contentDocument.getRootElement() != null)) {
            element.add(contentDocument.getRootElement());
        }/*www .j a  va2  s .  co  m*/
    }
    return document;
}

From source file:org.snipsnap.snip.storage.XMLFileSnipStorage.java

License:Open Source License

protected void storeSnip(snipsnap.api.snip.Snip snip, OutputStream out) {
    Document snipDocument = DocumentHelper.createDocument();
    snipDocument.add(serializer.serialize(snip));

    try {/*from   w w w .j  ava  2  s.  c  o  m*/
        OutputFormat outputFormat = new OutputFormat();
        outputFormat.setEncoding("UTF-8");
        XMLWriter xmlWriter = new XMLWriter(out, outputFormat);
        xmlWriter.write(snipDocument);
        xmlWriter.flush();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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  w w.  j  ava2  s  .  c  om*/
    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:server.data.ObjectSystemData.java

License:Open Source License

public Document toXML() {
    Document doc = DocumentHelper.createDocument();
    doc.add(convertToElement());

    return doc;
}