📄 emaildata.java
字号:
int end = xml.indexOf(endToken, start); if (end == -1) { throw new IllegalArgumentException("EmailData token '" + endToken + "' is missing"); } value.append(xml.substring(start + startToken.length(), end)); return end + endToken.length(); } /** * Internal helper for parsing. * * @param startIndex >= * 0 * @param token * The tag name without "<", ">" * @param value * The wanted text between the tags * @return The current start position and -1 if not found */ private static int parseTag(int startIndex, String token, String xml, StringBuffer value) { int start = parseTag(startIndex, "<" + token + "><![CDATA[", "]]></" + token + ">", xml, value); if (start == -1) { // Try again without CDATA section start = parseTag(startIndex, "<" + token + ">", "</" + token + ">", xml, value); } return start; } /** * Hand made parser to parse xml, much faster than SAX. Will fail if a tag is * omitted and this tag occurs for example in the CDATA section of the * content. Therefor we always dump the complete xml in toXml(). * Not for production use, Attachments are not yet supported! */ public static EmailData parseXml(String xml) { int start = 0; StringBuffer sb = new StringBuffer(256); start = parseTag(start, "from", xml, sb); String from = sb.toString(); ArrayList toList = new ArrayList(); int startTmp; while (true) { startTmp = parseTag(start, "to", xml, sb); if (startTmp == -1) { break; } start = startTmp; if (sb.length() > 0) { toList.add(sb.toString()); } } String[] recipients = (String[]) toList .toArray(new String[toList.size()]); start = parseTag(start, "subject", xml, sb); String subject = sb.toString(); start = parseTag(start, "content", xml, sb); String content = sb.toString(); EmailData msg = new EmailData(recipients, from, subject, content); return msg; } /** * The requestId from the <messageId><requestId>123456</requestId></messageId> markup. * * If not found the sent-date from the email header is used, * note that this is not unique if more than one emails per seconds are send. * It is more safe to explicitely use our requestId markup. * @return Returns the requestId, never null */ public String getRequestId() { if (this.requestId == null) { this.requestId = extractMessageId(REQUESTID_TAG); if (this.requestId == null) { if (this.sentDate != null) { this.requestIdFromSentDate = true; this.requestId = ""+this.sentDate.getTime(); } } } return (this.requestId == null) ? "" : this.requestId; } /** * @param requestId * The requestId to set. */ public void setRequestId(String requestId) { this.requestId = requestId; } /** * The emails session id. * Can (but must not) be identical to the SessionInfo-secretSessionId * @return Returns the sessionId, never null */ public String getSessionId() { if (this.sessionId == null) { this.sessionId = extractMessageId(SESSIONID_TAG); } return (this.sessionId == null) ? "" : this.sessionId; } /** * @param sessionId * The sessionId to set. */ public void setSessionId(String sessionId) { this.sessionId = sessionId; } /** * Find the messageId of this message. * * This is usually in the subject or in an attachment * with extension ".mid" * * @return null if none is found * or for example <messageId><sessionId>somesecret</sessionId><requestId>5</requestId><methodName>update</methodName></messageId> */ public String getMessageId() { AttachmentHolder attachmentHolder = getMessageIdAttachment(); if (attachmentHolder == null) return null; return new String(attachmentHolder.getContent()); } /** * Find the messageId of this message. * * This is usually in the subject or in an attachment * with extension ".mid" * * @return null if none is found * or for example <messageId><sessionId>somesecret</sessionId><requestId>5</requestId><methodName>update</methodName></messageId> */ public AttachmentHolder getMessageIdAttachment() { String subject = getSubject(); final String startToken = "<" + MESSAGEID_TAG + ">"; if (subject.indexOf(startToken) == -1) { // Look into attachment ... // The <messageId> is not in the subject, // search in an attachment with extension ".mid" // or in an attachment without extension AttachmentHolder[] atts = getAttachments(); for (int i = 0; i < atts.length; i++) { if (atts[i].hasExtension(MESSAGEID_EXTENSION)) { return atts[i]; // strongest } } for (int i = 0; i < atts.length; i++) { if (atts[i].getFileName().indexOf(".") == -1) { // Trying extensionless attachments String str = new String(atts[i].getContent()); if (str.indexOf(startToken) == -1) { log.warning("Can't guess messageId, trying this failed: '" + str + "'"); } else { return atts[i]; } } } } else { // strip other text in subject final String endToken = "</" + MESSAGEID_TAG + ">"; int startIndex = subject.indexOf(startToken); int endIndex = subject.indexOf(endToken); if (endIndex > startIndex) subject = subject.substring(startIndex, endIndex+endToken.length()); // "messageId.mid" return new AttachmentHolder(MESSAGEID_TAG+MESSAGEID_EXTENSION,subject); } return null; } public boolean isMessageIdAttachment(AttachmentHolder holder) { AttachmentHolder messageIdHolder = getMessageIdAttachment(); if (messageIdHolder == null) return false; return messageIdHolder.equals(holder); } /** * Find the given tag in the messageId of this message. * * Subject: <messageId><sessionId>abcd</sessionId><requestId>5</requestId><methodName>update</methodName></messageId> * * @param tag * "requestId" or "sessionId" or "methodName" * @return null if none is found */ public String extractMessageId(String tag) { String str = getMessageId(); final String startToken = "<" + tag + ">"; if (str != null) { final String endToken = "</" + tag + ">"; int start = str.indexOf(startToken); int end = str.indexOf(endToken); if (start != -1 && end != -1) { return str.substring(start + startToken.length(), end); } } if (log.isLoggable(Level.FINE)) log.fine("No <" + tag + "> found for " + toXml(true)); return null; } /** * Use together with extractMessageId(EmailData messageData, String tag). * * @param methodName Can be null * @param expiryTimestamp Can be null * @return A well formatted XML * <messageId><sessionId>abcd</sessionId><requestId>5</requestId><methodName>update</methodName></messageId> */ public String createMessageId(MethodName methodName, Timestamp expiryTimestamp) { return createMessageId(this.sessionId, this.requestId, methodName, expiryTimestamp); } /** * If any of the params is null no markup for this param is added. * If any of the param is empty "", an empty markup is added * @param methodName Can be null * @param expiryTimestamp Can be null * @return A well formatted XML, the timestamp follows the ASCII ISO notation * <messageId><sessionId>abcd</sessionId><requestId>5</requestId><methodName>update</methodName><expires>2005-11-30T12:42:24.200Z</expires></messageId> */ public static String createMessageId(String sessionId, String requestId, MethodName methodName, Timestamp expiryTimestamp) { if (sessionId == null && requestId == null && methodName == null && expiryTimestamp == null) return ""; StringBuffer sb = new StringBuffer(512); sb.append("<").append(MESSAGEID_TAG).append(">"); if (sessionId != null) sb.append("<").append(SESSIONID_TAG).append(">").append(sessionId).append("</").append(SESSIONID_TAG).append(">"); if (requestId != null) sb.append("<").append(REQUESTID_TAG).append(">").append(requestId).append("</").append(REQUESTID_TAG).append(">"); if (methodName != null) sb.append("<").append(METHODNAME_TAG).append(">").append(methodName).append("</").append(METHODNAME_TAG).append(">"); if (expiryTimestamp != null) sb.append("<").append(EXPIRES_TAG).append(">").append(IsoDateParser.getUTCTimestampT(expiryTimestamp)).append("</").append(EXPIRES_TAG).append(">"); sb.append("</").append(MESSAGEID_TAG).append(">"); return sb.toString(); } public String toString() { return "from: " + this.from + " to: " + getRecipientsList() + " subject:" + this.subject + ((this.expiryTime != null) ? (" " + EXPIRES_HEADER_RFC2156 + ":" + MailUtil.dateTime(this.expiryTime)) : "") + " attachments:" + getFileNameList(); } public void setContent(String content) { this.content = content; } /** * @return Returns the bcc array, is never null */ public InternetAddress[] getBcc() { return (this.bcc==null) ? new InternetAddress[0] : this.bcc; } /** * @param bcc The bcc to set. */ public void setBcc(String bcc) { String[] bccs = StringPairTokenizer.parseLine(bcc); this.bcc = new InternetAddress[bccs.length]; for (int i=0; i<bccs.length; i++) this.bcc[i] = toInternetAddress(bccs[i]); } /** * @return Returns the cc array, is never null */ public InternetAddress[] getCc() { return (this.cc==null) ? new InternetAddress[0] : this.cc; } /** * @param cc The cc to set. */ public void setCc(String cc) { String[] ccs = StringPairTokenizer.parseLine(cc); this.cc = new InternetAddress[ccs.length]; for (int i=0; i<ccs.length; i++) this.cc[i] = toInternetAddress(ccs[i]); } /** * Check if an email can be deleted. * <p /> * RFC 2822 defines: * The header field "Date:" must exist in an email * exactly once, example: "Fri, 21 Nov 1997 09:55:06 -0600" * "The origination date specifies the date and time at which the creator * of the message indicated that the message was complete and ready to * enter the mail delivery system." * @param emailData email to check * @return true if is expired */ public boolean isExpired() { // Currently we have two approaches to transport expiryDate: // first as an email-Header: "Expires: " // second in our messageId XML markup: <expires>2005-12-24T16:45:12Z</expires> if (this.expiryTime != null) { Date now = new Date(); if (now.getTime() > this.expiryTime.getTime()) { if (log.isLoggable(Level.FINE)) log.fine("Email is epxired, we discard it: " + toString()); return true; } return false; } String expires = extractMessageId(EmailData.EXPIRES_TAG); if (expires != null) { /* The string may contain CR LF as shown here (added by any MTA): <messageId><sessionId>lm4e560ghdFzj</sessionId><requestId>1138093430247000000</requestId><methodName>ping</methodName><expires>2006-01-24T 09:04:50.248Z</expires></messageId> or somethin like MimeUtility.decode(expires, "quoted-printable"); ? */ expires = ReplaceVariable.replaceAll(expires, "\r\n", ""); try { Timestamp timestamp = new Timestamp(IsoDateParser.parse(expires).getTime()); Date now = new Date(); if (now.getTime() > timestamp.getTime()) { if (log.isLoggable(Level.FINE)) log.fine("Email is epxired, we discard it: " + toString()); return true; } } catch (Throwable e) { log.warning("Ignoring expires setting '" + expires + "':" + e.toString()); } } return false; } /** * Is transported in the email header "Expires: " * @return Returns the expiryTime or null if none is defined */ public Timestamp getExpiryTime() { return this.expiryTime; } /** * Set an absolute time in future when this email is regarded as obsolete. * @param expiryTime The expiryTime to set. */ public void setExpiryTime(Timestamp expiryTime) { this.expiryTime = expiryTime; } /** * Returns the value of the RFC 822 "Date" field. This is the date * on which this message was sent. Returns null if this field is * unavailable or its value is absent. <p> * According to RC 822 this field exists always for incoming emails. * @return Returns the sentDate. */ public Date getSentDate() { return this.sentDate; } /** * @param sentDate The sentDate to set. */ public void setSentDate(Date sentDate) { this.sentDate = sentDate; } /** * Currenlty not supported! * @param replyTo The address to set. */ public void setReplyTo(InternetAddress[] replyTo) { this.replyTo = replyTo; } /** * @return Returns the requestIdFromSentDate. */ public boolean isRequestIdFromSentDate() { return this.requestIdFromSentDate; } /** * @param requestIdFromSentDate The requestIdFromSentDate to set. */ public void setRequestIdFromSentDate(boolean requestIdFromSentDate) { this.requestIdFromSentDate = requestIdFromSentDate; } /** * For manual tests. java org.xmlBlaster.util.protocol.email.EmailData */ public static void main(String[] args) { if (false) { String[] receivers = { "Receiver1", "Receiver2" }; EmailData msg = new EmailData(receivers, "Sender", "A subject", "A content"); msg.addAttachment(new AttachmentHolder("xy.xbf", "application/xmlBlaster", "Hello World".getBytes())); System.out.println("ORIG:\n" + msg.toXml(true)); msg = EmailData.parseXml(msg.toXml(true)); System.out.println("NEW:\n" + msg.toXml(true)); } { String[] receivers = { "Receiver" }; String subject = "<messageId><expires>2006-01-24\r\nT09:04:50.248Z</expires></messageId>"; EmailData msg = new EmailData(receivers, "Sender", subject, "A content"); System.out.println("Is " + ((msg.isExpired()) ? "" : "not ") + "expired"); } }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -