@Override
 public ParseMimeMessage.InviteParserResult parseInviteElement(
     ZimbraSoapContext zc, OperationContext octxt, Account account, Element inviteElem)
     throws ServiceException {
   Element content = inviteElem.getOptionalElement(MailConstants.E_CONTENT);
   if (content != null) {
     ParseMimeMessage.InviteParserResult toRet =
         CalendarUtils.parseInviteRaw(account, inviteElem);
     return toRet;
   } else {
     if (mForCancel) {
       return CalendarUtils.parseInviteForCancel(
           account, mFolder, type, inviteElem, null, mExceptOk, CalendarUtils.RECUR_ALLOWED);
     } else {
       return CalendarUtils.parseInviteForCreate(
           account, type, inviteElem, null, null, mExceptOk, CalendarUtils.RECUR_ALLOWED);
     }
   }
 }
Exemple #2
0
 public Element handleNetworkRequest(Element document, Map context)
     throws ServiceException
 {
     Element backup;
     String method;
     String bkupTarget;
     String label;
     Element response;
     Log.backup.info("Backup request started");
     ZimbraSoapContext lc = getZimbraSoapContext(context);
     checkRights(lc, context);
     backup = document.getElement("backup");
     method = backup.getAttribute("method");
     bkupTarget = backup.getAttribute("target", null);
     label = backup.getAttribute("label", null);
     response = lc.createElement(BackupService.BACKUP_RESPONSE);
     BackupManager mgr;
     BackupTarget backupTarget;
     boolean sync;
     boolean sentReportEmail;
     ServiceException error;
     mgr = BackupManager.getInstance();
     if(bkupTarget != null && "incremental".equals(method))
         throw ServiceException.FAILURE("Custom backup target is not allowed for incremental backup", null);
     backupTarget = mgr.getBackupTarget(bkupTarget, true);
     if("abort".equals(method))
     {
         BackupSet bak = backupTarget.getBackupSet(label);
         bak.abortFullBackup();
         break MISSING_BLOCK_LABEL_852;
     }
     if("delete".equals(method))
     {
         String val = backup.getAttribute("before");
         long cutoffTime = getCutoffTime(val, backupTarget);
         mgr.deleteBackups(backupTarget, cutoffTime);
         break MISSING_BLOCK_LABEL_852;
     }
     sync = backup.getAttributeBool("sync", false);
     sentReportEmail = false;
     error = null;
     BackupParams params;
     List syncBackups;
     BackupSet fullBak;
     BackupSet incrBak;
     params = new BackupParams();
     params.sync = sync;
     parseComponentIncludeExcludeAttrs(backup, params);
     Element fcOptsElem = backup.getOptionalElement("fileCopier");
     if(fcOptsElem != null)
         params.fcOpts = ParseXML.parseFileCopierOptions(fcOptsElem);
     syncBackups = new ArrayList();
     fullBak = null;
     incrBak = null;
     int size;
     try
     {
         com.zimbra.cs.backup.BackupManager.BackupMode backupMode = mgr.getBackupMode();
         boolean autoGroupedMode = com.zimbra.cs.backup.BackupManager.BackupMode.AUTO_GROUPED.equals(backupMode);
         if("full".equals(method))
         {
             params.zip = backup.getAttributeBool("zip", true);
             params.zipStore = backup.getAttributeBool("zipStore", true);
             List acctElems = backup.listElements("account");
             if(acctElems.size() > 0)
             {
                 params.redologs = false;
                 List acctNames = parseAccountNames(acctElems);
                 boolean all = acctNames.size() == 1 && "all".equals(acctNames.get(0));
                 if(all)
                 {
                     if(!sync)
                         fullBak = mgr.startBackupFull(backupTarget, params);
                     else
                         fullBak = mgr.backupFull(backupTarget, params, syncBackups);
                 } else
                 {
                     com.zimbra.cs.account.Account accounts[] = mgr.lookupAccounts(acctNames, com.zimbra.cs.account.Provisioning.AccountBy.name, backupTarget);
                     if(!sync)
                         fullBak = mgr.startBackupFull(accounts, backupTarget, params);
                     else
                         fullBak = mgr.backupFull(accounts, backupTarget, params, syncBackups);
                 }
             } else
             if(autoGroupedMode)
             {
                 if(backupTarget.isCustom())
                     throw ServiceException.FAILURE("Custom backup target is not allowed for auto-grouped backup", null);
                 params.redologs = true;
                 com.zimbra.cs.account.Account accounts[] = mgr.lookupAccountsByOldestBackup(backupTarget);
                 if(accounts == null || accounts.length == 0)
                     throw BackupServiceException.AUTO_GROUPED_BACKUP_TOO_SOON();
                 if(!sync)
                     fullBak = mgr.startBackupFull(accounts, backupTarget, params);
                 else
                     fullBak = mgr.backupFull(accounts, backupTarget, params, syncBackups);
             } else
             {
                 throw ServiceException.INVALID_REQUEST("Missing account list", null);
             }
         } else
         if("incremental".equals(method))
         {
             params.zip = backup.getAttributeBool("zip", true);
             params.zipStore = backup.getAttributeBool("zipStore", true);
             BackupSet baks[] = mgr.backupIncremental(backupTarget, params, syncBackups);
             incrBak = baks[0];
             fullBak = baks[1];
         } else
         {
             throw ServiceException.INVALID_REQUEST((new StringBuilder()).append("Invalid backup method: ").append(method).toString(), null);
         }
     }
     catch(IOException e)
     {
         throw ServiceException.FAILURE(e.getMessage(), e);
     }
     size = syncBackups.size();
     if(size > 0)
     {
         BackupSet baks[] = new BackupSet[size];
         syncBackups.toArray(baks);
         mgr.sendReportEmail(baks);
         sentReportEmail = true;
     }
     break MISSING_BLOCK_LABEL_756;
     Exception exception;
     exception;
     int size = syncBackups.size();
     if(size > 0)
     {
         BackupSet baks[] = new BackupSet[size];
         syncBackups.toArray(baks);
         mgr.sendReportEmail(baks);
         sentReportEmail = true;
     }
     throw exception;
     Element body = response.addElement("backup");
     if(fullBak != null)
         body.addAttribute("label", fullBak.getLabel());
     if(incrBak != null)
         body.addAttribute("incr-label", incrBak.getLabel());
     if(error != null && !sentReportEmail)
         mgr.sendErrorReportEmail(error);
     break MISSING_BLOCK_LABEL_852;
     ServiceException e;
     e;
     error = e;
     throw e;
     Exception exception1;
     exception1;
     if(error != null && !sentReportEmail)
         mgr.sendErrorReportEmail(error);
     throw exception1;
     Log.backup.info("Backup request finished");
     return response;
     IOException e;
     e;
     throw ServiceException.FAILURE(e.getMessage(), e);
 }
  @Override
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(context);
    Mailbox mbox = getRequestedMailbox(zsc);
    OperationContext octxt = getOperationContext(zsc, context);
    ItemIdFormatter ifmt = new ItemIdFormatter(zsc);

    int flags = Flag.toBitmask(request.getAttribute(MailConstants.A_FLAGS, null));
    String[] tags = TagUtil.parseTags(request, mbox, octxt);

    mbox.lock.lock();
    try {
      int defaultFolder =
          getItemType() == MailItem.Type.TASK
              ? Mailbox.ID_FOLDER_TASKS
              : Mailbox.ID_FOLDER_CALENDAR;
      String defaultFolderStr = Integer.toString(defaultFolder);
      String folderIdStr = request.getAttribute(MailConstants.A_FOLDER, defaultFolderStr);
      ItemId iidFolder = new ItemId(folderIdStr, zsc);
      Folder folder = mbox.getFolderById(octxt, iidFolder.getId());
      SetCalendarItemParseResult parsed =
          parseSetAppointmentRequest(request, zsc, octxt, folder, getItemType(), false);

      CalendarItem calItem =
          mbox.setCalendarItem(
              octxt,
              iidFolder.getId(),
              flags,
              tags,
              parsed.defaultInv,
              parsed.exceptions,
              parsed.replies,
              parsed.nextAlarm);

      Element response = getResponseElement(zsc);

      if (parsed.defaultInv != null) {
        response
            .addElement(MailConstants.A_DEFAULT)
            .addAttribute(
                MailConstants.A_ID, ifmt.formatItemId(parsed.defaultInv.invite.getMailItemId()));
      }

      if (parsed.exceptions != null) {
        for (SetCalendarItemData cur : parsed.exceptions) {
          Element e = response.addElement(MailConstants.E_CAL_EXCEPT);
          e.addAttribute(MailConstants.A_CAL_RECURRENCE_ID, cur.invite.getRecurId().toString());
          e.addAttribute(MailConstants.A_ID, ifmt.formatItemId(cur.invite.getMailItemId()));
        }
      }
      String itemId = ifmt.formatItemId(calItem == null ? 0 : calItem.getId());
      response.addAttribute(MailConstants.A_CAL_ID, itemId);
      try {
        Element inv =
            request
                .getElement(MailConstants.A_DEFAULT)
                .getElement(MailConstants.E_MSG)
                .getElement(MailConstants.E_INVITE);
        Element comp = inv.getOptionalElement(MailConstants.E_INVITE_COMPONENT);
        if (comp != null) {
          inv = comp;
        }
        String reqCalItemId = inv.getAttribute(MailConstants.A_CAL_ID);
        String uid = inv.getAttribute(MailConstants.A_UID);
        boolean uidSame =
            (calItem == null
                || (calItem.getUid() == null && uid == null)
                || (calItem.getUid() != null
                    && (calItem.getUid().equals(uid)
                        || (Invite.isOutlookUid(calItem.getUid())
                            && calItem
                                .getUid()
                                .equalsIgnoreCase(
                                    uid))))); // new or same as requested, or Outlook and
        // case-insensitive equal
        if (ZimbraLog.calendar.isInfoEnabled()) {
          StringBuilder logBuf = new StringBuilder();
          if (!reqCalItemId.equals(itemId)) {
            logBuf
                .append("Mapped requested id ")
                .append(reqCalItemId)
                .append(" -> ")
                .append(itemId);
          }
          if (!uidSame) {
            logBuf
                .append(" ?? requested UID ")
                .append(uid)
                .append(" differs from mapped ")
                .append(calItem.getUid());
            ZimbraLog.calendar.warn(logBuf.toString());
          } else if (logBuf.length() > 0) {
            ZimbraLog.calendar.info(logBuf.toString());
          }
        }
        assert (uidSame);
      } catch (ServiceException se) {
        // one of the elements we wanted to use doesn't exist; ignore; no log/assertion possible
      }
      if (!parsed.isTodo)
        response.addAttribute(MailConstants.A_APPT_ID_DEPRECATE_ME, itemId); // for backward compat

      return response;
    } finally {
      mbox.lock.release();
    }
  }
  public static SetCalendarItemParseResult parseSetAppointmentRequest(
      Element request,
      ZimbraSoapContext zsc,
      OperationContext octxt,
      Folder folder,
      MailItem.Type type,
      boolean parseIds)
      throws ServiceException {
    Account acct = getRequestedAccount(zsc);
    Mailbox mbox = getRequestedMailbox(zsc);

    SetCalendarItemParseResult result = new SetCalendarItemParseResult();
    ArrayList<SetCalendarItemData> exceptions = new ArrayList<SetCalendarItemData>();
    Invite defInv = null;

    // First, the <default>
    {
      Element e = request.getOptionalElement(MailConstants.A_DEFAULT);
      if (e != null) {
        result.defaultInv =
            getSetCalendarItemData(
                zsc,
                octxt,
                acct,
                mbox,
                e,
                new SetCalendarItemInviteParser(false, false, folder, type));
        defInv = result.defaultInv.invite;
      }
    }

    // for each <except>
    for (Element e : request.listElements(MailConstants.E_CAL_EXCEPT)) {
      SetCalendarItemData exDat =
          getSetCalendarItemData(
              zsc,
              octxt,
              acct,
              mbox,
              e,
              new SetCalendarItemInviteParser(true, false, folder, type));
      exceptions.add(exDat);
      if (defInv == null) {
        defInv = exDat.invite;
      }
    }

    // for each <cancel>
    for (Element e : request.listElements(MailConstants.E_CAL_CANCEL)) {
      SetCalendarItemData exDat =
          getSetCalendarItemData(
              zsc, octxt, acct, mbox, e, new SetCalendarItemInviteParser(true, true, folder, type));
      exceptions.add(exDat);
      if (defInv == null) {
        defInv = exDat.invite;
      }
    }

    if (exceptions.size() > 0) {
      result.exceptions = new SetCalendarItemData[exceptions.size()];
      exceptions.toArray(result.exceptions);
    } else {
      if (result.defaultInv == null)
        throw ServiceException.INVALID_REQUEST("No default/except/cancel specified", null);
    }

    // <replies>
    Element repliesElem = request.getOptionalElement(MailConstants.E_CAL_REPLIES);
    if (repliesElem != null)
      result.replies = CalendarUtils.parseReplyList(repliesElem, defInv.getTimeZoneMap());

    result.isTodo = defInv != null && defInv.isTodo();

    boolean noNextAlarm = request.getAttributeBool(MailConstants.A_CAL_NO_NEXT_ALARM, false);
    if (noNextAlarm) result.nextAlarm = CalendarItem.NEXT_ALARM_ALL_DISMISSED;
    else
      result.nextAlarm =
          request.getAttributeLong(
              MailConstants.A_CAL_NEXT_ALARM, CalendarItem.NEXT_ALARM_KEEP_CURRENT);

    return result;
  }
  static SetCalendarItemData getSetCalendarItemData(
      ZimbraSoapContext zsc,
      OperationContext octxt,
      Account acct,
      Mailbox mbox,
      Element e,
      ParseMimeMessage.InviteParser parser)
      throws ServiceException {
    String partStatStr =
        e.getAttribute(MailConstants.A_CAL_PARTSTAT, IcalXmlStrMap.PARTSTAT_NEEDS_ACTION);

    // <M>
    Element msgElem = e.getElement(MailConstants.E_MSG);

    // check to see whether the entire message has been uploaded under separate cover
    String attachmentId = msgElem.getAttribute(MailConstants.A_ATTACHMENT_ID, null);
    Element contentElement = msgElem.getOptionalElement(MailConstants.E_CONTENT);

    InviteParserResult ipr = null;

    MimeMessage mm = null;
    if (attachmentId != null) {
      ParseMimeMessage.MimeMessageData mimeData = new ParseMimeMessage.MimeMessageData();
      mm = SendMsg.parseUploadedMessage(zsc, attachmentId, mimeData);
    } else if (contentElement != null) {
      mm = ParseMimeMessage.importMsgSoap(msgElem);
    } else {
      CalSendData dat = handleMsgElement(zsc, octxt, msgElem, acct, mbox, parser);
      mm = dat.mMm;
      ipr = parser.getResult();
    }

    if (ipr == null && msgElem.getOptionalElement(MailConstants.E_INVITE) != null) {
      ipr = parser.parse(zsc, octxt, mbox.getAccount(), msgElem.getElement(MailConstants.E_INVITE));
      // Get description texts out of the MimeMessage and set in the parsed invite.  Do it only if
      // the MimeMessage has text parts.  This prevents discarding texts when they're specified only
      // in the <inv> but not in mime parts.
      if (ipr != null && ipr.mInvite != null && mm != null) {
        String desc = Invite.getDescription(mm, MimeConstants.CT_TEXT_PLAIN);
        String descHtml = Invite.getDescription(mm, MimeConstants.CT_TEXT_HTML);
        if ((desc != null && desc.length() > 0) || (descHtml != null && descHtml.length() > 0))
          ipr.mInvite.setDescription(desc, descHtml);
      }
    }

    ParsedMessage pm = new ParsedMessage(mm, mbox.attachmentsIndexingEnabled());

    Invite inv = (ipr == null ? null : ipr.mInvite);
    if (inv == null || inv.getDTStamp() == -1) { // zdsync if -1 for 4.5 back compat
      CalendarPartInfo cpi = pm.getCalendarPartInfo();
      ZVCalendar cal = null;
      if (cpi != null && CalendarItem.isAcceptableInvite(mbox.getAccount(), cpi)) cal = cpi.cal;
      if (cal == null)
        throw ServiceException.FAILURE("SetCalendarItem could not build an iCalendar object", null);
      boolean sentByMe = false; // not applicable in the SetCalendarItem case
      Invite iCalInv = Invite.createFromCalendar(acct, pm.getFragment(), cal, sentByMe).get(0);

      if (inv == null) {
        inv = iCalInv;
      } else {
        inv.setDtStamp(iCalInv.getDTStamp()); // zdsync
        inv.setFragment(iCalInv.getFragment()); // zdsync
      }
    }
    inv.setPartStat(partStatStr);

    SetCalendarItemData sadata = new SetCalendarItemData();
    sadata.invite = inv;
    sadata.message = pm;
    return sadata;
  }
  public Element handle(Element request, Map<String, Object> context) throws ServiceException {
    ZimbraSoapContext zsc = getZimbraSoapContext(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;
    String sourceType = request.getElement(AdminExtConstants.A_sourceType).getTextTrim();
    String indexBatchSize = ZimbraBulkProvisionExt.DEFAULT_INDEX_BATCH_SIZE;
    boolean useAdminLogin = false;
    if (sourceType.equalsIgnoreCase(AdminFileDownload.FILE_FORMAT_BULK_XML)) {
      String aid = request.getElement(AdminExtConstants.E_attachmentID).getTextTrim();
      ZimbraLog.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 = "******".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(ZimbraBulkProvisionExt.FILE_FORMAT_ZIMBRA)) {
      IMAPAccounts = getZimbraAccounts(request, zsc);
    } else {
      throw ServiceException.INVALID_REQUEST(
          String.format(
              "Invalid value of %s parameter: %s. Allowed values: %s, %s",
              AdminExtConstants.A_sourceType,
              sourceType,
              ZimbraBulkProvisionExt.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 = "******".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 (ZimbraBulkProvisionExt.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 (ZimbraBulkProvisionExt.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 = ZimbraBulkProvisionExt.DEFAULT_INDEX_BATCH_SIZE;
      } catch (Exception e) {
        indexBatchSize = ZimbraBulkProvisionExt.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 (ZimbraBulkProvisionExt.OP_DISMISS_IMPORT.equalsIgnoreCase(op)) {

    }
    return response;
  }
Exemple #7
0
  public ZAlarm(Element alarmElem) throws ServiceException {
    ZAction action = ZAction.DISPLAY;
    ZTriggerType triggerType = ZTriggerType.RELATIVE;
    ZRelated triggerRelated = null;
    ParsedDuration triggerRelative = null;
    ParsedDateTime triggerAbsolute = null;
    ParsedDuration repeatDuration = null;
    int repeatCount = 0;
    String description = null;
    String summary = null;
    Attach attach = null;
    List<ZAttendee> attendees = null;

    String val;
    val = alarmElem.getAttribute(MailConstants.A_CAL_ALARM_ACTION);
    action = ZAction.lookup(val);
    if (action == null)
      throw ServiceException.INVALID_REQUEST(
          "Invalid " + MailConstants.A_CAL_ALARM_ACTION + " value " + val, null);

    Element triggerElem = alarmElem.getElement(MailConstants.E_CAL_ALARM_TRIGGER);
    Element triggerRelativeElem =
        triggerElem.getOptionalElement(MailConstants.E_CAL_ALARM_RELATIVE);
    if (triggerRelativeElem != null) {
      triggerType = ZTriggerType.RELATIVE;
      String related = triggerRelativeElem.getAttribute(MailConstants.A_CAL_ALARM_RELATED, null);
      if (related != null) {
        triggerRelated = ZRelated.lookup(related);
        if (triggerRelated == null)
          throw ServiceException.INVALID_REQUEST(
              "Invalid " + MailConstants.A_CAL_ALARM_RELATED + " value " + val, null);
      }
      triggerRelative = ParsedDuration.parse(triggerRelativeElem);
    } else {
      triggerType = ZTriggerType.ABSOLUTE;
      Element triggerAbsoluteElem =
          triggerElem.getOptionalElement(MailConstants.E_CAL_ALARM_ABSOLUTE);
      if (triggerAbsoluteElem == null)
        throw ServiceException.INVALID_REQUEST(
            "<"
                + MailConstants.E_CAL_ALARM_TRIGGER
                + "> must have either <"
                + MailConstants.E_CAL_ALARM_RELATIVE
                + "> or <"
                + MailConstants.E_CAL_ALARM_ABSOLUTE
                + "> child element",
            null);
      String datetime = triggerAbsoluteElem.getAttribute(MailConstants.A_DATE);
      try {
        triggerAbsolute = ParsedDateTime.parseUtcOnly(datetime);
      } catch (ParseException e) {
        throw ServiceException.INVALID_REQUEST("Invalid absolute trigger value " + val, e);
      }
    }

    Element repeatElem = alarmElem.getOptionalElement(MailConstants.E_CAL_ALARM_REPEAT);
    if (repeatElem != null) {
      repeatDuration = ParsedDuration.parse(repeatElem);
      repeatCount = (int) repeatElem.getAttributeLong(MailConstants.A_CAL_ALARM_COUNT, 0);
    }

    Element descElem = alarmElem.getOptionalElement(MailConstants.E_CAL_ALARM_DESCRIPTION);
    if (descElem != null) {
      description = descElem.getText();
    }

    Element summaryElem = alarmElem.getOptionalElement(MailConstants.E_CAL_ALARM_SUMMARY);
    if (summaryElem != null) {
      summary = summaryElem.getText();
    }

    Element attachElem = alarmElem.getOptionalElement(MailConstants.E_CAL_ATTACH);
    if (attachElem != null) attach = Attach.parse(attachElem);

    Iterator<Element> attendeesIter = alarmElem.elementIterator(MailConstants.E_CAL_ATTENDEE);
    while (attendeesIter.hasNext()) {
      ZAttendee at = new ZAttendee(attendeesIter.next());
      if (this.mAttendees == null) this.mAttendees = new ArrayList<ZAttendee>();
      this.mAttendees.add(at);
    }
    setAction(action);
    setDescription(description);
    setSummary(summary);
    setTriggerRelative(triggerRelative);
  }