use of com.zimbra.cs.mailbox.MailItem in project zm-mailbox by Zimbra.
the class ImapURL method getContentAsStream.
public Pair<Long, InputStream> getContentAsStream(ImapHandler handler, ImapCredentials creds, String tag) throws ImapException {
ImapHandler.State state = handler.getState();
if (state == ImapHandler.State.NOT_AUTHENTICATED) {
throw new ImapUrlException(tag, mURL, "must be in AUTHENTICATED state");
}
try {
Account acct = Provisioning.getInstance().get(AccountBy.name, mUsername);
if (acct == null) {
throw new ImapUrlException(tag, mURL, "cannot find user: " + mUsername);
}
ImapSession i4session = handler.getCurrentSession();
OperationContext octxt = creds.getContext().setSession(i4session);
Pair<Long, InputStream> content = null;
// special-case the situation where the relevant folder is already SELECTed
ImapFolder i4folder = handler.getSelectedFolder();
if (state == ImapHandler.State.SELECTED && i4session != null && i4folder != null) {
if (acct.getId().equals(i4session.getTargetAccountId()) && mPath.isEquivalent(i4folder.getPath())) {
ImapMessage i4msg = i4folder.getByImapId(mUid);
if (i4msg == null || i4msg.isExpunged()) {
throw new ImapUrlException(tag, mURL, "no such message");
}
MailItem item = i4folder.getMailbox().getItemById(octxt, i4msg.msgId, i4msg.getType());
content = ImapMessage.getContent(item);
}
}
// if not, have to fetch by IMAP UID if we're local
if (content == null && mPath.onLocalServer()) {
Mailbox mbox = (Mailbox) mPath.getOwnerMailbox();
MailItem item = mbox.getItemByImapId(octxt, mUid, mPath.asItemId().getId());
if (!ImapMessage.SUPPORTED_TYPES.contains(item.getType())) {
throw new ImapUrlException(tag, mURL, "no such message");
}
content = ImapMessage.getContent(item);
}
// last option: handle off-server URLs
if (content == null) {
Account authacct = Provisioning.getInstance().get(AccountBy.id, creds.getAccountId());
AuthToken auth = AuthProvider.getAuthToken(authacct, System.currentTimeMillis() + 60 * 1000);
HashMap<String, String> params = new HashMap<String, String>();
params.put(UserServlet.QP_IMAP_ID, Integer.toString(mUid));
UserServlet.HttpInputStream is = UserServlet.getRemoteContentAsStream(auth, acct, mPath.asResolvedPath(), params);
content = new Pair<Long, InputStream>((long) is.getContentLength(), is);
}
// fetch the content of the message
if (mPart == null) {
return content;
}
// and return the appropriate subpart of the selected message
MimeMessage mm;
try {
mm = new Mime.FixedMimeMessage(JMSession.getSession(), content.getSecond());
} finally {
content.getSecond().close();
}
Pair<Long, InputStream> part = mPart.getContent(mm);
if (part == null) {
throw new ImapUrlException(tag, mURL, "no such part");
}
return part;
} catch (NoSuchItemException e) {
ZimbraLog.imap.info("no such message", e);
} catch (ServiceException e) {
ZimbraLog.imap.info("can't fetch content from IMAP URL", e);
} catch (MessagingException e) {
ZimbraLog.imap.info("can't fetch content from IMAP URL", e);
} catch (IOException e) {
ZimbraLog.imap.info("error reading content from IMAP URL", e);
} catch (BinaryDecodingException e) {
ZimbraLog.imap.info("can't fetch content from IMAP URL", e);
}
throw new ImapUrlException(tag, mURL, "error fetching IMAP URL content");
}
use of com.zimbra.cs.mailbox.MailItem in project zm-mailbox by Zimbra.
the class ZimbraHit method getParentId.
public int getParentId() throws ServiceException {
if (cachedParentId == 0) {
MailItem item = getMailItem();
cachedParentId = item != null ? item.getParentId() : -1;
}
return cachedParentId;
}
use of com.zimbra.cs.mailbox.MailItem in project zm-mailbox by Zimbra.
the class GetSearchFolder method handle.
@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);
Element response = zsc.createElement(MailConstants.GET_SEARCH_FOLDER_RESPONSE);
List<? extends MailItem> results = mbox.getItemList(octxt, MailItem.Type.SEARCHFOLDER, -1, SortBy.NONE);
if (results != null) {
for (MailItem item : results) ToXML.encodeSearchFolder(response, ifmt, (SearchFolder) item);
}
return response;
}
use of com.zimbra.cs.mailbox.MailItem in project zm-mailbox by Zimbra.
the class ArchiveFormatter method formatCallback.
@Override
public void formatCallback(UserServletContext context) throws IOException, ServiceException, UserServletException {
// Disable the jetty timeout
disableJettyTimeout(context);
HashMap<Integer, Integer> cnts = new HashMap<Integer, Integer>();
int dot;
HashMap<Integer, String> fldrs = new HashMap<Integer, String>();
String emptyname = context.params.get("emptyname");
String ext = "." + getType();
String filename = context.params.get("filename");
String lock = context.params.get("lock");
String query = context.getQueryString();
Set<String> names = new HashSet<String>(4096);
Set<MailItem.Type> sysTypes = EnumSet.of(MailItem.Type.FOLDER, MailItem.Type.SEARCHFOLDER, MailItem.Type.TAG, MailItem.Type.FLAG, MailItem.Type.MOUNTPOINT);
Set<MailItem.Type> searchTypes = EnumSet.of(MailItem.Type.MESSAGE, MailItem.Type.CONTACT, MailItem.Type.DOCUMENT, MailItem.Type.WIKI, MailItem.Type.APPOINTMENT, MailItem.Type.TASK, MailItem.Type.CHAT, MailItem.Type.NOTE);
ArchiveOutputStream aos = null;
String types = context.getTypesString();
MailboxMaintenance maintenance = null;
try {
if (filename == null || filename.equals("")) {
Date date = new Date();
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT);
SimpleDateFormat sdf = new SimpleDateFormat(".H-m-s");
if (context.hasPart()) {
filename = "attachments";
} else {
filename = context.targetMailbox.getAccountId() + '.' + df.format(date).replace('/', '-') + sdf.format(date);
}
} else if ((dot = filename.lastIndexOf('.')) != -1) {
String userProvidedExtension = filename.substring(dot + 1);
if (BLE.contains(userProvidedExtension.toUpperCase())) {
filename = filename.substring(0, dot);
}
}
if (!filename.endsWith(ext)) {
filename += ext;
}
if (emptyname != null && !emptyname.equals("") && !emptyname.endsWith(ext)) {
emptyname += ext;
}
context.resp.addHeader("Content-Disposition", HttpUtil.createContentDisposition(context.req, Part.ATTACHMENT, filename));
if (ext.equals(".tar")) {
context.resp.setContentType("application/x-tar");
} else if (ext.equals(".tgz")) {
context.resp.setContentType("application/x-compressed-tar");
} else if (ext.equals(".zip")) {
context.resp.setContentType("application/zip");
}
if (!Strings.isNullOrEmpty(types)) {
try {
searchTypes = MailItem.Type.setOf(types);
} catch (IllegalArgumentException e) {
throw MailServiceException.INVALID_TYPE(e.getMessage());
}
sysTypes.clear();
// do not include conversations even when requested
// (to be compatible with 7.1.4 and later. bug 67407)
searchTypes.remove(MailItem.Type.CONVERSATION);
}
if (lock != null && (lock.equals("1") || lock.equals("t") || lock.equals("true"))) {
maintenance = MailboxManager.getInstance().beginMaintenance(context.targetMailbox.getAccountId(), context.targetMailbox.getId());
}
Charset charset = context.getCharset();
CharsetEncoder encoder = charset.newEncoder();
if (context.requestedItems != null) {
try {
for (UserServletContext.Item item : context.requestedItems) aos = saveItem(context, item.mailItem, fldrs, cnts, item.versioned, aos, encoder, names);
} catch (Exception e) {
warn(e);
}
} else if (context.target != null && !(context.target instanceof Folder)) {
try {
aos = saveItem(context, context.target, fldrs, cnts, false, aos, encoder, names);
} catch (Exception e) {
warn(e);
}
} else {
ZimbraQueryResults results = null;
boolean saveTargetFolder = false;
if (context.target instanceof Folder) {
Folder f = (Folder) context.target;
if (f.getId() != Mailbox.ID_FOLDER_USER_ROOT) {
saveTargetFolder = true;
query = "under:\"" + f.getPath() + "\"" + (query == null ? "" : " " + query);
}
}
int maxDays = context.targetAccount.getIntAttr(Provisioning.A_zimbraExportMaxDays, 0);
if (maxDays > 0) {
if (context.getStartTime() == TIME_UNSPECIFIED || context.getEndTime() == TIME_UNSPECIFIED || context.getEndTime() == 0) {
ZimbraLog.misc.warn("Export rejected. start and end param must be set. end param must be non-zero");
throw new ExportPeriodNotSpecifiedException(maxDays);
} else if (context.getEndTime() - context.getStartTime() > maxDays * Constants.MILLIS_PER_DAY) {
long requestDays = (long) Math.ceil((double) (context.getEndTime() - context.getStartTime()) / Constants.MILLIS_PER_DAY);
ZimbraLog.misc.warn("Export rejected. Specified period %d days is longer than zimbraExportMaxDays %d days.", requestDays, maxDays);
throw new ExportPeriodTooLongException(requestDays, maxDays);
}
}
String taskQuery = query;
if (query == null) {
query = "";
}
String calendarQuery = query;
if (context.getStartTime() != TIME_UNSPECIFIED) {
query = query + " after:" + context.getStartTime();
calendarQuery = calendarQuery + " appt-start:>=" + context.getStartTime();
}
if (context.getEndTime() != TIME_UNSPECIFIED) {
query = query + " before:" + context.getEndTime();
calendarQuery = calendarQuery + " appt-end:<" + context.getEndTime();
}
if (query == null || query.equals("")) {
SortPath sp = new SortPath();
for (MailItem.Type type : sysTypes) {
List<MailItem> items = context.targetMailbox.getItemList(context.opContext, type);
Collections.sort(items, sp);
for (MailItem item : items) {
aos = saveItem(context, item, fldrs, cnts, false, aos, encoder, names);
}
}
query = "is:local";
}
Map<Set<MailItem.Type>, String> typesMap = new HashMap<Set<MailItem.Type>, String>();
typesMap.put(searchTypes, query);
if (context.getStartTime() != TIME_UNSPECIFIED || context.getEndTime() != TIME_UNSPECIFIED) {
if (searchTypes.contains(MailItem.Type.APPOINTMENT)) {
searchTypes.remove(MailItem.Type.APPOINTMENT);
Set<MailItem.Type> calendarTypes = new HashSet<MailItem.Type>();
calendarTypes.add(MailItem.Type.APPOINTMENT);
typesMap.put(calendarTypes, calendarQuery);
}
if (searchTypes.contains(MailItem.Type.TASK)) {
searchTypes.remove(MailItem.Type.TASK);
Set<MailItem.Type> taskTypes = new HashSet<MailItem.Type>();
taskTypes.add(MailItem.Type.TASK);
typesMap.put(taskTypes, (StringUtil.isNullOrEmpty(taskQuery)) ? "is:local" : taskQuery);
}
}
for (Map.Entry<Set<MailItem.Type>, String> entry : typesMap.entrySet()) {
results = context.targetMailbox.index.search(context.opContext, entry.getValue(), entry.getKey(), SortBy.NONE, LC.zimbra_archive_formatter_search_chunk_size.intValue());
try {
while (results.hasNext()) {
if (saveTargetFolder) {
saveTargetFolder = false;
aos = saveItem(context, context.target, fldrs, cnts, false, aos, encoder, names);
}
aos = saveItem(context, results.getNext().getMailItem(), fldrs, cnts, false, aos, encoder, names);
}
Closeables.closeQuietly(results);
results = null;
} catch (Exception e) {
warn(e);
} finally {
Closeables.closeQuietly(results);
}
}
}
if (aos == null) {
if (emptyname == null) {
context.resp.setHeader("Content-Disposition", null);
throw new UserServletException(HttpServletResponse.SC_NO_CONTENT, "No data found");
}
context.resp.setHeader("Content-Disposition", HttpUtil.createContentDisposition(context.req, Part.ATTACHMENT, emptyname));
aos = getOutputStream(context, UTF8);
}
} finally {
if (maintenance != null) {
MailboxManager.getInstance().endMaintenance(maintenance, true, true);
}
if (aos != null) {
try {
aos.close();
} catch (Exception e) {
}
}
}
}
use of com.zimbra.cs.mailbox.MailItem in project zm-mailbox by Zimbra.
the class ArchiveFormatter method addData.
private void addData(UserServletContext context, Folder fldr, Map<Object, Folder> fmap, Set<MailItem.Type> types, Resolve r, boolean timestamp, ArchiveInputStream ais, ArchiveInputEntry aie, List<ServiceException> errs) throws ServiceException {
try {
int defaultFldr;
Mailbox mbox = fldr.getMailbox();
String dir, file;
String name = aie.getName();
int idx = name.lastIndexOf('/');
MailItem newItem = null, oldItem;
OperationContext oc = context.opContext;
BufferedReader reader;
MailItem.Type type, view;
if (idx == -1) {
file = name;
dir = "";
} else {
file = name.substring(idx + 1);
dir = name.substring(0, idx + 1);
if (!dir.startsWith("/"))
dir = '/' + dir;
}
if (file.length() == 0) {
return;
} else if (file.endsWith(".csv") || file.endsWith(".vcf")) {
defaultFldr = Mailbox.ID_FOLDER_CONTACTS;
type = MailItem.Type.CONTACT;
view = MailItem.Type.CONTACT;
} else if (file.endsWith(".eml")) {
defaultFldr = Mailbox.ID_FOLDER_INBOX;
type = MailItem.Type.MESSAGE;
view = MailItem.Type.MESSAGE;
} else if (file.endsWith(".ics")) {
if (dir.startsWith("Tasks/")) {
defaultFldr = Mailbox.ID_FOLDER_TASKS;
type = MailItem.Type.TASK;
view = MailItem.Type.TASK;
} else {
defaultFldr = Mailbox.ID_FOLDER_CALENDAR;
type = MailItem.Type.APPOINTMENT;
view = MailItem.Type.APPOINTMENT;
}
} else if (file.endsWith(".wiki")) {
defaultFldr = Mailbox.ID_FOLDER_NOTEBOOK;
type = MailItem.Type.WIKI;
view = MailItem.Type.WIKI;
} else {
defaultFldr = Mailbox.ID_FOLDER_BRIEFCASE;
type = MailItem.Type.DOCUMENT;
view = MailItem.Type.DOCUMENT;
}
if (types != null && !types.contains(type)) {
return;
}
if (dir.equals("")) {
if (fldr.getPath().equals("/")) {
fldr = mbox.getFolderById(oc, defaultFldr);
}
if (fldr.getDefaultView() != MailItem.Type.UNKNOWN && fldr.getDefaultView() != view && !((view == MailItem.Type.DOCUMENT || view == MailItem.Type.WIKI) && (fldr.getDefaultView() == MailItem.Type.DOCUMENT || fldr.getDefaultView() == MailItem.Type.WIKI))) {
throw FormatterServiceException.INVALID_TYPE(view.toString(), fldr.getPath());
}
} else {
String s = fldr.getPath();
if (!s.endsWith("/"))
s += '/';
if (dir.startsWith(s))
dir = dir.substring(s.length());
fldr = createPath(context, fmap, fldr.getPath() + dir, view);
}
switch(type) {
case APPOINTMENT:
case TASK:
boolean continueOnError = context.ignoreAndContinueOnError();
boolean preserveExistingAlarms = context.preserveAlarms();
InputStream is = ais.getInputStream();
try {
if (aie.getSize() <= LC.calendar_ics_import_full_parse_max_size.intValue()) {
List<ZVCalendar> icals = ZCalendarBuilder.buildMulti(is, UTF8);
ImportInviteVisitor visitor = new ImportInviteVisitor(oc, fldr, preserveExistingAlarms);
Invite.createFromCalendar(context.targetAccount, null, icals, true, continueOnError, visitor);
} else {
ZICalendarParseHandler handler = new IcsImportParseHandler(oc, context.targetAccount, fldr, continueOnError, preserveExistingAlarms);
ZCalendarBuilder.parse(is, UTF8, handler);
}
} finally {
is.close();
}
break;
case CONTACT:
if (file.endsWith(".csv")) {
reader = new BufferedReader(new InputStreamReader(ais.getInputStream(), UTF8));
ImportContacts.ImportCsvContacts(oc, context.targetMailbox, new ItemId(fldr), ContactCSV.getContacts(reader, null));
} else {
List<VCard> cards = VCard.parseVCard(new String(readArchiveEntry(ais, aie), UTF8));
if (cards == null || cards.size() == 0 || (cards.size() == 1 && cards.get(0).fields.isEmpty())) {
addError(errs, FormatterServiceException.MISSING_VCARD_FIELDS(name));
return;
}
for (VCard vcf : cards) {
if (vcf.fields.isEmpty())
continue;
mbox.createContact(oc, vcf.asParsedContact(), fldr.getId(), null);
}
}
break;
case DOCUMENT:
case WIKI:
String creator = context.getAuthAccount() == null ? null : context.getAuthAccount().getName();
try {
oldItem = mbox.getItemByPath(oc, file, fldr.getId());
if (oldItem.getType() != type) {
addError(errs, FormatterServiceException.MISMATCHED_TYPE(name));
} else if (r == Resolve.Replace) {
mbox.delete(oc, oldItem.getId(), type);
throw MailServiceException.NO_SUCH_ITEM(oldItem.getId());
} else if (r != Resolve.Skip) {
newItem = mbox.addDocumentRevision(oc, oldItem.getId(), creator, oldItem.getName(), null, ais.getInputStream());
}
} catch (NoSuchItemException e) {
if (type == MailItem.Type.WIKI) {
newItem = mbox.createWiki(oc, fldr.getId(), file, creator, null, ais.getInputStream());
} else {
newItem = mbox.createDocument(oc, fldr.getId(), file, null, creator, null, ais.getInputStream());
}
}
if (newItem != null) {
if (timestamp)
mbox.setDate(oc, newItem.getId(), type, aie.getModTime());
}
break;
case MESSAGE:
int flags = aie.isUnread() ? Flag.BITMASK_UNREAD : 0;
DeliveryOptions opt = new DeliveryOptions().setFolderId(fldr.getId()).setNoICal(true).setFlags(flags);
mbox.addMessage(oc, ais.getInputStream(), (int) aie.getSize(), timestamp ? aie.getModTime() : ParsedMessage.DATE_HEADER, opt, null);
break;
}
} catch (Exception e) {
if (e instanceof MailServiceException && ((MailServiceException) e).getCode() == MailServiceException.QUOTA_EXCEEDED)
throw (MailServiceException) e;
else
addError(errs, FormatterServiceException.UNKNOWN_ERROR(aie.getName(), e));
}
}
Aggregations