Example usage for org.dom4j DocumentException DocumentException

List of usage examples for org.dom4j DocumentException DocumentException

Introduction

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

Prototype

public DocumentException(Throwable cause) 

Source Link

Usage

From source file:org.waarp.common.xml.XmlUtil.java

License:Open Source License

/**
 * /*  ww  w.j a  v a 2  s .c  o m*/
 * @param doc
 * @param path
 * @return the element associated with the path relatively to the document
 * @throws DocumentException
 */
@SuppressWarnings("unchecked")
static public List<Element> getElementMultiple(Document doc, String path) throws DocumentException {
    List<Element> list = doc.selectNodes(path);
    if (list == null || list.isEmpty()) {
        throw new DocumentException("Nodes not found: " + path);
    }
    return list;
}

From source file:org.withinsea.izayoi.cortile.template.html.parser.HTMLReader.java

License:Mozilla Public License

@Override
protected void configureReader(XMLReader reader, DefaultHandler handler) throws DocumentException {
    super.configureReader(reader, handler);
    try {/*  w  w  w  . jav  a  2 s.  c  o  m*/
        reader.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACES_FEATURE, false);
        reader.setFeature(Constants.SAX_FEATURE_PREFIX + Constants.NAMESPACE_PREFIXES_FEATURE, true);
        reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.CONTINUE_AFTER_FATAL_ERROR_FEATURE, true);
        reader.setFeature(Constants.XERCES_FEATURE_PREFIX + Constants.LOAD_EXTERNAL_DTD_FEATURE, false);
    } catch (Exception e) {
        throw new DocumentException(e);
    }
}

From source file:org.withinsea.izayoi.cortile.template.html.parser.HTMLReader.java

License:Mozilla Public License

@Override
public Document read(InputSource in) throws DocumentException {
    String html;// w w w  . j ava 2s .  com
    try {
        html = IOUtils.toString(in.getCharacterStream());
    } catch (IOException e) {
        throw new DocumentException(e);
    }
    Tricker tricker = new Tricker();
    InputSource newIn = new InputSource(new StringReader(tricker.trickBefore(html)));
    {
        newIn.setEncoding(in.getEncoding());
        newIn.setPublicId(in.getPublicId());
        newIn.setSystemId(in.getSystemId());
    }
    return tricker.trickAfter(super.read(newIn));
}

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

License:Open Source License

public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZmailSoapContext zsc = getZmailSoapContext(context);
    Server localServer = Provisioning.getInstance().getLocalServer();
    checkRight(zsc, context, localServer, Admin.R_createMigrationTask);
    String op = request.getAttribute(AdminExtConstants.A_op);
    Element response = zsc.createElement(AdminExtConstants.BULK_IMAP_DATA_IMPORT_RESPONSE);
    Map<accountState, List<ExternalIMAPAccount>> IMAPAccounts = null;
    String IMAPhost = null, IMAPport = null, adminLogin = null, adminPassword = null, connectionType = null,
            sourceServerType = null;//w  ww .j av  a 2s .co m
    String sourceType = request.getElement(AdminExtConstants.A_sourceType).getTextTrim();
    String indexBatchSize = ZmailBulkProvisionExt.DEFAULT_INDEX_BATCH_SIZE;
    boolean useAdminLogin = false;
    if (sourceType.equalsIgnoreCase(AdminFileDownload.FILE_FORMAT_BULK_XML)) {
        String aid = request.getElement(AdminExtConstants.E_attachmentID).getTextTrim();
        ZmailLog.extensions.debug("Uploaded XML file id = " + aid);
        FileUploadServlet.Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), aid,
                zsc.getAuthToken());
        if (up == null) {
            throw ServiceException.FAILURE("Uploaded XML file with id " + aid + " was not found.", null);
        }

        try {
            SAXReader reader = new SAXReader();
            Document doc = reader.read(up.getInputStream());
            org.dom4j.Element root = doc.getRootElement();

            if (!root.getName().equals(AdminExtConstants.E_ZCSImport)) {
                throw new DocumentException(
                        "Bulk provisioning XML file's root element must be " + AdminExtConstants.E_ZCSImport);
            }
            Iterator rootIter = root.elementIterator(AdminExtConstants.E_ImportUsers);
            if (!rootIter.hasNext()) {
                throw new DocumentException("Cannot find element " + AdminExtConstants.E_ImportUsers
                        + " in uploaded bulk provisioning XML file");
            }
            org.dom4j.Element elImportUsers = (org.dom4j.Element) rootIter.next();

            IMAPAccounts = parseExternalIMAPAccounts(elImportUsers, zsc);

            Iterator connectionTypeIter = root.elementIterator(AdminExtConstants.E_connectionType);
            if (connectionTypeIter.hasNext()) {
                org.dom4j.Element elConnectionType = (org.dom4j.Element) connectionTypeIter.next();
                connectionType = elConnectionType.getTextTrim();
            }
            Iterator sourceServerTypeIter = root.elementIterator(AdminExtConstants.E_sourceServerType);
            if (sourceServerTypeIter.hasNext()) {
                org.dom4j.Element elSourceServerType = (org.dom4j.Element) sourceServerTypeIter.next();
                sourceServerType = elSourceServerType.getTextTrim();
            }
            Iterator IMAPHostIter = root.elementIterator(AdminExtConstants.E_IMAPHost);
            if (IMAPHostIter.hasNext()) {
                org.dom4j.Element elIMAPHost = (org.dom4j.Element) IMAPHostIter.next();
                IMAPhost = elIMAPHost.getTextTrim();
            }

            Iterator IMAPPortIter = root.elementIterator(AdminExtConstants.E_IMAPPort);
            if (IMAPPortIter.hasNext()) {
                org.dom4j.Element elIMAPPort = (org.dom4j.Element) IMAPPortIter.next();
                IMAPport = elIMAPPort.getTextTrim();
            }

            Iterator IndexBatchSizeIter = root.elementIterator(AdminExtConstants.E_indexBatchSize);
            if (IndexBatchSizeIter.hasNext()) {
                org.dom4j.Element elIxBatchSize = (org.dom4j.Element) IndexBatchSizeIter.next();
                indexBatchSize = elIxBatchSize.getTextTrim();
            }

            Iterator useAdminLoginIter = root.elementIterator(AdminExtConstants.E_useAdminLogin);
            if (useAdminLoginIter.hasNext()) {
                org.dom4j.Element elUseAdminLogin = (org.dom4j.Element) useAdminLoginIter.next();
                useAdminLogin = "1".equalsIgnoreCase(elUseAdminLogin.getTextTrim());
                if (useAdminLogin) {
                    Iterator adminLoginIter = root.elementIterator(AdminExtConstants.E_IMAPAdminLogin);
                    if (adminLoginIter.hasNext()) {
                        org.dom4j.Element elAdminLogin = (org.dom4j.Element) adminLoginIter.next();
                        adminLogin = elAdminLogin.getTextTrim();
                    }

                    Iterator adminPassIter = root.elementIterator(AdminExtConstants.E_IMAPAdminPassword);
                    if (adminPassIter.hasNext()) {
                        org.dom4j.Element elAdminPassword = (org.dom4j.Element) adminPassIter.next();
                        adminPassword = elAdminPassword.getTextTrim();
                    }
                }
            }

        } catch (DocumentException e) {
            throw ServiceException.FAILURE("Bulk provisioning failed to read uploaded XML document.", e);
        } catch (IOException e) {
            throw ServiceException.FAILURE("Bulk provisioning failed to read uploaded XML document.", e);
        }
    } else if (sourceType.equalsIgnoreCase(ZmailBulkProvisionExt.FILE_FORMAT_ZIMBRA)) {
        IMAPAccounts = getZmailAccounts(request, zsc);
    } else {
        throw ServiceException
                .INVALID_REQUEST(String.format("Invalid value of %s parameter: %s. Allowed values: %s, %s",
                        AdminExtConstants.A_sourceType, sourceType, ZmailBulkProvisionExt.FILE_FORMAT_ZIMBRA,
                        AdminFileDownload.FILE_FORMAT_BULK_XML), null);
    }

    /*
     * Process the list of accounts. Find existing datasources and check their states.
     */
    int numIdleAccounts = 0;
    int numRunningAccounts = 0;
    int numFinishedAccounts = 0;
    List<ExternalIMAPAccount> idleAccounts = null;
    if (IMAPAccounts.containsKey(accountState.idle)) {
        idleAccounts = IMAPAccounts.get(accountState.idle);
        if (idleAccounts != null) {
            numIdleAccounts = idleAccounts.size();
        }
    }
    List<ExternalIMAPAccount> runningAccounts;
    if (IMAPAccounts.containsKey(accountState.running)) {
        runningAccounts = IMAPAccounts.get(accountState.running);
        if (runningAccounts != null) {
            Element elRunningAccounts = response.addElement(AdminExtConstants.E_runningAccounts);
            numRunningAccounts = runningAccounts.size();
            Iterator<ExternalIMAPAccount> accountsIter = runningAccounts.iterator();
            while (accountsIter.hasNext()) {
                ExternalIMAPAccount acct = accountsIter.next();
                Element elAccount = elRunningAccounts.addElement(AdminConstants.E_ACCOUNT);
                elAccount.addAttribute(AdminConstants.A_NAME, acct.getAccount().getName());
                elAccount.addAttribute(AdminConstants.A_ID, acct.getAccount().getId());
            }
        }
    }

    if (IMAPAccounts.containsKey(accountState.finished)) {
        List accounts = IMAPAccounts.get(accountState.finished);
        if (accounts != null) {
            numFinishedAccounts = accounts.size();
        }
    }

    /*
     * Check for overwritten options
     */
    Element elConnectionType = request.getOptionalElement(AdminExtConstants.E_connectionType);
    if (elConnectionType != null) {
        connectionType = elConnectionType.getTextTrim();
    }
    Element elSourceServerType = request.getOptionalElement(AdminExtConstants.E_sourceServerType);
    if (elSourceServerType != null) {
        sourceServerType = elSourceServerType.getTextTrim();
    }
    Element elIMAPHost = request.getOptionalElement(AdminExtConstants.E_IMAPHost);
    if (elIMAPHost != null) {
        IMAPhost = elIMAPHost.getTextTrim();
    }

    Element elIMAPPort = request.getOptionalElement(AdminExtConstants.E_IMAPPort);
    if (elIMAPPort != null) {
        IMAPport = elIMAPPort.getTextTrim();
    }

    Element elBatchSize = request.getOptionalElement(AdminExtConstants.E_indexBatchSize);
    if (elBatchSize != null) {
        indexBatchSize = elBatchSize.getTextTrim();
    }

    Element elUseAdminLogin = request.getOptionalElement(AdminExtConstants.E_useAdminLogin);
    if (elUseAdminLogin != null) {
        useAdminLogin = "1".equalsIgnoreCase(elUseAdminLogin.getTextTrim());
    }

    if (useAdminLogin) {
        Element elAdminLogin = request.getOptionalElement(AdminExtConstants.E_IMAPAdminLogin);
        if (elAdminLogin != null) {
            adminLogin = elAdminLogin.getTextTrim();
        }
        Element elAdminPassword = request.getOptionalElement(AdminExtConstants.E_IMAPAdminPassword);
        if (elAdminPassword != null) {
            adminPassword = elAdminPassword.getTextTrim();
        }
    }

    if (ZmailBulkProvisionExt.OP_PREVIEW.equalsIgnoreCase(op)) {
        /*
         * Do not start the import. Just generate a preview. We will count
         * idle and non-idle accounts.
         */
        response.addElement(AdminExtConstants.E_totalCount)
                .setText(Integer.toString(numIdleAccounts + numRunningAccounts + numFinishedAccounts));
        response.addElement(AdminExtConstants.E_idleCount).setText(Integer.toString(numIdleAccounts));
        response.addElement(AdminExtConstants.E_runningCount).setText(Integer.toString(numRunningAccounts));
        response.addElement(AdminExtConstants.E_finishedCount).setText(Integer.toString(numFinishedAccounts));

        response.addElement(AdminExtConstants.E_connectionType).setText(connectionType);
        response.addElement(AdminExtConstants.E_IMAPHost).setText(IMAPhost);
        response.addElement(AdminExtConstants.E_IMAPPort).setText(IMAPport);
        response.addElement(AdminExtConstants.E_indexBatchSize).setText(indexBatchSize);
        if (useAdminLogin) {
            response.addElement(AdminExtConstants.E_useAdminLogin).setText("1");
            response.addElement(AdminExtConstants.E_IMAPAdminLogin).setText(adminLogin);
            response.addElement(AdminExtConstants.E_IMAPAdminPassword).setText(adminPassword);
        } else {
            response.addElement(AdminExtConstants.E_useAdminLogin).setText("0");
        }
    } else if (ZmailBulkProvisionExt.OP_START_IMPORT.equalsIgnoreCase(op)) {
        if (idleAccounts == null) {
            throw ServiceException.INVALID_REQUEST(
                    "None of the specified accounts are available to start import right now.", null);
        }
        if (IMAPhost == null) {
            throw ServiceException.INVALID_REQUEST("Must specify IMAP server address!", null);
        }

        if (IMAPport == null) {
            throw ServiceException.INVALID_REQUEST("Must specify IMAP server port number!", null);
        }

        if (useAdminLogin) {
            /*
             * We must have admin login/password if we are going to connect
             * to IMAP server with admin credentials
             */
            if (adminPassword == null || adminLogin == null) {
                throw ServiceException.INVALID_REQUEST(
                        "Must specify admin credentials in order to log in as admin to IMAP server if "
                                + AdminExtConstants.E_useAdminLogin + " option is selected!",
                        null);
            }

        }
        /*
         * Create the import queue
         */
        Queue<HashMap<taskKeys, String>> queue = BulkIMAPImportTaskManager
                .createQueue(zsc.getAuthtokenAccountId());
        Queue<HashMap<taskKeys, String>> runningQ = BulkIMAPImportTaskManager
                .createRunningQueue(zsc.getAuthtokenAccountId());
        Iterator<ExternalIMAPAccount> idleAccIter = idleAccounts.iterator();
        try {
            int size = Integer.parseInt(indexBatchSize);
            if (size <= 0)
                indexBatchSize = ZmailBulkProvisionExt.DEFAULT_INDEX_BATCH_SIZE;
        } catch (Exception e) {
            indexBatchSize = ZmailBulkProvisionExt.DEFAULT_INDEX_BATCH_SIZE;
        }
        while (idleAccIter.hasNext()) {
            ExternalIMAPAccount acct = idleAccIter.next();
            HashMap<taskKeys, String> task = new HashMap<taskKeys, String>();
            String dataSourceID = createIMAPDataSource(acct.getAccount(), IMAPhost, IMAPport, connectionType,
                    sourceServerType, acct.getUserEmail(), useAdminLogin ? adminLogin : acct.getUserLogin(),
                    useAdminLogin ? adminPassword : acct.getUserPassword(), indexBatchSize, useAdminLogin)
                            .getId();
            String acctID = acct.getAccount().getId();
            task.put(taskKeys.accountID, acctID);
            task.put(taskKeys.dataSourceID, dataSourceID);

            synchronized (queue) {
                queue.add(task);
            }
            synchronized (runningQ) {
                runningQ.add(task);
            }

        }
        /*
         * Start the import process
         */
        BulkIMAPImportTaskManager.startImport(zsc.getAuthtokenAccountId());
    } else if (ZmailBulkProvisionExt.OP_DISMISS_IMPORT.equalsIgnoreCase(op)) {

    }
    return response;
}

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

License:Open Source License

@Override
public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZmailSoapContext zsc = getZmailSoapContext(context);
    Map attrs = AdminService.getAttrs(request, true);
    String op = request.getAttribute(AdminExtConstants.A_op);
    Element response = zsc.createElement(AdminExtConstants.BULK_IMPORT_ACCOUNTS_RESPONSE);
    Provisioning prov = Provisioning.getInstance();
    if (ZmailBulkProvisionExt.OP_PREVIEW.equalsIgnoreCase(op)
            || ZmailBulkProvisionExt.OP_START_IMPORT.equalsIgnoreCase(op)) {
        int totalAccounts = 0;
        int totalExistingAccounts = 0;
        String SMTPHost = "";
        String SMTPPort = "";
        String zmailMailTransport = "";
        boolean createDomains = "TRUE"
                .equalsIgnoreCase(request.getElement(AdminExtConstants.E_createDomains).getTextTrim());

        Element eSMTPHost = request.getOptionalElement(AdminExtConstants.E_SMTPHost);
        if (eSMTPHost != null) {
            SMTPHost = eSMTPHost.getTextTrim();
        }/*ww  w .j  ava 2 s  .  c o  m*/
        Element eSMTPPort = request.getOptionalElement(AdminExtConstants.E_SMTPPort);
        if (eSMTPPort != null) {
            SMTPPort = eSMTPPort.getTextTrim();
        }
        if (SMTPPort.length() > 0 && SMTPHost.length() > 0) {
            zmailMailTransport = "smtp:" + SMTPHost + ":" + SMTPPort;
        }

        /**
         * list of entries found in the source (CSV file, XML file or directory)
         */
        List<Map<String, Object>> sourceEntries = new ArrayList<Map<String, Object>>();

        String sourceType = request.getElement(AdminExtConstants.A_sourceType).getTextTrim();
        if (sourceType.equalsIgnoreCase(AdminFileDownload.FILE_FORMAT_BULK_CSV)) {
            String aid = request.getElement(AdminExtConstants.E_attachmentID).getTextTrim();
            ZmailLog.extensions.debug("Uploaded CSV file id = " + aid);
            // response.addElement(E_attachmentID).addText(aid);
            FileUploadServlet.Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), aid,
                    zsc.getAuthToken());
            if (up == null) {
                throw ServiceException.FAILURE("Uploaded CSV file with id " + aid + " was not found.", null);
            }
            InputStream in = null;
            CSVReader reader = null;
            try {
                in = up.getInputStream();
                reader = new CSVReader(new InputStreamReader(in));
                String[] nextLine;

                List<String[]> allEntries = reader.readAll();
                int totalNumberOfEntries = allEntries.size();

                checkAccountLimits(allEntries, zsc, prov);

                /**
                 * Iterate through records obtained from CSV file and add
                 * each record to sourceEntries
                 */
                for (int i = 0; i < totalNumberOfEntries; i++) {
                    nextLine = allEntries.get(i);
                    boolean isValidEntry = false;
                    try {
                        isValidEntry = validEntry(nextLine, zsc);
                    } catch (ServiceException e) {
                        ZmailLog.extensions.error(e);
                        throw e;
                    }

                    if (!isValidEntry) {
                        throw ServiceException.INVALID_REQUEST(
                                String.format("Entry %d is not valid (%s %s %s %s %s %s)", i, nextLine[0],
                                        nextLine[1], nextLine[2], nextLine[3], nextLine[4], nextLine[5]),
                                null);
                    }
                    String userEmail = nextLine[0].trim();
                    String parts[] = EmailUtil.getLocalPartAndDomain(userEmail);
                    if (parts == null) {
                        throw ServiceException.INVALID_REQUEST("must be valid email address: " + userEmail,
                                null);
                    }

                    Domain domain = prov.getDomainByName(parts[1]);
                    if (domain != null) {
                        checkDomainRight(zsc, domain, Admin.R_createAccount);
                    } else if (createDomains) {
                        if (ZmailBulkProvisionExt.OP_START_IMPORT.equalsIgnoreCase(op)) {
                            domain = createMissingDomain(parts[1], zsc, context);
                        }
                        checkDomainRight(zsc, domain, Admin.R_createAccount);
                    } else {
                        throw AccountServiceException.NO_SUCH_DOMAIN(parts[1]);
                    }
                    Account acct = Provisioning.getInstance().getAccountByName(userEmail);
                    if (acct != null) {
                        totalExistingAccounts++;
                    } else {
                        Map<String, Object> accAttrs = new HashMap<String, Object>();
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_displayName, nextLine[1].trim());
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_givenName, nextLine[2].trim());
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_sn, nextLine[3].trim());
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_zmailPasswordMustChange,
                                nextLine[5].trim());

                        checkSetAttrsOnCreate(zsc, TargetType.account, userEmail, accAttrs);

                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_mail, userEmail);
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_userPassword, nextLine[4].trim());
                        if (zmailMailTransport.length() > 0) {
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_zmailMailTransport,
                                    zmailMailTransport);
                        }
                        sourceEntries.add(accAttrs);
                    }
                    totalAccounts++;
                }

                in.close();

            } catch (IOException e) {
                throw ServiceException.FAILURE("", e);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        ZmailLog.extensions.error(e);
                    }
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException e) {
                        ZmailLog.extensions.error(e);
                    }
                }

            }
        } else if (sourceType.equalsIgnoreCase(AdminFileDownload.FILE_FORMAT_BULK_XML)) {
            String aid = request.getElement(AdminExtConstants.E_attachmentID).getTextTrim();
            ZmailLog.extensions.debug("Uploaded XML file id = " + aid);
            FileUploadServlet.Upload up = FileUploadServlet.fetchUpload(zsc.getAuthtokenAccountId(), aid,
                    zsc.getAuthToken());
            if (up == null) {
                throw ServiceException.FAILURE("Uploaded CSV file with id " + aid + " was not found.", null);
            }
            SAXReader reader = new SAXReader();
            try {
                Document doc = reader.read(up.getInputStream());
                org.dom4j.Element root = doc.getRootElement();
                if (!root.getName().equals(AdminExtConstants.E_ZCSImport)) {
                    throw new DocumentException("Bulk provisioning XML file's root element must be "
                            + AdminExtConstants.E_ZCSImport);
                }
                Iterator iter = root.elementIterator(AdminExtConstants.E_ImportUsers);
                if (!iter.hasNext()) {
                    throw new DocumentException("Cannot find element " + AdminExtConstants.E_ImportUsers
                            + " in uploaded bulk provisioning XML file");
                }

                /**
                 * Settings from SOAP request take preference over settings in the XML file
                 */
                if (SMTPHost.length() == 0) {
                    Iterator iterMTPHost = root.elementIterator(AdminExtConstants.E_SMTPHost);
                    if (iterMTPHost.hasNext()) {
                        org.dom4j.Element elSMTPHost = (org.dom4j.Element) iterMTPHost.next();
                        SMTPHost = elSMTPHost.getTextTrim();
                    }
                }
                if (SMTPPort.length() == 0) {
                    Iterator iterSMTPort = root.elementIterator(AdminExtConstants.E_SMTPPort);
                    if (iterSMTPort.hasNext()) {
                        org.dom4j.Element elSMTPPort = (org.dom4j.Element) iterSMTPort.next();
                        SMTPPort = elSMTPPort.getTextTrim();
                    }
                }
                if (zmailMailTransport.length() == 0) {
                    if (SMTPPort.length() > 0 && SMTPHost.length() > 0) {
                        zmailMailTransport = "smtp:" + SMTPHost + ":" + SMTPPort;
                    }
                }
                org.dom4j.Element elImportUsers = (org.dom4j.Element) iter.next();
                for (Iterator userIter = elImportUsers.elementIterator(AdminExtConstants.E_User); userIter
                        .hasNext();) {
                    org.dom4j.Element elUser = (org.dom4j.Element) userIter.next();
                    String userEmail = "";
                    String userFN = "";
                    String userLN = "";
                    String userDN = "";
                    String userPassword = "";
                    String userPwdMustChange = "FALSE";
                    for (Iterator userPropsIter = elUser.elementIterator(); userPropsIter.hasNext();) {
                        org.dom4j.Element el = (org.dom4j.Element) userPropsIter.next();
                        /*
                         * We support <ExchangeMail> element for
                         * compatibility with desktop based Exchange
                         * Migration utility <RemoteEmailAddress> takes
                         * prevalence over <ExchangeMail> element
                         */
                        if (userEmail == ""
                                && AdminExtConstants.E_ExchangeMail.equalsIgnoreCase(el.getName())) {
                            userEmail = el.getTextTrim();
                        }
                        if (AdminExtConstants.E_remoteEmail.equalsIgnoreCase(el.getName())) {
                            userEmail = el.getTextTrim();
                        }
                        if (Provisioning.A_displayName.equalsIgnoreCase(el.getName())) {
                            userDN = el.getTextTrim();
                        }

                        if (Provisioning.A_givenName.equalsIgnoreCase(el.getName())) {
                            userFN = el.getTextTrim();
                        }

                        if (Provisioning.A_sn.equalsIgnoreCase(el.getName())) {
                            userLN = el.getTextTrim();
                        }

                        if (AdminExtConstants.A_password.equalsIgnoreCase(el.getName())) {
                            userPassword = el.getTextTrim();
                        }

                        if (Provisioning.A_zmailPasswordMustChange.equalsIgnoreCase(el.getName())) {
                            userPwdMustChange = el.getTextTrim();
                        }
                    }
                    String parts[] = EmailUtil.getLocalPartAndDomain(userEmail);
                    if (parts == null) {
                        throw ServiceException.INVALID_REQUEST("must be valid email address: " + userEmail,
                                null);
                    }

                    Domain domain = prov.getDomainByName(parts[1]);
                    if (domain != null) {
                        checkDomainRight(zsc, domain, Admin.R_createAccount);
                    } else if (createDomains) {
                        domain = createMissingDomain(parts[1], zsc, context);
                        checkDomainRight(zsc, domain, Admin.R_createAccount);
                    } else {
                        throw AccountServiceException.NO_SUCH_DOMAIN(parts[1]);
                    }

                    Account acct = Provisioning.getInstance().getAccountByName(userEmail);
                    if (acct != null) {
                        totalExistingAccounts++;
                    } else {
                        Map<String, Object> accAttrs = new HashMap<String, Object>();
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_givenName, userFN);
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_displayName, userDN);
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_sn, userLN);
                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_zmailPasswordMustChange,
                                userPwdMustChange);

                        checkSetAttrsOnCreate(zsc, TargetType.account, userEmail, accAttrs);

                        StringUtil.addToMultiMap(accAttrs, Provisioning.A_mail, userEmail);
                        if (userPassword != null) {
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_userPassword, userPassword);
                        }
                        if (zmailMailTransport.length() > 0) {
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_zmailMailTransport,
                                    zmailMailTransport);
                        }
                        sourceEntries.add(accAttrs);
                    }
                    totalAccounts++;
                }

            } catch (DocumentException e) {
                throw ServiceException.FAILURE("Bulk provisioning failed to read uploaded XML document.", e);
            } catch (IOException e) {
                throw ServiceException.FAILURE("Bulk provisioning failed to read uploaded XML document.", e);
            }
        } else if (sourceType.equalsIgnoreCase(ZmailBulkProvisionExt.FILE_FORMAT_BULK_LDAP)) {
            GalParams.ExternalGalParams galParams = new GalParams.ExternalGalParams(attrs, GalOp.search);
            LdapGalMapRules rules = new LdapGalMapRules(Provisioning.getInstance().getConfig(), true);

            Element elPassword = request.getOptionalElement(AdminExtConstants.A_password);
            Element elPasswordLength = request.getOptionalElement(AdminExtConstants.A_genPasswordLength);

            String generatePwd = request.getElement(AdminExtConstants.A_generatePassword).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());
            }

            String password = null;
            if (elPassword != null) {
                password = elPassword.getTextTrim();
            }
            String mustChangePassword = request.getElement(AdminExtConstants.E_mustChangePassword)
                    .getTextTrim();
            if (SMTPPort.length() > 0 && SMTPHost.length() > 0) {
                zmailMailTransport = "smtp:" + SMTPHost + ":" + SMTPPort;
            }
            try {
                SearchGalResult result = LdapGalSearch.searchLdapGal(galParams, GalOp.search, "*", maxResults,
                        rules, null, null);
                List<GalContact> entries = result.getMatches();

                if (entries != null) {
                    for (GalContact entry : entries) {
                        String emailAddress = entry.getSingleAttr(ContactConstants.A_email);
                        if (emailAddress == null) {
                            continue;
                        }

                        String parts[] = EmailUtil.getLocalPartAndDomain(emailAddress);
                        if (parts == null) {
                            throw ServiceException
                                    .INVALID_REQUEST("must be valid email address: " + emailAddress, null);
                        }

                        Domain domain = prov.getDomainByName(parts[1]);
                        if (domain != null) {
                            checkDomainRight(zsc, domain, Admin.R_createAccount);
                        } else if (createDomains) {
                            if (ZmailBulkProvisionExt.OP_START_IMPORT.equalsIgnoreCase(op)) {
                                domain = createMissingDomain(parts[1], zsc, context);
                            }
                            checkDomainRight(zsc, domain, Admin.R_createAccount);
                        } else {
                            throw AccountServiceException.NO_SUCH_DOMAIN(parts[1]);
                        }
                        if (domain != null) {
                            checkDomainRight(zsc, domain, Admin.R_createAccount);
                        } else {
                            throw AccountServiceException.NO_SUCH_DOMAIN(parts[1]);
                        }
                        Account acct = Provisioning.getInstance().getAccountByName(emailAddress);
                        if (acct != null) {
                            totalExistingAccounts++;
                        } else {
                            Map<String, Object> accAttrs = new HashMap<String, Object>();
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_givenName,
                                    entry.getSingleAttr(ContactConstants.A_firstName));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_displayName,
                                    entry.getSingleAttr(ContactConstants.A_fullName));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_sn,
                                    entry.getSingleAttr(ContactConstants.A_lastName));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_initials,
                                    entry.getSingleAttr(ContactConstants.A_initials));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_description,
                                    entry.getSingleAttr(ContactConstants.A_notes));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_telephoneNumber,
                                    entry.getSingleAttr(ContactConstants.A_homePhone));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_mobile,
                                    entry.getSingleAttr(ContactConstants.A_mobilePhone));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_homePhone,
                                    entry.getSingleAttr(ContactConstants.A_homePhone));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_l,
                                    entry.getSingleAttr(ContactConstants.A_homeCity));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_st,
                                    entry.getSingleAttr(ContactConstants.A_homeState));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_co,
                                    entry.getSingleAttr(ContactConstants.A_homeCountry));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_postalCode,
                                    entry.getSingleAttr(ContactConstants.A_homePostalCode));
                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_street,
                                    entry.getSingleAttr(ContactConstants.A_homeAddress));
                            if (zmailMailTransport.length() > 0) {
                                StringUtil.addToMultiMap(accAttrs, Provisioning.A_zmailMailTransport,
                                        zmailMailTransport);
                            }
                            if ("true".equalsIgnoreCase(mustChangePassword)) {
                                StringUtil.addToMultiMap(accAttrs, Provisioning.A_zmailPasswordMustChange,
                                        "TRUE");
                            }
                            checkSetAttrsOnCreate(zsc, TargetType.account, emailAddress, accAttrs);

                            StringUtil.addToMultiMap(accAttrs, Provisioning.A_mail,
                                    entry.getSingleAttr(ContactConstants.A_email));
                            if (password != null) {
                                StringUtil.addToMultiMap(accAttrs, Provisioning.A_userPassword, password);
                            } else if (generatePwd.equalsIgnoreCase("true")) {
                                StringUtil.addToMultiMap(accAttrs, Provisioning.A_userPassword,
                                        String.valueOf(generateStrongPassword(genPwdLength)));
                            }

                            sourceEntries.add(accAttrs);
                        }
                        totalAccounts++;
                    }

                }
            } catch (ServiceException e) {
                throw ServiceException.FAILURE("", e);
            }
        } else {
            throw ServiceException.INVALID_REQUEST(
                    sourceType + " is not a valid value for parameter " + AdminExtConstants.A_sourceType, null);
        }
        if (ZmailBulkProvisionExt.OP_PREVIEW.equalsIgnoreCase(op)) {
            /*
             * Do not start the import. Just generate a preview.
             */
            response.addElement(AdminExtConstants.E_totalCount).setText(Integer.toString(totalAccounts));
            response.addElement(AdminExtConstants.E_skippedAccountCount)
                    .setText(Integer.toString(totalExistingAccounts));
            response.addElement(AdminExtConstants.E_SMTPHost).setText(SMTPHost);
            response.addElement(AdminExtConstants.E_SMTPPort).setText(SMTPPort);

        } else if (ZmailBulkProvisionExt.OP_START_IMPORT.equalsIgnoreCase(op)) {
            /*
             * Spin off a provisioning thread
             */
            if (sourceEntries.size() > 0) {
                BulkProvisioningThread thread = BulkProvisioningThread
                        .getThreadInstance(zsc.getAuthtokenAccountId(), true);
                int status = thread.getStatus();
                if (status == BulkProvisioningThread.iSTATUS_FINISHED) {
                    BulkProvisioningThread.deleteThreadInstance(zsc.getAuthtokenAccountId());
                    thread = BulkProvisioningThread.getThreadInstance(zsc.getAuthtokenAccountId(), true);
                    status = thread.getStatus();
                }
                if (status != BulkProvisioningThread.iSTATUS_IDLE) {
                    throw BulkProvisionException.BP_IMPORT_ALREADY_RUNNING();
                }
                thread.setSourceAccounts(sourceEntries);
                thread.start();
                response.addElement(AdminExtConstants.E_status).setText(Integer.toString(thread.getStatus()));
            } else {
                throw BulkProvisionException.BP_NO_ACCOUNTS_TO_IMPORT();
            }
        }
    }

    if (ZmailBulkProvisionExt.OP_ABORT_IMPORT.equalsIgnoreCase(op)) {
        BulkProvisioningThread thread = BulkProvisioningThread.getThreadInstance(zsc.getAuthtokenAccountId(),
                false);
        if (thread != null) {
            int status = thread.getStatus();
            if (status != BulkProvisioningThread.iSTATUS_FINISHED) {
                thread.abort();
                response.addElement(AdminExtConstants.E_status).setText(Integer.toString(thread.getStatus()));
                response.addElement(AdminExtConstants.E_provisionedCount)
                        .setText(Integer.toString(thread.getProvisionedCounter()));
                response.addElement(AdminExtConstants.E_skippedCount)
                        .setText(Integer.toString(thread.getSkippedCounter()));
                response.addElement(AdminExtConstants.E_totalCount)
                        .setText(Integer.toString(thread.getTotalCount()));
                if (thread.getWithErrors()) {
                    response.addElement(AdminExtConstants.E_errorCount)
                            .addText(Integer.toString(thread.getFailCounter()));
                }
                status = thread.getStatus();
                if (status == BulkProvisioningThread.iSTATUS_ABORTED) {
                    BulkProvisioningThread.deleteThreadInstance(zsc.getAuthtokenAccountId());
                }
            } else {
                response.addElement(AdminExtConstants.E_status).setText(Integer.toString(status));
            }
        } else {
            response.addElement(AdminExtConstants.E_status)
                    .setText(Integer.toString(BulkProvisioningThread.iSTATUS_NOT_RUNNING));
        }
    } else if (ZmailBulkProvisionExt.OP_GET_STATUS.equalsIgnoreCase(op)) {
        BulkProvisioningThread thread = BulkProvisioningThread.getThreadInstance(zsc.getAuthtokenAccountId(),
                false);
        if (thread != null) {
            int status = thread.getStatus();
            response.addElement(AdminExtConstants.E_status).setText(Integer.toString(status));
            response.addElement(AdminExtConstants.E_provisionedCount)
                    .setText(Integer.toString(thread.getProvisionedCounter()));
            response.addElement(AdminExtConstants.E_skippedCount)
                    .setText(Integer.toString(thread.getSkippedCounter()));
            response.addElement(AdminExtConstants.E_totalCount)
                    .setText(Integer.toString(thread.getTotalCount()));
            if (thread.getWithErrors()) {
                response.addElement(AdminExtConstants.E_errorCount)
                        .addText(Integer.toString(thread.getFailCounter()));
            }
            if (status == BulkProvisioningThread.iSTATUS_FINISHED
                    || status == BulkProvisioningThread.iSTATUS_ABORTED
                    || status == BulkProvisioningThread.iSTATUS_ERROR) {
                String fileToken = Double.toString(Math.random() * 100);
                String outSuccessFileName = String.format("%s%s_bulk_report_%s_%s.csv",
                        LC.zmail_tmp_directory.value(), File.separator, zsc.getAuthtokenAccountId(), fileToken);
                FileOutputStream outReport = null;
                CSVWriter reportWriter = null;
                try {
                    outReport = new FileOutputStream(outSuccessFileName);
                    reportWriter = new CSVWriter(new OutputStreamWriter(outReport));
                    for (String completedAccount : thread.getCompletedAccounts().keySet()) {
                        String[] line = new String[2];
                        line[0] = completedAccount; // account name
                        line[1] = thread.getCompletedAccounts().get(completedAccount); // account password
                        reportWriter.writeNext(line);
                    }
                    reportWriter.close();
                } catch (FileNotFoundException e) {
                    throw ServiceException
                            .FAILURE("Failed to create CSV file with a list of provisioned accounts", e);
                } catch (IOException e) {
                    throw ServiceException
                            .FAILURE("Failed to create CSV file with a list of provisioned accounts", e);
                } finally {
                    if (reportWriter != null) {
                        try {
                            reportWriter.close();
                        } catch (IOException e) {
                            ZmailLog.extensions.error(e);
                        }
                    }

                    if (outReport != null) {
                        try {
                            outReport.close();
                        } catch (IOException e) {
                            ZmailLog.extensions.error(e);
                        }
                    }
                }
                response.addElement(AdminExtConstants.E_reportFileToken).addText(fileToken);
                /**
                 * if thread is done for whichever reason and there are
                 * errors, generate an error report
                 */
                if (thread.getWithErrors()) {
                    FileOutputStream out = null;
                    CSVWriter errorWriter = null;
                    try {
                        String outErrorsFileName = String.format("%s%s_bulk_errors_%s_%s.csv",
                                LC.zmail_tmp_directory.value(), File.separator, zsc.getAuthtokenAccountId(),
                                fileToken);
                        out = new FileOutputStream(outErrorsFileName);
                        errorWriter = new CSVWriter(new OutputStreamWriter(out));
                        for (String failedAccount : thread.getfailedAccounts().keySet()) {
                            String[] line = new String[2];
                            line[0] = failedAccount;
                            line[1] = thread.getfailedAccounts().get(failedAccount).getMessage();
                            errorWriter.writeNext(line);
                        }
                        errorWriter.close();
                    } catch (FileNotFoundException e) {
                        throw ServiceException.FAILURE("Failed to create CSV file with error report", e);
                    } catch (IOException e) {
                        throw ServiceException.FAILURE("Failed to create CSV file with error report", e);
                    } finally {
                        if (errorWriter != null) {
                            try {
                                errorWriter.close();
                            } catch (IOException e) {
                                ZmailLog.extensions.error(e);
                            }
                        }
                        if (out != null) {
                            try {
                                out.close();
                            } catch (IOException e) {
                                ZmailLog.extensions.error(e);
                            }
                        }
                    }
                }
                BulkProvisioningThread.deleteThreadInstance(zsc.getAuthtokenAccountId());
            }
        } else {
            response.addElement(AdminExtConstants.E_status)
                    .setText(Integer.toString(BulkProvisioningThread.iSTATUS_NOT_RUNNING));
        }
    }
    return response;
}

From source file:tokyo.northside.jrst.JRSTReader.java

License:Open Source License

/**
 * *// w  w w  .j  a va2  s. c  o m
 * <p>
 * Corps du document
 * </p>
 *
 * @param lexer
 * @return Element
 * @throws DocumentException
 * @throws IOException
 */
private Element composeBody(JRSTLexer lexer, Element parent) throws Exception {

    Element item = lexer.peekTitleOrBodyElement();
    if (item == null && !lexer.eof()) {
        item = lexer.peekTitleOrBodyElement();
    }

    while (!lexer.eof() && itemNotEquals(TITLE, item) && isUpperLevel(item, parent)) {
        if (itemEquals(JRSTLexer.BLANK_LINE, item)) {
            // go to the next element
            lexer.remove();
        } else if (itemEquals(REMOVE, item)) {
            lexer.remove();
        } else if (itemEquals(INCLUDE, item)) {
            lexer.remove();
            Element list = composeInclude(item);
            parent.add(list);
        } else if (itemEquals(DOCTEST_BLOCK, item)) {
            lexer.remove();
            Element list = composeDoctestBlock(item);
            parent.add(list);
        } else if (itemEquals(ADMONITION, item)) {
            lexer.remove();
            Element list = composeAdmonition(item);
            parent.add(list);
        } else if (itemEquals(SIDEBAR, item)) {
            lexer.remove();
            Element list = composeSidebar(item);
            parent.add(list);
        } else if (itemEquals(TOPIC, item)) {
            lexer.remove();
            Element list = composeTopic(item);
            parent.add(list);
        } else if (itemEquals(TRANSITION, item)) {
            lexer.remove();
            Element para = parent.addElement(TRANSITION);
            copyLevel(item, para);
        } else if (itemEquals(PARAGRAPH, item)) {
            lexer.remove();
            Element para = parent.addElement(PARAGRAPH);
            copyLevel(item, para);
            para.addAttribute(ATTR_INLINE, TRUE).setText(item.getText());
        } else if (itemEquals(JRSTLexer.DIRECTIVE, item)) {
            lexer.remove();
            Node directive = composeDirective(item);
            parent.add(directive);
        } else if (itemEquals(SUBSTITUTION_DEFINITION, item)) {
            lexer.remove();
            Element subst = composeSubstitutionDefinition(item);
            parent.add(subst);
        } else if (itemEquals(LITERAL_BLOCK, item)) {
            lexer.remove();
            Element para = parent.addElement(LITERAL_BLOCK);
            copyLevel(item, para);
            para.setText(item.getText());
        } else if (itemEquals(JRSTLexer.TABLE, item)) {
            lexer.remove();
            Element table = composeTable(item);
            parent.add(table);
            // Element para = parent.addElement(TABLE);
            // copyLevel(item, para);
            // para.setText(item.getText());
        } else if (itemEquals(LINE_BLOCK, item)) {
            lexer.remove();
            Element list = composeLineBlock(lexer, item);
            parent.add(list);
        } else if (itemEquals(BULLET_LIST, item)) {
            Element list = composeBulletList(lexer);
            parent.add(list);
        } else if (itemEquals(ENUMERATED_LIST, item)) {
            Element list = composeEnumeratedList(lexer);
            parent.add(list);
        } else if (itemEquals(DEFINITION_LIST, item)) {
            Element list = composeDefinitionList(lexer);
            parent.add(list);
        } else if (itemEquals(FIELD_LIST, item)) {
            Element list = composeFieldList(lexer);
            parent.add(list);
        } else if (itemEquals(BLOCK_QUOTE, item)) {
            lexer.remove();
            Element list = composeBlockQuote(item);
            parent.add(list);
        } else if (itemEquals(OPTION_LIST, item)) {
            Element list = composeOptionList(lexer);
            parent.add(list);
        } else if (itemEquals(TARGET, item)) {
            lexer.remove();
            Element list = composeTarget(item);
            if (list != null) {
                try {
                    parent.add(list);
                } catch (IllegalAddException e) {
                }
            } else
                System.err.println("Unknown target name : \"" + item.attributeValue(ATTR_IDS) + "\"");
        } else if (itemEquals(TARGETANONYMOUS, item)) {
            lexer.remove();
            Element list = composeTargetAnonymous(item);
            parent.add(list);
        } else if (itemEquals(FOOTNOTES, item)) {
            lexer.remove();
            Element[] list = composeFootnote(item);
            for (Element l : list) {
                parent.add(l);
            }
        } else if (itemEquals(COMMENT, item)) {
            lexer.remove();
            Element list = composeComment(item);
            parent.add(list);
        }

        else {
            if (ERROR_MISSING_ITEM) {
                throw new DocumentException("Unknow item type: " + item.getName());
            } else {
                lexer.remove();
            }
        }

        // Pour afficher le "PseudoXML"
        // if (item!=null) System.out.println(item.asXML());

        item = lexer.peekTitleOrBodyElement();
    }

    return parent;
}

From source file:tokyo.northside.jrst.JRSTReader.java

License:Open Source License

/**
 * <pre>/* www  . ja v  a 2  s.  c  o  m*/
 * :field1: avec un
 *    petit texte
 *    - et meme un
 *    - debut
 *    - de list
 * </pre>
 *
 * @param lexer
 * @return Element
 * @throws Exception
 */
private Element composeFieldItemList(JRSTLexer lexer) throws Exception {
    Element item = lexer.peekFieldList();
    if (itemEquals(FIELD_LIST, item)) {
        lexer.remove();
        Element field = DocumentHelper.createElement(FIELD);
        copyLevel(item, field);
        Element fieldName = field.addElement(FIELD_NAME);
        copyLevel(item, fieldName);
        fieldName.addAttribute(ATTR_INLINE, TRUE).setText(item.attributeValue(NAME));
        Element fieldBody = field.addElement(FIELD_BODY);
        fieldBody.addElement(PARAGRAPH).addAttribute(ATTR_INLINE, TRUE).setText(item.getText());
        copyLevel(item, fieldBody);
        composeBody(lexer, fieldBody);

        return field;
    } else {
        throw new DocumentException("Waiting for " + FIELD_LIST + " and found " + item.getName());
    }
}

From source file:tokyo.northside.jrst.JRSTReader.java

License:Open Source License

/**
 * @param from element//from  ww w  . ja va2s .co  m
 * @param to element
 * @throws DocumentException
 */
private void copyLevel(Element from, Element to) throws DocumentException {
    String level = from.attributeValue(LEVEL);
    if (level == null) {
        throw new DocumentException("Element without level: " + from);
    }
    to.addAttribute(LEVEL, level);
}

From source file:tokyo.northside.jrst.JRSTReader.java

License:Open Source License

/**
 * @param name name of element/*from   w  ww .  j  ava 2 s .  com*/
 * @param e Element
 * @param throwError
 * @param eof
 * @return boolean
 * @throws DocumentException
 */
private boolean itemEquals(String name, Element e, boolean throwError, boolean eof) throws DocumentException {
    boolean result = e != null && name.equals(e.getName());
    if (ERROR_MISSING_ITEM && !result && throwError && !eof) {
        throw new DocumentException(
                "Malformed document waiting " + name + " and found " + (e != null ? e.getName() : "null"));
    }
    return result;
}