From 861422fa010e77e72297db64be0a9639d92255e9 Mon Sep 17 00:00:00 2001 From: Iwao AVE! Date: Tue, 22 Nov 2011 01:08:13 +0900 Subject: [PATCH] =?utf8?q?=E6=96=87=E5=AD=97=E3=82=B3=E3=83=BC=E3=83=89?= =?utf8?q?=E3=82=92=20UTF-8=E3=80=81=E6=94=B9=E8=A1=8C=E3=82=B3=E3=83=BC?= =?utf8?q?=E3=83=89=E3=82=92LF=E3=81=AB=E7=B5=B1=E4=B8=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- sandbox/src/com/ozacc/mail/util/MXCheck.java | 176 +- src/main/java/com/ozacc/mail/Mail.java | 1994 +++++++++--------- .../ozacc/mail/MailAuthenticationException.java | 64 +- .../java/com/ozacc/mail/MailBuildException.java | 52 +- src/main/java/com/ozacc/mail/MailBuilder.java | 70 +- src/main/java/com/ozacc/mail/MailException.java | 52 +- .../java/com/ozacc/mail/MailSendException.java | 56 +- .../java/com/ozacc/mail/MultipleMailBuilder.java | 66 +- .../java/com/ozacc/mail/NotConnectedException.java | 52 +- src/main/java/com/ozacc/mail/SendMail.java | 90 +- src/main/java/com/ozacc/mail/SendMailPro.java | 102 +- .../java/com/ozacc/mail/VelocityMailBuilder.java | 140 +- .../ozacc/mail/VelocityMultipleMailBuilder.java | 80 +- src/main/java/com/ozacc/mail/fetch/FetchMail.java | 88 +- .../java/com/ozacc/mail/fetch/FetchMailPro.java | 234 +-- .../java/com/ozacc/mail/fetch/MailConverter.java | 58 +- .../com/ozacc/mail/fetch/MailFetchException.java | 54 +- .../java/com/ozacc/mail/fetch/ReceivedMail.java | 812 ++++---- .../com/ozacc/mail/fetch/impl/FetchMailImpl.java | 354 ++-- .../ozacc/mail/fetch/impl/FetchMailProImpl.java | 828 ++++---- .../ozacc/mail/fetch/impl/MailConverterImpl.java | 998 ++++----- .../java/com/ozacc/mail/fetch/impl/package.html | 8 +- .../fetch/impl/sk_jp/AttachmentsExtractor.java | 336 ++-- .../impl/sk_jp/CorrectedContentTypeDataSource.java | 222 +- .../CorrectedContentTypeDataSourceUTF7Support.java | 338 ++-- .../fetch/impl/sk_jp/FirstPlainPartExtractor.java | 96 +- .../mail/fetch/impl/sk_jp/HtmlPartExtractor.java | 88 +- .../ozacc/mail/fetch/impl/sk_jp/JISDataSource.java | 102 +- .../ozacc/mail/fetch/impl/sk_jp/MailUtility.java | 2118 ++++++++++---------- .../mail/fetch/impl/sk_jp/MultipartUtility.java | 344 ++-- .../ozacc/mail/fetch/impl/sk_jp/PartHandler.java | 94 +- .../mail/fetch/impl/sk_jp/PlainPartExtractor.java | 108 +- .../mail/fetch/impl/sk_jp/io/ByteToCharUTF7.java | 278 +-- .../fetch/impl/sk_jp/io/CharCodeConverter.java | 320 +-- .../fetch/impl/sk_jp/io/FromCP932Corrector.java | 96 +- .../mail/fetch/impl/sk_jp/io/ToCP932Corrector.java | 102 +- .../mail/fetch/impl/sk_jp/io/UnicodeCorrector.java | 258 +-- .../com/ozacc/mail/fetch/impl/sk_jp/package.html | 10 +- .../fetch/impl/sk_jp/text/EntityRefEncoder.java | 354 ++-- .../mail/fetch/impl/sk_jp/text/Translator.java | 64 +- .../mail/fetch/impl/sk_jp/util/StringValues.java | 314 +-- src/main/java/com/ozacc/mail/fetch/package.html | 8 +- .../ozacc/mail/impl/AbstractXMLMailBuilder.java | 546 ++--- .../com/ozacc/mail/impl/ByteArrayDataSource.java | 242 +-- src/main/java/com/ozacc/mail/impl/Cp932.java | 234 +-- .../com/ozacc/mail/impl/DTDEntityResolver.java | 114 +- .../com/ozacc/mail/impl/JDomXMLMailBuilder.java | 1006 +++++----- .../com/ozacc/mail/impl/MimeMessageBuilder.java | 860 ++++---- .../java/com/ozacc/mail/impl/OMLMimeMessage.java | 170 +- .../java/com/ozacc/mail/impl/SendMailImpl.java | 948 ++++----- .../java/com/ozacc/mail/impl/SendMailProImpl.java | 1000 ++++----- .../com/ozacc/mail/impl/VelocityLogSystem.java | 102 +- .../com/ozacc/mail/impl/XMLMailBuilderImpl.java | 300 +-- .../mail/impl/XMLVelocityMailBuilderImpl.java | 678 +++---- src/main/java/com/ozacc/mail/impl/package.html | 74 +- src/main/java/com/ozacc/mail/mailet/Mailet.java | 30 +- .../java/com/ozacc/mail/mailet/MailetRunner.java | 148 +- .../java/com/ozacc/mail/mailet/MailetWrapper.java | 180 +- src/main/java/com/ozacc/mail/mailet/Matcher.java | 42 +- src/main/java/com/ozacc/mail/mailet/package.html | 8 +- .../ozacc/mail/mock/AssertionFailedException.java | 54 +- .../java/com/ozacc/mail/mock/EqualityCheck.java | 330 +-- .../java/com/ozacc/mail/mock/MockFetchMail.java | 362 ++-- .../java/com/ozacc/mail/mock/MockFetchMailPro.java | 550 ++--- src/main/java/com/ozacc/mail/mock/MockMail.java | 60 +- .../java/com/ozacc/mail/mock/MockSendMail.java | 1070 +++++----- src/main/java/com/ozacc/mail/mock/package.html | 8 +- src/main/java/com/ozacc/mail/ozacc-mail.dtd | 118 +- .../java/com/ozacc/mail/ozacc-multiple-mails.dtd | 128 +- src/main/java/com/ozacc/mail/package.html | 8 +- .../com/ozacc/mail/spring/MailetRunnerJob.java | 168 +- .../com/ozacc/mail/spring/XMLMailFactoryBean.java | 260 +-- src/main/java/com/ozacc/mail/spring/package.html | 8 +- .../java/com/ozacc/mail/xml/XMLBuildException.java | 50 +- src/main/java/com/ozacc/mail/xml/XMLBuilder.java | 78 +- .../com/ozacc/mail/xml/impl/JDomXMLBuilder.java | 418 ++-- .../com/ozacc/mail/xml/impl/XMLBuilderImpl.java | 448 ++--- src/main/java/com/ozacc/mail/xml/impl/package.html | 8 +- src/main/java/com/ozacc/mail/xml/package.html | 8 +- .../java/com/dumbster/smtp/SimpleSmtpServer.java | 400 ++-- .../java/com/dumbster/smtp/SmtpActionType.java | 334 +-- src/test/java/com/dumbster/smtp/SmtpMessage.java | 292 +-- src/test/java/com/dumbster/smtp/SmtpRequest.java | 422 ++-- src/test/java/com/dumbster/smtp/SmtpResponse.java | 140 +- src/test/java/com/dumbster/smtp/SmtpState.java | 206 +- .../mail/fetch/impl/FetchMailImplRealTest.java | 120 +- .../mail/fetch/impl/FetchMailProImplRealTest.java | 116 +- .../ozacc/mail/impl/JDomXMLMailBuilderTest.java | 604 +++--- .../com/ozacc/mail/impl/OMLMimeMessageTest.java | 56 +- .../com/ozacc/mail/impl/SendMailImplRealTest.java | 274 +-- .../java/com/ozacc/mail/impl/SendMailImplTest.java | 412 ++-- .../ozacc/mail/impl/SendMailProImplRealTest.java | 170 +- .../ozacc/mail/impl/XMLMailBuilderImplTest.java | 418 ++-- .../mail/impl/XMLVelocityMailBuilderImplTest.java | 252 +-- .../com/ozacc/mail/mailet/MailetRunnerTest.java | 226 +-- .../com/ozacc/mail/mock/MockFetchMailTest.java | 120 +- .../java/com/ozacc/mail/mock/MockSendMailTest.java | 542 ++--- .../ozacc/mail/spring/XMLMailFactoryBeanTest.java | 184 +- .../java/com/ozacc/mail/spring/testContext.xml | 48 +- src/test/java/com/ozacc/mail/test-mail1.xml | 72 +- .../java/com/ozacc/mail/test-mail2-invalid.xml | 52 +- .../java/com/ozacc/mail/test-mail3-velocity.xml | 52 +- src/test/java/com/ozacc/mail/test-mail4.xml | 72 +- src/test/java/com/ozacc/mail/test-mail5-html.xml | 244 +-- src/test/java/com/ozacc/mail/test-mail6-cdata.xml | 30 +- .../java/com/ozacc/mail/test-mail7-multiple.xml | 82 +- .../ozacc/mail/xml/impl/JDomXMLBuilderTest.java | 196 +- .../ozacc/mail/xml/impl/XMLBuilderImplTest.java | 196 +- xdocs/index.xml | 578 +++--- 109 files changed, 14902 insertions(+), 14902 deletions(-) mode change 100755 => 100644 sandbox/src/com/ozacc/mail/util/MXCheck.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/Mail.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/MailAuthenticationException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/MailBuildException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/MailBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/MailException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/MailSendException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/MultipleMailBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/NotConnectedException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/SendMail.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/SendMailPro.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/VelocityMailBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/VelocityMultipleMailBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/FetchMail.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/FetchMailPro.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/MailConverter.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/MailFetchException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/ReceivedMail.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/FetchMailImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/FetchMailProImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/MailConverterImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/AttachmentsExtractor.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSource.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSourceUTF7Support.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/FirstPlainPartExtractor.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/HtmlPartExtractor.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/JISDataSource.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MailUtility.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MultipartUtility.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PartHandler.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PlainPartExtractor.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ByteToCharUTF7.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/CharCodeConverter.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/FromCP932Corrector.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ToCP932Corrector.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/UnicodeCorrector.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/EntityRefEncoder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/Translator.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/impl/sk_jp/util/StringValues.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/fetch/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/AbstractXMLMailBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/ByteArrayDataSource.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/Cp932.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/DTDEntityResolver.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/JDomXMLMailBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/MimeMessageBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/OMLMimeMessage.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/SendMailImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/SendMailProImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/VelocityLogSystem.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/XMLMailBuilderImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/impl/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/mailet/Mailet.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mailet/MailetRunner.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mailet/MailetWrapper.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mailet/Matcher.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mailet/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/mock/AssertionFailedException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mock/EqualityCheck.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mock/MockFetchMail.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mock/MockFetchMailPro.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mock/MockMail.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mock/MockSendMail.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/mock/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/ozacc-mail.dtd mode change 100755 => 100644 src/main/java/com/ozacc/mail/ozacc-multiple-mails.dtd mode change 100755 => 100644 src/main/java/com/ozacc/mail/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/spring/MailetRunnerJob.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/spring/XMLMailFactoryBean.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/spring/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/xml/XMLBuildException.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/xml/XMLBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/xml/impl/JDomXMLBuilder.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/xml/impl/XMLBuilderImpl.java mode change 100755 => 100644 src/main/java/com/ozacc/mail/xml/impl/package.html mode change 100755 => 100644 src/main/java/com/ozacc/mail/xml/package.html mode change 100755 => 100644 src/test/java/com/dumbster/smtp/SimpleSmtpServer.java mode change 100755 => 100644 src/test/java/com/dumbster/smtp/SmtpActionType.java mode change 100755 => 100644 src/test/java/com/dumbster/smtp/SmtpMessage.java mode change 100755 => 100644 src/test/java/com/dumbster/smtp/SmtpRequest.java mode change 100755 => 100644 src/test/java/com/dumbster/smtp/SmtpResponse.java mode change 100755 => 100644 src/test/java/com/dumbster/smtp/SmtpState.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/fetch/impl/FetchMailImplRealTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/fetch/impl/FetchMailProImplRealTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/impl/JDomXMLMailBuilderTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/impl/OMLMimeMessageTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/impl/SendMailImplRealTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/impl/SendMailImplTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/impl/SendMailProImplRealTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/impl/XMLMailBuilderImplTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImplTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/mailet/MailetRunnerTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/mock/MockFetchMailTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/mock/MockSendMailTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/spring/XMLMailFactoryBeanTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/spring/testContext.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/test-mail1.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/test-mail2-invalid.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/test-mail3-velocity.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/test-mail4.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/test-mail5-html.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/test-mail6-cdata.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/test-mail7-multiple.xml mode change 100755 => 100644 src/test/java/com/ozacc/mail/xml/impl/JDomXMLBuilderTest.java mode change 100755 => 100644 src/test/java/com/ozacc/mail/xml/impl/XMLBuilderImplTest.java mode change 100755 => 100644 xdocs/index.xml diff --git a/sandbox/src/com/ozacc/mail/util/MXCheck.java b/sandbox/src/com/ozacc/mail/util/MXCheck.java old mode 100755 new mode 100644 index b0b74bc..389c739 --- a/sandbox/src/com/ozacc/mail/util/MXCheck.java +++ b/sandbox/src/com/ozacc/mail/util/MXCheck.java @@ -1,89 +1,89 @@ -package com.ozacc.mail.util; - -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.InitialDirContext; - -/** - * DNS ¤Ë MX ¥ì¥³¡¼¥É¤¬ÅÐÏ¿¤µ¤ì¤Æ¤¤¤ë¤«¤ò¥Á¥§¥Ã¥¯¤¹¤ë¥¯¥é¥¹¡£ - * Sun JDK 1.4 °Ê¾å¤Ç»ÈÍѤǤ­¤Þ¤¹¡£ - *

- * TODO: ̤´°À®¡£Àµ¤·¤¯Æ°ºî¤·¤Þ¤»¤ó¡£ - * - * @since 1.1 - * @version $Id: MXCheck.java,v 1.1 2004/09/14 22:27:57 otsuka Exp $ - * @author Tomohiro Otsuka - */ -public class MXCheck { - - public static boolean isValidEmailAddress(String email, String dns) { - try { - new InternetAddress(email, true); - } catch (AddressException e) { - return false; - } - - int pos = email.lastIndexOf("@"); - String hostName = email.substring(pos + 1); - return hasMXRecord(hostName, dns); - } - - /** - * »ØÄꤵ¤ì¤¿ host ¤Ë MX ¥ì¥³¡¼¥É¤¬´ØÏ¢ÉÕ¤±¤é¤ì¤Æ¤¤¤ë¤« - * ¤É¤¦¤«È½Äꤷ¤Þ¤¹¡£ - * - * @param hostName ¸¡ºº¤¹¤ë¥Û¥¹¥È̾ - * @param dns ¸¡ºº¤Ë»ÈÍѤ¹¤ë DNS ¥µ¡¼¥Ð - * @return MX ¥ì¥³¡¼¥É¤¬Â¸ºß¤¹¤ì¤Ð true - */ - public static boolean hasMXRecord(String hostName, String dns) { - String name = "dns://" + dns + "/" + hostName; - try { - DirContext ictx = new InitialDirContext(); - Attributes attrs = ictx.getAttributes(name, new String[] { "MX" }); - NamingEnumeration namingEnumeration = attrs.getAll(); - if (namingEnumeration.hasMore()) { - return true; - } - } catch (NamingException e) { - return false; - } - - return false; - } - - /** - * »ØÄꤵ¤ì¤¿ host ¤Ë MX ¥ì¥³¡¼¥É¤¬´ØÏ¢ÉÕ¤±¤é¤ì¤Æ¤¤¤ë¤«¤É¤¦¤«È½Äꤷ¤Þ¤¹¡£ - * ¸¡ºº¤Ë»ÈÍѤ¹¤ë DNS ¥µ¡¼¥Ð¤Ï localhost ¤Ç¤¹¡£ - * - * @param hostName ¸¡ºº¤¹¤ë¥Û¥¹¥È̾ - * @return MX ¥ì¥³¡¼¥É¤¬Â¸ºß¤¹¤ì¤Ð true - */ - public static boolean hasMXRecord(String hostName) { - return hasMXRecord(hostName, "localhost"); - } - - /** - * ¼¡¤Î¥³¥Þ¥ó¥É¤Ç¡¢¥Û¥¹¥È̾¤Ë MX ¥ì¥³¡¼¥É¤¬Â¸ºß¤¹¤ë¤«¤É¤¦¤«Ä´¤Ù¤Þ¤¹¡£ - *

- * java com.ozacc.mail.util.MXChecker [¥Û¥¹¥È̾] [»ÈÍѤ¹¤ëDNS¥µ¡¼¥Ð] - * - */ - public static void main(String[] args) { - boolean result = false; - if (args.length == 1) { - result = hasMXRecord(args[0]); - } else { - result = hasMXRecord(args[0], args[1]); - } - - if (result) - System.out.println(args[0] + " ¤Î MX ¥ì¥³¡¼¥É¤Ï¸ºß¤·¤Þ¤¹¡£"); - else - System.out.println(args[0] + " ¤Î MX ¥ì¥³¡¼¥É¤ÏÅÐÏ¿¤µ¤ì¤Æ¤¤¤Þ¤»¤ó¡£"); - } +package com.ozacc.mail.util; + +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.directory.Attributes; +import javax.naming.directory.DirContext; +import javax.naming.directory.InitialDirContext; + +/** + * DNS に MX レコードが登録されているかをチェックするクラス。 + * Sun JDK 1.4 以上で使用できます。 + *

+ * TODO: 未完成。正しく動作しません。 + * + * @since 1.1 + * @version $Id: MXCheck.java,v 1.1 2004/09/14 22:27:57 otsuka Exp $ + * @author Tomohiro Otsuka + */ +public class MXCheck { + + public static boolean isValidEmailAddress(String email, String dns) { + try { + new InternetAddress(email, true); + } catch (AddressException e) { + return false; + } + + int pos = email.lastIndexOf("@"); + String hostName = email.substring(pos + 1); + return hasMXRecord(hostName, dns); + } + + /** + * 指定された host に MX レコードが関連付けられているか + * どうか判定します。 + * + * @param hostName 検査するホスト名 + * @param dns 検査に使用する DNS サーバ + * @return MX レコードが存在すれば true + */ + public static boolean hasMXRecord(String hostName, String dns) { + String name = "dns://" + dns + "/" + hostName; + try { + DirContext ictx = new InitialDirContext(); + Attributes attrs = ictx.getAttributes(name, new String[] { "MX" }); + NamingEnumeration namingEnumeration = attrs.getAll(); + if (namingEnumeration.hasMore()) { + return true; + } + } catch (NamingException e) { + return false; + } + + return false; + } + + /** + * 指定された host に MX レコードが関連付けられているかどうか判定します。 + * 検査に使用する DNS サーバは localhost です。 + * + * @param hostName 検査するホスト名 + * @return MX レコードが存在すれば true + */ + public static boolean hasMXRecord(String hostName) { + return hasMXRecord(hostName, "localhost"); + } + + /** + * 次のコマンドで、ホスト名に MX レコードが存在するかどうか調べます。 + *

+ * java com.ozacc.mail.util.MXChecker [ホスト名] [使用するDNSサーバ] + * + */ + public static void main(String[] args) { + boolean result = false; + if (args.length == 1) { + result = hasMXRecord(args[0]); + } else { + result = hasMXRecord(args[0], args[1]); + } + + if (result) + System.out.println(args[0] + " の MX レコードは存在します。"); + else + System.out.println(args[0] + " の MX レコードは登録されていません。"); + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/Mail.java b/src/main/java/com/ozacc/mail/Mail.java old mode 100755 new mode 100644 index f86d3be..c2f70f3 --- a/src/main/java/com/ozacc/mail/Mail.java +++ b/src/main/java/com/ozacc/mail/Mail.java @@ -1,998 +1,998 @@ -package com.ozacc.mail; - -import java.io.File; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.activation.FileTypeMap; -import javax.activation.URLDataSource; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; - -import com.ozacc.mail.impl.ByteArrayDataSource; - -/** - * メール。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: Mail.java,v 1.10.2.9 2007/03/30 13:03:44 otsuka Exp $ - */ -public class Mail { - - /** ISO-2022-JP */ - public static final String JIS_CHARSET = "ISO-2022-JP"; - - public static final String DOCTYPE_PUBLIC = "-//OZACC//DTD MAIL//EN"; - - public static final String DOCTYPE_SYSTEM = "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"; - - public static final String DOCTYPE_PUBLIC_MULTIPLE = "-//OZACC//DTD MULTIPLE MAILS//EN"; - - public static final String DOCTYPE_SYSTEM_MULTIPLE = "http://www.ozacc.com/library/dtd/ozacc-multiple-mails.dtd"; - - private String charset = JIS_CHARSET; - - protected String text; - - protected InternetAddress from; - - protected String subject; - - protected List to; - - protected List cc; - - protected List bcc; - - protected List envelopeTo; - - protected InternetAddress returnPath; - - protected InternetAddress replyTo; - - protected String importance; - - protected Map headers = new HashMap(); - - protected String htmlText; - - protected List attachmentFiles; - - /** - * コンストラクタ。 - */ - public Mail() {} - - /** - * コンストラクタ。 - * 宛先や差出人の名前をエンコードする時に使用する文字コードを指定します。 - *

- * 日本語環境で利用する場合は通常設定する必要はありません。 - * - * @param charset エンコードに使用する文字コード - */ - public Mail(String charset) { - this(); - this.charset = charset; - } - - /** - * コピーコンストラクタ。 - * シャローコピー(shallow copy)です。 - * - * @since 1.0.2 - * - * @param original コピー元のMailインスタンス - */ - public Mail(Mail original) { - this.bcc = original.bcc; - this.cc = original.cc; - this.charset = original.charset; - this.from = original.from; - this.importance = original.importance; - this.replyTo = original.replyTo; - this.returnPath = original.returnPath; - this.subject = original.subject; - this.text = original.text; - this.to = original.to; - this.headers = original.headers; - this.htmlText = original.htmlText; - this.attachmentFiles = original.attachmentFiles; - this.envelopeTo = original.envelopeTo; - } - - /** - * エンコードに使用する文字コードを返します。コンストラクタで設定されなかった場合はnullを返します。 - * - * @return エンコードに使用する文字コード、またはnull - */ - public String getCharset() { - return charset; - } - - /** - * メールの重要度をセットします。 - * 引数で指定可能な値は「high」、「normal」、「low」のいずれかです。 - * - * @param importance メールの重要度。「high」、「normal」、「low」のいずれか。 - * @throws IllegalArgumentException 指定可能な値以外が指定された場合 - * - * @see Mail.Importance - */ - public void setImportance(String importance) throws IllegalArgumentException { - if ("high".equals(importance) || "normal".equals(importance) || "low".equals(importance)) { - this.importance = importance; - } else { - throw new IllegalArgumentException("'" + importance + "'は、メール重要度には指定できない値です。"); - } - } - - /** - * メールの重要度を返します。 - * 値は「high」、「normal」、「low」のいずれかです。 - * - * @return メールの重要度。「high」、「normal」、「low」のいずれか。 - */ - public String getImportance() { - return importance; - } - - /** - * メールの送信先アドレスを追加します。 - * - * @param address 送信先アドレス - */ - public void addTo(InternetAddress address) { - if (to == null) { - to = new ArrayList(); - } - to.add(address); - } - - /** - * メールの送信先アドレスを追加します。 - * - * @param email 送信先アドレス - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void addTo(String email) throws IllegalArgumentException { - try { - addTo(new InternetAddress(email)); - } catch (AddressException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * メールの送信先名とアドレスを追加します。 - * - * @param email 送信先アドレス - * @param name 送信先名 - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void addTo(String email, String name) throws IllegalArgumentException { - try { - addTo(new InternetAddress(email, name, charset)); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * メールの送信先アドレスの配列を返します。 - * 送信先アドレスが一件もセットされていないときは空の配列を返します。 - * - * @return 送信先アドレスの配列 - */ - public InternetAddress[] getTo() { - if (to == null) { - return new InternetAddress[0]; - } - return (InternetAddress[])to.toArray(new InternetAddress[to.size()]); - } - - /** - * CCアドレスを追加します。 - * - * @param address CCのアドレス - */ - public void addCc(InternetAddress address) { - if (cc == null) { - cc = new ArrayList(); - } - cc.add(address); - } - - /** - * CCアドレスを追加します。 - * - * @param email CCのアドレス - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void addCc(String email) throws IllegalArgumentException { - try { - addCc(new InternetAddress(email)); - } catch (AddressException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * CCの宛名とアドレスを追加します。 - * - * @param email CCのアドレス - * @param name CCの宛名 - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void addCc(String email, String name) throws IllegalArgumentException { - try { - addCc(new InternetAddress(email, name, charset)); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * メールのCCアドレス配列を返します。 - * CCアドレスが一件もセットされていないときは空の配列を返します。 - * - * @return CCアドレスの配列 - */ - public InternetAddress[] getCc() { - if (cc == null) { - return new InternetAddress[0]; - } - return (InternetAddress[])cc.toArray(new InternetAddress[cc.size()]); - } - - /** - * BCCアドレスを追加します。 - * - * @param address BCCのアドレス - */ - public void addBcc(InternetAddress address) { - if (bcc == null) { - bcc = new ArrayList(); - } - bcc.add(address); - } - - /** - * BCCアドレスを追加します。 - * - * @param email BCCのアドレス - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void addBcc(String email) throws IllegalArgumentException { - try { - addBcc(new InternetAddress(email)); - } catch (AddressException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * メールのBCCアドレスの配列を返します。 - * BCCアドレスが一件もセットされていないときは空の配列を返します。 - * - * @return BCCアドレスの配列 - */ - public InternetAddress[] getBcc() { - if (bcc == null) { - return new InternetAddress[0]; - } - return (InternetAddress[])bcc.toArray(new InternetAddress[bcc.size()]); - } - - /** - * メールの差出人アドレスをセットします。 - * - * @param address 差出人アドレス - */ - public void setFrom(InternetAddress address) { - from = address; - } - - /** - * メールの差出人アドレスをセットします。 - * - * @param email 差出人アドレス - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void setFrom(String email) throws IllegalArgumentException { - try { - setFrom(new InternetAddress(email)); - } catch (AddressException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * メールの差出人名とアドレスをセットします。 - * - * @param email 差出人アドレス - * @param name 差出人名 - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void setFrom(String email, String name) throws IllegalArgumentException { - try { - setFrom(new InternetAddress(email, name, charset)); - } catch (UnsupportedEncodingException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * メールの差出人アドレスを返します。セットされていない場合はnullを返します。 - * - * @return メールの差出人アドレス - */ - public InternetAddress getFrom() { - return from; - } - - /** - * Return-Pathアドレスをセットします。 - * - * @param address Return-Pathアドレス - */ - public void setReturnPath(InternetAddress address) { - returnPath = address; - } - - /** - * Return-Pathアドレスをセットします。 - * - * @param email Return-Pathアドレス - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void setReturnPath(String email) throws IllegalArgumentException { - try { - setReturnPath(new InternetAddress(email)); - } catch (AddressException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * Return-Pathアドレスを返します。 - * - * @return Return-Pathアドレス - */ - public InternetAddress getReturnPath() { - return returnPath; - } - - /** - * 返信先アドレスをセットします。 - * - * @param address 返信先アドレス - */ - public void setReplyTo(InternetAddress address) { - replyTo = address; - } - - /** - * 返信先アドレスをセットします。 - * - * @param email 返信先アドレス - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void setReplyTo(String email) throws IllegalArgumentException { - try { - setReplyTo(new InternetAddress(email)); - } catch (AddressException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * メールの返信先アドレスを返します。セットされていない場合はnullを返します。 - * - * @return 返信先アドレス - */ - public InternetAddress getReplyTo() { - return replyTo; - } - - /** - * メールの件名を返します。セットされていない場合は空文字列を返します。 - * - * @return メールの件名 - */ - public String getSubject() { - if (subject == null) { - return ""; - } - return subject; - } - - /** - * メールの件名をセットします。 - * - * @param subject メールの件名 - */ - public void setSubject(String subject) { - this.subject = subject; - } - - /** - * メール本文を返します。 - * 本文セットされていない場合は空文字列を返します。 - * - * @return メール本文 - */ - public String getText() { - if (text == null) { - return ""; - } - return text; - } - - /** - * メール本文をセットします。 - * - * @param text メール本文 - */ - public void setText(String text) { - this.text = text; - } - - /** - * メールヘッダに任意のヘッダフィールドを追加します。 - * 任意ヘッダは「X-key: value」のフォーマットでメールヘッダに組み込まれます。
- * 同じヘッダ名の値は上書きされます。 - * - * @param name 任意ヘッダ名。頭が"X-"で始まっていなければ、自動的に付与されます。 - * @param value 任意ヘッダの値 - */ - public void addXHeader(String name, String value) { - if (headers == null) { - headers = new HashMap(); - } - if (name.startsWith("X-")) { - headers.put(name, value); - } else { - headers.put("X-" + name, value); - } - } - - /** - * メールヘッダに任意のヘッダフィールドを追加します。
- * このメソッドはユーザが使用することを想定していません。 - * 使用する際は、To や From などのフィールドをセットしないように注意してください。 - *

- * このメソッドで設定した同じヘッダ名の値は上書きされます。 - * - * @since 1.2 - * @param name 任意ヘッダ名 - * @param value 任意ヘッダの値 - */ - public void addHeader(String name, String value) { - if (headers == null) { - headers = new HashMap(); - } - headers.put(name, value); - } - - /** - * メールの任意ヘッダ名と値のMapインスタンスを返します。 - * 任意ヘッダが一件もセットされていないときはnullを返します。 - *

- * このMapインスタンスへの修正はできません。(unmodifiableMapになっています。) - * - * @return メールの任意ヘッダ名と値のMapインスタンス。またはnull。 - */ - public Map getHeaders() { - if (headers == null) { - return null; - } - return Collections.unmodifiableMap(headers); - } - - /** - * メール内容を出力します。
- * メールのソースに似たフォーマットで出力されます。 - * - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer buf = new StringBuffer(1000); - buf.append("Mail\n"); - buf.append("Return-Path: ").append(returnPath).append("\n"); - buf.append("From: ").append(from != null ? from.toUnicodeString() : null).append("\n"); - buf.append("To: ").append(arrayToCommaDelimitedString(to)).append("\n"); - buf.append("Cc: ").append(arrayToCommaDelimitedString(cc)).append("\n"); - buf.append("Bcc: ").append(arrayToCommaDelimitedString(bcc)).append("\n"); - buf.append("Subject: ").append(subject).append("\n"); - - if (headers != null) { - for (Iterator itr = headers.keySet().iterator(); itr.hasNext();) { - String header = (String)itr.next(); - String value = (String)headers.get(header); - buf.append(header).append(": ").append(value).append("\n"); - } - } - - buf.append("\n"); - buf.append(text); - - if (htmlText != null) { - buf.append("\n\n-----\n\n"); - buf.append(htmlText); - } - - return buf.toString(); - } - - /** - * 指定されたリストの要素をコンマ区切りの文字列に変換します。 - * nullが指定された場合は「null」文字列を返します。 - * - * @param list - * @return リスト要素のコンマ区切り文字列 - */ - protected String arrayToCommaDelimitedString(List list) { - if (list == null) { - return "null"; - } else { - StringBuffer sb = new StringBuffer(); - for (int i = 0, num = list.size(); i < num; i++) { - if (i > 0) { - sb.append(", "); - } - sb.append(((InternetAddress)list.get(i)).toUnicodeString()); - } - return sb.toString(); - } - } - - /** - * セットされている送信先アドレス(Toアドレス)を全てクリアします。 - * - * @since 1.0.2 - */ - public void clearTo() { - to = null; - } - - /** - * セットされているCCアドレスを全てクリアします。 - * - * @since 1.0.2 - */ - public void clearCc() { - cc = null; - } - - /** - * セットされているBCCアドレスを全てクリアします。 - * - * @since 1.0.2 - */ - public void clearBcc() { - bcc = null; - } - - /** - * HTMLの本文をセットします。 - * - * @since 1.1 - * - * @param htmlText HTMLの本文 - */ - public void setHtmlText(String htmlText) { - this.htmlText = htmlText; - } - - /** - * HTMLの本文を返します。 - * - * @since 1.1 - * - * @return HTMLの本文。またはnull。 - */ - public String getHtmlText() { - return htmlText; - } - - /** - * 指定されたファイルを添付します。 - * 添付ファイル名には、指定されたファイルの名前が使用されます。 - * このファイルの名前は適切な拡張子が付けられている必要があります。 - * - * @since 1.1 - * - * @param file 添付ファイル - */ - public void addFile(File file) { - if (attachmentFiles == null) { - initAttachmentFiles(); - } - addFile(file, file.getName()); - } - - /** - * 指定されたファイルを添付します。 - * 指定するファイル名には適切な拡張子が付けられている必要があります。 - * - * @since 1.1 - * - * @param file 添付ファイル - * @param fileName ファイル名 - */ - public void addFile(File file, String fileName) { - if (attachmentFiles == null) { - initAttachmentFiles(); - } - attachmentFiles.add(new AttachmentFile(fileName, file)); - } - - /** - * 指定されたURLのファイルを添付します。 - * 指定するファイル名には適切な拡張子が付けられている必要があります。 - * - * @since 1.1 - * - * @param url 添付ファイル - * @param fileName ファイル名 - */ - public void addFile(URL url, String fileName) { - if (attachmentFiles == null) { - initAttachmentFiles(); - } - attachmentFiles.add(new AttachmentFile(fileName, url)); - } - - /** - * 指定されたInputStreamをファイルとして添付します。 - * 指定するファイル名には適切な拡張子が付けられている必要があります。 - * - * @since 1.1 - * - * @param is 添付ファイルを生成するInputStream - * @param fileName ファイル名 - */ - public void addFile(InputStream is, String fileName) { - if (attachmentFiles == null) { - initAttachmentFiles(); - } - attachmentFiles.add(new AttachmentFile(fileName, is)); - } - - /** - * 指定されたbyte配列をファイルとして添付します。 - * 指定するファイル名には適切な拡張子が付けられている必要があります。 - * - * @since 1.2 - * - * @param bytes 添付ファイルを生成するbyte配列 - * @param fileName ファイル名 - */ - public void addFile(byte[] bytes, String fileName) { - if (attachmentFiles == null) { - initAttachmentFiles(); - } - attachmentFiles.add(new AttachmentFile(fileName, bytes)); - } - - /** - * attachmentFilesプロパティを初期化。 - */ - private void initAttachmentFiles() { - attachmentFiles = new ArrayList(); - } - - /** - * 添付ファイルの配列を返します。 - * 添付ファイルがセットされていない場合は、空の配列を返します。 - * - * @since 1.1 - * - * @return 添付ファイルの配列。または空の配列。 - */ - public AttachmentFile[] getAttachmentFiles() { - if (attachmentFiles == null) { - return new AttachmentFile[0]; - } - return (AttachmentFile[])attachmentFiles - .toArray(new AttachmentFile[attachmentFiles.size()]); - } - - /** - * HTMLの本文がセットされているかどうか判定します。 - * - * @since 1.1 - * - * @return HTMLの本文がセットされている場合 true - */ - public boolean isHtmlMail() { - return (htmlText != null); - } - - /** - * ファイルが添付されているかどうか判定します。 - * - * @since 1.1 - * - * @return ファイルが添付されている場合 true - */ - public boolean isFileAttached() { - return attachmentFiles != null && attachmentFiles.size() > 0; - } - - /** - * マルチパート・メールかどうか判定します。
- * HTML本文がセットされているか、ファイルが添付されている場合に true が返されます。 - *

- * 注: ここで判定されるマルチパートは、厳密な意味でのマルチパートではありません。 - * - * @since 1.1 - * - * @return マルチパート・メールの場合 true - */ - public boolean isMultipartMail() { - return isHtmlMail() || isFileAttached(); - } - - /** - * セットされている添付ファイルを全てクリアします。 - * - * @since 1.1 - */ - public void clearFile() { - initAttachmentFiles(); - } - - /** - * envelope-toの宛先アドレスを追加します。 - *

- * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 - * To、Cc、Bccアドレスには実際には送信されません。 - * - * @since 1.2 - * @param address - */ - public void addEnvelopeTo(InternetAddress address) { - if (envelopeTo == null) { - envelopeTo = new ArrayList(); - } - envelopeTo.add(address); - } - - /** - * envelope-toの宛先アドレスを追加します。 - *

- * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 - * To、Cc、Bccアドレスには実際には送信されません。 - * - * @since 1.2 - * @param email - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void addEnvelopeTo(String email) { - try { - addEnvelopeTo(new InternetAddress(email)); - } catch (AddressException e) { - throw new IllegalArgumentException(e.getMessage()); - } - } - - /** - * envelope-toの宛先アドレスを追加します。 - *

- * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 - * To、Cc、Bccアドレスには実際には送信されません。 - * - * @since 1.2 - * @param addresses - */ - public void addEnvelopeTo(InternetAddress[] addresses) { - for (int i = 0; i < addresses.length; i++) { - addEnvelopeTo(addresses[i]); - } - } - - /** - * envelope-toの宛先アドレスを追加します。 - *

- * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 - * To、Cc、Bccアドレスには実際には送信されません。 - * - * @since 1.2 - * @param emails - * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 - */ - public void addEnvelopeTo(String[] emails) { - for (int i = 0; i < emails.length; i++) { - addEnvelopeTo(emails[i]); - } - } - - /** - * セットされているenvelope-toアドレスを全てクリアします。 - * - * @since 1.2 - */ - public void clearEnvelopeTo() { - envelopeTo = null; - } - - /** - * envelope-toアドレス配列を返します。 - * envelope-toアドレスが一件もセットされていないときは空の配列を返します。 - * - * @since 1.2 - * @return envelope-toアドレスの配列 - */ - public InternetAddress[] getEnvelopeTo() { - if (envelopeTo == null) { - return new InternetAddress[0]; - } - return (InternetAddress[])envelopeTo.toArray(new InternetAddress[envelopeTo.size()]); - } - - /** - * 添付ファイル。 - *

- * 受信メール(ReceivedMail)の添付ファイルは、常にgetFile()メソッドで取得します。 - * getInputStream()、getUrl()メソッドはnullを返します。 - * 受信メールに対しては、ReceivedMail.getFiles()メソッドを使うと添付ファイルの - * Fileインスタンス配列を取得することができます。 - * - * @since 1.1 - * @author Tomohiro Otsuka - * @version $Id: Mail.java,v 1.10.2.9 2007/03/30 13:03:44 otsuka Exp $ - */ - public class AttachmentFile { - - private String name; - - private File file; - - private InputStream is; - - private URL url; - - private byte[] bytes = null; - - /** - * ファイル名とファイルを指定して、このクラスのインタンスを生成します。 - * ファイル名には適切な拡張子が付けられている必要があります。 - * - * @param name メールに表示するファイル名 - * @param file 添付ファイル - */ - public AttachmentFile(String name, File file) { - this.name = name; - this.file = file; - } - - /** - * ファイル名とInputStreamを指定して、このクラスのインタンスを生成します。 - * ファイル名には適切な拡張子が付けられている必要があります。 - * - * @param name メールに表示するファイル名 - * @param is 添付ファイルを生成するInputStream - */ - public AttachmentFile(String name, InputStream is) { - this.name = name; - this.is = is; - } - - /** - * ファイル名とファイルロケーションのURLを指定して、このクラスのインタンスを生成します。 - * ファイル名には適切な拡張子が付けられている必要があります。 - * - * @param name メールに表示するファイル名 - * @param url 添付ファイルのロケーションURL - */ - public AttachmentFile(String name, URL url) { - this.name = name; - this.url = url; - } - - /** - * ファイル名とbyte配列を指定して、このクラスのインタンスを生成します。 - * ファイル名には適切な拡張子が付けられている必要があります。 - * - * @param name メールに表示するファイル名 - * @param bytes 添付ファイルを生成するbyte配列 - */ - public AttachmentFile(String name, byte[] bytes) { - this.name = name; - this.bytes = bytes; - } - - /** - * 添付ファイルのDataSourceインスタンスを生成して返します。 - * - * @return 添付ファイルのDataSourceインスタンス - */ - public DataSource getDataSource() { - if (file != null) { - return new FileDataSource(file); - } - - if (url != null) { - return new URLDataSource(url); - } - - // InputStreamからDataSourceを生成 - String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(name); - if (is != null) { - // InputStreamからDataSourceを生成 - return new ByteArrayDataSource(is, contentType); - } else { - // byte配列からDataSourceを生成 - return new ByteArrayDataSource(bytes, contentType); - } - } - - /** - * 添付ファイル名を返します。 - * - * @return 添付ファイル名 - */ - public String getName() { - return name; - } - - /** - * @return セットされたファイル。またはnull。 - */ - public File getFile() { - return file; - } - - /** - * @return セットされたInputStream。またはnull。 - */ - public InputStream getInputStream() { - return is; - } - - /** - * @return セットされたURL。またはnull。 - */ - public URL getUrl() { - return url; - } - - /** - * @return セットされたbyte配列。またはnull。 - */ - public byte[] getBytes() { - return bytes; - } - } - - /** - * メールの重要度。定数のみを定義。 - * - * @author Tomohiro Otsuka - * @version $Id: Mail.java,v 1.10.2.9 2007/03/30 13:03:44 otsuka Exp $ - */ - public static class Importance { - - /** 重要度「高」 */ - public static final String HIGH = "high"; - - /** 重要度「中」 */ - public static final String NORMAL = "normal"; - - /** 重要度「低」 */ - public static final String LOW = "low"; - - } +package com.ozacc.mail; + +import java.io.File; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.activation.DataSource; +import javax.activation.FileDataSource; +import javax.activation.FileTypeMap; +import javax.activation.URLDataSource; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; + +import com.ozacc.mail.impl.ByteArrayDataSource; + +/** + * メール。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: Mail.java,v 1.10.2.9 2007/03/30 13:03:44 otsuka Exp $ + */ +public class Mail { + + /** ISO-2022-JP */ + public static final String JIS_CHARSET = "ISO-2022-JP"; + + public static final String DOCTYPE_PUBLIC = "-//OZACC//DTD MAIL//EN"; + + public static final String DOCTYPE_SYSTEM = "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"; + + public static final String DOCTYPE_PUBLIC_MULTIPLE = "-//OZACC//DTD MULTIPLE MAILS//EN"; + + public static final String DOCTYPE_SYSTEM_MULTIPLE = "http://www.ozacc.com/library/dtd/ozacc-multiple-mails.dtd"; + + private String charset = JIS_CHARSET; + + protected String text; + + protected InternetAddress from; + + protected String subject; + + protected List to; + + protected List cc; + + protected List bcc; + + protected List envelopeTo; + + protected InternetAddress returnPath; + + protected InternetAddress replyTo; + + protected String importance; + + protected Map headers = new HashMap(); + + protected String htmlText; + + protected List attachmentFiles; + + /** + * コンストラクタ。 + */ + public Mail() {} + + /** + * コンストラクタ。 + * 宛先や差出人の名前をエンコードする時に使用する文字コードを指定します。 + *

+ * 日本語環境で利用する場合は通常設定する必要はありません。 + * + * @param charset エンコードに使用する文字コード + */ + public Mail(String charset) { + this(); + this.charset = charset; + } + + /** + * コピーコンストラクタ。 + * シャローコピー(shallow copy)です。 + * + * @since 1.0.2 + * + * @param original コピー元のMailインスタンス + */ + public Mail(Mail original) { + this.bcc = original.bcc; + this.cc = original.cc; + this.charset = original.charset; + this.from = original.from; + this.importance = original.importance; + this.replyTo = original.replyTo; + this.returnPath = original.returnPath; + this.subject = original.subject; + this.text = original.text; + this.to = original.to; + this.headers = original.headers; + this.htmlText = original.htmlText; + this.attachmentFiles = original.attachmentFiles; + this.envelopeTo = original.envelopeTo; + } + + /** + * エンコードに使用する文字コードを返します。コンストラクタで設定されなかった場合はnullを返します。 + * + * @return エンコードに使用する文字コード、またはnull + */ + public String getCharset() { + return charset; + } + + /** + * メールの重要度をセットします。 + * 引数で指定可能な値は「high」、「normal」、「low」のいずれかです。 + * + * @param importance メールの重要度。「high」、「normal」、「low」のいずれか。 + * @throws IllegalArgumentException 指定可能な値以外が指定された場合 + * + * @see Mail.Importance + */ + public void setImportance(String importance) throws IllegalArgumentException { + if ("high".equals(importance) || "normal".equals(importance) || "low".equals(importance)) { + this.importance = importance; + } else { + throw new IllegalArgumentException("'" + importance + "'は、メール重要度には指定できない値です。"); + } + } + + /** + * メールの重要度を返します。 + * 値は「high」、「normal」、「low」のいずれかです。 + * + * @return メールの重要度。「high」、「normal」、「low」のいずれか。 + */ + public String getImportance() { + return importance; + } + + /** + * メールの送信先アドレスを追加します。 + * + * @param address 送信先アドレス + */ + public void addTo(InternetAddress address) { + if (to == null) { + to = new ArrayList(); + } + to.add(address); + } + + /** + * メールの送信先アドレスを追加します。 + * + * @param email 送信先アドレス + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void addTo(String email) throws IllegalArgumentException { + try { + addTo(new InternetAddress(email)); + } catch (AddressException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * メールの送信先名とアドレスを追加します。 + * + * @param email 送信先アドレス + * @param name 送信先名 + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void addTo(String email, String name) throws IllegalArgumentException { + try { + addTo(new InternetAddress(email, name, charset)); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * メールの送信先アドレスの配列を返します。 + * 送信先アドレスが一件もセットされていないときは空の配列を返します。 + * + * @return 送信先アドレスの配列 + */ + public InternetAddress[] getTo() { + if (to == null) { + return new InternetAddress[0]; + } + return (InternetAddress[])to.toArray(new InternetAddress[to.size()]); + } + + /** + * CCアドレスを追加します。 + * + * @param address CCのアドレス + */ + public void addCc(InternetAddress address) { + if (cc == null) { + cc = new ArrayList(); + } + cc.add(address); + } + + /** + * CCアドレスを追加します。 + * + * @param email CCのアドレス + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void addCc(String email) throws IllegalArgumentException { + try { + addCc(new InternetAddress(email)); + } catch (AddressException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * CCの宛名とアドレスを追加します。 + * + * @param email CCのアドレス + * @param name CCの宛名 + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void addCc(String email, String name) throws IllegalArgumentException { + try { + addCc(new InternetAddress(email, name, charset)); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * メールのCCアドレス配列を返します。 + * CCアドレスが一件もセットされていないときは空の配列を返します。 + * + * @return CCアドレスの配列 + */ + public InternetAddress[] getCc() { + if (cc == null) { + return new InternetAddress[0]; + } + return (InternetAddress[])cc.toArray(new InternetAddress[cc.size()]); + } + + /** + * BCCアドレスを追加します。 + * + * @param address BCCのアドレス + */ + public void addBcc(InternetAddress address) { + if (bcc == null) { + bcc = new ArrayList(); + } + bcc.add(address); + } + + /** + * BCCアドレスを追加します。 + * + * @param email BCCのアドレス + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void addBcc(String email) throws IllegalArgumentException { + try { + addBcc(new InternetAddress(email)); + } catch (AddressException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * メールのBCCアドレスの配列を返します。 + * BCCアドレスが一件もセットされていないときは空の配列を返します。 + * + * @return BCCアドレスの配列 + */ + public InternetAddress[] getBcc() { + if (bcc == null) { + return new InternetAddress[0]; + } + return (InternetAddress[])bcc.toArray(new InternetAddress[bcc.size()]); + } + + /** + * メールの差出人アドレスをセットします。 + * + * @param address 差出人アドレス + */ + public void setFrom(InternetAddress address) { + from = address; + } + + /** + * メールの差出人アドレスをセットします。 + * + * @param email 差出人アドレス + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void setFrom(String email) throws IllegalArgumentException { + try { + setFrom(new InternetAddress(email)); + } catch (AddressException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * メールの差出人名とアドレスをセットします。 + * + * @param email 差出人アドレス + * @param name 差出人名 + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void setFrom(String email, String name) throws IllegalArgumentException { + try { + setFrom(new InternetAddress(email, name, charset)); + } catch (UnsupportedEncodingException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * メールの差出人アドレスを返します。セットされていない場合はnullを返します。 + * + * @return メールの差出人アドレス + */ + public InternetAddress getFrom() { + return from; + } + + /** + * Return-Pathアドレスをセットします。 + * + * @param address Return-Pathアドレス + */ + public void setReturnPath(InternetAddress address) { + returnPath = address; + } + + /** + * Return-Pathアドレスをセットします。 + * + * @param email Return-Pathアドレス + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void setReturnPath(String email) throws IllegalArgumentException { + try { + setReturnPath(new InternetAddress(email)); + } catch (AddressException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * Return-Pathアドレスを返します。 + * + * @return Return-Pathアドレス + */ + public InternetAddress getReturnPath() { + return returnPath; + } + + /** + * 返信先アドレスをセットします。 + * + * @param address 返信先アドレス + */ + public void setReplyTo(InternetAddress address) { + replyTo = address; + } + + /** + * 返信先アドレスをセットします。 + * + * @param email 返信先アドレス + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void setReplyTo(String email) throws IllegalArgumentException { + try { + setReplyTo(new InternetAddress(email)); + } catch (AddressException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * メールの返信先アドレスを返します。セットされていない場合はnullを返します。 + * + * @return 返信先アドレス + */ + public InternetAddress getReplyTo() { + return replyTo; + } + + /** + * メールの件名を返します。セットされていない場合は空文字列を返します。 + * + * @return メールの件名 + */ + public String getSubject() { + if (subject == null) { + return ""; + } + return subject; + } + + /** + * メールの件名をセットします。 + * + * @param subject メールの件名 + */ + public void setSubject(String subject) { + this.subject = subject; + } + + /** + * メール本文を返します。 + * 本文セットされていない場合は空文字列を返します。 + * + * @return メール本文 + */ + public String getText() { + if (text == null) { + return ""; + } + return text; + } + + /** + * メール本文をセットします。 + * + * @param text メール本文 + */ + public void setText(String text) { + this.text = text; + } + + /** + * メールヘッダに任意のヘッダフィールドを追加します。 + * 任意ヘッダは「X-key: value」のフォーマットでメールヘッダに組み込まれます。
+ * 同じヘッダ名の値は上書きされます。 + * + * @param name 任意ヘッダ名。頭が"X-"で始まっていなければ、自動的に付与されます。 + * @param value 任意ヘッダの値 + */ + public void addXHeader(String name, String value) { + if (headers == null) { + headers = new HashMap(); + } + if (name.startsWith("X-")) { + headers.put(name, value); + } else { + headers.put("X-" + name, value); + } + } + + /** + * メールヘッダに任意のヘッダフィールドを追加します。
+ * このメソッドはユーザが使用することを想定していません。 + * 使用する際は、To や From などのフィールドをセットしないように注意してください。 + *

+ * このメソッドで設定した同じヘッダ名の値は上書きされます。 + * + * @since 1.2 + * @param name 任意ヘッダ名 + * @param value 任意ヘッダの値 + */ + public void addHeader(String name, String value) { + if (headers == null) { + headers = new HashMap(); + } + headers.put(name, value); + } + + /** + * メールの任意ヘッダ名と値のMapインスタンスを返します。 + * 任意ヘッダが一件もセットされていないときはnullを返します。 + *

+ * このMapインスタンスへの修正はできません。(unmodifiableMapになっています。) + * + * @return メールの任意ヘッダ名と値のMapインスタンス。またはnull。 + */ + public Map getHeaders() { + if (headers == null) { + return null; + } + return Collections.unmodifiableMap(headers); + } + + /** + * メール内容を出力します。
+ * メールのソースに似たフォーマットで出力されます。 + * + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuffer buf = new StringBuffer(1000); + buf.append("Mail\n"); + buf.append("Return-Path: ").append(returnPath).append("\n"); + buf.append("From: ").append(from != null ? from.toUnicodeString() : null).append("\n"); + buf.append("To: ").append(arrayToCommaDelimitedString(to)).append("\n"); + buf.append("Cc: ").append(arrayToCommaDelimitedString(cc)).append("\n"); + buf.append("Bcc: ").append(arrayToCommaDelimitedString(bcc)).append("\n"); + buf.append("Subject: ").append(subject).append("\n"); + + if (headers != null) { + for (Iterator itr = headers.keySet().iterator(); itr.hasNext();) { + String header = (String)itr.next(); + String value = (String)headers.get(header); + buf.append(header).append(": ").append(value).append("\n"); + } + } + + buf.append("\n"); + buf.append(text); + + if (htmlText != null) { + buf.append("\n\n-----\n\n"); + buf.append(htmlText); + } + + return buf.toString(); + } + + /** + * 指定されたリストの要素をコンマ区切りの文字列に変換します。 + * nullが指定された場合は「null」文字列を返します。 + * + * @param list + * @return リスト要素のコンマ区切り文字列 + */ + protected String arrayToCommaDelimitedString(List list) { + if (list == null) { + return "null"; + } else { + StringBuffer sb = new StringBuffer(); + for (int i = 0, num = list.size(); i < num; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(((InternetAddress)list.get(i)).toUnicodeString()); + } + return sb.toString(); + } + } + + /** + * セットされている送信先アドレス(Toアドレス)を全てクリアします。 + * + * @since 1.0.2 + */ + public void clearTo() { + to = null; + } + + /** + * セットされているCCアドレスを全てクリアします。 + * + * @since 1.0.2 + */ + public void clearCc() { + cc = null; + } + + /** + * セットされているBCCアドレスを全てクリアします。 + * + * @since 1.0.2 + */ + public void clearBcc() { + bcc = null; + } + + /** + * HTMLの本文をセットします。 + * + * @since 1.1 + * + * @param htmlText HTMLの本文 + */ + public void setHtmlText(String htmlText) { + this.htmlText = htmlText; + } + + /** + * HTMLの本文を返します。 + * + * @since 1.1 + * + * @return HTMLの本文。またはnull。 + */ + public String getHtmlText() { + return htmlText; + } + + /** + * 指定されたファイルを添付します。 + * 添付ファイル名には、指定されたファイルの名前が使用されます。 + * このファイルの名前は適切な拡張子が付けられている必要があります。 + * + * @since 1.1 + * + * @param file 添付ファイル + */ + public void addFile(File file) { + if (attachmentFiles == null) { + initAttachmentFiles(); + } + addFile(file, file.getName()); + } + + /** + * 指定されたファイルを添付します。 + * 指定するファイル名には適切な拡張子が付けられている必要があります。 + * + * @since 1.1 + * + * @param file 添付ファイル + * @param fileName ファイル名 + */ + public void addFile(File file, String fileName) { + if (attachmentFiles == null) { + initAttachmentFiles(); + } + attachmentFiles.add(new AttachmentFile(fileName, file)); + } + + /** + * 指定されたURLのファイルを添付します。 + * 指定するファイル名には適切な拡張子が付けられている必要があります。 + * + * @since 1.1 + * + * @param url 添付ファイル + * @param fileName ファイル名 + */ + public void addFile(URL url, String fileName) { + if (attachmentFiles == null) { + initAttachmentFiles(); + } + attachmentFiles.add(new AttachmentFile(fileName, url)); + } + + /** + * 指定されたInputStreamをファイルとして添付します。 + * 指定するファイル名には適切な拡張子が付けられている必要があります。 + * + * @since 1.1 + * + * @param is 添付ファイルを生成するInputStream + * @param fileName ファイル名 + */ + public void addFile(InputStream is, String fileName) { + if (attachmentFiles == null) { + initAttachmentFiles(); + } + attachmentFiles.add(new AttachmentFile(fileName, is)); + } + + /** + * 指定されたbyte配列をファイルとして添付します。 + * 指定するファイル名には適切な拡張子が付けられている必要があります。 + * + * @since 1.2 + * + * @param bytes 添付ファイルを生成するbyte配列 + * @param fileName ファイル名 + */ + public void addFile(byte[] bytes, String fileName) { + if (attachmentFiles == null) { + initAttachmentFiles(); + } + attachmentFiles.add(new AttachmentFile(fileName, bytes)); + } + + /** + * attachmentFilesプロパティを初期化。 + */ + private void initAttachmentFiles() { + attachmentFiles = new ArrayList(); + } + + /** + * 添付ファイルの配列を返します。 + * 添付ファイルがセットされていない場合は、空の配列を返します。 + * + * @since 1.1 + * + * @return 添付ファイルの配列。または空の配列。 + */ + public AttachmentFile[] getAttachmentFiles() { + if (attachmentFiles == null) { + return new AttachmentFile[0]; + } + return (AttachmentFile[])attachmentFiles + .toArray(new AttachmentFile[attachmentFiles.size()]); + } + + /** + * HTMLの本文がセットされているかどうか判定します。 + * + * @since 1.1 + * + * @return HTMLの本文がセットされている場合 true + */ + public boolean isHtmlMail() { + return (htmlText != null); + } + + /** + * ファイルが添付されているかどうか判定します。 + * + * @since 1.1 + * + * @return ファイルが添付されている場合 true + */ + public boolean isFileAttached() { + return attachmentFiles != null && attachmentFiles.size() > 0; + } + + /** + * マルチパート・メールかどうか判定します。
+ * HTML本文がセットされているか、ファイルが添付されている場合に true が返されます。 + *

+ * 注: ここで判定されるマルチパートは、厳密な意味でのマルチパートではありません。 + * + * @since 1.1 + * + * @return マルチパート・メールの場合 true + */ + public boolean isMultipartMail() { + return isHtmlMail() || isFileAttached(); + } + + /** + * セットされている添付ファイルを全てクリアします。 + * + * @since 1.1 + */ + public void clearFile() { + initAttachmentFiles(); + } + + /** + * envelope-toの宛先アドレスを追加します。 + *

+ * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 + * To、Cc、Bccアドレスには実際には送信されません。 + * + * @since 1.2 + * @param address + */ + public void addEnvelopeTo(InternetAddress address) { + if (envelopeTo == null) { + envelopeTo = new ArrayList(); + } + envelopeTo.add(address); + } + + /** + * envelope-toの宛先アドレスを追加します。 + *

+ * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 + * To、Cc、Bccアドレスには実際には送信されません。 + * + * @since 1.2 + * @param email + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void addEnvelopeTo(String email) { + try { + addEnvelopeTo(new InternetAddress(email)); + } catch (AddressException e) { + throw new IllegalArgumentException(e.getMessage()); + } + } + + /** + * envelope-toの宛先アドレスを追加します。 + *

+ * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 + * To、Cc、Bccアドレスには実際には送信されません。 + * + * @since 1.2 + * @param addresses + */ + public void addEnvelopeTo(InternetAddress[] addresses) { + for (int i = 0; i < addresses.length; i++) { + addEnvelopeTo(addresses[i]); + } + } + + /** + * envelope-toの宛先アドレスを追加します。 + *

+ * envelope-toアドレスがセットされている場合、envelope-toのアドレスにのみメールを送信し、 + * To、Cc、Bccアドレスには実際には送信されません。 + * + * @since 1.2 + * @param emails + * @throws IllegalArgumentException 不正なフォーマットのアドレスが指定された場合 + */ + public void addEnvelopeTo(String[] emails) { + for (int i = 0; i < emails.length; i++) { + addEnvelopeTo(emails[i]); + } + } + + /** + * セットされているenvelope-toアドレスを全てクリアします。 + * + * @since 1.2 + */ + public void clearEnvelopeTo() { + envelopeTo = null; + } + + /** + * envelope-toアドレス配列を返します。 + * envelope-toアドレスが一件もセットされていないときは空の配列を返します。 + * + * @since 1.2 + * @return envelope-toアドレスの配列 + */ + public InternetAddress[] getEnvelopeTo() { + if (envelopeTo == null) { + return new InternetAddress[0]; + } + return (InternetAddress[])envelopeTo.toArray(new InternetAddress[envelopeTo.size()]); + } + + /** + * 添付ファイル。 + *

+ * 受信メール(ReceivedMail)の添付ファイルは、常にgetFile()メソッドで取得します。 + * getInputStream()、getUrl()メソッドはnullを返します。 + * 受信メールに対しては、ReceivedMail.getFiles()メソッドを使うと添付ファイルの + * Fileインスタンス配列を取得することができます。 + * + * @since 1.1 + * @author Tomohiro Otsuka + * @version $Id: Mail.java,v 1.10.2.9 2007/03/30 13:03:44 otsuka Exp $ + */ + public class AttachmentFile { + + private String name; + + private File file; + + private InputStream is; + + private URL url; + + private byte[] bytes = null; + + /** + * ファイル名とファイルを指定して、このクラスのインタンスを生成します。 + * ファイル名には適切な拡張子が付けられている必要があります。 + * + * @param name メールに表示するファイル名 + * @param file 添付ファイル + */ + public AttachmentFile(String name, File file) { + this.name = name; + this.file = file; + } + + /** + * ファイル名とInputStreamを指定して、このクラスのインタンスを生成します。 + * ファイル名には適切な拡張子が付けられている必要があります。 + * + * @param name メールに表示するファイル名 + * @param is 添付ファイルを生成するInputStream + */ + public AttachmentFile(String name, InputStream is) { + this.name = name; + this.is = is; + } + + /** + * ファイル名とファイルロケーションのURLを指定して、このクラスのインタンスを生成します。 + * ファイル名には適切な拡張子が付けられている必要があります。 + * + * @param name メールに表示するファイル名 + * @param url 添付ファイルのロケーションURL + */ + public AttachmentFile(String name, URL url) { + this.name = name; + this.url = url; + } + + /** + * ファイル名とbyte配列を指定して、このクラスのインタンスを生成します。 + * ファイル名には適切な拡張子が付けられている必要があります。 + * + * @param name メールに表示するファイル名 + * @param bytes 添付ファイルを生成するbyte配列 + */ + public AttachmentFile(String name, byte[] bytes) { + this.name = name; + this.bytes = bytes; + } + + /** + * 添付ファイルのDataSourceインスタンスを生成して返します。 + * + * @return 添付ファイルのDataSourceインスタンス + */ + public DataSource getDataSource() { + if (file != null) { + return new FileDataSource(file); + } + + if (url != null) { + return new URLDataSource(url); + } + + // InputStreamからDataSourceを生成 + String contentType = FileTypeMap.getDefaultFileTypeMap().getContentType(name); + if (is != null) { + // InputStreamからDataSourceを生成 + return new ByteArrayDataSource(is, contentType); + } else { + // byte配列からDataSourceを生成 + return new ByteArrayDataSource(bytes, contentType); + } + } + + /** + * 添付ファイル名を返します。 + * + * @return 添付ファイル名 + */ + public String getName() { + return name; + } + + /** + * @return セットされたファイル。またはnull。 + */ + public File getFile() { + return file; + } + + /** + * @return セットされたInputStream。またはnull。 + */ + public InputStream getInputStream() { + return is; + } + + /** + * @return セットされたURL。またはnull。 + */ + public URL getUrl() { + return url; + } + + /** + * @return セットされたbyte配列。またはnull。 + */ + public byte[] getBytes() { + return bytes; + } + } + + /** + * メールの重要度。定数のみを定義。 + * + * @author Tomohiro Otsuka + * @version $Id: Mail.java,v 1.10.2.9 2007/03/30 13:03:44 otsuka Exp $ + */ + public static class Importance { + + /** 重要度「高」 */ + public static final String HIGH = "high"; + + /** 重要度「中」 */ + public static final String NORMAL = "normal"; + + /** 重要度「低」 */ + public static final String LOW = "low"; + + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/MailAuthenticationException.java b/src/main/java/com/ozacc/mail/MailAuthenticationException.java old mode 100755 new mode 100644 index 27be480..4ed144c --- a/src/main/java/com/ozacc/mail/MailAuthenticationException.java +++ b/src/main/java/com/ozacc/mail/MailAuthenticationException.java @@ -1,32 +1,32 @@ -package com.ozacc.mail; - -/** - * SMTPサーバ接続の認証に失敗した際にスローされる例外。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MailAuthenticationException.java,v 1.2 2004/09/13 07:08:22 otsuka Exp $ - */ -public class MailAuthenticationException extends MailException { - - /** - * @param message - */ - public MailAuthenticationException(String message) { - super(message); - } - - /** - * @param message - * @param cause - */ - public MailAuthenticationException(String message, Throwable cause) { - super(message, cause); - } - - public MailAuthenticationException(Throwable cause) { - super("Authentication failed: " + cause.getMessage(), cause); - } - -} - +package com.ozacc.mail; + +/** + * SMTPサーバ接続の認証に失敗した際にスローされる例外。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MailAuthenticationException.java,v 1.2 2004/09/13 07:08:22 otsuka Exp $ + */ +public class MailAuthenticationException extends MailException { + + /** + * @param message + */ + public MailAuthenticationException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public MailAuthenticationException(String message, Throwable cause) { + super(message, cause); + } + + public MailAuthenticationException(Throwable cause) { + super("Authentication failed: " + cause.getMessage(), cause); + } + +} + diff --git a/src/main/java/com/ozacc/mail/MailBuildException.java b/src/main/java/com/ozacc/mail/MailBuildException.java old mode 100755 new mode 100644 index f82e001..372a754 --- a/src/main/java/com/ozacc/mail/MailBuildException.java +++ b/src/main/java/com/ozacc/mail/MailBuildException.java @@ -1,27 +1,27 @@ -package com.ozacc.mail; - -/** - * MimeMessageオブジェクトの生成に失敗した際にスローされる例外。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MailBuildException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ - */ -public class MailBuildException extends MailException { - - /** - * @param message - */ - public MailBuildException(String message) { - super(message); - } - - /** - * @param message - * @param cause - */ - public MailBuildException(String message, Throwable cause) { - super(message, cause); - } - +package com.ozacc.mail; + +/** + * MimeMessageオブジェクトの生成に失敗した際にスローされる例外。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MailBuildException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ + */ +public class MailBuildException extends MailException { + + /** + * @param message + */ + public MailBuildException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public MailBuildException(String message, Throwable cause) { + super(message, cause); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/MailBuilder.java b/src/main/java/com/ozacc/mail/MailBuilder.java old mode 100755 new mode 100644 index b1d27ae..15fad14 --- a/src/main/java/com/ozacc/mail/MailBuilder.java +++ b/src/main/java/com/ozacc/mail/MailBuilder.java @@ -1,36 +1,36 @@ -package com.ozacc.mail; - -import java.io.File; - -/** - * メールデータが記述されたファイルからMailインスタンスを生成するインスターフェース。 - * サポートするファイルの種類やメールデータ書式は実装クラスに依存します。 - * - * @see com.ozacc.mail.impl.XMLMailBuilderImpl - * @see com.ozacc.mail.impl.JDomXMLMailBuilder - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MailBuilder.java,v 1.7 2004/09/17 23:07:01 otsuka Exp $ - */ -public interface MailBuilder { - - /** - * 指定されたクラスパス上のファイルを読み込んでMailインスタンスを生成します。 - * - * @param classPath メール内容を記述したファイルのパス - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(String classPath) throws MailBuildException; - - /** - * 指定されたファイルを読み込んでMailインスタンスを生成します。 - * - * @param file メール内容を記述したファイル - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(File file) throws MailBuildException; - +package com.ozacc.mail; + +import java.io.File; + +/** + * メールデータが記述されたファイルからMailインスタンスを生成するインスターフェース。 + * サポートするファイルの種類やメールデータ書式は実装クラスに依存します。 + * + * @see com.ozacc.mail.impl.XMLMailBuilderImpl + * @see com.ozacc.mail.impl.JDomXMLMailBuilder + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MailBuilder.java,v 1.7 2004/09/17 23:07:01 otsuka Exp $ + */ +public interface MailBuilder { + + /** + * 指定されたクラスパス上のファイルを読み込んでMailインスタンスを生成します。 + * + * @param classPath メール内容を記述したファイルのパス + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(String classPath) throws MailBuildException; + + /** + * 指定されたファイルを読み込んでMailインスタンスを生成します。 + * + * @param file メール内容を記述したファイル + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(File file) throws MailBuildException; + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/MailException.java b/src/main/java/com/ozacc/mail/MailException.java old mode 100755 new mode 100644 index e7e5938..948bd8b --- a/src/main/java/com/ozacc/mail/MailException.java +++ b/src/main/java/com/ozacc/mail/MailException.java @@ -1,27 +1,27 @@ -package com.ozacc.mail; - -/** - * メール関連例外の規定クラス。RuntimeExceptionを継承しています。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MailException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ - */ -public class MailException extends RuntimeException { - - /** - * @param message - */ - public MailException(String message) { - super(message); - } - - /** - * @param message - * @param cause - */ - public MailException(String message, Throwable cause) { - super(message, cause); - } - +package com.ozacc.mail; + +/** + * メール関連例外の規定クラス。RuntimeExceptionを継承しています。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MailException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ + */ +public class MailException extends RuntimeException { + + /** + * @param message + */ + public MailException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public MailException(String message, Throwable cause) { + super(message, cause); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/MailSendException.java b/src/main/java/com/ozacc/mail/MailSendException.java old mode 100755 new mode 100644 index cec0528..f70b71e --- a/src/main/java/com/ozacc/mail/MailSendException.java +++ b/src/main/java/com/ozacc/mail/MailSendException.java @@ -1,29 +1,29 @@ -package com.ozacc.mail; - -/** - * メール送信に失敗した時にスローされる例外。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MailSendException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ - */ -public class MailSendException extends MailException { - - private static final long serialVersionUID = -8590978542027055148L; - - /** - * @param message - */ - public MailSendException(String message) { - super(message); - } - - /** - * @param message - * @param cause - */ - public MailSendException(String message, Throwable cause) { - super(message, cause); - } - +package com.ozacc.mail; + +/** + * メール送信に失敗した時にスローされる例外。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MailSendException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ + */ +public class MailSendException extends MailException { + + private static final long serialVersionUID = -8590978542027055148L; + + /** + * @param message + */ + public MailSendException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public MailSendException(String message, Throwable cause) { + super(message, cause); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/MultipleMailBuilder.java b/src/main/java/com/ozacc/mail/MultipleMailBuilder.java old mode 100755 new mode 100644 index c220783..9af93fa --- a/src/main/java/com/ozacc/mail/MultipleMailBuilder.java +++ b/src/main/java/com/ozacc/mail/MultipleMailBuilder.java @@ -1,34 +1,34 @@ -package com.ozacc.mail; - -import java.io.File; - -/** - * 複数のメールデータが記述されたファイルからMailインスタンスを生成するインスターフェース。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: MultipleMailBuilder.java,v 1.1.2.2 2005/01/23 06:47:08 otsuka Exp $ - */ -public interface MultipleMailBuilder extends MailBuilder { - - /** - * 指定されたクラスパス上のファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 - * - * @param classPath メール内容を記述したファイルのパス - * @param mailId 生成するMailのメールデータを示すID - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(String classPath, String mailId) throws MailBuildException; - - /** - * 指定されたファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 - * - * @param file メール内容を記述したファイル - * @param mailId 生成するMailのメールデータを示すID - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(File file, String mailId) throws MailBuildException; - +package com.ozacc.mail; + +import java.io.File; + +/** + * 複数のメールデータが記述されたファイルからMailインスタンスを生成するインスターフェース。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: MultipleMailBuilder.java,v 1.1.2.2 2005/01/23 06:47:08 otsuka Exp $ + */ +public interface MultipleMailBuilder extends MailBuilder { + + /** + * 指定されたクラスパス上のファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 + * + * @param classPath メール内容を記述したファイルのパス + * @param mailId 生成するMailのメールデータを示すID + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(String classPath, String mailId) throws MailBuildException; + + /** + * 指定されたファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 + * + * @param file メール内容を記述したファイル + * @param mailId 生成するMailのメールデータを示すID + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(File file, String mailId) throws MailBuildException; + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/NotConnectedException.java b/src/main/java/com/ozacc/mail/NotConnectedException.java old mode 100755 new mode 100644 index 63e1af2..4210a5e --- a/src/main/java/com/ozacc/mail/NotConnectedException.java +++ b/src/main/java/com/ozacc/mail/NotConnectedException.java @@ -1,27 +1,27 @@ -package com.ozacc.mail; - -/** - * SMTPサーバに接続していない時に、接続状態を要する処理を実行してスローされる例外。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: NotConnectedException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ - */ -public class NotConnectedException extends MailException { - - /** - * @param message - */ - public NotConnectedException(String message) { - super(message); - } - - /** - * @param message - * @param cause - */ - public NotConnectedException(String message, Throwable cause) { - super(message, cause); - } - +package com.ozacc.mail; + +/** + * SMTPサーバに接続していない時に、接続状態を要する処理を実行してスローされる例外。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: NotConnectedException.java,v 1.2 2004/09/13 07:08:41 otsuka Exp $ + */ +public class NotConnectedException extends MailException { + + /** + * @param message + */ + public NotConnectedException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public NotConnectedException(String message, Throwable cause) { + super(message, cause); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/SendMail.java b/src/main/java/com/ozacc/mail/SendMail.java old mode 100755 new mode 100644 index 1db8c45..e5da52e --- a/src/main/java/com/ozacc/mail/SendMail.java +++ b/src/main/java/com/ozacc/mail/SendMail.java @@ -1,46 +1,46 @@ -package com.ozacc.mail; - -import javax.mail.internet.MimeMessage; - -/** - * SendMailインターフェース。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: SendMail.java,v 1.3 2004/09/25 02:12:12 otsuka Exp $ - */ -public interface SendMail { - - /** - * 指定されたメールを送信します。 - * - * @param mail 送信するメールのMailインスタンス - * @throws MailException メール送信に失敗した場合 - */ - void send(Mail mail) throws MailException; - - /** - * 指定されたメールを送信します。 - * - * @param mails 送信するメールのMailインスタンス配列 - * @throws MailException メール送信に失敗した場合 - */ - void send(Mail[] mails) throws MailException; - - /** - * 指定されたMimeMessageを送信します。 - * - * @param mimeMessage 送信するメールのMimeMessageインスタンス - * @throws MailException メール送信に失敗した場合 - */ - void send(MimeMessage mimeMessage) throws MailException; - - /** - * 指定されたMimeMessageを送信します。 - * - * @param mimeMessages 送信するメールのMimeMessageインスタンス配列 - * @throws MailException メール送信に失敗した場合 - */ - void send(MimeMessage[] mimeMessages) throws MailException; - +package com.ozacc.mail; + +import javax.mail.internet.MimeMessage; + +/** + * SendMailインターフェース。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: SendMail.java,v 1.3 2004/09/25 02:12:12 otsuka Exp $ + */ +public interface SendMail { + + /** + * 指定されたメールを送信します。 + * + * @param mail 送信するメールのMailインスタンス + * @throws MailException メール送信に失敗した場合 + */ + void send(Mail mail) throws MailException; + + /** + * 指定されたメールを送信します。 + * + * @param mails 送信するメールのMailインスタンス配列 + * @throws MailException メール送信に失敗した場合 + */ + void send(Mail[] mails) throws MailException; + + /** + * 指定されたMimeMessageを送信します。 + * + * @param mimeMessage 送信するメールのMimeMessageインスタンス + * @throws MailException メール送信に失敗した場合 + */ + void send(MimeMessage mimeMessage) throws MailException; + + /** + * 指定されたMimeMessageを送信します。 + * + * @param mimeMessages 送信するメールのMimeMessageインスタンス配列 + * @throws MailException メール送信に失敗した場合 + */ + void send(MimeMessage[] mimeMessages) throws MailException; + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/SendMailPro.java b/src/main/java/com/ozacc/mail/SendMailPro.java old mode 100755 new mode 100644 index 324a119..94c8685 --- a/src/main/java/com/ozacc/mail/SendMailPro.java +++ b/src/main/java/com/ozacc/mail/SendMailPro.java @@ -1,52 +1,52 @@ -package com.ozacc.mail; - -import javax.mail.internet.MimeMessage; - -/** - * SMTPサーバとの接続、切断を任意のタイミングで行いたい場合に使用するSendMailインターフェース。 - *

- * 大量メール配信で、MailやMimeMessageの配列を用意するとメモリを圧迫してしまう場合などに使用します。
- * 接続のクローズを忘れないように注意してください。 - *

- * このインターフェース実装クラスのインスタンスは、メールサーバとの接続を保持するため、 - * スレッドセーフではありません。
- * DIコンテナでの使用の際はシングルトンでインスタンスを取得しないように注意してください。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: SendMailPro.java,v 1.2.2.1 2004/11/25 08:02:27 otsuka Exp $ - */ -public interface SendMailPro { - - /** - * SMTPサーバに接続します。 - * - * @throws MailException - */ - void connect() throws MailException; - - /** - * SMTPサーバとの接続をクローズします。 - * 接続していない時にこのメソッドを呼んでも何も行いません。 - * - * @throws MailException - */ - void disconnect() throws MailException; - - /** - * 指定されたMimeMessageを送信します。SMTPサーバに接続していない場合は例外をスローします。 - * - * @param mimeMessage - * @throws MailException - */ - void send(MimeMessage mimeMessage) throws MailException; - - /** - * 指定されたMailを送信します。SMTPサーバに接続していない場合は例外をスローします。 - * - * @param mail - * @throws MailException - */ - void send(Mail mail) throws MailException; - +package com.ozacc.mail; + +import javax.mail.internet.MimeMessage; + +/** + * SMTPサーバとの接続、切断を任意のタイミングで行いたい場合に使用するSendMailインターフェース。 + *

+ * 大量メール配信で、MailやMimeMessageの配列を用意するとメモリを圧迫してしまう場合などに使用します。
+ * 接続のクローズを忘れないように注意してください。 + *

+ * このインターフェース実装クラスのインスタンスは、メールサーバとの接続を保持するため、 + * スレッドセーフではありません。
+ * DIコンテナでの使用の際はシングルトンでインスタンスを取得しないように注意してください。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: SendMailPro.java,v 1.2.2.1 2004/11/25 08:02:27 otsuka Exp $ + */ +public interface SendMailPro { + + /** + * SMTPサーバに接続します。 + * + * @throws MailException + */ + void connect() throws MailException; + + /** + * SMTPサーバとの接続をクローズします。 + * 接続していない時にこのメソッドを呼んでも何も行いません。 + * + * @throws MailException + */ + void disconnect() throws MailException; + + /** + * 指定されたMimeMessageを送信します。SMTPサーバに接続していない場合は例外をスローします。 + * + * @param mimeMessage + * @throws MailException + */ + void send(MimeMessage mimeMessage) throws MailException; + + /** + * 指定されたMailを送信します。SMTPサーバに接続していない場合は例外をスローします。 + * + * @param mail + * @throws MailException + */ + void send(Mail mail) throws MailException; + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/VelocityMailBuilder.java b/src/main/java/com/ozacc/mail/VelocityMailBuilder.java old mode 100755 new mode 100644 index 22de620..bbe99c0 --- a/src/main/java/com/ozacc/mail/VelocityMailBuilder.java +++ b/src/main/java/com/ozacc/mail/VelocityMailBuilder.java @@ -1,71 +1,71 @@ -package com.ozacc.mail; - -import java.io.File; - -import org.apache.velocity.VelocityContext; - -/** - * Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成するインターフェース。 - * - * @see com.ozacc.mail.impl.XMLVelocityMailBuilderImpl - * @see com.ozacc.mail.impl.JDomXMLMailBuilder - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: VelocityMailBuilder.java,v 1.4.2.3 2005/01/21 16:51:20 otsuka Exp $ - */ -public interface VelocityMailBuilder extends MailBuilder { - - /** - * 指定されたクラスパス上のファイルを読み込んでMailインスタンスを生成します。 - * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 - * - * @param classPath メール内容を記述したファイルのパス - * @param context VelocityContext - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(String classPath, VelocityContext context) throws MailBuildException; - - /** - * 指定されたファイルを読み込んでMailインスタンスを生成します。 - * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 - * - * @param file メール内容を記述したファイル - * @param context VelocityContext - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(File file, VelocityContext context) throws MailBuildException; - - /** - * メールデータキャッシュをクリアします。 - * - * @since 1.1.2 - */ - void clearCache(); - - /** - * VelocityContextとマージする前のメールデータをキャッシュするかどうかを設定します。 - * デフォルトはキャッシュしない設定です。 - *

- * キャッシュのキーは、buildMail()メソッド引数のメールデータファイルのクラスパス或いはファイルパスです。 - * キャッシュに有効期限はありません。 - * また、メールデータファイルの内容が途中で更新されても、キャッシュされているメールデータは更新されませんので注意してください。 - *

- * falseを指定してこのメソッドを呼ぶとメールデータキャッシュはクリアされます。 - * - * @since 1.1.2 - * @param cacheEnabled メールデータをキャッシュする場合は true - */ - void setCacheEnabled(boolean cacheEnabled); - - /** - * VelocityContextとマージする前のメールデータをキャッシュする設定かどうか判定します。 - * - * @since 1.1.2 - * @return メールデータをキャッシュする設定の場合は true - */ - boolean isCacheEnabled(); - +package com.ozacc.mail; + +import java.io.File; + +import org.apache.velocity.VelocityContext; + +/** + * Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成するインターフェース。 + * + * @see com.ozacc.mail.impl.XMLVelocityMailBuilderImpl + * @see com.ozacc.mail.impl.JDomXMLMailBuilder + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: VelocityMailBuilder.java,v 1.4.2.3 2005/01/21 16:51:20 otsuka Exp $ + */ +public interface VelocityMailBuilder extends MailBuilder { + + /** + * 指定されたクラスパス上のファイルを読み込んでMailインスタンスを生成します。 + * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 + * + * @param classPath メール内容を記述したファイルのパス + * @param context VelocityContext + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(String classPath, VelocityContext context) throws MailBuildException; + + /** + * 指定されたファイルを読み込んでMailインスタンスを生成します。 + * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 + * + * @param file メール内容を記述したファイル + * @param context VelocityContext + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(File file, VelocityContext context) throws MailBuildException; + + /** + * メールデータキャッシュをクリアします。 + * + * @since 1.1.2 + */ + void clearCache(); + + /** + * VelocityContextとマージする前のメールデータをキャッシュするかどうかを設定します。 + * デフォルトはキャッシュしない設定です。 + *

+ * キャッシュのキーは、buildMail()メソッド引数のメールデータファイルのクラスパス或いはファイルパスです。 + * キャッシュに有効期限はありません。 + * また、メールデータファイルの内容が途中で更新されても、キャッシュされているメールデータは更新されませんので注意してください。 + *

+ * falseを指定してこのメソッドを呼ぶとメールデータキャッシュはクリアされます。 + * + * @since 1.1.2 + * @param cacheEnabled メールデータをキャッシュする場合は true + */ + void setCacheEnabled(boolean cacheEnabled); + + /** + * VelocityContextとマージする前のメールデータをキャッシュする設定かどうか判定します。 + * + * @since 1.1.2 + * @return メールデータをキャッシュする設定の場合は true + */ + boolean isCacheEnabled(); + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/VelocityMultipleMailBuilder.java b/src/main/java/com/ozacc/mail/VelocityMultipleMailBuilder.java old mode 100755 new mode 100644 index 0325bcb..6e376d9 --- a/src/main/java/com/ozacc/mail/VelocityMultipleMailBuilder.java +++ b/src/main/java/com/ozacc/mail/VelocityMultipleMailBuilder.java @@ -1,41 +1,41 @@ -package com.ozacc.mail; - -import java.io.File; - -import org.apache.velocity.VelocityContext; - -/** - * Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成するインターフェース。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: VelocityMultipleMailBuilder.java,v 1.1.2.2 2005/01/23 06:47:08 otsuka Exp $ - */ -public interface VelocityMultipleMailBuilder extends VelocityMailBuilder { - - /** - * 指定されたクラスパス上のファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 - * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 - * - * @param classPath メール内容を記述したファイルのパス - * @param context VelocityContext - * @param mailId 生成するMailのメールデータを示すID - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(String classPath, VelocityContext context, String mailId) - throws MailBuildException; - - /** - * 指定されたファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 - * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 - * - * @param file メール内容を記述したファイル - * @param context VelocityContext - * @param mailId 生成するMailのメールデータを示すID - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - Mail buildMail(File file, VelocityContext context, String mailId) throws MailBuildException; - +package com.ozacc.mail; + +import java.io.File; + +import org.apache.velocity.VelocityContext; + +/** + * Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成するインターフェース。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: VelocityMultipleMailBuilder.java,v 1.1.2.2 2005/01/23 06:47:08 otsuka Exp $ + */ +public interface VelocityMultipleMailBuilder extends VelocityMailBuilder { + + /** + * 指定されたクラスパス上のファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 + * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 + * + * @param classPath メール内容を記述したファイルのパス + * @param context VelocityContext + * @param mailId 生成するMailのメールデータを示すID + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(String classPath, VelocityContext context, String mailId) + throws MailBuildException; + + /** + * 指定されたファイルを読み込み、mailIdが示すデータからMailインスタンスを生成します。 + * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 + * + * @param file メール内容を記述したファイル + * @param context VelocityContext + * @param mailId 生成するMailのメールデータを示すID + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + Mail buildMail(File file, VelocityContext context, String mailId) throws MailBuildException; + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/FetchMail.java b/src/main/java/com/ozacc/mail/fetch/FetchMail.java old mode 100755 new mode 100644 index 3b955c7..7e62d3e --- a/src/main/java/com/ozacc/mail/fetch/FetchMail.java +++ b/src/main/java/com/ozacc/mail/fetch/FetchMail.java @@ -1,45 +1,45 @@ -package com.ozacc.mail.fetch; - -import com.ozacc.mail.MailException; - -/** - * メールサーバからメールを取得するインターフェース。
- * このインターフェースの実装クラスでメールサーバの情報を設定します。 - *

- * getMails()メソッドはスレッドセーフです。メソッドを呼び出すとメールサーバに接続し、 - * メソッド終了時にサーバとの接続を切断します。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: FetchMail.java,v 1.1.2.5 2004/10/27 19:41:35 otsuka Exp $ - */ -public interface FetchMail { - - /** - * メールサーバからメールを受信し、ReceivedMailインスタンスに変換して返します。
- * 受信したメールは、メールサーバに残されます。 - *

- * このメソッドを呼び出すとメールサーバに接続します。メールを受信した後、メールサーバとの接続を切断します。 - *

- * メールサーバがimapサーバの場合、一度受信したメールには既読フラグ(SEENフラグ)が付けられます。 - * - * @return 受信したメールのReceivedMailインスタンス配列 - * @throws MailException - */ - ReceivedMail[] getMails() throws MailException; - - /** - * メールサーバからメールを受信し、ReceivedMailインスタンスに変換して返します。
- * deleteパラメータで、受信時にメールサーバからメールを削除するか残すかを指定します。 - *

- * このメソッドを呼び出すとメールサーバに接続します。メールを受信した後、メールサーバとの接続を切断します。 - *

- * メールサーバがimapサーバの場合、一度受信したメールには既読フラグ(SEENフラグ)が付けられます。 - * - * @param delete 受信時にメールサーバからメールを削除する場合 true - * @return 受信したメールのReceivedMailインスタンス配列 - * @throws MailException - */ - ReceivedMail[] getMails(boolean delete) throws MailException; - +package com.ozacc.mail.fetch; + +import com.ozacc.mail.MailException; + +/** + * メールサーバからメールを取得するインターフェース。
+ * このインターフェースの実装クラスでメールサーバの情報を設定します。 + *

+ * getMails()メソッドはスレッドセーフです。メソッドを呼び出すとメールサーバに接続し、 + * メソッド終了時にサーバとの接続を切断します。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: FetchMail.java,v 1.1.2.5 2004/10/27 19:41:35 otsuka Exp $ + */ +public interface FetchMail { + + /** + * メールサーバからメールを受信し、ReceivedMailインスタンスに変換して返します。
+ * 受信したメールは、メールサーバに残されます。 + *

+ * このメソッドを呼び出すとメールサーバに接続します。メールを受信した後、メールサーバとの接続を切断します。 + *

+ * メールサーバがimapサーバの場合、一度受信したメールには既読フラグ(SEENフラグ)が付けられます。 + * + * @return 受信したメールのReceivedMailインスタンス配列 + * @throws MailException + */ + ReceivedMail[] getMails() throws MailException; + + /** + * メールサーバからメールを受信し、ReceivedMailインスタンスに変換して返します。
+ * deleteパラメータで、受信時にメールサーバからメールを削除するか残すかを指定します。 + *

+ * このメソッドを呼び出すとメールサーバに接続します。メールを受信した後、メールサーバとの接続を切断します。 + *

+ * メールサーバがimapサーバの場合、一度受信したメールには既読フラグ(SEENフラグ)が付けられます。 + * + * @param delete 受信時にメールサーバからメールを削除する場合 true + * @return 受信したメールのReceivedMailインスタンス配列 + * @throws MailException + */ + ReceivedMail[] getMails(boolean delete) throws MailException; + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/FetchMailPro.java b/src/main/java/com/ozacc/mail/fetch/FetchMailPro.java old mode 100755 new mode 100644 index 54b91d0..532fef2 --- a/src/main/java/com/ozacc/mail/fetch/FetchMailPro.java +++ b/src/main/java/com/ozacc/mail/fetch/FetchMailPro.java @@ -1,118 +1,118 @@ -package com.ozacc.mail.fetch; - -import javax.mail.internet.MimeMessage; - -import com.ozacc.mail.MailException; - -/** - * メールサーバからメールを取得する上級インターフェース。
- * このインターフェースの実装クラスでメールサーバの情報を設定します。 - *

- * FetchMailインターフェースと異なり、メール取得時に例外が発生しても、 - * メールサーバとの接続は切断されません。finallyブロックを使用するなりして - * メールサーバとの接続を確実に切断できるようにすることを推奨します。 - *

- * このインターフェース実装クラスのインスタンスは、メールサーバとの接続を保持するため、 - * スレッドセーフではありません。
- * DIコンテナでの使用の際はシングルトンでインスタンスを取得しないように注意してください。 - * - * @see FetchMail - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: FetchMailPro.java,v 1.1.2.7 2005/04/10 05:22:24 otsuka Exp $ - */ -public interface FetchMailPro { - - /** - * メールサーバに接続し、「INBOX」フォルダをオープンします。 - * - * @throws MailException メールサーバとの接続に失敗した場合 - */ - void connect() throws MailException; - - /** - * メールサーバとの接続を切断します。接続されていなければ何も行いません。 - * - * @throws MailException メールサーバとの接続切断に失敗した場合 - */ - void disconnect() throws MailException; - - /** - * 現在のフォルダに届いているメール数を返します。 - * - * @return 現在のフォルダにあるメール数 - * @throws MailException - */ - int getMailCount() throws MailException; - - /** - * 現在のフォルダにある指定されたメッセージ番号のメールをReceivedMailに変換して返します。 - * メッセージ番号は1始まりです。 - *

- * メッセージはサーバから削除されません。 - * - * @param num メッセージ番号。1始まり。 - * @return 指定されたメッセージ番号のReceivedMailインスタンス - * @throws MailException メール取得に失敗した場合 - */ - ReceivedMail getMail(int num) throws MailException; - - /** - * 現在のフォルダにある指定されたメッセージ番号のメールをReceivedMailに変換して返します。 - * メッセージ番号は1始まりです。 - * 指定した番号のメッセージをサーバから削除するかどうかを指定できます。 - * - * @param num メッセージ番号。1始まり。 - * @param delete 指定された番号のメッセージをサーバから削除する場合 true を指定 - * @return 指定されたメッセージ番号のReceivedMailインスタンス - * @throws MailException メール取得に失敗した場合 - */ - ReceivedMail getMail(int num, boolean delete) throws MailException; - - /** - * 現在のフォルダにある全メールをReceivedMailに変換して返します。 - * - * @param delete メール取得後にサーバからメールを削除する場合 true - * @return 現在のフォルダにある全メールのReceivedMailインスタンス - * @throws MailException メール取得に失敗した場合 - */ - ReceivedMail[] getMails(boolean delete) throws MailException; - - /** - * 現在のフォルダにある指定されたメッセージ番号のメールを返します。 - * メッセージ番号は1始まりです。 - * - * @see javax.mail.Folder#getMessage(int) - * @param num メッセージ番号。1始まり。 - * @return 指定された番号のMimeMessageインスタンス - * @throws MailException メール取得に失敗した場合 - */ - MimeMessage getMessage(int num) throws MailException; - - /** - * 現在のフォルダにある全メールを返します。 - * - * @param delete メール取得後にサーバからメールを削除する場合 true - * @return 現在のフォルダにある全メールのMimeMessageインスタンス - * @throws MailException メール取得に失敗した場合 - */ - MimeMessage[] getMessages(boolean delete) throws MailException; - - /** - * 指定された名前のフォルダに移動します。 - * フォルダ名は"INBOX/XXXX"のように、INBOXからのパス指定します。 - *

- * 注: このメソッドは、メールサーバがimapサーバの時にのみ使用可能です。 - * - * @param folderName 移動先のフォルダ名 - * @throws MailException - */ - void changeFolder(String folderName) throws MailException; - - /** - * メールサーバと接続しているかどうか判定します。 - * - * @return 接続している場合 true - */ - boolean isConnected(); +package com.ozacc.mail.fetch; + +import javax.mail.internet.MimeMessage; + +import com.ozacc.mail.MailException; + +/** + * メールサーバからメールを取得する上級インターフェース。
+ * このインターフェースの実装クラスでメールサーバの情報を設定します。 + *

+ * FetchMailインターフェースと異なり、メール取得時に例外が発生しても、 + * メールサーバとの接続は切断されません。finallyブロックを使用するなりして + * メールサーバとの接続を確実に切断できるようにすることを推奨します。 + *

+ * このインターフェース実装クラスのインスタンスは、メールサーバとの接続を保持するため、 + * スレッドセーフではありません。
+ * DIコンテナでの使用の際はシングルトンでインスタンスを取得しないように注意してください。 + * + * @see FetchMail + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: FetchMailPro.java,v 1.1.2.7 2005/04/10 05:22:24 otsuka Exp $ + */ +public interface FetchMailPro { + + /** + * メールサーバに接続し、「INBOX」フォルダをオープンします。 + * + * @throws MailException メールサーバとの接続に失敗した場合 + */ + void connect() throws MailException; + + /** + * メールサーバとの接続を切断します。接続されていなければ何も行いません。 + * + * @throws MailException メールサーバとの接続切断に失敗した場合 + */ + void disconnect() throws MailException; + + /** + * 現在のフォルダに届いているメール数を返します。 + * + * @return 現在のフォルダにあるメール数 + * @throws MailException + */ + int getMailCount() throws MailException; + + /** + * 現在のフォルダにある指定されたメッセージ番号のメールをReceivedMailに変換して返します。 + * メッセージ番号は1始まりです。 + *

+ * メッセージはサーバから削除されません。 + * + * @param num メッセージ番号。1始まり。 + * @return 指定されたメッセージ番号のReceivedMailインスタンス + * @throws MailException メール取得に失敗した場合 + */ + ReceivedMail getMail(int num) throws MailException; + + /** + * 現在のフォルダにある指定されたメッセージ番号のメールをReceivedMailに変換して返します。 + * メッセージ番号は1始まりです。 + * 指定した番号のメッセージをサーバから削除するかどうかを指定できます。 + * + * @param num メッセージ番号。1始まり。 + * @param delete 指定された番号のメッセージをサーバから削除する場合 true を指定 + * @return 指定されたメッセージ番号のReceivedMailインスタンス + * @throws MailException メール取得に失敗した場合 + */ + ReceivedMail getMail(int num, boolean delete) throws MailException; + + /** + * 現在のフォルダにある全メールをReceivedMailに変換して返します。 + * + * @param delete メール取得後にサーバからメールを削除する場合 true + * @return 現在のフォルダにある全メールのReceivedMailインスタンス + * @throws MailException メール取得に失敗した場合 + */ + ReceivedMail[] getMails(boolean delete) throws MailException; + + /** + * 現在のフォルダにある指定されたメッセージ番号のメールを返します。 + * メッセージ番号は1始まりです。 + * + * @see javax.mail.Folder#getMessage(int) + * @param num メッセージ番号。1始まり。 + * @return 指定された番号のMimeMessageインスタンス + * @throws MailException メール取得に失敗した場合 + */ + MimeMessage getMessage(int num) throws MailException; + + /** + * 現在のフォルダにある全メールを返します。 + * + * @param delete メール取得後にサーバからメールを削除する場合 true + * @return 現在のフォルダにある全メールのMimeMessageインスタンス + * @throws MailException メール取得に失敗した場合 + */ + MimeMessage[] getMessages(boolean delete) throws MailException; + + /** + * 指定された名前のフォルダに移動します。 + * フォルダ名は"INBOX/XXXX"のように、INBOXからのパス指定します。 + *

+ * 注: このメソッドは、メールサーバがimapサーバの時にのみ使用可能です。 + * + * @param folderName 移動先のフォルダ名 + * @throws MailException + */ + void changeFolder(String folderName) throws MailException; + + /** + * メールサーバと接続しているかどうか判定します。 + * + * @return 接続している場合 true + */ + boolean isConnected(); } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/MailConverter.java b/src/main/java/com/ozacc/mail/fetch/MailConverter.java old mode 100755 new mode 100644 index d43cb22..83ac972 --- a/src/main/java/com/ozacc/mail/fetch/MailConverter.java +++ b/src/main/java/com/ozacc/mail/fetch/MailConverter.java @@ -1,30 +1,30 @@ -package com.ozacc.mail.fetch; - -import javax.mail.internet.MimeMessage; - -/** - * MimeMessageからReceivedMailを生成するインターフェース。 - * - * @since 1.2 - * @author gaku - * @version $Id: MailConverter.java,v 1.1.2.2 2005/04/10 05:25:21 otsuka Exp $ - */ -public interface MailConverter { - - /** - * 指定されたMimeMessageをReceivedMailに変換して返します。 - * - * @param message ReceivedMailに変換するMimeMessage - * @return MimeMessageから生成されたReceivedMail - */ - ReceivedMail convertIntoMail(MimeMessage message); - - /** - * 指定されたMimeMessageをReceivedMailに変換して返します。 - * - * @param message ReceivedMailに変換するMimeMessageの配列 - * @return MimeMessageから生成されたReceivedMailの配列 - */ - ReceivedMail[] convertIntoMails(MimeMessage[] messages); - +package com.ozacc.mail.fetch; + +import javax.mail.internet.MimeMessage; + +/** + * MimeMessageからReceivedMailを生成するインターフェース。 + * + * @since 1.2 + * @author gaku + * @version $Id: MailConverter.java,v 1.1.2.2 2005/04/10 05:25:21 otsuka Exp $ + */ +public interface MailConverter { + + /** + * 指定されたMimeMessageをReceivedMailに変換して返します。 + * + * @param message ReceivedMailに変換するMimeMessage + * @return MimeMessageから生成されたReceivedMail + */ + ReceivedMail convertIntoMail(MimeMessage message); + + /** + * 指定されたMimeMessageをReceivedMailに変換して返します。 + * + * @param message ReceivedMailに変換するMimeMessageの配列 + * @return MimeMessageから生成されたReceivedMailの配列 + */ + ReceivedMail[] convertIntoMails(MimeMessage[] messages); + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/MailFetchException.java b/src/main/java/com/ozacc/mail/fetch/MailFetchException.java old mode 100755 new mode 100644 index 737e3c8..f1e0133 --- a/src/main/java/com/ozacc/mail/fetch/MailFetchException.java +++ b/src/main/java/com/ozacc/mail/fetch/MailFetchException.java @@ -1,28 +1,28 @@ -package com.ozacc.mail.fetch; - -import com.ozacc.mail.MailException; - -/** - * メールの受信に失敗した時にスローされる例外。 - * - * @author Tomohiro Otsuka - * @version $Id: MailFetchException.java,v 1.1.2.1 2004/10/24 10:14:31 otsuka Exp $ - */ -public class MailFetchException extends MailException { - - /** - * @param message - */ - public MailFetchException(String message) { - super(message); - } - - /** - * @param message - * @param cause - */ - public MailFetchException(String message, Throwable cause) { - super(message, cause); - } - +package com.ozacc.mail.fetch; + +import com.ozacc.mail.MailException; + +/** + * メールの受信に失敗した時にスローされる例外。 + * + * @author Tomohiro Otsuka + * @version $Id: MailFetchException.java,v 1.1.2.1 2004/10/24 10:14:31 otsuka Exp $ + */ +public class MailFetchException extends MailException { + + /** + * @param message + */ + public MailFetchException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public MailFetchException(String message, Throwable cause) { + super(message, cause); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/ReceivedMail.java b/src/main/java/com/ozacc/mail/fetch/ReceivedMail.java old mode 100755 new mode 100644 index 055744a..1a6d4be --- a/src/main/java/com/ozacc/mail/fetch/ReceivedMail.java +++ b/src/main/java/com/ozacc/mail/fetch/ReceivedMail.java @@ -1,407 +1,407 @@ -package com.ozacc.mail.fetch; - -import java.io.File; -import java.util.ArrayList; -import java.util.Date; -import java.util.Iterator; -import java.util.List; - -import javax.mail.Flags; -import javax.mail.MessagingException; -import javax.mail.internet.MimeMessage; - -import com.ozacc.mail.Mail; - -/** - * 受信メール。 - *

- * FetchMail、FetchMailProの実装クラスで受信したメールが、 - * インターネットメールとしての仕様を満たしていないヘッダ(FromやToなど)の値がセットされていた場合、 - * そのヘッダに該当するReceivedMailインスタンスのプロパティには何もセットされません。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: ReceivedMail.java,v 1.1.2.9 2005/01/23 07:13:13 otsuka Exp $ - */ -public class ReceivedMail extends Mail { - - private String replySubjectPrefix = "Re: "; - - private Date date; - - private String messageId; - - private int size; - - private List receivedHeaders; - - private MimeMessage message; - - /** - * コンストラクタ。 - */ - public ReceivedMail() { - super(); - } - - /** - * コンストラクタ。 - * - * @param charset - */ - public ReceivedMail(String charset) { - super(charset); - } - - /** - * コピーコンストラクタ。 - * - * @param original - */ - public ReceivedMail(Mail original) { - super(original); - } - - /** - * 送信日時を返します。 - *

- * 注: メールの受信日時ではありません。 - * - * @return 送信日時 - */ - public Date getDate() { - return date; - } - - /** - * 送信日時をセットします。 - * - * @param date 送信日時 - */ - public void setDate(Date date) { - this.date = date; - } - - /** - * 前後に<>が付いたメッセージIDを返します。 - * 受信メールにメッセージIDが存在しない場合はnullを返します。 - * - * @return 前後に<>が付いたメッセージID、またはnull - */ - public String getMessageId() { - if (messageId == null || messageId.length() == 0) { - return null; - } - if (messageId.startsWith("<") && messageId.endsWith(">")) { - return messageId; - } - return "<" + messageId + ">"; - } - - /** - * メッセージIDを返します。前後に<>は付きません。 - * 受信メールにメッセージIDが存在しない場合はnullを返します。 - * - * @return メッセージID、またはnull - */ - public String getMessageIdWithoutBracket() { - if (messageId == null || messageId.length() == 0) { - return null; - } - if (messageId.startsWith("<") && messageId.endsWith(">")) { - return messageId.substring(1, messageId.length() - 1); - } - return messageId; - } - - /** - * メッセージIDをセットします。 - * - * @param messageId メッセージID - */ - public void setMessageId(String messageId) { - this.messageId = messageId; - } - - /** - * In-Reply-Toヘッダの値を返します。 - * In-Reply-Toヘッダがない場合はnullを返します。 - * - * @return In-Reply-Toヘッダの値 - */ - public String getInReplyTo() { - return (String)headers.get("In-Reply-To"); - } - - /** - * Referencesヘッダの値を返します。 - * Referencesヘッダがない場合はnullを返します。 - * - * @return Referencesヘッダの値 - */ - public String getRefereces() { - return (String)headers.get("References"); - } - - /** - * @return 返信時の件名に付ける接頭辞 - */ - public String getReplySubjectPrefix() { - return replySubjectPrefix; - } - - /** - * 返信時の件名に付ける接頭辞をセットします。 - * デフォルトは「Re: 」。 - * - * @param replySubjectPrefix 返信時の件名に付ける接頭辞 - */ - public void setReplySubjectPrefix(String replySubjectPrefix) { - this.replySubjectPrefix = replySubjectPrefix; - } - - /** - * メール内容を出力します。
- * メールのソースに似たフォーマットで出力されます。 - * - * @see java.lang.Object#toString() - */ - public String toString() { - StringBuffer buf = new StringBuffer(1000); - buf.append("Mail\n"); - buf.append("Return-Path: ").append(returnPath).append("\n"); - buf.append("Message-ID: ").append(messageId).append("\n"); - buf.append("Date: ").append(date).append("\n"); - buf.append("From: ").append(from != null ? from.toUnicodeString() : null).append("\n"); - buf.append("To: ").append(arrayToCommaDelimitedString(to)).append("\n"); - buf.append("Cc: ").append(arrayToCommaDelimitedString(cc)).append("\n"); - buf.append("Bcc: ").append(arrayToCommaDelimitedString(bcc)).append("\n"); - buf.append("Reply-To: ").append(replyTo != null ? replyTo.toUnicodeString() : null).append( - "\n"); - buf.append("Subject: ").append(subject).append("\n"); - - if (headers != null) { - for (Iterator itr = headers.keySet().iterator(); itr.hasNext();) { - String header = (String)itr.next(); - String value = (String)headers.get(header); - buf.append(header).append(": ").append(value).append("\n"); - } - } - - buf.append("\n"); - buf.append(text); - - if (htmlText != null) { - buf.append("\n\n-----\n\n"); - buf.append(htmlText); - } - - if (isFileAttached()) { - buf.append("\n\nAttachments\n"); - for (int i = 0, num = attachmentFiles.size(); i < num; i++) { - AttachmentFile f = (AttachmentFile)attachmentFiles.get(i); - buf.append("[").append(i + 1).append("] ").append(f.getName()).append("\n"); - } - } - - return buf.toString(); - } - - /** - * @return Returns the message. - */ - public MimeMessage getMessage() { - return message; - } - - /** - * @param message The message to set. - */ - public void setMessage(MimeMessage message) { - this.message = message; - } - - /** - * メールサーバとの接続切断時に、このメールをメールサーバから削除します。 - * 削除できるように設定ができた場合に true を返します。 - *

- * このメソッドは、FetchMailProのメソッドによって取得された - * ReceivedMailインスタンスでのみ有効です。 - * また、FetchMailProインスタンスがメールサーバに - * 接続されている状態での呼び出しのみ有効です。
- * これらの条件が満たされない時にこのメソッドが呼び出された場合 - * false を返します。 - * - * TODO: うまく動いてない。 - * - * @see FetchMailPro - * @param delete 削除するように設定する場合 true - * @return 削除設定が正常に行われた場合 true - */ - public boolean setDelete(boolean delete) { - if (message != null) { - try { - message.setFlag(Flags.Flag.DELETED, delete); - } catch (MessagingException e) { - return false; - } - return true; - } - return false; - } - - /** - * メールのサイズ(容量)を返します。単位はbyte。 - * この値は厳密なものではないので注意してください。 - * - * @see MimeMessage#getSize() - * @return メールのサイズ(単位はbyte) - */ - public int getSize() { - return size; - } - - /** - * メールのサイズ(容量)をセットします。単位はbyte。 - * - * @param size メールのサイズ(単位はbyte) - */ - public void setSize(int size) { - this.size = size; - } - - /** - * 添付ファイルのFileインスタンス配列を返します。 - * 添付ファイルがない場合は空の配列を返します。 - * - * @return 添付ファイルのFileインスタンス配列 - */ - public File[] getFiles() { - AttachmentFile[] aFiles = getAttachmentFiles(); - File[] files = new File[aFiles.length]; - for (int i = 0; i < aFiles.length; i++) { - AttachmentFile aFile = aFiles[i]; - files[i] = aFile.getFile(); - } - return files; - } - - /** - * このメールの返信メール用Mailインスタンスを生成して返します。 - *

- * - * @return 返信用のMailインスタンス - */ - public Mail reply() { - Mail mail = new Mail(); - - // 宛先 - if (getReplyTo() != null) { - mail.addTo(getReplyTo()); - } else { - mail.addTo(getFrom()); - } - - // 件名 - String subject = getSubject(); - if ((subject.length() >= 3 && !"Re:".equalsIgnoreCase(subject.substring(0, 3))) - || subject.length() < 3) { - subject = replySubjectPrefix + subject; - } - mail.setSubject(subject); - - // In-Reply-To, References - String messageId = getMessageId(); - if (messageId != null && !"<>".equals(messageId)) { - String references = getRefereces(); - if (references != null) { - references = messageId + " " + references; - } else if (getInReplyTo() != null) { - references = messageId + " " + getInReplyTo(); - } else { - references = messageId; - } - mail.addHeader("References", references); - mail.addHeader("In-Reply-To", messageId); - } - - return mail; - } - - /** - * Receivedヘッダフィールドを追加します。 - * - * @param rh Receivedヘッダフィールド - */ - public void addReceviedHeader(ReceivedHeader rh) { - if (receivedHeaders == null) { - receivedHeaders = new ArrayList(); - } - receivedHeaders.add(rh); - } - - /** - * Receivedヘッダフィールドの配列を返します。
- * 自分のサーバ(このメールが届いたサーバ)から送信元のメールサーバを辿る順で並んでいます。
- * 受信メールがReceivedヘッダフィールドを持たない、または解析できなかった場合は空の配列を返します。 - * - * @return Receivedヘッダフィールドの配列 - */ - public ReceivedHeader[] getReceivedHeaders() { - if (receivedHeaders == null) { - return new ReceivedHeader[0]; - } - return (ReceivedHeader[])receivedHeaders - .toArray(new ReceivedHeader[receivedHeaders.size()]); - } - - /** - * Receviedヘッダフィールドを表すクラス。 - */ - public static class ReceivedHeader { - - private String from; - - private String by; - - /** - * @param from メールを送信したサーバのホスト名 - * @param by メールを受信したサーバのホスト名 - */ - public ReceivedHeader(String from, String by) { - this.from = from; - this.by = by; - } - - /** - * @see java.lang.Object#toString() - */ - public String toString() { - return "Sent from " + from + " and received by " + by; - } - - /** - * メールを受信したサーバのホスト名を返します。 - * - * @return メールを受信したサーバのホスト名 - */ - public String getBy() { - return by; - } - - /** - * メールを送信したサーバのホスト名を返します。 - * - * @return メールを送信したサーバのホスト名 - */ - public String getFrom() { - return from; - } - } +package com.ozacc.mail.fetch; + +import java.io.File; +import java.util.ArrayList; +import java.util.Date; +import java.util.Iterator; +import java.util.List; + +import javax.mail.Flags; +import javax.mail.MessagingException; +import javax.mail.internet.MimeMessage; + +import com.ozacc.mail.Mail; + +/** + * 受信メール。 + *

+ * FetchMail、FetchMailProの実装クラスで受信したメールが、 + * インターネットメールとしての仕様を満たしていないヘッダ(FromやToなど)の値がセットされていた場合、 + * そのヘッダに該当するReceivedMailインスタンスのプロパティには何もセットされません。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: ReceivedMail.java,v 1.1.2.9 2005/01/23 07:13:13 otsuka Exp $ + */ +public class ReceivedMail extends Mail { + + private String replySubjectPrefix = "Re: "; + + private Date date; + + private String messageId; + + private int size; + + private List receivedHeaders; + + private MimeMessage message; + + /** + * コンストラクタ。 + */ + public ReceivedMail() { + super(); + } + + /** + * コンストラクタ。 + * + * @param charset + */ + public ReceivedMail(String charset) { + super(charset); + } + + /** + * コピーコンストラクタ。 + * + * @param original + */ + public ReceivedMail(Mail original) { + super(original); + } + + /** + * 送信日時を返します。 + *

+ * 注: メールの受信日時ではありません。 + * + * @return 送信日時 + */ + public Date getDate() { + return date; + } + + /** + * 送信日時をセットします。 + * + * @param date 送信日時 + */ + public void setDate(Date date) { + this.date = date; + } + + /** + * 前後に<>が付いたメッセージIDを返します。 + * 受信メールにメッセージIDが存在しない場合はnullを返します。 + * + * @return 前後に<>が付いたメッセージID、またはnull + */ + public String getMessageId() { + if (messageId == null || messageId.length() == 0) { + return null; + } + if (messageId.startsWith("<") && messageId.endsWith(">")) { + return messageId; + } + return "<" + messageId + ">"; + } + + /** + * メッセージIDを返します。前後に<>は付きません。 + * 受信メールにメッセージIDが存在しない場合はnullを返します。 + * + * @return メッセージID、またはnull + */ + public String getMessageIdWithoutBracket() { + if (messageId == null || messageId.length() == 0) { + return null; + } + if (messageId.startsWith("<") && messageId.endsWith(">")) { + return messageId.substring(1, messageId.length() - 1); + } + return messageId; + } + + /** + * メッセージIDをセットします。 + * + * @param messageId メッセージID + */ + public void setMessageId(String messageId) { + this.messageId = messageId; + } + + /** + * In-Reply-Toヘッダの値を返します。 + * In-Reply-Toヘッダがない場合はnullを返します。 + * + * @return In-Reply-Toヘッダの値 + */ + public String getInReplyTo() { + return (String)headers.get("In-Reply-To"); + } + + /** + * Referencesヘッダの値を返します。 + * Referencesヘッダがない場合はnullを返します。 + * + * @return Referencesヘッダの値 + */ + public String getRefereces() { + return (String)headers.get("References"); + } + + /** + * @return 返信時の件名に付ける接頭辞 + */ + public String getReplySubjectPrefix() { + return replySubjectPrefix; + } + + /** + * 返信時の件名に付ける接頭辞をセットします。 + * デフォルトは「Re: 」。 + * + * @param replySubjectPrefix 返信時の件名に付ける接頭辞 + */ + public void setReplySubjectPrefix(String replySubjectPrefix) { + this.replySubjectPrefix = replySubjectPrefix; + } + + /** + * メール内容を出力します。
+ * メールのソースに似たフォーマットで出力されます。 + * + * @see java.lang.Object#toString() + */ + public String toString() { + StringBuffer buf = new StringBuffer(1000); + buf.append("Mail\n"); + buf.append("Return-Path: ").append(returnPath).append("\n"); + buf.append("Message-ID: ").append(messageId).append("\n"); + buf.append("Date: ").append(date).append("\n"); + buf.append("From: ").append(from != null ? from.toUnicodeString() : null).append("\n"); + buf.append("To: ").append(arrayToCommaDelimitedString(to)).append("\n"); + buf.append("Cc: ").append(arrayToCommaDelimitedString(cc)).append("\n"); + buf.append("Bcc: ").append(arrayToCommaDelimitedString(bcc)).append("\n"); + buf.append("Reply-To: ").append(replyTo != null ? replyTo.toUnicodeString() : null).append( + "\n"); + buf.append("Subject: ").append(subject).append("\n"); + + if (headers != null) { + for (Iterator itr = headers.keySet().iterator(); itr.hasNext();) { + String header = (String)itr.next(); + String value = (String)headers.get(header); + buf.append(header).append(": ").append(value).append("\n"); + } + } + + buf.append("\n"); + buf.append(text); + + if (htmlText != null) { + buf.append("\n\n-----\n\n"); + buf.append(htmlText); + } + + if (isFileAttached()) { + buf.append("\n\nAttachments\n"); + for (int i = 0, num = attachmentFiles.size(); i < num; i++) { + AttachmentFile f = (AttachmentFile)attachmentFiles.get(i); + buf.append("[").append(i + 1).append("] ").append(f.getName()).append("\n"); + } + } + + return buf.toString(); + } + + /** + * @return Returns the message. + */ + public MimeMessage getMessage() { + return message; + } + + /** + * @param message The message to set. + */ + public void setMessage(MimeMessage message) { + this.message = message; + } + + /** + * メールサーバとの接続切断時に、このメールをメールサーバから削除します。 + * 削除できるように設定ができた場合に true を返します。 + *

+ * このメソッドは、FetchMailProのメソッドによって取得された + * ReceivedMailインスタンスでのみ有効です。 + * また、FetchMailProインスタンスがメールサーバに + * 接続されている状態での呼び出しのみ有効です。
+ * これらの条件が満たされない時にこのメソッドが呼び出された場合 + * false を返します。 + * + * TODO: うまく動いてない。 + * + * @see FetchMailPro + * @param delete 削除するように設定する場合 true + * @return 削除設定が正常に行われた場合 true + */ + public boolean setDelete(boolean delete) { + if (message != null) { + try { + message.setFlag(Flags.Flag.DELETED, delete); + } catch (MessagingException e) { + return false; + } + return true; + } + return false; + } + + /** + * メールのサイズ(容量)を返します。単位はbyte。 + * この値は厳密なものではないので注意してください。 + * + * @see MimeMessage#getSize() + * @return メールのサイズ(単位はbyte) + */ + public int getSize() { + return size; + } + + /** + * メールのサイズ(容量)をセットします。単位はbyte。 + * + * @param size メールのサイズ(単位はbyte) + */ + public void setSize(int size) { + this.size = size; + } + + /** + * 添付ファイルのFileインスタンス配列を返します。 + * 添付ファイルがない場合は空の配列を返します。 + * + * @return 添付ファイルのFileインスタンス配列 + */ + public File[] getFiles() { + AttachmentFile[] aFiles = getAttachmentFiles(); + File[] files = new File[aFiles.length]; + for (int i = 0; i < aFiles.length; i++) { + AttachmentFile aFile = aFiles[i]; + files[i] = aFile.getFile(); + } + return files; + } + + /** + * このメールの返信メール用Mailインスタンスを生成して返します。 + *

+ * + * @return 返信用のMailインスタンス + */ + public Mail reply() { + Mail mail = new Mail(); + + // 宛先 + if (getReplyTo() != null) { + mail.addTo(getReplyTo()); + } else { + mail.addTo(getFrom()); + } + + // 件名 + String subject = getSubject(); + if ((subject.length() >= 3 && !"Re:".equalsIgnoreCase(subject.substring(0, 3))) + || subject.length() < 3) { + subject = replySubjectPrefix + subject; + } + mail.setSubject(subject); + + // In-Reply-To, References + String messageId = getMessageId(); + if (messageId != null && !"<>".equals(messageId)) { + String references = getRefereces(); + if (references != null) { + references = messageId + " " + references; + } else if (getInReplyTo() != null) { + references = messageId + " " + getInReplyTo(); + } else { + references = messageId; + } + mail.addHeader("References", references); + mail.addHeader("In-Reply-To", messageId); + } + + return mail; + } + + /** + * Receivedヘッダフィールドを追加します。 + * + * @param rh Receivedヘッダフィールド + */ + public void addReceviedHeader(ReceivedHeader rh) { + if (receivedHeaders == null) { + receivedHeaders = new ArrayList(); + } + receivedHeaders.add(rh); + } + + /** + * Receivedヘッダフィールドの配列を返します。
+ * 自分のサーバ(このメールが届いたサーバ)から送信元のメールサーバを辿る順で並んでいます。
+ * 受信メールがReceivedヘッダフィールドを持たない、または解析できなかった場合は空の配列を返します。 + * + * @return Receivedヘッダフィールドの配列 + */ + public ReceivedHeader[] getReceivedHeaders() { + if (receivedHeaders == null) { + return new ReceivedHeader[0]; + } + return (ReceivedHeader[])receivedHeaders + .toArray(new ReceivedHeader[receivedHeaders.size()]); + } + + /** + * Receviedヘッダフィールドを表すクラス。 + */ + public static class ReceivedHeader { + + private String from; + + private String by; + + /** + * @param from メールを送信したサーバのホスト名 + * @param by メールを受信したサーバのホスト名 + */ + public ReceivedHeader(String from, String by) { + this.from = from; + this.by = by; + } + + /** + * @see java.lang.Object#toString() + */ + public String toString() { + return "Sent from " + from + " and received by " + by; + } + + /** + * メールを受信したサーバのホスト名を返します。 + * + * @return メールを受信したサーバのホスト名 + */ + public String getBy() { + return by; + } + + /** + * メールを送信したサーバのホスト名を返します。 + * + * @return メールを送信したサーバのホスト名 + */ + public String getFrom() { + return from; + } + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/FetchMailImpl.java b/src/main/java/com/ozacc/mail/fetch/impl/FetchMailImpl.java old mode 100755 new mode 100644 index a4efe50..19b2fb2 --- a/src/main/java/com/ozacc/mail/fetch/impl/FetchMailImpl.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/FetchMailImpl.java @@ -1,178 +1,178 @@ -package com.ozacc.mail.fetch.impl; - -import com.ozacc.mail.MailException; -import com.ozacc.mail.fetch.FetchMail; -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * FetchMailインターフェースの実装クラス。 - *

- * FetchMailProImplクラスに処理を委譲しています。 - * - * @since 1.2 - * @see FetchMailProImpl - * - * @author Tomohiro Otsuka - * @version $Id: FetchMailImpl.java,v 1.1.2.6 2005/01/29 22:33:40 otsuka Exp $ - */ -public class FetchMailImpl implements FetchMail { - - /** デフォルトのSMTPサーバ。「localhost」 */ - public static final String DEFAULT_HOST = "localhost"; - - /** デフォルトのプロトコル。「pop3」 */ - public static final String DEFAULT_PROTOCOL = "pop3"; - - /** - * デフォルトのポート。「-1」
- * -1はプロトコルに応じた適切なポートを設定する特別な値。 - */ - public static final int DEFAULT_PORT = -1; - - private static final String INBOX_NAME = "INBOX"; - - private String host = DEFAULT_HOST; - - private String protocol = DEFAULT_PROTOCOL; - - private int port = DEFAULT_PORT; - - private String username; - - private String password; - - /** - * コンストラクタ。 - */ - public FetchMailImpl() {} - - /** - * @see com.ozacc.mail.fetch.FetchMail#getMails() - */ - public ReceivedMail[] getMails() throws MailException { - return getMails(false); - } - - /** - * @see com.ozacc.mail.fetch.FetchMail#getMails(boolean) - */ - public ReceivedMail[] getMails(boolean delete) throws MailException { - FetchMailProImpl fetchMailProImpl = createFetchMailProImpl(); - fetchMailProImpl.connect(); - try { - return fetchMailProImpl.getMails(delete); - } finally { - fetchMailProImpl.disconnect(); - } - } - - /** - * サーバ情報をセットしたFetchMailProImplインスタンスを生成します。 - * - * @return サーバ情報をセットしたFetchMailProImplインスタンス - */ - private FetchMailProImpl createFetchMailProImpl() { - FetchMailProImpl fmp = new FetchMailProImpl(); - fmp.setHost(host); - fmp.setPort(port); - fmp.setProtocol(protocol); - fmp.setUsername(username); - fmp.setPassword(password); - return fmp; - } - - /** - * メールサーバのホスト名、またはIPアドレスをセットします。 - * デフォルトは localhost です。 - * - * @param host メールサーバのホスト名、またはIPアドレス - */ - public void setHost(String host) { - this.host = host; - } - - /** - * メールサーバの認証パスワード名をセットします。 - * - * @param password メールサーバの認証パスワード - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * メール受信に使用するポート番号をセットします。 - * プロトコルに応じたポート番号が自動的に使用されますので、通常ここでポート番号をセットする必要はありません。 - * - * @param port ポート番号 - */ - public void setPort(int port) { - this.port = port; - } - - /** - * メール受信に使用するプロトコロルをセットします。 - * 現在サポートされているプロトコルは、「pop3」と「imap」の二つです。 - * デフォルトは「pop3」です。 - *

- * POP3サーバへの認証をAPOPで行いたい場合は、プロトコル名ではありませんが、 - * 「apop」を指定してください。APOP認証を使用するには、JavaMail 1.3.2以降が必要です。 - * - * @param protocol プロトコル - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * メールサーバの認証ユーザ名をセットします。 - * - * @param username メールサーバの認証ユーザ名 - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * メールサーバのホスト名、またはIPアドレスを返します。 - * - * @return メールサーバのホスト名、またはIPアドレス - */ - public String getHost() { - return host; - } - - /** - * メールサーバの認証パスワードを返します。 - * - * @return メールサーバの認証パスワード - */ - public String getPassword() { - return password; - } - - /** - * @return ポート番号 - */ - public int getPort() { - return port; - } - - /** - * メール受信に使用するプロトコロルをセットします。 - * - * @return プロトコル - */ - public String getProtocol() { - return protocol; - } - - /** - * メールサーバの認証ユーザ名を返します。 - * - * @return メールサーバの認証ユーザ名 - */ - public String getUsername() { - return username; - } +package com.ozacc.mail.fetch.impl; + +import com.ozacc.mail.MailException; +import com.ozacc.mail.fetch.FetchMail; +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * FetchMailインターフェースの実装クラス。 + *

+ * FetchMailProImplクラスに処理を委譲しています。 + * + * @since 1.2 + * @see FetchMailProImpl + * + * @author Tomohiro Otsuka + * @version $Id: FetchMailImpl.java,v 1.1.2.6 2005/01/29 22:33:40 otsuka Exp $ + */ +public class FetchMailImpl implements FetchMail { + + /** デフォルトのSMTPサーバ。「localhost」 */ + public static final String DEFAULT_HOST = "localhost"; + + /** デフォルトのプロトコル。「pop3」 */ + public static final String DEFAULT_PROTOCOL = "pop3"; + + /** + * デフォルトのポート。「-1」
+ * -1はプロトコルに応じた適切なポートを設定する特別な値。 + */ + public static final int DEFAULT_PORT = -1; + + private static final String INBOX_NAME = "INBOX"; + + private String host = DEFAULT_HOST; + + private String protocol = DEFAULT_PROTOCOL; + + private int port = DEFAULT_PORT; + + private String username; + + private String password; + + /** + * コンストラクタ。 + */ + public FetchMailImpl() {} + + /** + * @see com.ozacc.mail.fetch.FetchMail#getMails() + */ + public ReceivedMail[] getMails() throws MailException { + return getMails(false); + } + + /** + * @see com.ozacc.mail.fetch.FetchMail#getMails(boolean) + */ + public ReceivedMail[] getMails(boolean delete) throws MailException { + FetchMailProImpl fetchMailProImpl = createFetchMailProImpl(); + fetchMailProImpl.connect(); + try { + return fetchMailProImpl.getMails(delete); + } finally { + fetchMailProImpl.disconnect(); + } + } + + /** + * サーバ情報をセットしたFetchMailProImplインスタンスを生成します。 + * + * @return サーバ情報をセットしたFetchMailProImplインスタンス + */ + private FetchMailProImpl createFetchMailProImpl() { + FetchMailProImpl fmp = new FetchMailProImpl(); + fmp.setHost(host); + fmp.setPort(port); + fmp.setProtocol(protocol); + fmp.setUsername(username); + fmp.setPassword(password); + return fmp; + } + + /** + * メールサーバのホスト名、またはIPアドレスをセットします。 + * デフォルトは localhost です。 + * + * @param host メールサーバのホスト名、またはIPアドレス + */ + public void setHost(String host) { + this.host = host; + } + + /** + * メールサーバの認証パスワード名をセットします。 + * + * @param password メールサーバの認証パスワード + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * メール受信に使用するポート番号をセットします。 + * プロトコルに応じたポート番号が自動的に使用されますので、通常ここでポート番号をセットする必要はありません。 + * + * @param port ポート番号 + */ + public void setPort(int port) { + this.port = port; + } + + /** + * メール受信に使用するプロトコロルをセットします。 + * 現在サポートされているプロトコルは、「pop3」と「imap」の二つです。 + * デフォルトは「pop3」です。 + *

+ * POP3サーバへの認証をAPOPで行いたい場合は、プロトコル名ではありませんが、 + * 「apop」を指定してください。APOP認証を使用するには、JavaMail 1.3.2以降が必要です。 + * + * @param protocol プロトコル + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * メールサーバの認証ユーザ名をセットします。 + * + * @param username メールサーバの認証ユーザ名 + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * メールサーバのホスト名、またはIPアドレスを返します。 + * + * @return メールサーバのホスト名、またはIPアドレス + */ + public String getHost() { + return host; + } + + /** + * メールサーバの認証パスワードを返します。 + * + * @return メールサーバの認証パスワード + */ + public String getPassword() { + return password; + } + + /** + * @return ポート番号 + */ + public int getPort() { + return port; + } + + /** + * メール受信に使用するプロトコロルをセットします。 + * + * @return プロトコル + */ + public String getProtocol() { + return protocol; + } + + /** + * メールサーバの認証ユーザ名を返します。 + * + * @return メールサーバの認証ユーザ名 + */ + public String getUsername() { + return username; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/FetchMailProImpl.java b/src/main/java/com/ozacc/mail/fetch/impl/FetchMailProImpl.java old mode 100755 new mode 100644 index bb862ec..fe025d0 --- a/src/main/java/com/ozacc/mail/fetch/impl/FetchMailProImpl.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/FetchMailProImpl.java @@ -1,415 +1,415 @@ -package com.ozacc.mail.fetch.impl; - -import java.util.Properties; - -import javax.mail.AuthenticationFailedException; -import javax.mail.Flags; -import javax.mail.Folder; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.NoSuchProviderException; -import javax.mail.Session; -import javax.mail.Store; -import javax.mail.internet.MimeMessage; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.ozacc.mail.MailAuthenticationException; -import com.ozacc.mail.MailException; -import com.ozacc.mail.NotConnectedException; -import com.ozacc.mail.fetch.FetchMailPro; -import com.ozacc.mail.fetch.MailConverter; -import com.ozacc.mail.fetch.MailFetchException; -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * FetchMailインターフェースの実装クラス。 - *

- * このクラスのインスタンスは、インスタンス変数を用いて状態を保持するため、 - * ステートレスではありません。ステートフルです。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @author gaku - * @version $Id: FetchMailProImpl.java,v 1.1.2.13 2005/04/10 05:22:24 otsuka Exp $ - */ -public class FetchMailProImpl implements FetchMailPro { - - private static Log log = LogFactory.getLog(FetchMailProImpl.class); - - /** デフォルトのSMTPサーバ。「localhost」 */ - public static final String DEFAULT_HOST = "localhost"; - - /** デフォルトのプロトコル。「pop3」 */ - public static final String DEFAULT_PROTOCOL = "pop3"; - - /** - * デフォルトのポート。「-1」
- * -1はプロトコルに応じた適切なポートを設定する特別な値。 - */ - public static final int DEFAULT_PORT = -1; - - private static final String INBOX_NAME = "INBOX"; - - private String host = DEFAULT_HOST; - - private String protocol = DEFAULT_PROTOCOL; - - private int port = DEFAULT_PORT; - - private String username; - - private String password; - - private boolean javaMailLogEnabled; - - private Store store; - - private Folder currentFolder; - - /** MailConver の実装インスタンス。 */ - private MailConverter mailConverter = new MailConverterImpl(); - - /** - * コンストラクタ。 - */ - public FetchMailProImpl() { - System.setProperty("mail.mime.multipart.ignoremissingendboundary", "true"); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#connect() - */ - public synchronized void connect() throws MailException { - if (isConnected()) { - log.warn("既にサーバ[" + host + "]に接続されています。再接続するには先に接続を切断する必要があります。"); - return; - } - - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続します。"); - Session session = Session.getInstance(createProperties(), null); - if (javaMailLogEnabled) { - session.setDebug(true); - } - try { - store = session.getStore(protocol); - store.connect(host, port, username, password); - } catch (NoSuchProviderException e) { - log.error("指定されたプロトコル[" + protocol + "]はサポートされていません。", e); - throw new MailException("指定されたプロトコル[" + protocol + "]はサポートされていません。", e); - } catch (AuthenticationFailedException e) { - log.error(protocol.toUpperCase() + "サーバ[" + host + "]への接続認証に失敗しました。", e); - throw new MailAuthenticationException(protocol.toUpperCase() + "サーバ[" + host - + "]への接続認証に失敗しました。", e); - } catch (MessagingException e) { - log.error(protocol.toUpperCase() + "サーバ[" + host + "]への接続に失敗しました。", e); - throw new MailException(protocol.toUpperCase() + "サーバ[" + host + "]への接続に失敗しました。", e); - } - log.info(protocol.toUpperCase() + "サーバ[" + host + "]に接続しました。"); - - changeFolder(INBOX_NAME); - } - - /** - * Sessionに渡すPropertiesインスタンスを返します。 - * APOP認証を行う場合に、"mail.pop3.apop.enable"をセットします。 - * - * @return Sessionに渡すPropertiesインスタンス - */ - private Properties createProperties() { - Properties prop = new Properties(); - if ("apop".equalsIgnoreCase(protocol)) { - prop.put("mail.pop3.apop.enable", "true"); - } - return prop; - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#disconnect() - */ - public synchronized void disconnect() throws MailException { - try { - closeCurrentFolderIfOpen(); - } finally { - if (isConnected()) { - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断します。"); - try { - store.close(); - store = null; - } catch (MessagingException e) { - throw new MailException("サーバ[" + host + "]との接続切断に失敗しました。", e); - } - } - } - log.info(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断しました。"); - } - - /** - * 現在のメッセージフォルダをクローズします。 - * - * @throws MailException メッセージフォルダのクローズに失敗した場合 - */ - private void closeCurrentFolderIfOpen() throws MailException { - if (currentFolder != null && currentFolder.isOpen()) { - log.debug("メッセージフォルダ[" + currentFolder.getName() + "]をクローズします。"); - try { - currentFolder.close(true); - } catch (MessagingException e) { - log.error("メッセージフォルダ[" + currentFolder.getName() + "]のクローズに失敗しました。", e); - throw new MailException("メッセージフォルダ[" + currentFolder.getName() + "]のクローズに失敗しました。", - e); - } - log.debug("メッセージフォルダ[" + currentFolder.getName() + "]をクローズしました。"); - currentFolder = null; - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#changeFolder(java.lang.String) - */ - public synchronized void changeFolder(String folderName) throws MailException { - if (!isConnected()) { - log.warn("メールサーバに接続されていません。"); - return; - } - - closeCurrentFolderIfOpen(); - log.debug("メッセージフォルダ[" + folderName + "]をオープンします。"); - try { - currentFolder = store.getFolder(folderName); - currentFolder.open(Folder.READ_WRITE); - } catch (MessagingException e) { - log.error("メッセージフォルダ[" + folderName + "]のオープンに失敗しました。", e); - throw new MailException("メッセージフォルダ[" + folderName + "]のオープンに失敗しました。", e); - } - log.debug("メッセージフォルダ[" + folderName + "]をオープンしました。"); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMailCount() - */ - public int getMailCount() throws MailException { - checkIfCurrentFolderIsOpen(); - try { - return currentFolder.getMessageCount(); - } catch (MessagingException e) { - throw new MailFetchException("メール数の取得に失敗しました。", e); - } - } - - /** - * メールサーバに接続されていて、フォルダが操作できる状態かどうか調べます。 - * フォルダが操作できる状態にない場合、NotConnectedExceptionをスローします。 - * - * @throws NotConnectedException - */ - private void checkIfCurrentFolderIsOpen() throws NotConnectedException { - if (currentFolder == null || !currentFolder.isOpen()) { - throw new NotConnectedException(protocol.toUpperCase() + "サーバ[" + host + "]に接続されていません。"); - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int) - */ - public ReceivedMail getMail(int num) throws MailException { - return getMail(num, false); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int, boolean) - */ - public ReceivedMail getMail(int num, boolean delete) throws MailException { - MimeMessage mimeMessage = getMessage(num); - try { - mimeMessage.setFlag(Flags.Flag.DELETED, delete); - log.debug(num + "番目のメッセージにDELETEDフラグをセットしました。"); - } catch (MessagingException e) { - throw new MailException("DELETEDフラグのセットに失敗しました。", e); - } - return mailConverter.convertIntoMail(mimeMessage); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMails(boolean) - */ - public ReceivedMail[] getMails(boolean delete) throws MailException { - MimeMessage[] mimeMessages = getMessages(delete); - return mailConverter.convertIntoMails(mimeMessages); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMessage(int) - */ - public synchronized MimeMessage getMessage(int num) throws MailException { - checkIfCurrentFolderIsOpen(); - try { - return (MimeMessage)currentFolder.getMessage(num); - } catch (MessagingException e) { - log.error("メッセージの取得に失敗しました。", e); - throw new MailFetchException("メッセージの取得に失敗しました。", e); - } - } - - public synchronized MimeMessage[] getMessages(boolean delete) throws MailException { - checkIfCurrentFolderIsOpen(); - try { - Message[] messages = currentFolder.getMessages(); - if (log.isInfoEnabled()) { - if (messages.length > 0) { - log.info(messages.length + "通のメールを受信します。"); - } else { - log.info("受信するメールはありません。"); - } - } - // SEENフラグを立てる - currentFolder.setFlags(messages, new Flags(Flags.Flag.SEEN), true); - // DELETEDフラグを立てる - if (delete) { - currentFolder.setFlags(messages, new Flags(Flags.Flag.DELETED), true); - } - MimeMessage[] mimeMessages = new MimeMessage[messages.length]; - for (int i = 0; i < messages.length; i++) { - mimeMessages[i] = (MimeMessage)messages[i]; - } - return mimeMessages; - } catch (MessagingException e) { - log.error("メッセージの取得に失敗しました。", e); - throw new MailFetchException("メッセージの取得に失敗しました。", e); - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#isConnected() - */ - public boolean isConnected() { - return store != null && store.isConnected(); - } - - /** - * メールサーバのホスト名、またはIPアドレスを返します。 - * - * @return メールサーバのホスト名、またはIPアドレス - */ - public String getHost() { - return host; - } - - /** - * メールサーバのホスト名、またはIPアドレスをセットします。 - * デフォルトは localhost です。 - * - * @param host メールサーバのホスト名、またはIPアドレス - */ - public void setHost(String host) { - this.host = host; - } - - /** - * メールサーバの認証パスワードを返します。 - * - * @return メールサーバの認証パスワード - */ - public String getPassword() { - return password; - } - - /** - * メールサーバの認証パスワード名をセットします。 - * - * @param password メールサーバの認証パスワード - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * メール受信に使用するプロトコロルをセットします。 - * - * @return プロトコル - */ - public String getProtocol() { - return protocol; - } - - /** - * メール受信に使用するプロトコロルをセットします。 - * 現在サポートされているプロトコルは、「pop3」と「imap」の二つです。 - * デフォルトは「pop3」です。 - *

- * POP3サーバへの認証をAPOPで行いたい場合は、プロトコル名ではありませんが、 - * 「apop」を指定してください。APOP認証を使用するには、JavaMail 1.3.2以降が必要です。 - * - * @param protocol プロトコル - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * @return 認証ユーザ名 - */ - public String getUsername() { - return username; - } - - /** - * メールサーバの認証ユーザ名をセットします。 - * - * @param username 認証ユーザ名 - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * @return ポート番号 - */ - public int getPort() { - return port; - } - - /** - * メール受信に使用するポート番号をセットします。 - * プロトコルに応じたポート番号が自動的に使用されますので、通常ここでポート番号をセットする必要はありません。 - * - * @param port ポート番号 - */ - public void setPort(int port) { - this.port = port; - } - - /** - * JavaMailのデバッグが有効かどうか判定します。 - * - * @return JavaMailのデバッグが有効な場合 ture - */ - public boolean isJavaMailLogEnabled() { - return javaMailLogEnabled; - } - - /** - * JavaMailのデバッグを有効にするかどうか指定します。 - * 有効にすると、System.outのデバッグメッセージが出力されます。
- * デフォルトは無効になっています。 - * - * @see javax.mail.session#setDebug(boolean) - * @param javaMailLogEnabled The javaMailLogEnabled to set. - */ - public void setJavaMailLogEnabled(boolean javaMailLogEnabled) { - this.javaMailLogEnabled = javaMailLogEnabled; - } - - /** - * MailConveterインターフェースの実装インスタンスをセットします。 - * デフォルトでは、MailConverterImplが使用されます。 - * - * @see com.ozacc.mail.fetch.MailConveter - * @see com.ozacc.mail.fetch.impl.MailConveterImpl - * @param mailConverter MailConveterインターフェースの実装インスタンス - */ - public void setMailConverter(MailConverter mailConverter) { - this.mailConverter = mailConverter; - } +package com.ozacc.mail.fetch.impl; + +import java.util.Properties; + +import javax.mail.AuthenticationFailedException; +import javax.mail.Flags; +import javax.mail.Folder; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.NoSuchProviderException; +import javax.mail.Session; +import javax.mail.Store; +import javax.mail.internet.MimeMessage; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.ozacc.mail.MailAuthenticationException; +import com.ozacc.mail.MailException; +import com.ozacc.mail.NotConnectedException; +import com.ozacc.mail.fetch.FetchMailPro; +import com.ozacc.mail.fetch.MailConverter; +import com.ozacc.mail.fetch.MailFetchException; +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * FetchMailインターフェースの実装クラス。 + *

+ * このクラスのインスタンスは、インスタンス変数を用いて状態を保持するため、 + * ステートレスではありません。ステートフルです。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @author gaku + * @version $Id: FetchMailProImpl.java,v 1.1.2.13 2005/04/10 05:22:24 otsuka Exp $ + */ +public class FetchMailProImpl implements FetchMailPro { + + private static Log log = LogFactory.getLog(FetchMailProImpl.class); + + /** デフォルトのSMTPサーバ。「localhost」 */ + public static final String DEFAULT_HOST = "localhost"; + + /** デフォルトのプロトコル。「pop3」 */ + public static final String DEFAULT_PROTOCOL = "pop3"; + + /** + * デフォルトのポート。「-1」
+ * -1はプロトコルに応じた適切なポートを設定する特別な値。 + */ + public static final int DEFAULT_PORT = -1; + + private static final String INBOX_NAME = "INBOX"; + + private String host = DEFAULT_HOST; + + private String protocol = DEFAULT_PROTOCOL; + + private int port = DEFAULT_PORT; + + private String username; + + private String password; + + private boolean javaMailLogEnabled; + + private Store store; + + private Folder currentFolder; + + /** MailConver の実装インスタンス。 */ + private MailConverter mailConverter = new MailConverterImpl(); + + /** + * コンストラクタ。 + */ + public FetchMailProImpl() { + System.setProperty("mail.mime.multipart.ignoremissingendboundary", "true"); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#connect() + */ + public synchronized void connect() throws MailException { + if (isConnected()) { + log.warn("既にサーバ[" + host + "]に接続されています。再接続するには先に接続を切断する必要があります。"); + return; + } + + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続します。"); + Session session = Session.getInstance(createProperties(), null); + if (javaMailLogEnabled) { + session.setDebug(true); + } + try { + store = session.getStore(protocol); + store.connect(host, port, username, password); + } catch (NoSuchProviderException e) { + log.error("指定されたプロトコル[" + protocol + "]はサポートされていません。", e); + throw new MailException("指定されたプロトコル[" + protocol + "]はサポートされていません。", e); + } catch (AuthenticationFailedException e) { + log.error(protocol.toUpperCase() + "サーバ[" + host + "]への接続認証に失敗しました。", e); + throw new MailAuthenticationException(protocol.toUpperCase() + "サーバ[" + host + + "]への接続認証に失敗しました。", e); + } catch (MessagingException e) { + log.error(protocol.toUpperCase() + "サーバ[" + host + "]への接続に失敗しました。", e); + throw new MailException(protocol.toUpperCase() + "サーバ[" + host + "]への接続に失敗しました。", e); + } + log.info(protocol.toUpperCase() + "サーバ[" + host + "]に接続しました。"); + + changeFolder(INBOX_NAME); + } + + /** + * Sessionに渡すPropertiesインスタンスを返します。 + * APOP認証を行う場合に、"mail.pop3.apop.enable"をセットします。 + * + * @return Sessionに渡すPropertiesインスタンス + */ + private Properties createProperties() { + Properties prop = new Properties(); + if ("apop".equalsIgnoreCase(protocol)) { + prop.put("mail.pop3.apop.enable", "true"); + } + return prop; + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#disconnect() + */ + public synchronized void disconnect() throws MailException { + try { + closeCurrentFolderIfOpen(); + } finally { + if (isConnected()) { + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断します。"); + try { + store.close(); + store = null; + } catch (MessagingException e) { + throw new MailException("サーバ[" + host + "]との接続切断に失敗しました。", e); + } + } + } + log.info(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断しました。"); + } + + /** + * 現在のメッセージフォルダをクローズします。 + * + * @throws MailException メッセージフォルダのクローズに失敗した場合 + */ + private void closeCurrentFolderIfOpen() throws MailException { + if (currentFolder != null && currentFolder.isOpen()) { + log.debug("メッセージフォルダ[" + currentFolder.getName() + "]をクローズします。"); + try { + currentFolder.close(true); + } catch (MessagingException e) { + log.error("メッセージフォルダ[" + currentFolder.getName() + "]のクローズに失敗しました。", e); + throw new MailException("メッセージフォルダ[" + currentFolder.getName() + "]のクローズに失敗しました。", + e); + } + log.debug("メッセージフォルダ[" + currentFolder.getName() + "]をクローズしました。"); + currentFolder = null; + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#changeFolder(java.lang.String) + */ + public synchronized void changeFolder(String folderName) throws MailException { + if (!isConnected()) { + log.warn("メールサーバに接続されていません。"); + return; + } + + closeCurrentFolderIfOpen(); + log.debug("メッセージフォルダ[" + folderName + "]をオープンします。"); + try { + currentFolder = store.getFolder(folderName); + currentFolder.open(Folder.READ_WRITE); + } catch (MessagingException e) { + log.error("メッセージフォルダ[" + folderName + "]のオープンに失敗しました。", e); + throw new MailException("メッセージフォルダ[" + folderName + "]のオープンに失敗しました。", e); + } + log.debug("メッセージフォルダ[" + folderName + "]をオープンしました。"); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMailCount() + */ + public int getMailCount() throws MailException { + checkIfCurrentFolderIsOpen(); + try { + return currentFolder.getMessageCount(); + } catch (MessagingException e) { + throw new MailFetchException("メール数の取得に失敗しました。", e); + } + } + + /** + * メールサーバに接続されていて、フォルダが操作できる状態かどうか調べます。 + * フォルダが操作できる状態にない場合、NotConnectedExceptionをスローします。 + * + * @throws NotConnectedException + */ + private void checkIfCurrentFolderIsOpen() throws NotConnectedException { + if (currentFolder == null || !currentFolder.isOpen()) { + throw new NotConnectedException(protocol.toUpperCase() + "サーバ[" + host + "]に接続されていません。"); + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int) + */ + public ReceivedMail getMail(int num) throws MailException { + return getMail(num, false); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int, boolean) + */ + public ReceivedMail getMail(int num, boolean delete) throws MailException { + MimeMessage mimeMessage = getMessage(num); + try { + mimeMessage.setFlag(Flags.Flag.DELETED, delete); + log.debug(num + "番目のメッセージにDELETEDフラグをセットしました。"); + } catch (MessagingException e) { + throw new MailException("DELETEDフラグのセットに失敗しました。", e); + } + return mailConverter.convertIntoMail(mimeMessage); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMails(boolean) + */ + public ReceivedMail[] getMails(boolean delete) throws MailException { + MimeMessage[] mimeMessages = getMessages(delete); + return mailConverter.convertIntoMails(mimeMessages); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMessage(int) + */ + public synchronized MimeMessage getMessage(int num) throws MailException { + checkIfCurrentFolderIsOpen(); + try { + return (MimeMessage)currentFolder.getMessage(num); + } catch (MessagingException e) { + log.error("メッセージの取得に失敗しました。", e); + throw new MailFetchException("メッセージの取得に失敗しました。", e); + } + } + + public synchronized MimeMessage[] getMessages(boolean delete) throws MailException { + checkIfCurrentFolderIsOpen(); + try { + Message[] messages = currentFolder.getMessages(); + if (log.isInfoEnabled()) { + if (messages.length > 0) { + log.info(messages.length + "通のメールを受信します。"); + } else { + log.info("受信するメールはありません。"); + } + } + // SEENフラグを立てる + currentFolder.setFlags(messages, new Flags(Flags.Flag.SEEN), true); + // DELETEDフラグを立てる + if (delete) { + currentFolder.setFlags(messages, new Flags(Flags.Flag.DELETED), true); + } + MimeMessage[] mimeMessages = new MimeMessage[messages.length]; + for (int i = 0; i < messages.length; i++) { + mimeMessages[i] = (MimeMessage)messages[i]; + } + return mimeMessages; + } catch (MessagingException e) { + log.error("メッセージの取得に失敗しました。", e); + throw new MailFetchException("メッセージの取得に失敗しました。", e); + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#isConnected() + */ + public boolean isConnected() { + return store != null && store.isConnected(); + } + + /** + * メールサーバのホスト名、またはIPアドレスを返します。 + * + * @return メールサーバのホスト名、またはIPアドレス + */ + public String getHost() { + return host; + } + + /** + * メールサーバのホスト名、またはIPアドレスをセットします。 + * デフォルトは localhost です。 + * + * @param host メールサーバのホスト名、またはIPアドレス + */ + public void setHost(String host) { + this.host = host; + } + + /** + * メールサーバの認証パスワードを返します。 + * + * @return メールサーバの認証パスワード + */ + public String getPassword() { + return password; + } + + /** + * メールサーバの認証パスワード名をセットします。 + * + * @param password メールサーバの認証パスワード + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * メール受信に使用するプロトコロルをセットします。 + * + * @return プロトコル + */ + public String getProtocol() { + return protocol; + } + + /** + * メール受信に使用するプロトコロルをセットします。 + * 現在サポートされているプロトコルは、「pop3」と「imap」の二つです。 + * デフォルトは「pop3」です。 + *

+ * POP3サーバへの認証をAPOPで行いたい場合は、プロトコル名ではありませんが、 + * 「apop」を指定してください。APOP認証を使用するには、JavaMail 1.3.2以降が必要です。 + * + * @param protocol プロトコル + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return 認証ユーザ名 + */ + public String getUsername() { + return username; + } + + /** + * メールサーバの認証ユーザ名をセットします。 + * + * @param username 認証ユーザ名 + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * @return ポート番号 + */ + public int getPort() { + return port; + } + + /** + * メール受信に使用するポート番号をセットします。 + * プロトコルに応じたポート番号が自動的に使用されますので、通常ここでポート番号をセットする必要はありません。 + * + * @param port ポート番号 + */ + public void setPort(int port) { + this.port = port; + } + + /** + * JavaMailのデバッグが有効かどうか判定します。 + * + * @return JavaMailのデバッグが有効な場合 ture + */ + public boolean isJavaMailLogEnabled() { + return javaMailLogEnabled; + } + + /** + * JavaMailのデバッグを有効にするかどうか指定します。 + * 有効にすると、System.outのデバッグメッセージが出力されます。
+ * デフォルトは無効になっています。 + * + * @see javax.mail.session#setDebug(boolean) + * @param javaMailLogEnabled The javaMailLogEnabled to set. + */ + public void setJavaMailLogEnabled(boolean javaMailLogEnabled) { + this.javaMailLogEnabled = javaMailLogEnabled; + } + + /** + * MailConveterインターフェースの実装インスタンスをセットします。 + * デフォルトでは、MailConverterImplが使用されます。 + * + * @see com.ozacc.mail.fetch.MailConveter + * @see com.ozacc.mail.fetch.impl.MailConveterImpl + * @param mailConverter MailConveterインターフェースの実装インスタンス + */ + public void setMailConverter(MailConverter mailConverter) { + this.mailConverter = mailConverter; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/MailConverterImpl.java b/src/main/java/com/ozacc/mail/fetch/impl/MailConverterImpl.java old mode 100755 new mode 100644 index cb7e571..0ac7385 --- a/src/main/java/com/ozacc/mail/fetch/impl/MailConverterImpl.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/MailConverterImpl.java @@ -1,500 +1,500 @@ -package com.ozacc.mail.fetch.impl; - -import java.io.BufferedOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Date; -import java.util.Enumeration; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.mail.Address; -import javax.mail.Header; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.ozacc.mail.fetch.MailConverter; -import com.ozacc.mail.fetch.ReceivedMail; -import com.ozacc.mail.fetch.ReceivedMail.ReceivedHeader; -import com.ozacc.mail.fetch.impl.sk_jp.AttachmentsExtractor; -import com.ozacc.mail.fetch.impl.sk_jp.HtmlPartExtractor; -import com.ozacc.mail.fetch.impl.sk_jp.MailUtility; -import com.ozacc.mail.fetch.impl.sk_jp.MultipartUtility; - -/** - * MimeMessageからMailを生成するクラス。 - *

- * 変換時に生じたチェック例外は、このクラス内でキャッチされ無視されます。 - * 例外が生じた項目(差出人や宛先など)に該当するMailインスタンスのプロパティには何もセットされません。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @author gaku - * @version $Id: MailConverterImpl.java,v 1.1.2.3 2006/03/03 06:01:18 otsuka Exp $ - */ -public class MailConverterImpl implements MailConverter { - - private static final String ATTACHMENT_DIR_PREFIX = "OML_"; - - private static final String JAVA_IO_TMPDIR = "java.io.tmpdir"; - - private static Log log = LogFactory.getLog(MailConverterImpl.class); - - private static Pattern receivedHeaderPattern = Pattern.compile("^from (.+?) .*by (.+?) .*$"); - - /** - * 保存された添付ファイルの生存時間。デフォルトは12時間。 - */ - private long attachmentLifetime = 3600 * 1000 * 12; - - /** - * コンストラクタ。 - */ - public MailConverterImpl() {} - - /** - * @see com.ozacc.mail.fetch.MailConverter#convertIntoMails(javax.mail.internet.MimeMessage[]) - */ - public ReceivedMail[] convertIntoMails(MimeMessage[] messages) { - log.debug("計" + messages.length + "通のMimeMessageをMailに変換します。"); - ReceivedMail[] results = new ReceivedMail[messages.length]; - for (int i = 0; i < messages.length; i++) { - log.debug((i + 1) + "通目のMimeMessageをMailに変換します。"); - results[i] = convertIntoMail(messages[i]); - log.debug((i + 1) + "通目のMimeMessageをMailに変換しました。"); - log.debug(results[i].toString()); - } - log.debug("計" + messages.length + "通のMimeMessageをMailに変換しました。"); - return results; - } - - /** - * @param mm - * @param mail - */ - private void setReceivedHeaders(MimeMessage mm, ReceivedMail mail) { - String[] headerValues = null; - try { - headerValues = mm.getHeader("Received"); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - if (headerValues != null) { - for (int i = 0; i < headerValues.length; i++) { - String received = headerValues[i]; - // from で始まるものだけを抽出し、改行を削除 - if (received.startsWith("from")) { - received = received.replaceAll("\n", "").replaceAll("\\s+", " "); - log.debug("Received='" + received + "'"); - - Matcher m = receivedHeaderPattern.matcher(received); - if (m.matches()) { - String from = m.group(1); - String by = m.group(2); - log.debug("Sent from '" + from + "', Received by '" + by + "'"); - ReceivedHeader rh = new ReceivedHeader(from, by); - mail.addReceviedHeader(rh); - } - } - } - - } - } - - /** - * 指定されたMimeMessageに添付されているファイルを全て抽出し、 - * システムプロパティにセットされた一時ファイルディレクトリ内に保存した後、 - * そのファイルを指定されたReceivedMailにセットします。 - *

- * 保存された添付ファイルはJVM終了時に削除されます。 - * - * @param mm - * @param mail - */ - private void setAttachmentFiles(MimeMessage mm, ReceivedMail mail) { - try { - cleanTempDir(); - - AttachmentsExtractor ae = new AttachmentsExtractor( - AttachmentsExtractor.MODE_IGNORE_MESSAGE); - MultipartUtility.process(mm, ae); - for (int i = 0, num = ae.getCount(); i < num; i++) { - String fileName = ae.getFileName(i); - if (fileName == null || "".equals(fileName)) { - fileName = "attachment" + (i + 1) + ".tmp"; - } - String path = getTempDirPath() + File.separator + ATTACHMENT_DIR_PREFIX - + System.currentTimeMillis() + File.separator + fileName; - log.debug((i + 1) + "個目の添付ファイルを保存します。[" + path + "]"); - File f = new File(path); - f.getParentFile().mkdirs(); - InputStream is = ae.getInputStream(i); - try { - writeTo(f, is); - } finally { - if (is != null) { - is.close(); - } - } - - f.getParentFile().deleteOnExit(); - f.deleteOnExit(); - - mail.addFile(f, fileName); - log.debug((i + 1) + "個目の添付ファイルを保存しました。[" + path + "]"); - } - } catch (IOException e) { - log.error("添付ファイルの取得に失敗しました。", e); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - } - - /** - * 一時ディレクトリ内に保存された添付ファイルの内、生存時間を越えているものを削除します。 - */ - private void cleanTempDir() { - File tempDir = new File(getTempDirPath()); - File[] omlDirs = tempDir.listFiles(new FilenameFilter() { - - public boolean accept(File dir, String name) { - return name.startsWith(ATTACHMENT_DIR_PREFIX); - } - }); - log.debug("現在" + omlDirs.length + "個の添付ファイル用ディレクトリ[" + tempDir.getAbsolutePath() - + "]が一時ディレクトリに存在します。"); - long now = System.currentTimeMillis(); - for (int i = 0; i < omlDirs.length; i++) { - File dir = omlDirs[i]; - log.debug(dir.lastModified() + ""); - if (now - dir.lastModified() >= attachmentLifetime) { - deleteDir(dir); - } - } - } - - /** - * 一時ディレクトリのパスを返します。 - * - * @return 一時ディレクトリのパス - */ - private String getTempDirPath() { - return System.getProperty(JAVA_IO_TMPDIR); - } - - /** - * 指定されたディレクトリを中身のファイルを含めて削除します。 - * - * @param dir 削除するディレクトリ - */ - private void deleteDir(File dir) { - File[] files = dir.listFiles(); - for (int i = 0; i < files.length; i++) { - File f = files[i]; - f.delete(); - } - dir.delete(); - } - - /** - * 指定されたInputStreamデータを指定されたファイルに保存します。 - * - * @param destFile 保存するファイル - * @param is ソースとなるInputStream - * @throws FileNotFoundException - * @throws IOException - */ - private void writeTo(File destFile, InputStream is) throws FileNotFoundException, IOException { - BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile), - 1024 * 50); - try { - copy(is, bos); - } finally { - if (bos != null) { - bos.close(); - } - } - } - - private static void copy(InputStream in, OutputStream out) throws IOException { - byte[] buffer = new byte[1024 * 4]; - int n = 0; - while (-1 != (n = in.read(buffer))) { - out.write(buffer, 0, n); - } - } - - /** - * 指定されたMimeMessageからX-Header、References、In-Reply-Toヘッダを解析し、 - * 指定されたReceivedMailにセットします。 - * - * @param mm - * @param mail - */ - private void setXHeaders(MimeMessage mm, ReceivedMail mail) { - log.debug("X-HeaderをMailにセットします。"); - Enumeration headerEnum = null; - try { - headerEnum = mm.getAllHeaders(); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - while (headerEnum != null && headerEnum.hasMoreElements()) { - Header header = (Header)headerEnum.nextElement(); - if (header.getName().startsWith("X-") - || "References".equalsIgnoreCase(header.getName()) - || "In-Reply-To".equalsIgnoreCase(header.getName())) { - mail.addHeader(header.getName(), header.getValue()); - log.debug(header.getName() + "をMailにセットしました。[" + header.getName() + "='" - + header.getValue() + "']"); - } - } - } - - private void setReplyToAddress(MimeMessage mm, ReceivedMail mail) { - log.debug("Reply-ToアドレスをMailにセットします。"); - Address[] addresses = null; - try { - addresses = mm.getReplyTo(); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - if (addresses != null) { - log.debug(addresses.length + "つのReply-Toアドレスが見つかりました。最初のアドレスのみ取得されます。"); - for (int j = 0; j < addresses.length; j++) { - Address address = addresses[j]; - mail.setReplyTo((InternetAddress)address); - break; - } - } else { - log.debug("Reply-Toアドレスは見つかりませんでした。"); - } - } - - /** - * メールの容量(byte)をMimeMessageから取得してReceivedMailにセットします。 - * 取得に失敗した場合は -1 をセットします。 - * - * @param mm - * @param mail - */ - private void setSize(MimeMessage mm, ReceivedMail mail) { - try { - mail.setSize(mm.getSize()); - } catch (MessagingException e) { - mail.setSize(-1); - } - } - - /** - * @param mm - * @param mail - * @throws MessagingException - */ - private void setHtmlText(MimeMessage mm, ReceivedMail mail) { - try { - HtmlPartExtractor hpe = new HtmlPartExtractor(); - MultipartUtility.process(mm, hpe); - String htmlText = hpe.getHtml(); - mail.setHtmlText(htmlText); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - } - - private void setText(MimeMessage mm, ReceivedMail mail) { - try { - String text = MultipartUtility.getPlainText(mm); - mail.setText(text); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - } - - private void setMessageId(MimeMessage mm, ReceivedMail mail) { - try { - String messageId = mm.getMessageID(); - mail.setMessageId(messageId); - log.debug("Message-IDをMailにセットしました。[Message-ID='" + messageId + "']"); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - } - - /** - * 指定されたMimeMessageから件名を取得し、ReceivedMailにセットします。 - * sk_jpのMailUtility.decodeText()メソッドを用いて、件名の文字化けを回避します。 - * - * @param mm - * @param mail - */ - private void setSubject(MimeMessage mm, ReceivedMail mail) { - try { - String subject = MailUtility.decodeText(mm.getSubject()); - mail.setSubject(subject); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - } - - private void setDate(MimeMessage mm, ReceivedMail mail) { - try { - Date d = mm.getSentDate(); - mail.setDate(d); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - } - - /** - * Return-Pathアドレスは必ずしもセットされてはいません。 - * 特にspam系のメールでは不正なフォーマットのメールアドレスが - * セットされている場合もあるので要注意。 - * - * @param mm - * @param mail - */ - private void setReturnPath(MimeMessage mm, ReceivedMail mail) { - log.debug("Return-Pathアドレスを検出します。"); - String[] returnPath = null; - try { - returnPath = mm.getHeader("Return-Path"); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - if (returnPath != null && returnPath.length > 0) { - String email = returnPath[0].substring(1, returnPath[0].length() - 1); - if (email.length() > 0) { - try { - mail.setReturnPath(email); - log.debug("Return-PathアドレスをMailにセットしました。[Return-Path='" + email + "']"); - } catch (IllegalArgumentException e) { - log.warn("Return-Pathアドレスが不正なメールアドレスフォーマットです。[Return-Path='" + email + "']"); - } - } else { - log.debug("Return-Pathアドレスは見つかりませんでした。"); - } - } else { - log.debug("Return-Pathアドレスは見つかりませんでした。"); - } - } - - private void setFromAddress(MimeMessage mm, ReceivedMail mail) { - log.debug("Fromアドレスを検出します。"); - Address[] addresses = null; - try { - addresses = mm.getFrom(); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - if (addresses != null) { - log.debug(addresses.length + "つのFromアドレスが見つかりました。"); - for (int j = 0; j < addresses.length; j++) { - InternetAddress address = (InternetAddress)addresses[j]; - mail.setFrom(address); - log.debug("FromアドレスをMailにセットしました。[From='" + address.toUnicodeString() + "']"); - } - } else { - log.debug("Fromアドレスは見つかりませんでした。"); - } - } - - private void setRecipientAddresses(MimeMessage mm, ReceivedMail mail) { - /* - * TOアドレスのパース - */ - log.debug("Toアドレスを検出します。"); - Address[] toAddresses = null; - try { - toAddresses = mm.getRecipients(Message.RecipientType.TO); - } catch (AddressException e) { - log.warn("不正なメールアドレスが検出されました。[" + e.getRef() + "]"); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - if (toAddresses != null) { - log.debug(toAddresses.length + "つのToアドレスが見つかりました。"); - for (int j = 0; j < toAddresses.length; j++) { - InternetAddress address = (InternetAddress)toAddresses[j]; - mail.addTo(address); - log.debug("ToアドレスをMailにセットしました。[To='" + address.toUnicodeString() + "']"); - } - } else { - log.debug("Toアドレスは見つかりませんでした。"); - } - - /* - * CCアドレスのパース - */ - log.debug("Ccアドレスを検出します。"); - Address[] ccAddresses = null; - try { - ccAddresses = mm.getRecipients(Message.RecipientType.CC); - } catch (AddressException e) { - log.warn("不正なメールアドレスが検出されました。[" + e.getRef() + "]"); - } catch (MessagingException e) { - // ignore - log.warn(e.getMessage()); - } - if (ccAddresses != null) { - log.debug(ccAddresses.length + "つのCcアドレスが見つかりました。"); - for (int j = 0; j < ccAddresses.length; j++) { - InternetAddress address = (InternetAddress)ccAddresses[j]; - mail.addCc(address); - log.debug("CcアドレスをMailにセットしました。[Cc='" + address.toUnicodeString() + "']"); - } - } else { - log.debug("Ccアドレスは見つかりませんでした。"); - } - } - - /** - * @see com.ozacc.mail.fetch.MailConverter#convertIntoMail(javax.mail.internet.MimeMessage) - */ - public ReceivedMail convertIntoMail(MimeMessage mm) { - ReceivedMail mail = createReceivedMail(); - setReturnPath(mm, mail); - setReceivedHeaders(mm, mail); - setDate(mm, mail); - setFromAddress(mm, mail); - setRecipientAddresses(mm, mail); - setMessageId(mm, mail); - setReplyToAddress(mm, mail); - setSubject(mm, mail); - setXHeaders(mm, mail); - setText(mm, mail); - setHtmlText(mm, mail); - setAttachmentFiles(mm, mail); - setSize(mm, mail); - mail.setMessage(mm); - return mail; - } - - protected ReceivedMail createReceivedMail() { - return new ReceivedMail(); - } - +package com.ozacc.mail.fetch.impl; + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FilenameFilter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.Date; +import java.util.Enumeration; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.mail.Address; +import javax.mail.Header; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.internet.AddressException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.ozacc.mail.fetch.MailConverter; +import com.ozacc.mail.fetch.ReceivedMail; +import com.ozacc.mail.fetch.ReceivedMail.ReceivedHeader; +import com.ozacc.mail.fetch.impl.sk_jp.AttachmentsExtractor; +import com.ozacc.mail.fetch.impl.sk_jp.HtmlPartExtractor; +import com.ozacc.mail.fetch.impl.sk_jp.MailUtility; +import com.ozacc.mail.fetch.impl.sk_jp.MultipartUtility; + +/** + * MimeMessageからMailを生成するクラス。 + *

+ * 変換時に生じたチェック例外は、このクラス内でキャッチされ無視されます。 + * 例外が生じた項目(差出人や宛先など)に該当するMailインスタンスのプロパティには何もセットされません。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @author gaku + * @version $Id: MailConverterImpl.java,v 1.1.2.3 2006/03/03 06:01:18 otsuka Exp $ + */ +public class MailConverterImpl implements MailConverter { + + private static final String ATTACHMENT_DIR_PREFIX = "OML_"; + + private static final String JAVA_IO_TMPDIR = "java.io.tmpdir"; + + private static Log log = LogFactory.getLog(MailConverterImpl.class); + + private static Pattern receivedHeaderPattern = Pattern.compile("^from (.+?) .*by (.+?) .*$"); + + /** + * 保存された添付ファイルの生存時間。デフォルトは12時間。 + */ + private long attachmentLifetime = 3600 * 1000 * 12; + + /** + * コンストラクタ。 + */ + public MailConverterImpl() {} + + /** + * @see com.ozacc.mail.fetch.MailConverter#convertIntoMails(javax.mail.internet.MimeMessage[]) + */ + public ReceivedMail[] convertIntoMails(MimeMessage[] messages) { + log.debug("計" + messages.length + "通のMimeMessageをMailに変換します。"); + ReceivedMail[] results = new ReceivedMail[messages.length]; + for (int i = 0; i < messages.length; i++) { + log.debug((i + 1) + "通目のMimeMessageをMailに変換します。"); + results[i] = convertIntoMail(messages[i]); + log.debug((i + 1) + "通目のMimeMessageをMailに変換しました。"); + log.debug(results[i].toString()); + } + log.debug("計" + messages.length + "通のMimeMessageをMailに変換しました。"); + return results; + } + + /** + * @param mm + * @param mail + */ + private void setReceivedHeaders(MimeMessage mm, ReceivedMail mail) { + String[] headerValues = null; + try { + headerValues = mm.getHeader("Received"); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + if (headerValues != null) { + for (int i = 0; i < headerValues.length; i++) { + String received = headerValues[i]; + // from で始まるものだけを抽出し、改行を削除 + if (received.startsWith("from")) { + received = received.replaceAll("\n", "").replaceAll("\\s+", " "); + log.debug("Received='" + received + "'"); + + Matcher m = receivedHeaderPattern.matcher(received); + if (m.matches()) { + String from = m.group(1); + String by = m.group(2); + log.debug("Sent from '" + from + "', Received by '" + by + "'"); + ReceivedHeader rh = new ReceivedHeader(from, by); + mail.addReceviedHeader(rh); + } + } + } + + } + } + + /** + * 指定されたMimeMessageに添付されているファイルを全て抽出し、 + * システムプロパティにセットされた一時ファイルディレクトリ内に保存した後、 + * そのファイルを指定されたReceivedMailにセットします。 + *

+ * 保存された添付ファイルはJVM終了時に削除されます。 + * + * @param mm + * @param mail + */ + private void setAttachmentFiles(MimeMessage mm, ReceivedMail mail) { + try { + cleanTempDir(); + + AttachmentsExtractor ae = new AttachmentsExtractor( + AttachmentsExtractor.MODE_IGNORE_MESSAGE); + MultipartUtility.process(mm, ae); + for (int i = 0, num = ae.getCount(); i < num; i++) { + String fileName = ae.getFileName(i); + if (fileName == null || "".equals(fileName)) { + fileName = "attachment" + (i + 1) + ".tmp"; + } + String path = getTempDirPath() + File.separator + ATTACHMENT_DIR_PREFIX + + System.currentTimeMillis() + File.separator + fileName; + log.debug((i + 1) + "個目の添付ファイルを保存します。[" + path + "]"); + File f = new File(path); + f.getParentFile().mkdirs(); + InputStream is = ae.getInputStream(i); + try { + writeTo(f, is); + } finally { + if (is != null) { + is.close(); + } + } + + f.getParentFile().deleteOnExit(); + f.deleteOnExit(); + + mail.addFile(f, fileName); + log.debug((i + 1) + "個目の添付ファイルを保存しました。[" + path + "]"); + } + } catch (IOException e) { + log.error("添付ファイルの取得に失敗しました。", e); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + } + + /** + * 一時ディレクトリ内に保存された添付ファイルの内、生存時間を越えているものを削除します。 + */ + private void cleanTempDir() { + File tempDir = new File(getTempDirPath()); + File[] omlDirs = tempDir.listFiles(new FilenameFilter() { + + public boolean accept(File dir, String name) { + return name.startsWith(ATTACHMENT_DIR_PREFIX); + } + }); + log.debug("現在" + omlDirs.length + "個の添付ファイル用ディレクトリ[" + tempDir.getAbsolutePath() + + "]が一時ディレクトリに存在します。"); + long now = System.currentTimeMillis(); + for (int i = 0; i < omlDirs.length; i++) { + File dir = omlDirs[i]; + log.debug(dir.lastModified() + ""); + if (now - dir.lastModified() >= attachmentLifetime) { + deleteDir(dir); + } + } + } + + /** + * 一時ディレクトリのパスを返します。 + * + * @return 一時ディレクトリのパス + */ + private String getTempDirPath() { + return System.getProperty(JAVA_IO_TMPDIR); + } + + /** + * 指定されたディレクトリを中身のファイルを含めて削除します。 + * + * @param dir 削除するディレクトリ + */ + private void deleteDir(File dir) { + File[] files = dir.listFiles(); + for (int i = 0; i < files.length; i++) { + File f = files[i]; + f.delete(); + } + dir.delete(); + } + + /** + * 指定されたInputStreamデータを指定されたファイルに保存します。 + * + * @param destFile 保存するファイル + * @param is ソースとなるInputStream + * @throws FileNotFoundException + * @throws IOException + */ + private void writeTo(File destFile, InputStream is) throws FileNotFoundException, IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destFile), + 1024 * 50); + try { + copy(is, bos); + } finally { + if (bos != null) { + bos.close(); + } + } + } + + private static void copy(InputStream in, OutputStream out) throws IOException { + byte[] buffer = new byte[1024 * 4]; + int n = 0; + while (-1 != (n = in.read(buffer))) { + out.write(buffer, 0, n); + } + } + + /** + * 指定されたMimeMessageからX-Header、References、In-Reply-Toヘッダを解析し、 + * 指定されたReceivedMailにセットします。 + * + * @param mm + * @param mail + */ + private void setXHeaders(MimeMessage mm, ReceivedMail mail) { + log.debug("X-HeaderをMailにセットします。"); + Enumeration headerEnum = null; + try { + headerEnum = mm.getAllHeaders(); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + while (headerEnum != null && headerEnum.hasMoreElements()) { + Header header = (Header)headerEnum.nextElement(); + if (header.getName().startsWith("X-") + || "References".equalsIgnoreCase(header.getName()) + || "In-Reply-To".equalsIgnoreCase(header.getName())) { + mail.addHeader(header.getName(), header.getValue()); + log.debug(header.getName() + "をMailにセットしました。[" + header.getName() + "='" + + header.getValue() + "']"); + } + } + } + + private void setReplyToAddress(MimeMessage mm, ReceivedMail mail) { + log.debug("Reply-ToアドレスをMailにセットします。"); + Address[] addresses = null; + try { + addresses = mm.getReplyTo(); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + if (addresses != null) { + log.debug(addresses.length + "つのReply-Toアドレスが見つかりました。最初のアドレスのみ取得されます。"); + for (int j = 0; j < addresses.length; j++) { + Address address = addresses[j]; + mail.setReplyTo((InternetAddress)address); + break; + } + } else { + log.debug("Reply-Toアドレスは見つかりませんでした。"); + } + } + + /** + * メールの容量(byte)をMimeMessageから取得してReceivedMailにセットします。 + * 取得に失敗した場合は -1 をセットします。 + * + * @param mm + * @param mail + */ + private void setSize(MimeMessage mm, ReceivedMail mail) { + try { + mail.setSize(mm.getSize()); + } catch (MessagingException e) { + mail.setSize(-1); + } + } + + /** + * @param mm + * @param mail + * @throws MessagingException + */ + private void setHtmlText(MimeMessage mm, ReceivedMail mail) { + try { + HtmlPartExtractor hpe = new HtmlPartExtractor(); + MultipartUtility.process(mm, hpe); + String htmlText = hpe.getHtml(); + mail.setHtmlText(htmlText); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + } + + private void setText(MimeMessage mm, ReceivedMail mail) { + try { + String text = MultipartUtility.getPlainText(mm); + mail.setText(text); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + } + + private void setMessageId(MimeMessage mm, ReceivedMail mail) { + try { + String messageId = mm.getMessageID(); + mail.setMessageId(messageId); + log.debug("Message-IDをMailにセットしました。[Message-ID='" + messageId + "']"); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + } + + /** + * 指定されたMimeMessageから件名を取得し、ReceivedMailにセットします。 + * sk_jpのMailUtility.decodeText()メソッドを用いて、件名の文字化けを回避します。 + * + * @param mm + * @param mail + */ + private void setSubject(MimeMessage mm, ReceivedMail mail) { + try { + String subject = MailUtility.decodeText(mm.getSubject()); + mail.setSubject(subject); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + } + + private void setDate(MimeMessage mm, ReceivedMail mail) { + try { + Date d = mm.getSentDate(); + mail.setDate(d); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + } + + /** + * Return-Pathアドレスは必ずしもセットされてはいません。 + * 特にspam系のメールでは不正なフォーマットのメールアドレスが + * セットされている場合もあるので要注意。 + * + * @param mm + * @param mail + */ + private void setReturnPath(MimeMessage mm, ReceivedMail mail) { + log.debug("Return-Pathアドレスを検出します。"); + String[] returnPath = null; + try { + returnPath = mm.getHeader("Return-Path"); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + if (returnPath != null && returnPath.length > 0) { + String email = returnPath[0].substring(1, returnPath[0].length() - 1); + if (email.length() > 0) { + try { + mail.setReturnPath(email); + log.debug("Return-PathアドレスをMailにセットしました。[Return-Path='" + email + "']"); + } catch (IllegalArgumentException e) { + log.warn("Return-Pathアドレスが不正なメールアドレスフォーマットです。[Return-Path='" + email + "']"); + } + } else { + log.debug("Return-Pathアドレスは見つかりませんでした。"); + } + } else { + log.debug("Return-Pathアドレスは見つかりませんでした。"); + } + } + + private void setFromAddress(MimeMessage mm, ReceivedMail mail) { + log.debug("Fromアドレスを検出します。"); + Address[] addresses = null; + try { + addresses = mm.getFrom(); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + if (addresses != null) { + log.debug(addresses.length + "つのFromアドレスが見つかりました。"); + for (int j = 0; j < addresses.length; j++) { + InternetAddress address = (InternetAddress)addresses[j]; + mail.setFrom(address); + log.debug("FromアドレスをMailにセットしました。[From='" + address.toUnicodeString() + "']"); + } + } else { + log.debug("Fromアドレスは見つかりませんでした。"); + } + } + + private void setRecipientAddresses(MimeMessage mm, ReceivedMail mail) { + /* + * TOアドレスのパース + */ + log.debug("Toアドレスを検出します。"); + Address[] toAddresses = null; + try { + toAddresses = mm.getRecipients(Message.RecipientType.TO); + } catch (AddressException e) { + log.warn("不正なメールアドレスが検出されました。[" + e.getRef() + "]"); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + if (toAddresses != null) { + log.debug(toAddresses.length + "つのToアドレスが見つかりました。"); + for (int j = 0; j < toAddresses.length; j++) { + InternetAddress address = (InternetAddress)toAddresses[j]; + mail.addTo(address); + log.debug("ToアドレスをMailにセットしました。[To='" + address.toUnicodeString() + "']"); + } + } else { + log.debug("Toアドレスは見つかりませんでした。"); + } + + /* + * CCアドレスのパース + */ + log.debug("Ccアドレスを検出します。"); + Address[] ccAddresses = null; + try { + ccAddresses = mm.getRecipients(Message.RecipientType.CC); + } catch (AddressException e) { + log.warn("不正なメールアドレスが検出されました。[" + e.getRef() + "]"); + } catch (MessagingException e) { + // ignore + log.warn(e.getMessage()); + } + if (ccAddresses != null) { + log.debug(ccAddresses.length + "つのCcアドレスが見つかりました。"); + for (int j = 0; j < ccAddresses.length; j++) { + InternetAddress address = (InternetAddress)ccAddresses[j]; + mail.addCc(address); + log.debug("CcアドレスをMailにセットしました。[Cc='" + address.toUnicodeString() + "']"); + } + } else { + log.debug("Ccアドレスは見つかりませんでした。"); + } + } + + /** + * @see com.ozacc.mail.fetch.MailConverter#convertIntoMail(javax.mail.internet.MimeMessage) + */ + public ReceivedMail convertIntoMail(MimeMessage mm) { + ReceivedMail mail = createReceivedMail(); + setReturnPath(mm, mail); + setReceivedHeaders(mm, mail); + setDate(mm, mail); + setFromAddress(mm, mail); + setRecipientAddresses(mm, mail); + setMessageId(mm, mail); + setReplyToAddress(mm, mail); + setSubject(mm, mail); + setXHeaders(mm, mail); + setText(mm, mail); + setHtmlText(mm, mail); + setAttachmentFiles(mm, mail); + setSize(mm, mail); + mail.setMessage(mm); + return mail; + } + + protected ReceivedMail createReceivedMail() { + return new ReceivedMail(); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/package.html b/src/main/java/com/ozacc/mail/fetch/impl/package.html old mode 100755 new mode 100644 index bfb996d..07f12fb --- a/src/main/java/com/ozacc/mail/fetch/impl/package.html +++ b/src/main/java/com/ozacc/mail/fetch/impl/package.html @@ -1,5 +1,5 @@ - - -com.ozacc.mail.fetch¥Ñ¥Ã¥±¡¼¥¸¤Î¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤ò¼ÂÁõ¤·¤¿¥¯¥é¥¹¤òÄ󶡤·¤Þ¤¹¡£ - + + +com.ozacc.mail.fetchパッケージのインターフェースを実装したクラスを提供します。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/AttachmentsExtractor.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/AttachmentsExtractor.java old mode 100755 new mode 100644 index dd86ac5..0a68b58 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/AttachmentsExtractor.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/AttachmentsExtractor.java @@ -1,169 +1,169 @@ -/* - * @(#) $Id: AttachmentsExtractor.java,v 1.1.2.2 2005/09/25 12:51:38 otsuka Exp $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; -import javax.mail.MessagingException; -import javax.mail.Part; -import javax.mail.internet.ContentType; - -/** - * 添付ファイルを抽出するPartHandlerです。 - *

- * MultipartUtility#process()呼び出し後にgetFileNames()によって、 添付ファイル名の配列を得ることができます。 - *

- *

- * ファイル名配列のindexを指定してその添付ファイルに対する - * InputStreamを得たり、渡されたOutputStreamに対して書き出すことができます。 - *

- * @version $Revision: 1.1.2.2 $ $Date: 2005/09/25 12:51:38 $ - * @author Shin - */ -public class AttachmentsExtractor implements PartHandler { - - /** message/*のパートを無視します。 */ - public static final int MODE_IGNORE_MESSAGE = 1; - - /** Content-Disposition: inline; パートはfilenameがあっても無視します。 */ - public static final int MODE_IGNORE_INLINE = 2; - - private final int mode; - - private final List attachmentParts = new ArrayList(); - - /** - * 添付ファイル一覧を得るためのPartHandlerを作成します。 message/*のパートやinline且つファイル名指定ありのパートも - * 添付ファイルとして扱います。 - */ - public AttachmentsExtractor() { - this(0); - } - - /** - * 添付ファイル一覧を得るためのPartHandlerを作成します。 - * @param mode 動作モード。MODE_で始まる識別子をor指定します。 - */ - public AttachmentsExtractor(int mode) { - this.mode = mode; - } - - /** MultipartUtility#process()から呼びだされるメソッドです。 */ - public boolean processPart(Part part, ContentType context) throws MessagingException, - IOException { - // Apple Mail対策 - if (part.getContentType().indexOf("application/applefile") != -1) { - return true; - } - - if (part.isMimeType("message/*")) { - if ((mode & MODE_IGNORE_MESSAGE) != 0) { - return true; - } - attachmentParts.add(part); - return true; - } - if (MailUtility.getFileName(part) == null) { - return true; - } - if ((mode & MODE_IGNORE_INLINE) != 0 && Part.INLINE.equalsIgnoreCase(part.getDisposition())) { - return true; - } - - attachmentParts.add(part); - return true; - } - - /** - * 添付ファイル個数を返します。 - */ - public int getCount() { - return attachmentParts.size(); - } - - /** - * 添付ファイル名の配列を返します。 - *

- * 添付ファイルが存在しない場合は空の配列を返します。
- * ファイル名は同一のものが複数存在する事もありえます。 - *

- */ - public String[] getFileNames() throws MessagingException { - String[] names = new String[getCount()]; - for (int i = 0; i < names.length; i++) { - names[i] = getFileName(i); - } - return names; - } - - /** - * 指定添付ファイルのファイル名を返します。 - */ - public String getFileName(int index) throws MessagingException { - Part part = (Part)attachmentParts.get(index); - String name = MailUtility.getFileName(part); - if (name == null) { - // 添付ファイル名が取得できない場合は、指定されていなかった場合か、 - // あるいはmessage/*のパートの場合です。 - // この場合は仮のファイル名を付けることとします。 - if (part.isMimeType("message/*")) { - // If part is Message, create temporary filename. - name = "message" + index + ".eml"; - } else { - name = "file" + index + ".tmp"; - } - } - return name; - } - - /** - * 指定添付ファイルのContent-Typeを返します。 - */ - public String getContentType(int index) throws MessagingException { - return MailUtility.unfold(((Part)attachmentParts.get(index)).getContentType()); - } - - /** - * 指定添付ファイルのサイズを返します。 - */ - public int getSize(int index) throws MessagingException { - return ((Part)attachmentParts.get(index)).getSize(); - } - - /** - * 指定添付ファイルを読み込むストリームを返します。 - */ - public InputStream getInputStream(int index) throws MessagingException, IOException { - return ((Part)attachmentParts.get(index)).getInputStream(); - } - - /** - * 指定添付ファイルを指定ストリームに書き出します。 - */ - public void writeTo(int index, OutputStream out) throws MessagingException, IOException { - InputStream in = getInputStream(index); - byte[] buf = new byte[1024]; - int len; - while ((len = in.read(buf)) != -1) { - out.write(buf, 0, len); - } - } - - public static void main(String[] args) throws Exception { - javax.mail.internet.MimeMessage msg = new javax.mail.internet.MimeMessage( - javax.mail.Session.getDefaultInstance(System.getProperties(), null), System.in); - AttachmentsExtractor h = new AttachmentsExtractor(); - MultipartUtility.process(msg, h); - for (int i = 0; i < h.getCount(); i++) { - System.out.println("Attachment no : " + i); - System.out.println("Filename = " + h.getFileName(i)); - System.out.println("******************"); - h.writeTo(i, System.out); - } - } +/* + * @(#) $Id: AttachmentsExtractor.java,v 1.1.2.2 2005/09/25 12:51:38 otsuka Exp $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; +import javax.mail.MessagingException; +import javax.mail.Part; +import javax.mail.internet.ContentType; + +/** + * 添付ファイルを抽出するPartHandlerです。 + *

+ * MultipartUtility#process()呼び出し後にgetFileNames()によって、 添付ファイル名の配列を得ることができます。 + *

+ *

+ * ファイル名配列のindexを指定してその添付ファイルに対する + * InputStreamを得たり、渡されたOutputStreamに対して書き出すことができます。 + *

+ * @version $Revision: 1.1.2.2 $ $Date: 2005/09/25 12:51:38 $ + * @author Shin + */ +public class AttachmentsExtractor implements PartHandler { + + /** message/*のパートを無視します。 */ + public static final int MODE_IGNORE_MESSAGE = 1; + + /** Content-Disposition: inline; パートはfilenameがあっても無視します。 */ + public static final int MODE_IGNORE_INLINE = 2; + + private final int mode; + + private final List attachmentParts = new ArrayList(); + + /** + * 添付ファイル一覧を得るためのPartHandlerを作成します。 message/*のパートやinline且つファイル名指定ありのパートも + * 添付ファイルとして扱います。 + */ + public AttachmentsExtractor() { + this(0); + } + + /** + * 添付ファイル一覧を得るためのPartHandlerを作成します。 + * @param mode 動作モード。MODE_で始まる識別子をor指定します。 + */ + public AttachmentsExtractor(int mode) { + this.mode = mode; + } + + /** MultipartUtility#process()から呼びだされるメソッドです。 */ + public boolean processPart(Part part, ContentType context) throws MessagingException, + IOException { + // Apple Mail対策 + if (part.getContentType().indexOf("application/applefile") != -1) { + return true; + } + + if (part.isMimeType("message/*")) { + if ((mode & MODE_IGNORE_MESSAGE) != 0) { + return true; + } + attachmentParts.add(part); + return true; + } + if (MailUtility.getFileName(part) == null) { + return true; + } + if ((mode & MODE_IGNORE_INLINE) != 0 && Part.INLINE.equalsIgnoreCase(part.getDisposition())) { + return true; + } + + attachmentParts.add(part); + return true; + } + + /** + * 添付ファイル個数を返します。 + */ + public int getCount() { + return attachmentParts.size(); + } + + /** + * 添付ファイル名の配列を返します。 + *

+ * 添付ファイルが存在しない場合は空の配列を返します。
+ * ファイル名は同一のものが複数存在する事もありえます。 + *

+ */ + public String[] getFileNames() throws MessagingException { + String[] names = new String[getCount()]; + for (int i = 0; i < names.length; i++) { + names[i] = getFileName(i); + } + return names; + } + + /** + * 指定添付ファイルのファイル名を返します。 + */ + public String getFileName(int index) throws MessagingException { + Part part = (Part)attachmentParts.get(index); + String name = MailUtility.getFileName(part); + if (name == null) { + // 添付ファイル名が取得できない場合は、指定されていなかった場合か、 + // あるいはmessage/*のパートの場合です。 + // この場合は仮のファイル名を付けることとします。 + if (part.isMimeType("message/*")) { + // If part is Message, create temporary filename. + name = "message" + index + ".eml"; + } else { + name = "file" + index + ".tmp"; + } + } + return name; + } + + /** + * 指定添付ファイルのContent-Typeを返します。 + */ + public String getContentType(int index) throws MessagingException { + return MailUtility.unfold(((Part)attachmentParts.get(index)).getContentType()); + } + + /** + * 指定添付ファイルのサイズを返します。 + */ + public int getSize(int index) throws MessagingException { + return ((Part)attachmentParts.get(index)).getSize(); + } + + /** + * 指定添付ファイルを読み込むストリームを返します。 + */ + public InputStream getInputStream(int index) throws MessagingException, IOException { + return ((Part)attachmentParts.get(index)).getInputStream(); + } + + /** + * 指定添付ファイルを指定ストリームに書き出します。 + */ + public void writeTo(int index, OutputStream out) throws MessagingException, IOException { + InputStream in = getInputStream(index); + byte[] buf = new byte[1024]; + int len; + while ((len = in.read(buf)) != -1) { + out.write(buf, 0, len); + } + } + + public static void main(String[] args) throws Exception { + javax.mail.internet.MimeMessage msg = new javax.mail.internet.MimeMessage( + javax.mail.Session.getDefaultInstance(System.getProperties(), null), System.in); + AttachmentsExtractor h = new AttachmentsExtractor(); + MultipartUtility.process(msg, h); + for (int i = 0; i < h.getCount(); i++) { + System.out.println("Attachment no : " + i); + System.out.println("Filename = " + h.getFileName(i)); + System.out.println("******************"); + h.writeTo(i, System.out); + } + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSource.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSource.java old mode 100755 new mode 100644 index 658ba79..65fedf4 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSource.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSource.java @@ -1,112 +1,112 @@ -/* - * @(#) $Id: CorrectedContentTypeDataSource.java,v 1.1.2.2 2004/10/24 10:27:40 otsuka Exp $ - * $Revision: 1.1.2.2 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import javax.activation.DataSource; -import javax.mail.MessageAware; -import javax.mail.MessageContext; -import javax.mail.MessagingException; -import javax.mail.Part; -import javax.mail.internet.ContentType; -import javax.mail.internet.ParseException; - -/** - * Content-Type:の不適合をISO-2022-JPに補正します。 - * 使用方法は
- * Object o = new DataHandler(
- *               new CorrectedContentTypeDataSource(part, charset)
- *            ).getContent();
- * 

のようになります。

- * スレッドセーフではありませんので利用者側で排他制御を行ってください。 - *

- * @author Shin - * @version $Revision: 1.1.2.2 $ $Date: 2004/10/24 10:27:40 $ - */ -class CorrectedContentTypeDataSource implements DataSource, MessageAware { - - protected DataSource source; - - protected String defaultCharset; - - protected String forceCharset; - - public CorrectedContentTypeDataSource() {} - - public CorrectedContentTypeDataSource(DataSource dataSource, String defaultCharset) { - setDataSource(dataSource); - setDefaultCharset(defaultCharset); - } - - public CorrectedContentTypeDataSource(Part part, String defaultCharset) - throws MessagingException { - setPart(part); - setDefaultCharset(defaultCharset); - } - - public void setPart(Part part) throws MessagingException { - // getDataHandler() method creates a implicit DataSource. - setDataSource(part.getDataHandler().getDataSource()); - } - - public void setDataSource(DataSource newSource) { - source = newSource; - } - - public void setDefaultCharset(String defaultCharset) { - this.defaultCharset = defaultCharset; - } - - /** - * 指定された文字コードで既存の文字コードを上書きします。 - * - * @param forceCharset 強制的に適用する文字コード - * @author Tomohiro Otsuka - */ - public void setForceCharset(String forceCharset) { - this.forceCharset = forceCharset; - } - - public String getContentType() { - ContentType contentType = null; - try { - contentType = new ContentType(source.getContentType()); - } catch (ParseException e) { - return "text/plain; charset=" + defaultCharset; - } - String specifiedCharset = contentType.getParameter("charset"); - if (specifiedCharset == null) { - // Content-Type:が存在しない場合は"text/plain"になってしまう。 - // 本当にtext/plainだった場合は正しくない事になるが、 - // charset=ISO-2022-JPにする場合は一応表示上は問題ない。 - contentType.setParameter("charset", defaultCharset); - } else if (forceCharset != null) { - contentType.setParameter("charset", forceCharset); - } - return contentType.toString(); - } - - public String getName() { - return source.getName(); - } - - public InputStream getInputStream() throws IOException { - return source.getInputStream(); - } - - public OutputStream getOutputStream() throws IOException { - return source.getOutputStream(); - } - - public synchronized MessageContext getMessageContext() { - if (source instanceof MessageAware) { - return ((MessageAware)source).getMessageContext(); - } - throw new RuntimeException(source + " isn't MessageAware."); - } +/* + * @(#) $Id: CorrectedContentTypeDataSource.java,v 1.1.2.2 2004/10/24 10:27:40 otsuka Exp $ + * $Revision: 1.1.2.2 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import javax.activation.DataSource; +import javax.mail.MessageAware; +import javax.mail.MessageContext; +import javax.mail.MessagingException; +import javax.mail.Part; +import javax.mail.internet.ContentType; +import javax.mail.internet.ParseException; + +/** + * Content-Type:の不適合をISO-2022-JPに補正します。 + * 使用方法は
+ * Object o = new DataHandler(
+ *               new CorrectedContentTypeDataSource(part, charset)
+ *            ).getContent();
+ * 

のようになります。

+ * スレッドセーフではありませんので利用者側で排他制御を行ってください。 + *

+ * @author Shin + * @version $Revision: 1.1.2.2 $ $Date: 2004/10/24 10:27:40 $ + */ +class CorrectedContentTypeDataSource implements DataSource, MessageAware { + + protected DataSource source; + + protected String defaultCharset; + + protected String forceCharset; + + public CorrectedContentTypeDataSource() {} + + public CorrectedContentTypeDataSource(DataSource dataSource, String defaultCharset) { + setDataSource(dataSource); + setDefaultCharset(defaultCharset); + } + + public CorrectedContentTypeDataSource(Part part, String defaultCharset) + throws MessagingException { + setPart(part); + setDefaultCharset(defaultCharset); + } + + public void setPart(Part part) throws MessagingException { + // getDataHandler() method creates a implicit DataSource. + setDataSource(part.getDataHandler().getDataSource()); + } + + public void setDataSource(DataSource newSource) { + source = newSource; + } + + public void setDefaultCharset(String defaultCharset) { + this.defaultCharset = defaultCharset; + } + + /** + * 指定された文字コードで既存の文字コードを上書きします。 + * + * @param forceCharset 強制的に適用する文字コード + * @author Tomohiro Otsuka + */ + public void setForceCharset(String forceCharset) { + this.forceCharset = forceCharset; + } + + public String getContentType() { + ContentType contentType = null; + try { + contentType = new ContentType(source.getContentType()); + } catch (ParseException e) { + return "text/plain; charset=" + defaultCharset; + } + String specifiedCharset = contentType.getParameter("charset"); + if (specifiedCharset == null) { + // Content-Type:が存在しない場合は"text/plain"になってしまう。 + // 本当にtext/plainだった場合は正しくない事になるが、 + // charset=ISO-2022-JPにする場合は一応表示上は問題ない。 + contentType.setParameter("charset", defaultCharset); + } else if (forceCharset != null) { + contentType.setParameter("charset", forceCharset); + } + return contentType.toString(); + } + + public String getName() { + return source.getName(); + } + + public InputStream getInputStream() throws IOException { + return source.getInputStream(); + } + + public OutputStream getOutputStream() throws IOException { + return source.getOutputStream(); + } + + public synchronized MessageContext getMessageContext() { + if (source instanceof MessageAware) { + return ((MessageAware)source).getMessageContext(); + } + throw new RuntimeException(source + " isn't MessageAware."); + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSourceUTF7Support.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSourceUTF7Support.java old mode 100755 new mode 100644 index 3e73518..aabce53 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSourceUTF7Support.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/CorrectedContentTypeDataSourceUTF7Support.java @@ -1,170 +1,170 @@ -/* - * @(#) $Id: CorrectedContentTypeDataSourceUTF7Support.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import javax.activation.DataSource; -import javax.mail.MessageAware; -import javax.mail.MessagingException; -import javax.mail.Part; -import javax.mail.internet.ContentType; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.ParseException; - -import com.ozacc.mail.fetch.impl.sk_jp.io.ByteToCharUTF7; - -/** - * Content-Type:の不適合をISO-2022-JPに補正します。 - * さらにcharset=UTF-7の場合にUTF-16のストリームに変換してgetContent()を - * 無理やり成功させます。
- * また、未知のTES(Content-Transfer-Encoding:)だった場合に、"7bit" - * と見なしてボディを取得します。 - * 使用方法は
- * Object o = new DataHandler(
- *               new CorrectedContentTypeDataSourceUTF7Support(part, charset)
- *            ).getContent();
- * 

のようになります。

- * スレッドセーフではありませんので利用者側で排他制御を行ってください。 - *

- * @author Shin - * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ - */ -class CorrectedContentTypeDataSourceUTF7Support extends CorrectedContentTypeDataSource { - - private boolean utf7 = false; - - public CorrectedContentTypeDataSourceUTF7Support() {} - - public CorrectedContentTypeDataSourceUTF7Support(DataSource dataSource, String defaultCharset) { - super(dataSource, defaultCharset); - } - - public CorrectedContentTypeDataSourceUTF7Support(Part part, String defaultCharset) - throws MessagingException { - super(part, defaultCharset); - } - - public void setDataSource(DataSource newSource) { - super.setDataSource(newSource); - utf7 = false; - } - - public void setDefaultCharset(String defaultCharset) { - super.setDefaultCharset(defaultCharset); - utf7 = false; - } - - public String getContentType() { - try { - ContentType contentType = new ContentType(super.getContentType()); - String specifiedCharset = contentType.getParameter("charset"); - if ("UTF-7".equalsIgnoreCase(specifiedCharset)) { - // UTF-7コンバータが存在しない為、 - // 独自フィルタストリームを用いる。 - contentType.setParameter("charset", "UTF-16"); - utf7 = true; - } - return contentType.toString(); - } catch (ParseException e) { - throw new InternalError(); - } - } - - public InputStream getInputStream() throws IOException { - InputStream in = null; - if (isInvalidEncodingAsMultipart()) { - // multipart/*でありながら、不正なTransfer-Encodingだった場合 - // 2001/09/01 JPhone(SH07)の送信する画像付きメイルが、 - // Content-Type: multipart/mixed - // Content-Transfer-Encoding: base64 - // 等というメッセージを送る場合があり、JavaMailが - // これをデコードできない問題を回避。 - // multipart/*の場合のContent-Transfer-Encodingは、 - // "7bit""8bit""binary"に限られる。 - // それ以外の場合は生ストリームを返すようにしておく。 - in = getRawInputStream(); - } - if (in == null) { - try { - in = super.getInputStream(); - } catch (IOException e) { - // ここでのIOExceptionはエンコーディング不良の可能性が高い。 - // 生InputStreamを得てリトライ - in = getRawInputStream(); - if (in == null) - throw e; - } - } - if (!utf7) { - return in; - } - ByteArrayOutputStream out = new ByteArrayOutputStream(); - int c; - - while ((c = in.read()) != -1) { - out.write(c); - } - - ByteToCharUTF7 btc = new ByteToCharUTF7(); - byte[] bytes = out.toByteArray(); - char[] chars = new char[bytes.length]; - - // Bug fixed. Thanx to MOHI. - // http://www.sk-jp.com/cgi-bin/treebbs.cgi?all=1220&s=1220 - int len = btc.convert(bytes, 0, bytes.length, chars, 0, chars.length); - char[] w = new char[len]; - System.arraycopy(chars, 0, w, 0, len); - String string = new String(w); - return new ByteArrayInputStream(string.getBytes("UTF-16")); - } - - // Transfer-Encodingにしたがったデコードを行う前のストリームを得ます。 - // sourceがMessageAwareでない場合はnullが返されます。 - private InputStream getRawInputStream() throws IOException { - if (!(source instanceof MessageAware)) { - return null; - } - Part part = ((MessageAware)source).getMessageContext().getPart(); - try { - if (part instanceof MimeMessage) { - return ((MimeMessage)part).getRawInputStream(); - } else if (part instanceof MimeBodyPart) { - return ((MimeBodyPart)part).getRawInputStream(); - } else { - return null; - } - } catch (MessagingException mex) { - throw new IOException(mex.toString()); - } - } - - // 不正なContent-Transfer-Encodingの場合にtrueを返します。 - private boolean isInvalidEncodingAsMultipart() { - try { - if (!new ContentType(getContentType()).match("multipart/*")) { - return false; - } - if (!(source instanceof MessageAware)) { - return false; - } - Part part = ((MessageAware)source).getMessageContext().getPart(); - String encoding = ((javax.mail.internet.MimePart)part).getEncoding(); - if ("7bit".equalsIgnoreCase(encoding) || "8bit".equalsIgnoreCase(encoding) - || "binary".equalsIgnoreCase(encoding)) { - return false; - } - } catch (Exception e) { - // この場合も不正だ、と。 - } - return true; - } - +/* + * @(#) $Id: CorrectedContentTypeDataSourceUTF7Support.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; + +import javax.activation.DataSource; +import javax.mail.MessageAware; +import javax.mail.MessagingException; +import javax.mail.Part; +import javax.mail.internet.ContentType; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.ParseException; + +import com.ozacc.mail.fetch.impl.sk_jp.io.ByteToCharUTF7; + +/** + * Content-Type:の不適合をISO-2022-JPに補正します。 + * さらにcharset=UTF-7の場合にUTF-16のストリームに変換してgetContent()を + * 無理やり成功させます。
+ * また、未知のTES(Content-Transfer-Encoding:)だった場合に、"7bit" + * と見なしてボディを取得します。 + * 使用方法は
+ * Object o = new DataHandler(
+ *               new CorrectedContentTypeDataSourceUTF7Support(part, charset)
+ *            ).getContent();
+ * 

のようになります。

+ * スレッドセーフではありませんので利用者側で排他制御を行ってください。 + *

+ * @author Shin + * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ + */ +class CorrectedContentTypeDataSourceUTF7Support extends CorrectedContentTypeDataSource { + + private boolean utf7 = false; + + public CorrectedContentTypeDataSourceUTF7Support() {} + + public CorrectedContentTypeDataSourceUTF7Support(DataSource dataSource, String defaultCharset) { + super(dataSource, defaultCharset); + } + + public CorrectedContentTypeDataSourceUTF7Support(Part part, String defaultCharset) + throws MessagingException { + super(part, defaultCharset); + } + + public void setDataSource(DataSource newSource) { + super.setDataSource(newSource); + utf7 = false; + } + + public void setDefaultCharset(String defaultCharset) { + super.setDefaultCharset(defaultCharset); + utf7 = false; + } + + public String getContentType() { + try { + ContentType contentType = new ContentType(super.getContentType()); + String specifiedCharset = contentType.getParameter("charset"); + if ("UTF-7".equalsIgnoreCase(specifiedCharset)) { + // UTF-7コンバータが存在しない為、 + // 独自フィルタストリームを用いる。 + contentType.setParameter("charset", "UTF-16"); + utf7 = true; + } + return contentType.toString(); + } catch (ParseException e) { + throw new InternalError(); + } + } + + public InputStream getInputStream() throws IOException { + InputStream in = null; + if (isInvalidEncodingAsMultipart()) { + // multipart/*でありながら、不正なTransfer-Encodingだった場合 + // 2001/09/01 JPhone(SH07)の送信する画像付きメイルが、 + // Content-Type: multipart/mixed + // Content-Transfer-Encoding: base64 + // 等というメッセージを送る場合があり、JavaMailが + // これをデコードできない問題を回避。 + // multipart/*の場合のContent-Transfer-Encodingは、 + // "7bit""8bit""binary"に限られる。 + // それ以外の場合は生ストリームを返すようにしておく。 + in = getRawInputStream(); + } + if (in == null) { + try { + in = super.getInputStream(); + } catch (IOException e) { + // ここでのIOExceptionはエンコーディング不良の可能性が高い。 + // 生InputStreamを得てリトライ + in = getRawInputStream(); + if (in == null) + throw e; + } + } + if (!utf7) { + return in; + } + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int c; + + while ((c = in.read()) != -1) { + out.write(c); + } + + ByteToCharUTF7 btc = new ByteToCharUTF7(); + byte[] bytes = out.toByteArray(); + char[] chars = new char[bytes.length]; + + // Bug fixed. Thanx to MOHI. + // http://www.sk-jp.com/cgi-bin/treebbs.cgi?all=1220&s=1220 + int len = btc.convert(bytes, 0, bytes.length, chars, 0, chars.length); + char[] w = new char[len]; + System.arraycopy(chars, 0, w, 0, len); + String string = new String(w); + return new ByteArrayInputStream(string.getBytes("UTF-16")); + } + + // Transfer-Encodingにしたがったデコードを行う前のストリームを得ます。 + // sourceがMessageAwareでない場合はnullが返されます。 + private InputStream getRawInputStream() throws IOException { + if (!(source instanceof MessageAware)) { + return null; + } + Part part = ((MessageAware)source).getMessageContext().getPart(); + try { + if (part instanceof MimeMessage) { + return ((MimeMessage)part).getRawInputStream(); + } else if (part instanceof MimeBodyPart) { + return ((MimeBodyPart)part).getRawInputStream(); + } else { + return null; + } + } catch (MessagingException mex) { + throw new IOException(mex.toString()); + } + } + + // 不正なContent-Transfer-Encodingの場合にtrueを返します。 + private boolean isInvalidEncodingAsMultipart() { + try { + if (!new ContentType(getContentType()).match("multipart/*")) { + return false; + } + if (!(source instanceof MessageAware)) { + return false; + } + Part part = ((MessageAware)source).getMessageContext().getPart(); + String encoding = ((javax.mail.internet.MimePart)part).getEncoding(); + if ("7bit".equalsIgnoreCase(encoding) || "8bit".equalsIgnoreCase(encoding) + || "binary".equalsIgnoreCase(encoding)) { + return false; + } + } catch (Exception e) { + // この場合も不正だ、と。 + } + return true; + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/FirstPlainPartExtractor.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/FirstPlainPartExtractor.java old mode 100755 new mode 100644 index 82e3285..4d53650 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/FirstPlainPartExtractor.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/FirstPlainPartExtractor.java @@ -1,49 +1,49 @@ -/* - * @(#) $Id: FirstPlainPartExtractor.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.IOException; -import javax.mail.Part; -import javax.mail.MessagingException; -import javax.mail.internet.ContentType; - -/** - * 最初に見つけたtext/plainパートの本文を得るPartHandlerです。 - *

- *

- * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ - * @author Shin - */ -public class FirstPlainPartExtractor implements PartHandler { - - private String text = null; - - public boolean processPart(Part part, ContentType context) throws MessagingException, - IOException { - String type = part.getContentType(); - // Bug fixed. Thx > ei - // http://www.sk-jp.com/cgi-bin/treebbs.cgi?kako=1&all=1292&s=1292 - if (!part.isMimeType("text/plain") && type != null && !type.trim().equalsIgnoreCase("text")) { - return true; - } - text = (String)MultipartUtility.getContent(part); - return false; - } - - public String getText() { - return text; - } - - public static void main(String[] args) throws Exception { - javax.mail.internet.MimeMessage msg = new javax.mail.internet.MimeMessage( - javax.mail.Session.getDefaultInstance(System.getProperties(), null), System.in); - FirstPlainPartExtractor h = new FirstPlainPartExtractor(); - MultipartUtility.process(msg, h); - - System.out.println("This is the first detected text/plain part."); - System.out.println(h.getText()); - } +/* + * @(#) $Id: FirstPlainPartExtractor.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.IOException; +import javax.mail.Part; +import javax.mail.MessagingException; +import javax.mail.internet.ContentType; + +/** + * 最初に見つけたtext/plainパートの本文を得るPartHandlerです。 + *

+ *

+ * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ + * @author Shin + */ +public class FirstPlainPartExtractor implements PartHandler { + + private String text = null; + + public boolean processPart(Part part, ContentType context) throws MessagingException, + IOException { + String type = part.getContentType(); + // Bug fixed. Thx > ei + // http://www.sk-jp.com/cgi-bin/treebbs.cgi?kako=1&all=1292&s=1292 + if (!part.isMimeType("text/plain") && type != null && !type.trim().equalsIgnoreCase("text")) { + return true; + } + text = (String)MultipartUtility.getContent(part); + return false; + } + + public String getText() { + return text; + } + + public static void main(String[] args) throws Exception { + javax.mail.internet.MimeMessage msg = new javax.mail.internet.MimeMessage( + javax.mail.Session.getDefaultInstance(System.getProperties(), null), System.in); + FirstPlainPartExtractor h = new FirstPlainPartExtractor(); + MultipartUtility.process(msg, h); + + System.out.println("This is the first detected text/plain part."); + System.out.println(h.getText()); + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/HtmlPartExtractor.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/HtmlPartExtractor.java old mode 100755 new mode 100644 index 5f37793..b8cfe9c --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/HtmlPartExtractor.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/HtmlPartExtractor.java @@ -1,45 +1,45 @@ -/* - * @(#) $Id: HtmlPartExtractor.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.IOException; - -import javax.mail.MessagingException; -import javax.mail.Part; -import javax.mail.internet.ContentType; - -/** - * text/htmlを結合した文字列を得るPartHandlerです。 - * - * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ - * @author Shin - */ -public class HtmlPartExtractor implements PartHandler { - - private String html = null; - - public boolean processPart(Part part, ContentType context) throws MessagingException, - IOException { - if (!part.isMimeType("text/html")) { - return true; - } - if (html == null) { - // 最初のテキストパートを無条件に抽出 - html = (String)MultipartUtility.getContent(part); - } else { - String disposition = part.getDisposition(); - if (disposition == null || disposition.equalsIgnoreCase(Part.INLINE)) { - html += "\r\n\r\n-- inline --\r\n\r\n" + (String)MultipartUtility.getContent(part); - } - } - return true; - } - - public String getHtml() { - return html; - } - +/* + * @(#) $Id: HtmlPartExtractor.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.IOException; + +import javax.mail.MessagingException; +import javax.mail.Part; +import javax.mail.internet.ContentType; + +/** + * text/htmlを結合した文字列を得るPartHandlerです。 + * + * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ + * @author Shin + */ +public class HtmlPartExtractor implements PartHandler { + + private String html = null; + + public boolean processPart(Part part, ContentType context) throws MessagingException, + IOException { + if (!part.isMimeType("text/html")) { + return true; + } + if (html == null) { + // 最初のテキストパートを無条件に抽出 + html = (String)MultipartUtility.getContent(part); + } else { + String disposition = part.getDisposition(); + if (disposition == null || disposition.equalsIgnoreCase(Part.INLINE)) { + html += "\r\n\r\n-- inline --\r\n\r\n" + (String)MultipartUtility.getContent(part); + } + } + return true; + } + + public String getHtml() { + return html; + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/JISDataSource.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/JISDataSource.java old mode 100755 new mode 100644 index 9675cf6..b844909 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/JISDataSource.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/JISDataSource.java @@ -1,52 +1,52 @@ -/* - * @(#) $Id: JISDataSource.java,v 1.1.2.1 2005/01/18 07:20:59 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; - -import javax.activation.DataSource; - -import com.ozacc.mail.fetch.impl.sk_jp.io.CharCodeConverter; -import com.ozacc.mail.fetch.impl.sk_jp.io.UnicodeCorrector; - -/** - * テキストの本文を送信するための DataSource です。 - */ -public class JISDataSource implements DataSource { - - private byte[] data; - - public JISDataSource(String s) { - try { - data = CharCodeConverter.sjisToJis(UnicodeCorrector.getInstance("Windows-31J").correct( - s).getBytes("Windows-31J")); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("CANT HAPPEN"); - } - } - - public String getContentType() { - return "text/plain; charset=ISO-2022-JP"; - } - - public InputStream getInputStream() throws IOException { - if (data == null) - throw new IOException("no data"); - return new ByteArrayInputStream(data); - } - - public OutputStream getOutputStream() throws IOException { - throw new IOException("cannot do this"); - } - - public String getName() { - return "dummy"; - } +/* + * @(#) $Id: JISDataSource.java,v 1.1.2.1 2005/01/18 07:20:59 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; + +import javax.activation.DataSource; + +import com.ozacc.mail.fetch.impl.sk_jp.io.CharCodeConverter; +import com.ozacc.mail.fetch.impl.sk_jp.io.UnicodeCorrector; + +/** + * テキストの本文を送信するための DataSource です。 + */ +public class JISDataSource implements DataSource { + + private byte[] data; + + public JISDataSource(String s) { + try { + data = CharCodeConverter.sjisToJis(UnicodeCorrector.getInstance("Windows-31J").correct( + s).getBytes("Windows-31J")); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("CANT HAPPEN"); + } + } + + public String getContentType() { + return "text/plain; charset=ISO-2022-JP"; + } + + public InputStream getInputStream() throws IOException { + if (data == null) + throw new IOException("no data"); + return new ByteArrayInputStream(data); + } + + public OutputStream getOutputStream() throws IOException { + throw new IOException("cannot do this"); + } + + public String getName() { + return "dummy"; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MailUtility.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MailUtility.java old mode 100755 new mode 100644 index 526ad10..f6f8f11 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MailUtility.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MailUtility.java @@ -1,1060 +1,1060 @@ -/* - * @(#) $Id: MailUtility.java,v 1.1.2.1 2005/01/18 07:20:59 otsuka Exp $ - * Copyright (c) 2000-2004 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.Date; - -import javax.activation.DataHandler; -import javax.mail.BodyPart; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Part; -import javax.mail.internet.AddressException; -import javax.mail.internet.ContentDisposition; -import javax.mail.internet.ContentType; -import javax.mail.internet.HeaderTokenizer; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MailDateFormat; -import javax.mail.internet.MimeUtility; -import javax.mail.internet.ParseException; - -import com.ozacc.mail.fetch.impl.sk_jp.io.CharCodeConverter; -import com.ozacc.mail.fetch.impl.sk_jp.io.UnicodeCorrector; -import com.ozacc.mail.fetch.impl.sk_jp.text.EntityRefEncoder; -import com.ozacc.mail.fetch.impl.sk_jp.util.StringValues; -import com.sun.mail.util.BASE64EncoderStream; - -/** - * JavaMailのサポートクラスです。 - *

- * 主にヘッダに対するさまざまな加工機能を提供します。 - *

- * @author Shin - * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:59 $ - */ -public class MailUtility { - - public static String getPersonal(InternetAddress a) { - if (a.getPersonal() != null) - return a.getPersonal(); - return a.toString(); - } - - /** get comma separated E-Mail addresses. */ - public static String getMailAddresses(InternetAddress[] addresses) { - if (addresses == null) - return null; - StringValues buf = new StringValues(); - for (int i = 0; i < addresses.length; i++) { - buf.add(addresses[i].getAddress()); - } - return buf.getString(); - } - - /** get comma separated personal names. */ - public static String getPersonalNames(InternetAddress[] addresses) { - if (addresses == null) - return null; - StringValues buf = new StringValues(); - String name; - for (int i = 0; i < addresses.length; i++) { - name = decodeText(unfold(addresses[i].getPersonal())); - if (name == null) { - name = addresses[i].toString(); - } - buf.add(name); - } - return buf.getString(); - } - - public static String getAddressesHTML(InternetAddress[] addresses) { - if (addresses == null) - return null; - StringValues buf = new StringValues(); - StringBuffer href = new StringBuffer(); - String name; - for (int i = 0; i < addresses.length; i++) { - href.append(""); - name = addresses[i].getPersonal(); - if (name != null) { - name = decodeText(name); - } - if (name == null) { - name = addresses[i].toString(); - } - href.append(EntityRefEncoder.encode(name)); - href.append(""); - buf.add(new String(href)); - href.setLength(0); - } - return buf.getString(); - } - - /** get the Content-Transfer-Encoding: header value. */ - public static String getTransferEncoding(byte[] b) { - int nonAscii = 0; - for (int i = 0; i < b.length; i++) { - if (b[i] < 0) { - nonAscii++; - } - } - if (nonAscii == 0) - return "7bit"; - if (nonAscii < b.length - nonAscii) - return "quoted-printable"; - return "base64"; - } - - /** - * パートを保有する親Messageオブジェクトを返します。 - * @param part パート - * @return ツリー構造の最上位にあたるメッセージオブジェクト - */ - public static Message getParentMessage(Part part) { - Part current = part; - Multipart mp; - while (!(current instanceof Message)) { - mp = ((BodyPart)current).getParent(); - if (mp == null) - return null; // Should it throw exception? - current = mp.getParent(); - if (current == null) - return null; // Should it throw exception? - } - return (Message)current; - } - - ////////////////////////////////////////////////////////////////////////// - // note: JavaMail1.2 later - private static MailDateFormat mailDateFormat = new MailDateFormat(); - - /** - * Date構文の誤った"JST"タイムゾーンの補正を行います。 - *

- * JavaMailは"JST"と記述されるタイムゾーンを解釈しません。 ここは本来"+0900"でなければならないところです。
- * 仕方がないので" JST"が含まれる文字列の場合は"+0900"を補完して - * MailDateFormat#parse()を通すようなparse()のラッパを用意します。 - *

- *

- * この実装は一時回避的なものであり、完全なものではありません。 - *

- */ - public static Date parseDate(String rfc822DateString) { - if (rfc822DateString == null) { - return null; - } - try { - if (rfc822DateString.indexOf(" JST") == -1 || rfc822DateString.indexOf('+') >= 0) { - synchronized (mailDateFormat) { - return mailDateFormat.parse(rfc822DateString); - } - } - // correct the pseudo header - StringBuffer buf = new StringBuffer(rfc822DateString.substring(0, rfc822DateString - .indexOf("JST"))); - buf.append("+0900"); - synchronized (mailDateFormat) { - return mailDateFormat.parse(new String(buf)); - } - } catch (java.text.ParseException e) { - return null; - } - } - - ////////////////////////////////////////////////////////////////////////// - /** - * Subject:に"Re: "を付加します。 - *

- * ある程度寛容に"Re: "に近い文字列と"[hoge]"を取り除きます。
- * ただし、意図しない部分が消されてしまう事もあり得ます。
- * JavaMailのreply()では"Re: "がエンコードされていた場合に 正しく"Re: "を取り除いてくれません。 - *

- */ - public static String createReplySubject(String src) { - if (src == null || src.length() == 0) { - return "Re: (no subject)"; - } - String work = src; - if (work.charAt(0) == '[' && work.indexOf(']') > 0) { - int afterBracket = indexOfNonLWSP(work, work.indexOf(']') + 1, false); - if (afterBracket < 0) { - work = ""; - } else { - work = work.substring(afterBracket); - } - } - if (work.length() > 3 && "Re:".equalsIgnoreCase(work.substring(0, 3))) { - int afterRe = indexOfNonLWSP(work, 3, false); - if (afterRe < 0) { - work = ""; - } else { - work = work.substring(afterRe); - } - } - return "Re: " + work; - } - - ////////////////////////////////////////////////////////////////////////// - /** - * 入力されたアドレスをInternetAddress形式に変換します。 - *

- * "名無し君 (コメント)"等の文字列(エンコード無し)を - * 渡されても、正しくpersonal文字列が設定されるようにします。
- * InternetAddress#parse()はエンコード済みの文字列を前提にしているため、 このメソッドの目的には沿いません。 - *

- * @param addresses メイルアドレス文字列(カンマ区切り) - */ - public static InternetAddress[] parseAddresses(String addressesString) throws AddressException { - return parseAddresses(addressesString, true); - } - - public static InternetAddress[] parseAddresses(String addressesString, boolean strict) - throws AddressException { - if (addressesString == null) - return null; - try { - InternetAddress[] addresses = InternetAddress.parse(addressesString, strict); - // correct personals - for (int i = 0; i < addresses.length; i++) { - addresses[i].setPersonal(addresses[i].getPersonal(), "ISO-2022-JP"); - } - return addresses; - } catch (UnsupportedEncodingException e) { - throw new InternalError(e.toString()); - } - } - - // InternetAddress.parse( - // encodeText(addressesString, "ISO-2022-JP", "B"), strict); - // で良さそうなものだが、これでは・・たしかなんか問題があったはず。 - ////////////////////////////////////////////////////////////////////////// - /** - * header valueの unfolding を行います。 空白を厳密に扱うためには decodeText より先に呼び出す必要があります。 - */ - public static String unfold(String source) { - if (source == null) - return null; - StringBuffer buf = new StringBuffer(); - boolean skip = false; - char c; - // シーケンスを前提とするならindexOf()で十分ですが、 - // 念のためCR、LFいずれも許容します。 - for (int i = 0; i < source.length(); i++) { - c = source.charAt(i); - if (skip) { - if (isLWSP(c)) { - continue; - } - skip = false; - } - if (c != '\r' && c != '\n') { - buf.append(c); - } else { - buf.append(' '); - skip = true; - } - } - return new String(buf); - } - - /** - * header valueの folding を行います。 - *

- * white spaceをfolding対象にします。
- * 76bytesを超えないwhite space位置に を挿入します。 - *

- *

- * 注:quoteを無視しますので、structured fieldでは不都合が 発生する可能性があります。 - *

- * @param used ヘッダの':'までの文字数。76 - usedが最初のfolding候補桁 - * @return foldingされた( SPACEが挿入された)文字列 - */ - public static String fold(String source, int used) { - if (source == null) - return null; - StringBuffer buf = new StringBuffer(); - String work = source; - int lineBreakIndex; - while (work.length() > 76) { - lineBreakIndex = work.lastIndexOf(' ', 76); - if (lineBreakIndex == -1) - break; - buf.append(work.substring(0, lineBreakIndex)); - buf.append("\r\n"); - work = work.substring(lineBreakIndex); - } - buf.append(work); - return new String(buf); - } - - ////////////////////////////////////////////////////////////////////////// - /** - * パートにテキストをセットします。 - * Part#setText() の代わりにこちらを使うことで、 - * "ISO-2022-JP" コンバータではエンコードできない CP932 の - * 文字をエンコードできます。 - */ - public static void setTextContent(Part p, String s) throws MessagingException { - //p.setText(content, "ISO-2022-JP"); - p.setDataHandler(new DataHandler(new JISDataSource(s))); - p.setHeader("Content-Transfer-Encoding", "7bit"); - } - - /** - * 日本語を含むヘッダ用テキストを生成します。 - * 変換結果は ASCII なので、これをそのまま setSubject や InternetAddress - * のパラメタとして使用してください。 - * "ISO-2022-JP" コンバータではエンコードできない CP932 の - * 文字をエンコードできます。ただし、encodeText() と異なり、 - * folding の意識をしておらず、また ASCII 部分を除いて分割 - * エンコードを行うこともできません。 - */ - public static String encodeWordJIS(String s) { - try { - return "=?ISO-2022-JP?B?" - + new String(BASE64EncoderStream.encode(CharCodeConverter - .sjisToJis(UnicodeCorrector.getInstance("Windows-31J").correct(s) - .getBytes("Windows-31J")))) + "?="; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("CANT HAPPEN"); - } - } - - ////////////////////////////////////////////////////////////////////////// - /** - * ヘッダ内の文字列をデコードします。 - *

- * MimeUtilityの制約を緩めて日本で流通するエンコード形式に対応。 - * 本来は、encoded-wordとnon-encoded-wordの間にはlinear-white-spaceが必要 - * なのですが、空白が無い場所でエンコードするタコメイラが多いので。 - *

- *

- * JISコードをエンコード無しで記述するタコメイラもあります。
- * ソースにESCが含まれていたら生JISと見なします。 - *

- *

- * =?utf-8?Q?・・・JISコード・・?=なんてさらにタコなメイラも。
- * 試しにデコード後にまだESCが残ってたらISO-2022-JPと見なすことにします。 - *

- *

- * さらに、multibyte character の前後で別の encoded-word に切ってしまう メイラも…。隣接する - * encoded-word の CES が同じ場合はバイト列の 結合を行ってから CES デコードを行うようにした…。 - *

- *

- * 日本語に特化してますねえ・・・。 - *

- * @param source encoded text - * @return decoded text - */ - public static String decodeText(String source) { - if (source == null) - return null; - // specially for Japanese - if (source.indexOf('\u001b') >= 0) { - // ISO-2022-JP - try { - return new String(source.getBytes("ISO-8859-1"), "ISO-2022-JP"); - } catch (UnsupportedEncodingException e) { - throw new InternalError(); - } - } - String decodedText = new RFC2047Decoder(source).get(); - if (decodedText.indexOf('\u001b') >= 0) { - try { - return new String(decodedText.getBytes("ISO-8859-1"), "ISO-2022-JP"); - } catch (UnsupportedEncodingException e) { - throw new InternalError(); - } - } - return decodedText; - } - - // 日本語をデコードする上で問題があるので、encoded-wordの切り出しはすべて独自に - // Netscapeなどは"()."等の文字でencoded-wordを切ってしまうが、JavaMailは - // このときencoded-wordの終わりを判定できず、一部の文字を欠落させてしまう。 - // また、encoded-word を文字デコードするのを遅延させ、隣接する encoded-word - // の CES が同じ場合は、先に TES デコードを行ったバイト列を結合してから - // CES に従ったデコードを行う。マルチバイト文字を分断する sender がいるから。 - static class RFC2047Decoder { - - private String source; - - private String pooledCES; - - private byte[] pooledBytes; - - private StringBuffer buf; - - private int pos = 0; - - private int startIndex; - - private int endIndex; - - public RFC2047Decoder(String source) { - this.source = source; - buf = new StringBuffer(source.length()); - parse(); - } - - private void parse() { - while (hasEncodedWord()) { - String work = source.substring(pos, startIndex); - if (indexOfNonLWSP(work, 0, false) > -1) { - sweepPooledBytes(); - buf.append(work); - } // encoded-word同士の間のLWSPは削除 - parseWord(); - } - sweepPooledBytes(); - buf.append(source.substring(pos)); - } - - // encoded-word があった場合、startIndex/endIndex をセットする - private boolean hasEncodedWord() { - startIndex = source.indexOf("=?", pos); - if (startIndex == -1) - return false; - endIndex = source.indexOf("?=", startIndex + 2); - if (endIndex == -1) - return false; - // 本来は encoded-word 中に LWSP があってはいけないが - // encoded-word の途中で folding してしまう sender がいるらしい - // 以下をコメントにすることで encoded-word の誤認識の可能性も - // 出てくるが、誤認識になる確率以上に前記のような illegal な - // メッセージの方が多いのが実情のようだ。 - // thx > YOSI - //int i = indexOfLWSP(source, startIndex + 2, false, (char)0); - //if (i >= 0 && i < endIndex) - // return false; - endIndex += 2; - return true; - } - - private void parseWord() { - try { - int s = startIndex + 2; - int e = source.indexOf('?', s); - if (e == endIndex - 2) - throw new RuntimeException(); - String ces = source.substring(s, e); - try { - "".getBytes(ces); // FIXME: check whether supported or not - } catch (UnsupportedEncodingException ex) { - ces = "JISAutoDetect"; - } - s = e + 1; - e = source.indexOf('?', s); - if (e == endIndex - 2) - throw new RuntimeException(); - String tes = source.substring(s, e); - byte[] bytes = decodeByTES(source.substring(e + 1, endIndex - 2), tes); - if (ces.equals(pooledCES)) { - // append bytes - byte[] w = new byte[pooledBytes.length + bytes.length]; - System.arraycopy(pooledBytes, 0, w, 0, pooledBytes.length); - System.arraycopy(bytes, 0, w, pooledBytes.length, bytes.length); - pooledBytes = w; - } else { - sweepPooledBytes(); - pooledCES = ces; - pooledBytes = bytes; - } - } catch (Exception ex) { - ex.printStackTrace(); - // contains RuntimeException - buf.append(source.substring(startIndex, endIndex)); - } - pos = endIndex; - } - - private void sweepPooledBytes() { - if (pooledBytes == null) - return; - try { - buf.append(new String(pooledBytes, pooledCES)); - } catch (UnsupportedEncodingException e) { - throw new InternalError("CANT HAPPEN: Illegal encoding = " + pooledCES); - } - pooledCES = null; - pooledBytes = null; - } - - public String get() { - return new String(buf); - } - } - - private static byte[] decodeByTES(String s, String tes) { - // 通常あり得ないが、LWSP を詰める - int i; - while ((i = indexOfLWSP(s, 0, false, (char)0)) >= 0) - s = s.substring(0, i) + s.substring(i + 1); - if (tes.equalsIgnoreCase("B") && s.length() % 4 != 0) { - // BASE64DecoderStream は正確にパディングされていないと - // IOException になるので、無理やり矯正。 - switch (4 - s.length() % 4) { - case 1: - s += '='; - break; - case 2: - s += "=="; - break; - case 3: - if (s.charAt(s.length() - 1) != '=') - s += "==="; - else - s = s.substring(0, s.length() - 1); - break; - } - } - try { - ByteArrayInputStream bis = new ByteArrayInputStream(com.sun.mail.util.ASCIIUtility - .getBytes(s)); - InputStream is; - if (tes.equalsIgnoreCase("B")) - is = new com.sun.mail.util.BASE64DecoderStream(bis); - else if (tes.equalsIgnoreCase("Q")) - is = new com.sun.mail.util.QDecoderStream(bis); - else - throw new UnsupportedEncodingException(tes); - int count = bis.available(); - byte[] bytes = new byte[count]; - count = is.read(bytes, 0, count); - if (count != bytes.length) { - byte[] w = new byte[count]; - System.arraycopy(bytes, 0, w, 0, count); - bytes = w; - } - return bytes; - } catch (IOException e) { - e.printStackTrace(); - throw new RuntimeException("CANT HAPPEN"); - } - } - - /** - * 文字列をエンコードします。 - *

- * MimeUtility(強いてはMimeMessage等も)では、1字でも非ASCII文字が含まれる - * と文字列全体をエンコードしてしまいます。 - *
- * このメソッドでは空白で区切られた範囲だけをエンコードします。
- * Subjectの"Re: "等がエンコードされていると、この文字列でIn-Reply-To: - * References:の代わりにスレッドを形成しようとしても失敗することになる - * ため、こちらのエンコード方式を用いたがる人もいるかもしれません・・。 - *

- *

- * 方針は、ASCII部に前後の空白一つを含ませ、それ以外は空白も含めて全て - * encoded-wordとします。()の内側は空白無しでもエンコード対象です。 - *

- * @param source text - * @return encoded text - */ - // "()" の扱いにこだわりすぎて異常に汚い-_-。 - // "()"なんか無視してまとめて encode するようにすればすっきるするけど…。 - public static String encodeText(String source, String charset, String encoding) - throws UnsupportedEncodingException { - if (source == null) - return null; - int boundaryIndex; - int startIndex; - int endIndex = 0; - int lastLWSPIndex; - StringBuffer buf = new StringBuffer(); - while (true) { - // check the end of ASCII part - boundaryIndex = indexOfNonAscii(source, endIndex); - if (boundaryIndex == -1) { - buf.append(source.substring(endIndex)); - return new String(buf); - } - // any LWSP has taken (back track). - lastLWSPIndex = indexOfLWSP(source, boundaryIndex, true, '('); - startIndex = indexOfNonLWSP(source, lastLWSPIndex, true) + 1; - // ASCII part の終了位置は、次の non ASCII と比べて - // 最も ASCII 文字よりの空白文字位置または'('の次位置 - startIndex = (endIndex > startIndex) ? endIndex : startIndex; - if (startIndex > endIndex) { - // ASCII part - buf.append(source.substring(endIndex, startIndex)); - // JavaMailはencodeWord内でfoldingするけどそれはencodedWord - // に対してのみ。ヘッダそのものに対するfoldingはしてくれない。 - if (isLWSP(source.charAt(startIndex))) { - // folding により 空白一つが確保されるのでスキップ - buf.append("\r\n "); - startIndex++; - // なお、'('の場合は空白を入れないので folding しない - } - } - // any LWSP has taken. - endIndex = indexOfNonLWSP(source, boundaryIndex, false); - while ((endIndex = indexOfLWSP(source, endIndex, false, ')')) != -1) { - endIndex = indexOfNonLWSP(source, endIndex, false); - int nextBoundary = indexOfLWSP(source, endIndex, false, (char)0); - if (nextBoundary == -1) { - if (indexOfNonAscii(source, endIndex) != -1) { - endIndex = -1; - break; - } - } else { - int nonAscii = indexOfNonAscii(source, endIndex); - if (nonAscii != -1 && nonAscii < nextBoundary) { - endIndex = nextBoundary; - continue; - } - } - break; - } - boolean needFolding = false; - if (endIndex < 0) { - endIndex = source.length(); - } else if (isLWSP(source.charAt(endIndex - 1))) { - // folding により 空白一つが確保される(予定)なので減らす - endIndex--; - needFolding = true; - } - String encodeTargetText = source.substring(startIndex, endIndex); - buf.append(MimeUtility.encodeWord(encodeTargetText, charset, encoding)); - if (needFolding) { - // folding により 空白一つが確保されるのでスキップ - endIndex++; - buf.append("\r\n "); - } - } - } - - /** - * 指定位置から最初に見つかった非ASCII文字のIndexを返します。 startIndex が範囲外の場合は -1 を返します。 - * (IndexOutOfBoundsException ではない) - * @param source 検索する文字列 - * @param startIndex 検索開始位置 - * @return 検出した非ASCII文字Index。見つからなければ-1。 - */ - public static int indexOfNonAscii(String source, int startIndex) { - for (int i = startIndex; i < source.length(); i++) { - if (source.charAt(i) > 0x7f) { - return i; - } - } - return -1; - } - - /** - * 指定位置から最初に見つかったLWSP以外の文字のIndexを返します。 startIndex が範囲外の場合は -1 を返します。 - * (IndexOutOfBoundsException ではない) - * @param source 検索する文字列 - * @param startIndex 検索開始位置 - * @param decrease trueで後方検索 - * @return 検出した非ASCII文字Index。見つからなければ-1。 - */ - public static int indexOfNonLWSP(String source, int startIndex, boolean decrease) { - char c; - int inc = 1; - if (decrease) - inc = -1; - for (int i = startIndex; i >= 0 && i < source.length(); i += inc) { - c = source.charAt(i); - if (!isLWSP(c)) { - return i; - } - } - return -1; - } - - /** - * 指定位置から最初に見つかったLWSPのIndexを返します。 startIndex が範囲外の場合は -1 を返します。 - * (IndexOutOfBoundsException ではない) - * @param source 検索する文字列 - * @param startIndex 検索開始位置 - * @param decrease trueで後方検索 - * @param additionalDelimiter LWSP以外に区切りとみなす文字(1字のみ) - * @return 検出した非ASCII文字Index。見つからなければ-1。 - */ - public static int indexOfLWSP(String source, int startIndex, boolean decrease, - char additionalDelimiter) { - char c; - int inc = 1; - if (decrease) - inc = -1; - for (int i = startIndex; i >= 0 && i < source.length(); i += inc) { - c = source.charAt(i); - if (isLWSP(c) || c == additionalDelimiter) { - return i; - } - } - return -1; - } - - public static boolean isLWSP(char c) { - return c == '\r' || c == '\n' || c == ' ' || c == '\t'; - } - - ////////////////////////////////////////////////////////////////////////// - /** - * This method set Content-Disposition: with RFC2231 encoding. It is - * required JavaMail1.2. - */ - /** - * Part#setFileName()のマルチバイト対応版です。 JavaMail1.2でなければコンパイルできません - */ - public static void setFileName(Part part, String filename, String charset, String lang) - throws MessagingException { - // Set the Content-Disposition "filename" parameter - ContentDisposition disposition; - String[] strings = part.getHeader("Content-Disposition"); - if (strings == null || strings.length < 1) { - disposition = new ContentDisposition(Part.ATTACHMENT); - } else { - disposition = new ContentDisposition(strings[0]); - disposition.getParameterList().remove("filename"); - } - part.setHeader("Content-Disposition", disposition.toString() - + encodeParameter("filename", filename, charset, lang)); - ContentType cType; - strings = part.getHeader("Content-Type"); - if (strings == null || strings.length < 1) { - cType = new ContentType(part.getDataHandler().getContentType()); - } else { - cType = new ContentType(strings[0]); - } - try { - // I want to public the MimeUtility#doEncode()!!! - String mimeString = MimeUtility.encodeWord(filename, charset, "B"); - // cut ... - StringBuffer sb = new StringBuffer(); - int i; - while ((i = mimeString.indexOf('\r')) != -1) { - sb.append(mimeString.substring(0, i)); - mimeString = mimeString.substring(i + 2); - } - sb.append(mimeString); - cType.setParameter("name", new String(sb)); - } catch (UnsupportedEncodingException e) { - throw new MessagingException("Encoding error", e); - } - part.setHeader("Content-Type", cType.toString()); - } - - /** - * This method encodes the parameter. - *

- * But most MUA cannot decode the encoded parameters by this method.
- * I recommend using the "Content-Type:"'s name parameter both. - *

- */ - /** - * ヘッダのパラメタ部のエンコードを行います。 - *

- * 現状は受信できないものが多いのでこのメソッドだけでは使えません。
- * Content-Disposition:のfilenameのみに使用し、さらに Content-Type:のnameにMIME - * encodingでの記述も行うのが妥当でしょう。
- * パラメタは必ず行頭から始まるものとします。 (ヘッダの開始行から折り返された位置を開始位置とします) - *

- *

- * foldingの方針はascii/non ascii境界のみをチェックします。 現状は連続するascii/non - * asciiの長さのチェックは現状行っていません。 (エンコード後のバイト数でチェックしなければならないのでかなり面倒) - *

- * @param name パラメタ名 - * @param value エンコード対象のパラメタ値 - * @param encoding 文字エンコーディング - * @param lang 言語指定子 - * @return エンコード済み文字列 ";\r\n name*0*=ISO-8859-2''・・・;\r\n name*1*=・・" - */ - // 1.全体をエンコードして長かったら半分に切ってエンコードを繰り返す - public static String encodeParameter(String name, String value, String encoding, String lang) { - StringBuffer result = new StringBuffer(); - StringBuffer encodedPart = new StringBuffer(); - boolean needWriteCES = !isAllAscii(value); - boolean CESWasWritten = false; - boolean encoded; - boolean needFolding = false; - int sequenceNo = 0; - int column; - while (value.length() > 0) { - // index of boundary of ascii/non ascii - int lastIndex; - boolean isAscii = value.charAt(0) < 0x80; - for (lastIndex = 1; lastIndex < value.length(); lastIndex++) { - if (value.charAt(lastIndex) < 0x80) { - if (!isAscii) - break; - } else { - if (isAscii) - break; - } - } - if (lastIndex != value.length()) - needFolding = true; - RETRY: while (true) { - encodedPart.setLength(0); - String target = value.substring(0, lastIndex); - byte[] bytes; - try { - if (isAscii) { - bytes = target.getBytes("us-ascii"); - } else { - bytes = target.getBytes(encoding); - } - } catch (UnsupportedEncodingException e) { - bytes = target.getBytes(); // use default encoding - encoding = MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset()); - } - encoded = false; - // It is not strict. - column = name.length() + 7; // size of " " and "*nn*=" and ";" - for (int i = 0; i < bytes.length; i++) { - if ((bytes[i] >= '0' && bytes[i] <= '9') - || (bytes[i] >= 'A' && bytes[i] <= 'Z') - || (bytes[i] >= 'a' && bytes[i] <= 'z') || bytes[i] == '$' - || bytes[i] == '.' || bytes[i] == '!') { - // 2001/09/01 しかるべき文字が符号化されない問題修正 - // attribute-char(符号化しなくてもよい文字)の定義は - // - // だが、ややこしいので英数字のみとしておく - // "$.!"はおまけ^^。エンコード時は大して意識はいらない - encodedPart.append((char)bytes[i]); - column++; - } else { - encoded = true; - encodedPart.append('%'); - String hex = Integer.toString(bytes[i] & 0xff, 16); - if (hex.length() == 1) { - encodedPart.append('0'); - } - encodedPart.append(hex); - column += 3; - } - if (column > 76) { - needFolding = true; - lastIndex /= 2; - continue RETRY; - } - } - result.append(";\r\n ").append(name); - if (needFolding) { - result.append('*').append(sequenceNo); - sequenceNo++; - } - if (!CESWasWritten && needWriteCES) { - result.append("*="); - CESWasWritten = true; - result.append(encoding).append('\''); - if (lang != null) - result.append(lang); - result.append('\''); - } else if (encoded) { - result.append("*="); - /* - * 本当にcharacter encodingは先頭パートに書かないとだめなのか? if (encoded) { - * result.append("*="); if (!CESWasWritten && needWriteCES) { - * CESWasWritten = true; - * result.append(encoding).append('\''); if (lang != null) - * result.append(lang); result.append('\''); } - */ - } else { - result.append('='); - } - result.append(new String(encodedPart)); - value = value.substring(lastIndex); - break; - } - } - return new String(result); - } - - /** check if contains only ascii characters in text. */ - public static boolean isAllAscii(String text) { - for (int i = 0; i < text.length(); i++) { - if (text.charAt(i) > 0x7f) { // non-ascii - return false; - } - } - return true; - } - - ////////////////////////////////////////////////////////////////////////// - /** - * This method decode the RFC2231 encoded filename parameter instead of - * Part#getFileName(). - */ - /** - * Part#getFileName()のマルチバイト対応版です。 - */ - public static String getFileName(Part part) throws MessagingException { - String[] disposition = part.getHeader("Content-Disposition"); - // A patch by YOSI (Thanx) - // http://www.sk-jp.com/cgibin/treebbs.cgi?kako=1&all=227&s=227 - String filename; - if (disposition == null || disposition.length < 1 - || (filename = getParameter(disposition[0], "filename")) == null) { - filename = part.getFileName(); - if (filename != null) { - return decodeParameterSpciallyJapanese(filename); - } - return null; - } - return filename; - } - - static class Encoding { - - String encoding = "us-ascii"; - - String lang = ""; - } - - /** - * This method decodes the parameter which be encoded (folded) by RFC2231 - * method. - *

- * The parameter's order should be considered. - *

- */ - /** - * ヘッダのパラメタ部のデコードを行います。 - *

- * RFC2231形式でfolding(分割)されたパラメタを結合し、デコードします。 - * 尚、RFC2231にはパラメタの順番に依存するなと書かれていますが、 それを実装すると大変面倒(一度分割された全てのパートを - * 保持してソートしなければならない)なので、 シーケンス番号に関係なく(0から)順番に 並んでいるものとみなして処理することにします。 - *

- * @param header ヘッダの値全体 - * @param name 取得したいパラメタ名 - * @return デコード済み文字列 (パラメタが存在しない場合は null) - */ - public static String getParameter(String header, String name) throws ParseException { - if (header == null) - return null; - // 本来これは不要。日本固有のデコード処理です。 - // 2001/07/22 書籍版では"あ.txt"の生JISパラメタ値がデコードできない - // これは、ISO-2022-JPバイト列のままHeaderTokenizerにかけると、 - // "あ"のバイトシーケンスに含まれる0x22がダブルクォートと - // 解釈されるため。 - // JIS/Shift_JISの生バイトと思われるもののデコードを先に行う事で回避 - header = decodeParameterSpciallyJapanese(header); - HeaderTokenizer tokenizer = new HeaderTokenizer(header, ";=\t ", true); - HeaderTokenizer.Token token; - StringBuffer sb = new StringBuffer(); - // It is specified in first encoded-part. - Encoding encoding = new Encoding(); - String n; - String v; - try { - while (true) { - token = tokenizer.next(); - if (token.getType() == HeaderTokenizer.Token.EOF) - break; - if (token.getType() != ';') - continue; - token = tokenizer.next(); - checkType(token); - n = token.getValue(); - token = tokenizer.next(); - if (token.getType() != '=') { - throw new ParseException("Illegal token : " + token.getValue()); - } - token = tokenizer.next(); - checkType(token); - v = token.getValue(); - if (n.equalsIgnoreCase(name)) { - // It is not divided and is not encoded. - return v; - } - int index = name.length(); - if (!n.startsWith(name) || n.charAt(index) != '*') { - // another parameter - continue; - } - // be folded, or be encoded - int lastIndex = n.length() - 1; - if (n.charAt(lastIndex) == '*') { - // http://www.sk-jp.com/cgibin/treebbs.cgi?all=399&s=399 - if (index == lastIndex || n.charAt(index + 1) == '0') { - // decode as initial-section - sb.append(decodeRFC2231(v, encoding, true)); - } else { - // decode as other-sections - sb.append(decodeRFC2231(v, encoding, false)); - } - } else { - sb.append(v); - } - if (index == lastIndex) { - // not folding - break; - } - } - if (sb.length() == 0) - return null; - return new String(sb); - } catch (UnsupportedEncodingException e) { - throw new ParseException(e.toString()); - } - } - - private static void checkType(HeaderTokenizer.Token token) throws ParseException { - int t = token.getType(); - if (t != HeaderTokenizer.Token.ATOM && t != HeaderTokenizer.Token.QUOTEDSTRING) { - throw new ParseException("Illegal token : " + token.getValue()); - } - } - - // "lang" tag is ignored... - private static String decodeRFC2231(String s, Encoding encoding, boolean isInitialSection) - throws ParseException, - UnsupportedEncodingException { - StringBuffer sb = new StringBuffer(); - int i = 0; - if (isInitialSection) { - int work = s.indexOf('\''); - if (work > 0) { - encoding.encoding = s.substring(0, work); - work++; - i = s.indexOf('\'', work); - if (i < 0) { - throw new ParseException("lang tag area was missing."); - } - encoding.lang = s.substring(work, i); - i++; - } - } - try { - for (; i < s.length(); i++) { - if (s.charAt(i) == '%') { - sb.append((char)Integer.parseInt(s.substring(i + 1, i + 3), 16)); - i += 2; - continue; - } - sb.append(s.charAt(i)); - } - return new String(new String(sb).getBytes("ISO-8859-1"), encoding.encoding); - } catch (IndexOutOfBoundsException e) { - throw new ParseException(s + " :: this string were not decoded."); - } - } - - // 日本語向けデコード - private static String decodeParameterSpciallyJapanese(String s) throws ParseException { - try { - // decode by character encoding. - // if string are all ASCII, it is not translated. - s = new String(s.getBytes("ISO-8859-1"), "JISAutoDetect"); - // decode by RFC2047. - // if string doesn't contain encoded-word, it is not translated. - return decodeText(s); - } catch (UnsupportedEncodingException e) {} - throw new ParseException("Unsupported Encoding"); - } - - private MailUtility() {} +/* + * @(#) $Id: MailUtility.java,v 1.1.2.1 2005/01/18 07:20:59 otsuka Exp $ + * Copyright (c) 2000-2004 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.Date; + +import javax.activation.DataHandler; +import javax.mail.BodyPart; +import javax.mail.Message; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Part; +import javax.mail.internet.AddressException; +import javax.mail.internet.ContentDisposition; +import javax.mail.internet.ContentType; +import javax.mail.internet.HeaderTokenizer; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MailDateFormat; +import javax.mail.internet.MimeUtility; +import javax.mail.internet.ParseException; + +import com.ozacc.mail.fetch.impl.sk_jp.io.CharCodeConverter; +import com.ozacc.mail.fetch.impl.sk_jp.io.UnicodeCorrector; +import com.ozacc.mail.fetch.impl.sk_jp.text.EntityRefEncoder; +import com.ozacc.mail.fetch.impl.sk_jp.util.StringValues; +import com.sun.mail.util.BASE64EncoderStream; + +/** + * JavaMailのサポートクラスです。 + *

+ * 主にヘッダに対するさまざまな加工機能を提供します。 + *

+ * @author Shin + * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:59 $ + */ +public class MailUtility { + + public static String getPersonal(InternetAddress a) { + if (a.getPersonal() != null) + return a.getPersonal(); + return a.toString(); + } + + /** get comma separated E-Mail addresses. */ + public static String getMailAddresses(InternetAddress[] addresses) { + if (addresses == null) + return null; + StringValues buf = new StringValues(); + for (int i = 0; i < addresses.length; i++) { + buf.add(addresses[i].getAddress()); + } + return buf.getString(); + } + + /** get comma separated personal names. */ + public static String getPersonalNames(InternetAddress[] addresses) { + if (addresses == null) + return null; + StringValues buf = new StringValues(); + String name; + for (int i = 0; i < addresses.length; i++) { + name = decodeText(unfold(addresses[i].getPersonal())); + if (name == null) { + name = addresses[i].toString(); + } + buf.add(name); + } + return buf.getString(); + } + + public static String getAddressesHTML(InternetAddress[] addresses) { + if (addresses == null) + return null; + StringValues buf = new StringValues(); + StringBuffer href = new StringBuffer(); + String name; + for (int i = 0; i < addresses.length; i++) { + href.append(""); + name = addresses[i].getPersonal(); + if (name != null) { + name = decodeText(name); + } + if (name == null) { + name = addresses[i].toString(); + } + href.append(EntityRefEncoder.encode(name)); + href.append(""); + buf.add(new String(href)); + href.setLength(0); + } + return buf.getString(); + } + + /** get the Content-Transfer-Encoding: header value. */ + public static String getTransferEncoding(byte[] b) { + int nonAscii = 0; + for (int i = 0; i < b.length; i++) { + if (b[i] < 0) { + nonAscii++; + } + } + if (nonAscii == 0) + return "7bit"; + if (nonAscii < b.length - nonAscii) + return "quoted-printable"; + return "base64"; + } + + /** + * パートを保有する親Messageオブジェクトを返します。 + * @param part パート + * @return ツリー構造の最上位にあたるメッセージオブジェクト + */ + public static Message getParentMessage(Part part) { + Part current = part; + Multipart mp; + while (!(current instanceof Message)) { + mp = ((BodyPart)current).getParent(); + if (mp == null) + return null; // Should it throw exception? + current = mp.getParent(); + if (current == null) + return null; // Should it throw exception? + } + return (Message)current; + } + + ////////////////////////////////////////////////////////////////////////// + // note: JavaMail1.2 later + private static MailDateFormat mailDateFormat = new MailDateFormat(); + + /** + * Date構文の誤った"JST"タイムゾーンの補正を行います。 + *

+ * JavaMailは"JST"と記述されるタイムゾーンを解釈しません。 ここは本来"+0900"でなければならないところです。
+ * 仕方がないので" JST"が含まれる文字列の場合は"+0900"を補完して + * MailDateFormat#parse()を通すようなparse()のラッパを用意します。 + *

+ *

+ * この実装は一時回避的なものであり、完全なものではありません。 + *

+ */ + public static Date parseDate(String rfc822DateString) { + if (rfc822DateString == null) { + return null; + } + try { + if (rfc822DateString.indexOf(" JST") == -1 || rfc822DateString.indexOf('+') >= 0) { + synchronized (mailDateFormat) { + return mailDateFormat.parse(rfc822DateString); + } + } + // correct the pseudo header + StringBuffer buf = new StringBuffer(rfc822DateString.substring(0, rfc822DateString + .indexOf("JST"))); + buf.append("+0900"); + synchronized (mailDateFormat) { + return mailDateFormat.parse(new String(buf)); + } + } catch (java.text.ParseException e) { + return null; + } + } + + ////////////////////////////////////////////////////////////////////////// + /** + * Subject:に"Re: "を付加します。 + *

+ * ある程度寛容に"Re: "に近い文字列と"[hoge]"を取り除きます。
+ * ただし、意図しない部分が消されてしまう事もあり得ます。
+ * JavaMailのreply()では"Re: "がエンコードされていた場合に 正しく"Re: "を取り除いてくれません。 + *

+ */ + public static String createReplySubject(String src) { + if (src == null || src.length() == 0) { + return "Re: (no subject)"; + } + String work = src; + if (work.charAt(0) == '[' && work.indexOf(']') > 0) { + int afterBracket = indexOfNonLWSP(work, work.indexOf(']') + 1, false); + if (afterBracket < 0) { + work = ""; + } else { + work = work.substring(afterBracket); + } + } + if (work.length() > 3 && "Re:".equalsIgnoreCase(work.substring(0, 3))) { + int afterRe = indexOfNonLWSP(work, 3, false); + if (afterRe < 0) { + work = ""; + } else { + work = work.substring(afterRe); + } + } + return "Re: " + work; + } + + ////////////////////////////////////////////////////////////////////////// + /** + * 入力されたアドレスをInternetAddress形式に変換します。 + *

+ * "名無し君 (コメント)"等の文字列(エンコード無し)を + * 渡されても、正しくpersonal文字列が設定されるようにします。
+ * InternetAddress#parse()はエンコード済みの文字列を前提にしているため、 このメソッドの目的には沿いません。 + *

+ * @param addresses メイルアドレス文字列(カンマ区切り) + */ + public static InternetAddress[] parseAddresses(String addressesString) throws AddressException { + return parseAddresses(addressesString, true); + } + + public static InternetAddress[] parseAddresses(String addressesString, boolean strict) + throws AddressException { + if (addressesString == null) + return null; + try { + InternetAddress[] addresses = InternetAddress.parse(addressesString, strict); + // correct personals + for (int i = 0; i < addresses.length; i++) { + addresses[i].setPersonal(addresses[i].getPersonal(), "ISO-2022-JP"); + } + return addresses; + } catch (UnsupportedEncodingException e) { + throw new InternalError(e.toString()); + } + } + + // InternetAddress.parse( + // encodeText(addressesString, "ISO-2022-JP", "B"), strict); + // で良さそうなものだが、これでは・・たしかなんか問題があったはず。 + ////////////////////////////////////////////////////////////////////////// + /** + * header valueの unfolding を行います。 空白を厳密に扱うためには decodeText より先に呼び出す必要があります。 + */ + public static String unfold(String source) { + if (source == null) + return null; + StringBuffer buf = new StringBuffer(); + boolean skip = false; + char c; + // シーケンスを前提とするならindexOf()で十分ですが、 + // 念のためCR、LFいずれも許容します。 + for (int i = 0; i < source.length(); i++) { + c = source.charAt(i); + if (skip) { + if (isLWSP(c)) { + continue; + } + skip = false; + } + if (c != '\r' && c != '\n') { + buf.append(c); + } else { + buf.append(' '); + skip = true; + } + } + return new String(buf); + } + + /** + * header valueの folding を行います。 + *

+ * white spaceをfolding対象にします。
+ * 76bytesを超えないwhite space位置に を挿入します。 + *

+ *

+ * 注:quoteを無視しますので、structured fieldでは不都合が 発生する可能性があります。 + *

+ * @param used ヘッダの':'までの文字数。76 - usedが最初のfolding候補桁 + * @return foldingされた( SPACEが挿入された)文字列 + */ + public static String fold(String source, int used) { + if (source == null) + return null; + StringBuffer buf = new StringBuffer(); + String work = source; + int lineBreakIndex; + while (work.length() > 76) { + lineBreakIndex = work.lastIndexOf(' ', 76); + if (lineBreakIndex == -1) + break; + buf.append(work.substring(0, lineBreakIndex)); + buf.append("\r\n"); + work = work.substring(lineBreakIndex); + } + buf.append(work); + return new String(buf); + } + + ////////////////////////////////////////////////////////////////////////// + /** + * パートにテキストをセットします。 + * Part#setText() の代わりにこちらを使うことで、 + * "ISO-2022-JP" コンバータではエンコードできない CP932 の + * 文字をエンコードできます。 + */ + public static void setTextContent(Part p, String s) throws MessagingException { + //p.setText(content, "ISO-2022-JP"); + p.setDataHandler(new DataHandler(new JISDataSource(s))); + p.setHeader("Content-Transfer-Encoding", "7bit"); + } + + /** + * 日本語を含むヘッダ用テキストを生成します。 + * 変換結果は ASCII なので、これをそのまま setSubject や InternetAddress + * のパラメタとして使用してください。 + * "ISO-2022-JP" コンバータではエンコードできない CP932 の + * 文字をエンコードできます。ただし、encodeText() と異なり、 + * folding の意識をしておらず、また ASCII 部分を除いて分割 + * エンコードを行うこともできません。 + */ + public static String encodeWordJIS(String s) { + try { + return "=?ISO-2022-JP?B?" + + new String(BASE64EncoderStream.encode(CharCodeConverter + .sjisToJis(UnicodeCorrector.getInstance("Windows-31J").correct(s) + .getBytes("Windows-31J")))) + "?="; + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("CANT HAPPEN"); + } + } + + ////////////////////////////////////////////////////////////////////////// + /** + * ヘッダ内の文字列をデコードします。 + *

+ * MimeUtilityの制約を緩めて日本で流通するエンコード形式に対応。 + * 本来は、encoded-wordとnon-encoded-wordの間にはlinear-white-spaceが必要 + * なのですが、空白が無い場所でエンコードするタコメイラが多いので。 + *

+ *

+ * JISコードをエンコード無しで記述するタコメイラもあります。
+ * ソースにESCが含まれていたら生JISと見なします。 + *

+ *

+ * =?utf-8?Q?・・・JISコード・・?=なんてさらにタコなメイラも。
+ * 試しにデコード後にまだESCが残ってたらISO-2022-JPと見なすことにします。 + *

+ *

+ * さらに、multibyte character の前後で別の encoded-word に切ってしまう メイラも…。隣接する + * encoded-word の CES が同じ場合はバイト列の 結合を行ってから CES デコードを行うようにした…。 + *

+ *

+ * 日本語に特化してますねえ・・・。 + *

+ * @param source encoded text + * @return decoded text + */ + public static String decodeText(String source) { + if (source == null) + return null; + // specially for Japanese + if (source.indexOf('\u001b') >= 0) { + // ISO-2022-JP + try { + return new String(source.getBytes("ISO-8859-1"), "ISO-2022-JP"); + } catch (UnsupportedEncodingException e) { + throw new InternalError(); + } + } + String decodedText = new RFC2047Decoder(source).get(); + if (decodedText.indexOf('\u001b') >= 0) { + try { + return new String(decodedText.getBytes("ISO-8859-1"), "ISO-2022-JP"); + } catch (UnsupportedEncodingException e) { + throw new InternalError(); + } + } + return decodedText; + } + + // 日本語をデコードする上で問題があるので、encoded-wordの切り出しはすべて独自に + // Netscapeなどは"()."等の文字でencoded-wordを切ってしまうが、JavaMailは + // このときencoded-wordの終わりを判定できず、一部の文字を欠落させてしまう。 + // また、encoded-word を文字デコードするのを遅延させ、隣接する encoded-word + // の CES が同じ場合は、先に TES デコードを行ったバイト列を結合してから + // CES に従ったデコードを行う。マルチバイト文字を分断する sender がいるから。 + static class RFC2047Decoder { + + private String source; + + private String pooledCES; + + private byte[] pooledBytes; + + private StringBuffer buf; + + private int pos = 0; + + private int startIndex; + + private int endIndex; + + public RFC2047Decoder(String source) { + this.source = source; + buf = new StringBuffer(source.length()); + parse(); + } + + private void parse() { + while (hasEncodedWord()) { + String work = source.substring(pos, startIndex); + if (indexOfNonLWSP(work, 0, false) > -1) { + sweepPooledBytes(); + buf.append(work); + } // encoded-word同士の間のLWSPは削除 + parseWord(); + } + sweepPooledBytes(); + buf.append(source.substring(pos)); + } + + // encoded-word があった場合、startIndex/endIndex をセットする + private boolean hasEncodedWord() { + startIndex = source.indexOf("=?", pos); + if (startIndex == -1) + return false; + endIndex = source.indexOf("?=", startIndex + 2); + if (endIndex == -1) + return false; + // 本来は encoded-word 中に LWSP があってはいけないが + // encoded-word の途中で folding してしまう sender がいるらしい + // 以下をコメントにすることで encoded-word の誤認識の可能性も + // 出てくるが、誤認識になる確率以上に前記のような illegal な + // メッセージの方が多いのが実情のようだ。 + // thx > YOSI + //int i = indexOfLWSP(source, startIndex + 2, false, (char)0); + //if (i >= 0 && i < endIndex) + // return false; + endIndex += 2; + return true; + } + + private void parseWord() { + try { + int s = startIndex + 2; + int e = source.indexOf('?', s); + if (e == endIndex - 2) + throw new RuntimeException(); + String ces = source.substring(s, e); + try { + "".getBytes(ces); // FIXME: check whether supported or not + } catch (UnsupportedEncodingException ex) { + ces = "JISAutoDetect"; + } + s = e + 1; + e = source.indexOf('?', s); + if (e == endIndex - 2) + throw new RuntimeException(); + String tes = source.substring(s, e); + byte[] bytes = decodeByTES(source.substring(e + 1, endIndex - 2), tes); + if (ces.equals(pooledCES)) { + // append bytes + byte[] w = new byte[pooledBytes.length + bytes.length]; + System.arraycopy(pooledBytes, 0, w, 0, pooledBytes.length); + System.arraycopy(bytes, 0, w, pooledBytes.length, bytes.length); + pooledBytes = w; + } else { + sweepPooledBytes(); + pooledCES = ces; + pooledBytes = bytes; + } + } catch (Exception ex) { + ex.printStackTrace(); + // contains RuntimeException + buf.append(source.substring(startIndex, endIndex)); + } + pos = endIndex; + } + + private void sweepPooledBytes() { + if (pooledBytes == null) + return; + try { + buf.append(new String(pooledBytes, pooledCES)); + } catch (UnsupportedEncodingException e) { + throw new InternalError("CANT HAPPEN: Illegal encoding = " + pooledCES); + } + pooledCES = null; + pooledBytes = null; + } + + public String get() { + return new String(buf); + } + } + + private static byte[] decodeByTES(String s, String tes) { + // 通常あり得ないが、LWSP を詰める + int i; + while ((i = indexOfLWSP(s, 0, false, (char)0)) >= 0) + s = s.substring(0, i) + s.substring(i + 1); + if (tes.equalsIgnoreCase("B") && s.length() % 4 != 0) { + // BASE64DecoderStream は正確にパディングされていないと + // IOException になるので、無理やり矯正。 + switch (4 - s.length() % 4) { + case 1: + s += '='; + break; + case 2: + s += "=="; + break; + case 3: + if (s.charAt(s.length() - 1) != '=') + s += "==="; + else + s = s.substring(0, s.length() - 1); + break; + } + } + try { + ByteArrayInputStream bis = new ByteArrayInputStream(com.sun.mail.util.ASCIIUtility + .getBytes(s)); + InputStream is; + if (tes.equalsIgnoreCase("B")) + is = new com.sun.mail.util.BASE64DecoderStream(bis); + else if (tes.equalsIgnoreCase("Q")) + is = new com.sun.mail.util.QDecoderStream(bis); + else + throw new UnsupportedEncodingException(tes); + int count = bis.available(); + byte[] bytes = new byte[count]; + count = is.read(bytes, 0, count); + if (count != bytes.length) { + byte[] w = new byte[count]; + System.arraycopy(bytes, 0, w, 0, count); + bytes = w; + } + return bytes; + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("CANT HAPPEN"); + } + } + + /** + * 文字列をエンコードします。 + *

+ * MimeUtility(強いてはMimeMessage等も)では、1字でも非ASCII文字が含まれる + * と文字列全体をエンコードしてしまいます。 + *
+ * このメソッドでは空白で区切られた範囲だけをエンコードします。
+ * Subjectの"Re: "等がエンコードされていると、この文字列でIn-Reply-To: + * References:の代わりにスレッドを形成しようとしても失敗することになる + * ため、こちらのエンコード方式を用いたがる人もいるかもしれません・・。 + *

+ *

+ * 方針は、ASCII部に前後の空白一つを含ませ、それ以外は空白も含めて全て + * encoded-wordとします。()の内側は空白無しでもエンコード対象です。 + *

+ * @param source text + * @return encoded text + */ + // "()" の扱いにこだわりすぎて異常に汚い-_-。 + // "()"なんか無視してまとめて encode するようにすればすっきるするけど…。 + public static String encodeText(String source, String charset, String encoding) + throws UnsupportedEncodingException { + if (source == null) + return null; + int boundaryIndex; + int startIndex; + int endIndex = 0; + int lastLWSPIndex; + StringBuffer buf = new StringBuffer(); + while (true) { + // check the end of ASCII part + boundaryIndex = indexOfNonAscii(source, endIndex); + if (boundaryIndex == -1) { + buf.append(source.substring(endIndex)); + return new String(buf); + } + // any LWSP has taken (back track). + lastLWSPIndex = indexOfLWSP(source, boundaryIndex, true, '('); + startIndex = indexOfNonLWSP(source, lastLWSPIndex, true) + 1; + // ASCII part の終了位置は、次の non ASCII と比べて + // 最も ASCII 文字よりの空白文字位置または'('の次位置 + startIndex = (endIndex > startIndex) ? endIndex : startIndex; + if (startIndex > endIndex) { + // ASCII part + buf.append(source.substring(endIndex, startIndex)); + // JavaMailはencodeWord内でfoldingするけどそれはencodedWord + // に対してのみ。ヘッダそのものに対するfoldingはしてくれない。 + if (isLWSP(source.charAt(startIndex))) { + // folding により 空白一つが確保されるのでスキップ + buf.append("\r\n "); + startIndex++; + // なお、'('の場合は空白を入れないので folding しない + } + } + // any LWSP has taken. + endIndex = indexOfNonLWSP(source, boundaryIndex, false); + while ((endIndex = indexOfLWSP(source, endIndex, false, ')')) != -1) { + endIndex = indexOfNonLWSP(source, endIndex, false); + int nextBoundary = indexOfLWSP(source, endIndex, false, (char)0); + if (nextBoundary == -1) { + if (indexOfNonAscii(source, endIndex) != -1) { + endIndex = -1; + break; + } + } else { + int nonAscii = indexOfNonAscii(source, endIndex); + if (nonAscii != -1 && nonAscii < nextBoundary) { + endIndex = nextBoundary; + continue; + } + } + break; + } + boolean needFolding = false; + if (endIndex < 0) { + endIndex = source.length(); + } else if (isLWSP(source.charAt(endIndex - 1))) { + // folding により 空白一つが確保される(予定)なので減らす + endIndex--; + needFolding = true; + } + String encodeTargetText = source.substring(startIndex, endIndex); + buf.append(MimeUtility.encodeWord(encodeTargetText, charset, encoding)); + if (needFolding) { + // folding により 空白一つが確保されるのでスキップ + endIndex++; + buf.append("\r\n "); + } + } + } + + /** + * 指定位置から最初に見つかった非ASCII文字のIndexを返します。 startIndex が範囲外の場合は -1 を返します。 + * (IndexOutOfBoundsException ではない) + * @param source 検索する文字列 + * @param startIndex 検索開始位置 + * @return 検出した非ASCII文字Index。見つからなければ-1。 + */ + public static int indexOfNonAscii(String source, int startIndex) { + for (int i = startIndex; i < source.length(); i++) { + if (source.charAt(i) > 0x7f) { + return i; + } + } + return -1; + } + + /** + * 指定位置から最初に見つかったLWSP以外の文字のIndexを返します。 startIndex が範囲外の場合は -1 を返します。 + * (IndexOutOfBoundsException ではない) + * @param source 検索する文字列 + * @param startIndex 検索開始位置 + * @param decrease trueで後方検索 + * @return 検出した非ASCII文字Index。見つからなければ-1。 + */ + public static int indexOfNonLWSP(String source, int startIndex, boolean decrease) { + char c; + int inc = 1; + if (decrease) + inc = -1; + for (int i = startIndex; i >= 0 && i < source.length(); i += inc) { + c = source.charAt(i); + if (!isLWSP(c)) { + return i; + } + } + return -1; + } + + /** + * 指定位置から最初に見つかったLWSPのIndexを返します。 startIndex が範囲外の場合は -1 を返します。 + * (IndexOutOfBoundsException ではない) + * @param source 検索する文字列 + * @param startIndex 検索開始位置 + * @param decrease trueで後方検索 + * @param additionalDelimiter LWSP以外に区切りとみなす文字(1字のみ) + * @return 検出した非ASCII文字Index。見つからなければ-1。 + */ + public static int indexOfLWSP(String source, int startIndex, boolean decrease, + char additionalDelimiter) { + char c; + int inc = 1; + if (decrease) + inc = -1; + for (int i = startIndex; i >= 0 && i < source.length(); i += inc) { + c = source.charAt(i); + if (isLWSP(c) || c == additionalDelimiter) { + return i; + } + } + return -1; + } + + public static boolean isLWSP(char c) { + return c == '\r' || c == '\n' || c == ' ' || c == '\t'; + } + + ////////////////////////////////////////////////////////////////////////// + /** + * This method set Content-Disposition: with RFC2231 encoding. It is + * required JavaMail1.2. + */ + /** + * Part#setFileName()のマルチバイト対応版です。 JavaMail1.2でなければコンパイルできません + */ + public static void setFileName(Part part, String filename, String charset, String lang) + throws MessagingException { + // Set the Content-Disposition "filename" parameter + ContentDisposition disposition; + String[] strings = part.getHeader("Content-Disposition"); + if (strings == null || strings.length < 1) { + disposition = new ContentDisposition(Part.ATTACHMENT); + } else { + disposition = new ContentDisposition(strings[0]); + disposition.getParameterList().remove("filename"); + } + part.setHeader("Content-Disposition", disposition.toString() + + encodeParameter("filename", filename, charset, lang)); + ContentType cType; + strings = part.getHeader("Content-Type"); + if (strings == null || strings.length < 1) { + cType = new ContentType(part.getDataHandler().getContentType()); + } else { + cType = new ContentType(strings[0]); + } + try { + // I want to public the MimeUtility#doEncode()!!! + String mimeString = MimeUtility.encodeWord(filename, charset, "B"); + // cut ... + StringBuffer sb = new StringBuffer(); + int i; + while ((i = mimeString.indexOf('\r')) != -1) { + sb.append(mimeString.substring(0, i)); + mimeString = mimeString.substring(i + 2); + } + sb.append(mimeString); + cType.setParameter("name", new String(sb)); + } catch (UnsupportedEncodingException e) { + throw new MessagingException("Encoding error", e); + } + part.setHeader("Content-Type", cType.toString()); + } + + /** + * This method encodes the parameter. + *

+ * But most MUA cannot decode the encoded parameters by this method.
+ * I recommend using the "Content-Type:"'s name parameter both. + *

+ */ + /** + * ヘッダのパラメタ部のエンコードを行います。 + *

+ * 現状は受信できないものが多いのでこのメソッドだけでは使えません。
+ * Content-Disposition:のfilenameのみに使用し、さらに Content-Type:のnameにMIME + * encodingでの記述も行うのが妥当でしょう。
+ * パラメタは必ず行頭から始まるものとします。 (ヘッダの開始行から折り返された位置を開始位置とします) + *

+ *

+ * foldingの方針はascii/non ascii境界のみをチェックします。 現状は連続するascii/non + * asciiの長さのチェックは現状行っていません。 (エンコード後のバイト数でチェックしなければならないのでかなり面倒) + *

+ * @param name パラメタ名 + * @param value エンコード対象のパラメタ値 + * @param encoding 文字エンコーディング + * @param lang 言語指定子 + * @return エンコード済み文字列 ";\r\n name*0*=ISO-8859-2''・・・;\r\n name*1*=・・" + */ + // 1.全体をエンコードして長かったら半分に切ってエンコードを繰り返す + public static String encodeParameter(String name, String value, String encoding, String lang) { + StringBuffer result = new StringBuffer(); + StringBuffer encodedPart = new StringBuffer(); + boolean needWriteCES = !isAllAscii(value); + boolean CESWasWritten = false; + boolean encoded; + boolean needFolding = false; + int sequenceNo = 0; + int column; + while (value.length() > 0) { + // index of boundary of ascii/non ascii + int lastIndex; + boolean isAscii = value.charAt(0) < 0x80; + for (lastIndex = 1; lastIndex < value.length(); lastIndex++) { + if (value.charAt(lastIndex) < 0x80) { + if (!isAscii) + break; + } else { + if (isAscii) + break; + } + } + if (lastIndex != value.length()) + needFolding = true; + RETRY: while (true) { + encodedPart.setLength(0); + String target = value.substring(0, lastIndex); + byte[] bytes; + try { + if (isAscii) { + bytes = target.getBytes("us-ascii"); + } else { + bytes = target.getBytes(encoding); + } + } catch (UnsupportedEncodingException e) { + bytes = target.getBytes(); // use default encoding + encoding = MimeUtility.mimeCharset(MimeUtility.getDefaultJavaCharset()); + } + encoded = false; + // It is not strict. + column = name.length() + 7; // size of " " and "*nn*=" and ";" + for (int i = 0; i < bytes.length; i++) { + if ((bytes[i] >= '0' && bytes[i] <= '9') + || (bytes[i] >= 'A' && bytes[i] <= 'Z') + || (bytes[i] >= 'a' && bytes[i] <= 'z') || bytes[i] == '$' + || bytes[i] == '.' || bytes[i] == '!') { + // 2001/09/01 しかるべき文字が符号化されない問題修正 + // attribute-char(符号化しなくてもよい文字)の定義は + // + // だが、ややこしいので英数字のみとしておく + // "$.!"はおまけ^^。エンコード時は大して意識はいらない + encodedPart.append((char)bytes[i]); + column++; + } else { + encoded = true; + encodedPart.append('%'); + String hex = Integer.toString(bytes[i] & 0xff, 16); + if (hex.length() == 1) { + encodedPart.append('0'); + } + encodedPart.append(hex); + column += 3; + } + if (column > 76) { + needFolding = true; + lastIndex /= 2; + continue RETRY; + } + } + result.append(";\r\n ").append(name); + if (needFolding) { + result.append('*').append(sequenceNo); + sequenceNo++; + } + if (!CESWasWritten && needWriteCES) { + result.append("*="); + CESWasWritten = true; + result.append(encoding).append('\''); + if (lang != null) + result.append(lang); + result.append('\''); + } else if (encoded) { + result.append("*="); + /* + * 本当にcharacter encodingは先頭パートに書かないとだめなのか? if (encoded) { + * result.append("*="); if (!CESWasWritten && needWriteCES) { + * CESWasWritten = true; + * result.append(encoding).append('\''); if (lang != null) + * result.append(lang); result.append('\''); } + */ + } else { + result.append('='); + } + result.append(new String(encodedPart)); + value = value.substring(lastIndex); + break; + } + } + return new String(result); + } + + /** check if contains only ascii characters in text. */ + public static boolean isAllAscii(String text) { + for (int i = 0; i < text.length(); i++) { + if (text.charAt(i) > 0x7f) { // non-ascii + return false; + } + } + return true; + } + + ////////////////////////////////////////////////////////////////////////// + /** + * This method decode the RFC2231 encoded filename parameter instead of + * Part#getFileName(). + */ + /** + * Part#getFileName()のマルチバイト対応版です。 + */ + public static String getFileName(Part part) throws MessagingException { + String[] disposition = part.getHeader("Content-Disposition"); + // A patch by YOSI (Thanx) + // http://www.sk-jp.com/cgibin/treebbs.cgi?kako=1&all=227&s=227 + String filename; + if (disposition == null || disposition.length < 1 + || (filename = getParameter(disposition[0], "filename")) == null) { + filename = part.getFileName(); + if (filename != null) { + return decodeParameterSpciallyJapanese(filename); + } + return null; + } + return filename; + } + + static class Encoding { + + String encoding = "us-ascii"; + + String lang = ""; + } + + /** + * This method decodes the parameter which be encoded (folded) by RFC2231 + * method. + *

+ * The parameter's order should be considered. + *

+ */ + /** + * ヘッダのパラメタ部のデコードを行います。 + *

+ * RFC2231形式でfolding(分割)されたパラメタを結合し、デコードします。 + * 尚、RFC2231にはパラメタの順番に依存するなと書かれていますが、 それを実装すると大変面倒(一度分割された全てのパートを + * 保持してソートしなければならない)なので、 シーケンス番号に関係なく(0から)順番に 並んでいるものとみなして処理することにします。 + *

+ * @param header ヘッダの値全体 + * @param name 取得したいパラメタ名 + * @return デコード済み文字列 (パラメタが存在しない場合は null) + */ + public static String getParameter(String header, String name) throws ParseException { + if (header == null) + return null; + // 本来これは不要。日本固有のデコード処理です。 + // 2001/07/22 書籍版では"あ.txt"の生JISパラメタ値がデコードできない + // これは、ISO-2022-JPバイト列のままHeaderTokenizerにかけると、 + // "あ"のバイトシーケンスに含まれる0x22がダブルクォートと + // 解釈されるため。 + // JIS/Shift_JISの生バイトと思われるもののデコードを先に行う事で回避 + header = decodeParameterSpciallyJapanese(header); + HeaderTokenizer tokenizer = new HeaderTokenizer(header, ";=\t ", true); + HeaderTokenizer.Token token; + StringBuffer sb = new StringBuffer(); + // It is specified in first encoded-part. + Encoding encoding = new Encoding(); + String n; + String v; + try { + while (true) { + token = tokenizer.next(); + if (token.getType() == HeaderTokenizer.Token.EOF) + break; + if (token.getType() != ';') + continue; + token = tokenizer.next(); + checkType(token); + n = token.getValue(); + token = tokenizer.next(); + if (token.getType() != '=') { + throw new ParseException("Illegal token : " + token.getValue()); + } + token = tokenizer.next(); + checkType(token); + v = token.getValue(); + if (n.equalsIgnoreCase(name)) { + // It is not divided and is not encoded. + return v; + } + int index = name.length(); + if (!n.startsWith(name) || n.charAt(index) != '*') { + // another parameter + continue; + } + // be folded, or be encoded + int lastIndex = n.length() - 1; + if (n.charAt(lastIndex) == '*') { + // http://www.sk-jp.com/cgibin/treebbs.cgi?all=399&s=399 + if (index == lastIndex || n.charAt(index + 1) == '0') { + // decode as initial-section + sb.append(decodeRFC2231(v, encoding, true)); + } else { + // decode as other-sections + sb.append(decodeRFC2231(v, encoding, false)); + } + } else { + sb.append(v); + } + if (index == lastIndex) { + // not folding + break; + } + } + if (sb.length() == 0) + return null; + return new String(sb); + } catch (UnsupportedEncodingException e) { + throw new ParseException(e.toString()); + } + } + + private static void checkType(HeaderTokenizer.Token token) throws ParseException { + int t = token.getType(); + if (t != HeaderTokenizer.Token.ATOM && t != HeaderTokenizer.Token.QUOTEDSTRING) { + throw new ParseException("Illegal token : " + token.getValue()); + } + } + + // "lang" tag is ignored... + private static String decodeRFC2231(String s, Encoding encoding, boolean isInitialSection) + throws ParseException, + UnsupportedEncodingException { + StringBuffer sb = new StringBuffer(); + int i = 0; + if (isInitialSection) { + int work = s.indexOf('\''); + if (work > 0) { + encoding.encoding = s.substring(0, work); + work++; + i = s.indexOf('\'', work); + if (i < 0) { + throw new ParseException("lang tag area was missing."); + } + encoding.lang = s.substring(work, i); + i++; + } + } + try { + for (; i < s.length(); i++) { + if (s.charAt(i) == '%') { + sb.append((char)Integer.parseInt(s.substring(i + 1, i + 3), 16)); + i += 2; + continue; + } + sb.append(s.charAt(i)); + } + return new String(new String(sb).getBytes("ISO-8859-1"), encoding.encoding); + } catch (IndexOutOfBoundsException e) { + throw new ParseException(s + " :: this string were not decoded."); + } + } + + // 日本語向けデコード + private static String decodeParameterSpciallyJapanese(String s) throws ParseException { + try { + // decode by character encoding. + // if string are all ASCII, it is not translated. + s = new String(s.getBytes("ISO-8859-1"), "JISAutoDetect"); + // decode by RFC2047. + // if string doesn't contain encoded-word, it is not translated. + return decodeText(s); + } catch (UnsupportedEncodingException e) {} + throw new ParseException("Unsupported Encoding"); + } + + private MailUtility() {} } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MultipartUtility.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MultipartUtility.java old mode 100755 new mode 100644 index 95ab8cb..7c779d5 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MultipartUtility.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/MultipartUtility.java @@ -1,173 +1,173 @@ -/* - * @(#) $Id: MultipartUtility.java,v 1.1.2.2 2004/10/24 10:26:50 otsuka Exp $ - * $Revision: 1.1.2.2 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; - -import javax.activation.DataHandler; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.Part; -import javax.mail.internet.ContentType; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMultipart; - -/** - * メッセージボディを取り出す手段を提供するstaticメソッドのセットです。 - *

- *

- * @version $Revision: 1.1.2.2 $ $Date: 2004/10/24 10:26:50 $ - * @author Shin - * @author Tomohiro Otsuka - */ -public class MultipartUtility { - - private static final String JIS_CHARSET = "ISO-2022-JP"; - - /** - * 指定パートのボディを返します。 - *

- * Part#getContent()の代わりです。 - * MIMEに準拠しないContent-Type:の補正を行います。 - * charset指定がない場合は"ISO-2022-JP"を補います。 - *

- * パートがUTF-7の場合も正常に内容を取得出来ます。 - *

- */ - public static Object getContent(Part part) throws MessagingException, IOException { - return getContent(part, JIS_CHARSET); - } - - private static CorrectedContentTypeDataSource correctedDataSource = new CorrectedContentTypeDataSourceUTF7Support(); - - private static DataHandler correctedDataHandler = new DataHandler(correctedDataSource); - - /** - * 指定パートのボディを返します。 - *

- * MIMEに準拠しないContent-Type:の補正を行います。 - * charset指定がない場合はcharsetで指定されたもので補います。 - *

- * パートがUTF-7の場合も正常に内容を取得出来ます。 - *

- */ - public static Object getContent(Part part, String charset) throws MessagingException, - IOException { - synchronized (correctedDataSource) { - - correctedDataSource.setPart(part); - try { - correctedDataSource.setDefaultCharset(charset); - return correctedDataHandler.getContent(); - } catch (UnsupportedEncodingException e) { - /* - * 不正な文字コードがcharsetにセットされ例外がスローされた場合に - * JIS_CHARSETに文字コードを置き換え、再度ホディの取得を試みます。 - * - * by otsuka - */ - correctedDataSource.setForceCharset(JIS_CHARSET); - return correctedDataHandler.getContent(); - } - - } - } - - /** - * 指定パート配下で最初に見つけたテキストパートのボディを返します。 - * process()を呼び出して結果を返すだけのconvenience methodです。 - */ - public static String getFirstPlainText(Part part) throws MessagingException { - FirstPlainPartExtractor h = new FirstPlainPartExtractor(); - process(part, h); - return h.getText(); - } - - /** - * 指定パート配下のinlineなテキストパートを集めて表示用のボディを返します。 - * process()を呼び出して結果を返すだけのconvenience methodです。 - */ - public static String getPlainText(Part part) throws MessagingException { - PlainPartExtractor h = new PlainPartExtractor(); - process(part, h); - return h.getText(); - } - - /** - * 指定パート配下の各パートを処理します。 - *

- * すべてのPartに対してPartHandlerが呼び出されます。
- *

- */ - public static void process(Part part, PartHandler handler) throws MessagingException { - process(part, handler, null); - } - - private static boolean process(Part part, PartHandler handler, ContentType context) - throws MessagingException { - try { - if (part.isMimeType("multipart/*")) { - Multipart mp = (Multipart)part.getContent(); - ContentType cType = new ContentType(part.getContentType()); - for (int i = 0; i < mp.getCount(); i++) { - if (!process(mp.getBodyPart(i), handler, cType)) { - return false; - } - } - return true; - } - return handler.processPart(part, context); - } catch (IOException e) { - throw new MessagingException("Got exception \nin " + part + "\n", e); - } - } - - /** - * 指定partにbodyPartを追加します。 - * partがマルチパーとコンテナの場合はそのコンテナにbodyPartを追加します。 - * そうでない場合はpartのボディとしてmultipart/mixedのコンテナを設定し、 - * 元のpartのボディとbodyPartのボディをそのコンテナに追加します。 - */ - public static void addBodyPart(Part part, MimeBodyPart bodyPart) throws MessagingException, - IOException { - if (part.isMimeType("multipart/*")) { - ((MimeMultipart)part.getContent()).addBodyPart(bodyPart); - return; - } - // 仮 - MimeMultipart mp = new MimeMultipart("mixed"); - MimeBodyPart original = new MimeBodyPart(); - original.setContent(part.getContent(), part.getContentType()); - mp.addBodyPart(original); - mp.addBodyPart(bodyPart); - part.setContent(mp); - } - - /** - * partのツリー構造をダンプするデバッグ用メソッドです。 - */ - public static void dump(Part part) { - dump(part, 0); - } - - private static void dump(Part part, int layer) { - for (int i = 0; i < layer; i++) { - System.out.print(" "); - } - try { - System.out.println(part.getClass() + ":" + part.getContentType()); - if (part.isMimeType("multipart/*")) { - MimeMultipart mp = (MimeMultipart)part.getContent(); - for (int i = 0; i < mp.getCount(); i++) { - dump(mp.getBodyPart(i), layer + 1); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - } +/* + * @(#) $Id: MultipartUtility.java,v 1.1.2.2 2004/10/24 10:26:50 otsuka Exp $ + * $Revision: 1.1.2.2 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import javax.activation.DataHandler; +import javax.mail.MessagingException; +import javax.mail.Multipart; +import javax.mail.Part; +import javax.mail.internet.ContentType; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMultipart; + +/** + * メッセージボディを取り出す手段を提供するstaticメソッドのセットです。 + *

+ *

+ * @version $Revision: 1.1.2.2 $ $Date: 2004/10/24 10:26:50 $ + * @author Shin + * @author Tomohiro Otsuka + */ +public class MultipartUtility { + + private static final String JIS_CHARSET = "ISO-2022-JP"; + + /** + * 指定パートのボディを返します。 + *

+ * Part#getContent()の代わりです。 + * MIMEに準拠しないContent-Type:の補正を行います。 + * charset指定がない場合は"ISO-2022-JP"を補います。 + *

+ * パートがUTF-7の場合も正常に内容を取得出来ます。 + *

+ */ + public static Object getContent(Part part) throws MessagingException, IOException { + return getContent(part, JIS_CHARSET); + } + + private static CorrectedContentTypeDataSource correctedDataSource = new CorrectedContentTypeDataSourceUTF7Support(); + + private static DataHandler correctedDataHandler = new DataHandler(correctedDataSource); + + /** + * 指定パートのボディを返します。 + *

+ * MIMEに準拠しないContent-Type:の補正を行います。 + * charset指定がない場合はcharsetで指定されたもので補います。 + *

+ * パートがUTF-7の場合も正常に内容を取得出来ます。 + *

+ */ + public static Object getContent(Part part, String charset) throws MessagingException, + IOException { + synchronized (correctedDataSource) { + + correctedDataSource.setPart(part); + try { + correctedDataSource.setDefaultCharset(charset); + return correctedDataHandler.getContent(); + } catch (UnsupportedEncodingException e) { + /* + * 不正な文字コードがcharsetにセットされ例外がスローされた場合に + * JIS_CHARSETに文字コードを置き換え、再度ホディの取得を試みます。 + * + * by otsuka + */ + correctedDataSource.setForceCharset(JIS_CHARSET); + return correctedDataHandler.getContent(); + } + + } + } + + /** + * 指定パート配下で最初に見つけたテキストパートのボディを返します。 + * process()を呼び出して結果を返すだけのconvenience methodです。 + */ + public static String getFirstPlainText(Part part) throws MessagingException { + FirstPlainPartExtractor h = new FirstPlainPartExtractor(); + process(part, h); + return h.getText(); + } + + /** + * 指定パート配下のinlineなテキストパートを集めて表示用のボディを返します。 + * process()を呼び出して結果を返すだけのconvenience methodです。 + */ + public static String getPlainText(Part part) throws MessagingException { + PlainPartExtractor h = new PlainPartExtractor(); + process(part, h); + return h.getText(); + } + + /** + * 指定パート配下の各パートを処理します。 + *

+ * すべてのPartに対してPartHandlerが呼び出されます。
+ *

+ */ + public static void process(Part part, PartHandler handler) throws MessagingException { + process(part, handler, null); + } + + private static boolean process(Part part, PartHandler handler, ContentType context) + throws MessagingException { + try { + if (part.isMimeType("multipart/*")) { + Multipart mp = (Multipart)part.getContent(); + ContentType cType = new ContentType(part.getContentType()); + for (int i = 0; i < mp.getCount(); i++) { + if (!process(mp.getBodyPart(i), handler, cType)) { + return false; + } + } + return true; + } + return handler.processPart(part, context); + } catch (IOException e) { + throw new MessagingException("Got exception \nin " + part + "\n", e); + } + } + + /** + * 指定partにbodyPartを追加します。 + * partがマルチパーとコンテナの場合はそのコンテナにbodyPartを追加します。 + * そうでない場合はpartのボディとしてmultipart/mixedのコンテナを設定し、 + * 元のpartのボディとbodyPartのボディをそのコンテナに追加します。 + */ + public static void addBodyPart(Part part, MimeBodyPart bodyPart) throws MessagingException, + IOException { + if (part.isMimeType("multipart/*")) { + ((MimeMultipart)part.getContent()).addBodyPart(bodyPart); + return; + } + // 仮 + MimeMultipart mp = new MimeMultipart("mixed"); + MimeBodyPart original = new MimeBodyPart(); + original.setContent(part.getContent(), part.getContentType()); + mp.addBodyPart(original); + mp.addBodyPart(bodyPart); + part.setContent(mp); + } + + /** + * partのツリー構造をダンプするデバッグ用メソッドです。 + */ + public static void dump(Part part) { + dump(part, 0); + } + + private static void dump(Part part, int layer) { + for (int i = 0; i < layer; i++) { + System.out.print(" "); + } + try { + System.out.println(part.getClass() + ":" + part.getContentType()); + if (part.isMimeType("multipart/*")) { + MimeMultipart mp = (MimeMultipart)part.getContent(); + for (int i = 0; i < mp.getCount(); i++) { + dump(mp.getBodyPart(i), layer + 1); + } + } + } catch (Exception e) { + e.printStackTrace(); + } + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PartHandler.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PartHandler.java old mode 100755 new mode 100644 index 410b277..328d2bf --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PartHandler.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PartHandler.java @@ -1,48 +1,48 @@ -/* - * @(#) $Id: PartHandler.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.IOException; -import javax.mail.Part; -import javax.mail.MessagingException; -import javax.mail.internet.ContentType; - -/** - * PartHandlerです。 - *

- * MultipartUtility#process()に渡すことで、Message内の各Partオブジェクト - * に対してprocessPartが呼び出されます。
- * 特定のMIMEタイプに対してのみ処理を行う場合などに有効です。 - *

- * 使用方法としては、実装クラス上に各パートの処理結果を蓄積していき、 - * MultipartUtility#process()メソッド復帰後にそのオブジェクトから最終結果を - * 取り出すような形式が考えられます。 - *

- * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ - * @author Shin - */ -public interface PartHandler { - - /** - * パートに対して処理を行います。 - *

- * contextにはそのパートがmultipart/*の子パートである場合に、 - * そのmultipart/*のMIMEタイプが渡されます。
- * 続けて次のパートを処理するか否かを復帰値で返してください。 - *

- * message/rfc822パートの内部も走査したい場合は、実装クラス内で - * 以下のようにコーディングしてください。 - *

- *
if (part.isMimeType("message/rfc822")) {
-	 *     // message/rfc822パートの処理オブジェクト
-	 *     AnyHandler h = new AnyHandler();
-	 *     MultipartUtility.process(part, h);
-	 * }
-	 * 
- * @return true:次のパート、或いは内包メッセージ内部も処理する - */ - boolean processPart(Part part, ContentType context) throws MessagingException, IOException; +/* + * @(#) $Id: PartHandler.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.IOException; +import javax.mail.Part; +import javax.mail.MessagingException; +import javax.mail.internet.ContentType; + +/** + * PartHandlerです。 + *

+ * MultipartUtility#process()に渡すことで、Message内の各Partオブジェクト + * に対してprocessPartが呼び出されます。
+ * 特定のMIMEタイプに対してのみ処理を行う場合などに有効です。 + *

+ * 使用方法としては、実装クラス上に各パートの処理結果を蓄積していき、 + * MultipartUtility#process()メソッド復帰後にそのオブジェクトから最終結果を + * 取り出すような形式が考えられます。 + *

+ * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ + * @author Shin + */ +public interface PartHandler { + + /** + * パートに対して処理を行います。 + *

+ * contextにはそのパートがmultipart/*の子パートである場合に、 + * そのmultipart/*のMIMEタイプが渡されます。
+ * 続けて次のパートを処理するか否かを復帰値で返してください。 + *

+ * message/rfc822パートの内部も走査したい場合は、実装クラス内で + * 以下のようにコーディングしてください。 + *

+ *
if (part.isMimeType("message/rfc822")) {
+	 *     // message/rfc822パートの処理オブジェクト
+	 *     AnyHandler h = new AnyHandler();
+	 *     MultipartUtility.process(part, h);
+	 * }
+	 * 
+ * @return true:次のパート、或いは内包メッセージ内部も処理する + */ + boolean processPart(Part part, ContentType context) throws MessagingException, IOException; } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PlainPartExtractor.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PlainPartExtractor.java old mode 100755 new mode 100644 index ed6a565..f251f28 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PlainPartExtractor.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/PlainPartExtractor.java @@ -1,55 +1,55 @@ -/* - * @(#) $Id: PlainPartExtractor.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp; - -import java.io.IOException; - -import javax.mail.MessagingException; -import javax.mail.Part; -import javax.mail.internet.ContentType; -import javax.mail.internet.MimeMessage; - -/** - * text/plainを結合した文字列を得るPartHandlerです。 - * - * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ - * @author Shin - */ -public class PlainPartExtractor implements PartHandler { - - private String text = null; - - public boolean processPart(Part part, ContentType context) throws MessagingException, - IOException { - if (!part.isMimeType("text/plain")) { - return true; - } - if (text == null) { - // 最初のテキストパートを無条件に抽出 - text = (String)MultipartUtility.getContent(part); - } else { - String disposition = part.getDisposition(); - if (disposition == null || disposition.equalsIgnoreCase(Part.INLINE)) { - text += "\r\n\r\n-- inline --\r\n\r\n" + (String)MultipartUtility.getContent(part); - } - } - return true; - } - - public String getText() { - return text; - } - - public static void main(String[] args) throws Exception { - MimeMessage msg = new MimeMessage(javax.mail.Session.getDefaultInstance(System - .getProperties(), null), System.in); - PlainPartExtractor h = new PlainPartExtractor(); - MultipartUtility.process(msg, h); - - System.out.println("This is the detected text/plain parts."); - System.out.println(h.getText()); - } +/* + * @(#) $Id: PlainPartExtractor.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp; + +import java.io.IOException; + +import javax.mail.MessagingException; +import javax.mail.Part; +import javax.mail.internet.ContentType; +import javax.mail.internet.MimeMessage; + +/** + * text/plainを結合した文字列を得るPartHandlerです。 + * + * @version $Revision: 1.1.2.1 $ $Date: 2004/09/29 00:57:59 $ + * @author Shin + */ +public class PlainPartExtractor implements PartHandler { + + private String text = null; + + public boolean processPart(Part part, ContentType context) throws MessagingException, + IOException { + if (!part.isMimeType("text/plain")) { + return true; + } + if (text == null) { + // 最初のテキストパートを無条件に抽出 + text = (String)MultipartUtility.getContent(part); + } else { + String disposition = part.getDisposition(); + if (disposition == null || disposition.equalsIgnoreCase(Part.INLINE)) { + text += "\r\n\r\n-- inline --\r\n\r\n" + (String)MultipartUtility.getContent(part); + } + } + return true; + } + + public String getText() { + return text; + } + + public static void main(String[] args) throws Exception { + MimeMessage msg = new MimeMessage(javax.mail.Session.getDefaultInstance(System + .getProperties(), null), System.in); + PlainPartExtractor h = new PlainPartExtractor(); + MultipartUtility.process(msg, h); + + System.out.println("This is the detected text/plain parts."); + System.out.println(h.getText()); + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ByteToCharUTF7.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ByteToCharUTF7.java old mode 100755 new mode 100644 index 8a4315c..1a62f21 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ByteToCharUTF7.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ByteToCharUTF7.java @@ -1,139 +1,139 @@ -/* - * @(#) $Id: ByteToCharUTF7.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp.io; - -/** - * UTF-7のデコーダです。 - *

- *

- * @author Shin - */ -public class ByteToCharUTF7 extends sun.io.ByteToCharConverter { - public String getCharacterEncoding() { - return "UTF7"; - } - - public int flush(char[] chars, int off, int len) { - byteOff = 0; - charOff = 0; - b64Context = false; - currentB64Off = 0; - currentChar = 0; - return 0; - } - public void reset() { - byteOff = 0; - charOff = 0; - b64Context = false; - currentB64Off = 0; - currentChar = 0; - } - - private boolean b64Context = false; - private int currentB64Off = 0; - private char currentChar = 0; - - public int convert( - byte[] bytes, - int byteStart, - int byteEnd, - char[] chars, - int charStart, - int charEnd) - throws - sun.io.ConversionBufferFullException, - sun.io.UnknownCharacterException { - charOff = charStart; - - for (byteOff = byteStart; byteOff < byteEnd; byteOff++) { - if (charOff >= charEnd) { - throw new sun.io.ConversionBufferFullException(); - } - if (b64Context) { - if (bytes[byteOff] == '-') { - if (currentB64Off != 0 && currentChar > 0) { - chars[charOff] = currentChar; - charOff++; - } - b64Context = false; - continue; - } - int part = - ( - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - + "abcdefghijklmnopqrstuvwxyz0123456789+/").indexOf( - bytes[byteOff]); - if (part == -1) { - throw new sun.io.UnknownCharacterException( - "Invalid UTF-7 code: " + (char)bytes[byteOff]); - } - - switch (currentB64Off) { - case 0 : - currentChar = (char) (part << 10); - break; - case 1 : - currentChar |= (char) (part << 4); - break; - case 2 : - currentChar |= (char) (part >> 2); - chars[charOff] = currentChar; - charOff++; - currentChar = (char) ((part & 0x03) << 14); - break; - case 3 : - currentChar |= (char) (part << 8); - break; - case 4 : - currentChar |= (char) (part << 2); - break; - case 5 : - currentChar |= (char) (part >> 4); - chars[charOff] = currentChar; - charOff++; - currentChar = (char) ((part & 0x0f) << 12); - break; - case 6 : - currentChar |= (char) (part << 6); - break; - case 7 : - currentChar |= (char)part; - chars[charOff] = currentChar; - charOff++; - break; - } - currentB64Off = (currentB64Off + 1) % 8; - continue; - } - - if (bytes[byteOff] == '+') { - // shift character - // This is start of the Base64 sequence. - b64Context = true; - currentB64Off = 0; - continue; - } - chars[charOff] = (char)bytes[byteOff]; - charOff++; - } - return charOff - charStart; - } - - /* - public static void main(String[] args) throws Exception { - System.setProperty("file.encoding.pkg", "com.sk_jp.io"); - ByteArrayOutputStream o = new ByteArrayOutputStream(); - byte[] b = new byte[2048]; - int len; - while ((len = System.in.read(b)) != -1) { - o.write(b, 0, len); - } - byte[] bytes = o.toByteArray(); - - System.out.println(new String(bytes, "UTF7")); - } - */ -} +/* + * @(#) $Id: ByteToCharUTF7.java,v 1.1.2.1 2004/09/29 00:57:59 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp.io; + +/** + * UTF-7のデコーダです。 + *

+ *

+ * @author Shin + */ +public class ByteToCharUTF7 extends sun.io.ByteToCharConverter { + public String getCharacterEncoding() { + return "UTF7"; + } + + public int flush(char[] chars, int off, int len) { + byteOff = 0; + charOff = 0; + b64Context = false; + currentB64Off = 0; + currentChar = 0; + return 0; + } + public void reset() { + byteOff = 0; + charOff = 0; + b64Context = false; + currentB64Off = 0; + currentChar = 0; + } + + private boolean b64Context = false; + private int currentB64Off = 0; + private char currentChar = 0; + + public int convert( + byte[] bytes, + int byteStart, + int byteEnd, + char[] chars, + int charStart, + int charEnd) + throws + sun.io.ConversionBufferFullException, + sun.io.UnknownCharacterException { + charOff = charStart; + + for (byteOff = byteStart; byteOff < byteEnd; byteOff++) { + if (charOff >= charEnd) { + throw new sun.io.ConversionBufferFullException(); + } + if (b64Context) { + if (bytes[byteOff] == '-') { + if (currentB64Off != 0 && currentChar > 0) { + chars[charOff] = currentChar; + charOff++; + } + b64Context = false; + continue; + } + int part = + ( + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + "abcdefghijklmnopqrstuvwxyz0123456789+/").indexOf( + bytes[byteOff]); + if (part == -1) { + throw new sun.io.UnknownCharacterException( + "Invalid UTF-7 code: " + (char)bytes[byteOff]); + } + + switch (currentB64Off) { + case 0 : + currentChar = (char) (part << 10); + break; + case 1 : + currentChar |= (char) (part << 4); + break; + case 2 : + currentChar |= (char) (part >> 2); + chars[charOff] = currentChar; + charOff++; + currentChar = (char) ((part & 0x03) << 14); + break; + case 3 : + currentChar |= (char) (part << 8); + break; + case 4 : + currentChar |= (char) (part << 2); + break; + case 5 : + currentChar |= (char) (part >> 4); + chars[charOff] = currentChar; + charOff++; + currentChar = (char) ((part & 0x0f) << 12); + break; + case 6 : + currentChar |= (char) (part << 6); + break; + case 7 : + currentChar |= (char)part; + chars[charOff] = currentChar; + charOff++; + break; + } + currentB64Off = (currentB64Off + 1) % 8; + continue; + } + + if (bytes[byteOff] == '+') { + // shift character + // This is start of the Base64 sequence. + b64Context = true; + currentB64Off = 0; + continue; + } + chars[charOff] = (char)bytes[byteOff]; + charOff++; + } + return charOff - charStart; + } + + /* + public static void main(String[] args) throws Exception { + System.setProperty("file.encoding.pkg", "com.sk_jp.io"); + ByteArrayOutputStream o = new ByteArrayOutputStream(); + byte[] b = new byte[2048]; + int len; + while ((len = System.in.read(b)) != -1) { + o.write(b, 0, len); + } + byte[] bytes = o.toByteArray(); + + System.out.println(new String(bytes, "UTF7")); + } + */ +} diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/CharCodeConverter.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/CharCodeConverter.java old mode 100755 new mode 100644 index 5522e0f..b42bb19 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/CharCodeConverter.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/CharCodeConverter.java @@ -1,160 +1,160 @@ -/* - * Copyright (c) 2003 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp.io; - -import java.io.ByteArrayOutputStream; -import java.io.UnsupportedEncodingException; - -/** - * 文字関係のコンバータです。 - * 一部コードのオリジナルはJapanese Kanji Codeにて公開されているものです。 - * また、http://www.sk-jp.com/cgi-bin/treebbs.cgi?kako=1&all=644&s=681 - * にて YOSI さんが公開されたコードも参考にしています(というか実質同じです)。 - * - * @author Shin - * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ - */ -public class CharCodeConverter { - public static final byte[] SJIS_KANA; - static { - try { - // 全角への変換テーブル - SJIS_KANA = "。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜".getBytes("Shift_JIS"); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("CANT HAPPEN"); - } - } - - /** - * Shift_JIS エンコーディングスキームに基づくバイト列を - * ISO-2022-JP エンコーディングスキームに変換します。 - * 「半角カナ」は対応する全角文字に変換します。 - */ - public static byte[] sjisToJis(byte[] sjisBytes) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - boolean nonAscii = false; - int len = sjisBytes.length; - for (int i = 0; i < len; i++ ) { - if (sjisBytes[i] >= 0) { - if (nonAscii) { - nonAscii = false; - out.write(0x1b); - out.write('('); - out.write('B'); - } - out.write(sjisBytes[i]); - } else { - if (!nonAscii) { - nonAscii = true; - out.write(0x1b); - out.write('$'); - out.write('B'); - } - int b = sjisBytes[i] & 0xff; - if (b >= 0xa1 && b <= 0xdf) { - // 半角カナは全角に変換 - int kanaIndex = (b - 0xA1) * 2; - sjisToJis(out, SJIS_KANA[kanaIndex], SJIS_KANA[kanaIndex + 1]); - } else { - i++; - if (i == len) break; - sjisToJis(out, sjisBytes[i - 1], sjisBytes[i]); - } - } - } - if (nonAscii) { - out.write(0x1b); - out.write('('); - out.write('B'); - } - return out.toByteArray(); - } - /** - * 1文字の2バイト Shift_JIS コードを JIS コードに変換して書き出します。 - */ - private static void sjisToJis( - ByteArrayOutputStream out, byte bh, byte bl) { - int h = (bh << 1) & 0xFF; - int l = bl & 0xFF; - if (l < 0x9F) { - if (h < 0x3F) h += 0x1F; else h -= 0x61; - if (l > 0x7E) l -= 0x20; else l -= 0x1F; - } else { - if (h < 0x3F) h += 0x20; else h -= 0x60; - l -= 0x7E; - } - out.write(h); - out.write(l); - } - - /** - * 配列はワイドキャラクタの境界にないことを前提としています。 - * また、エスケープシーケンスが適切に含まれることも前提です。 - * エスケープシーケンスが"(B"/"$B"以外の場合は無視します。 - */ - public byte[] jisTosjis(byte[] jisBytes) { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - boolean nonAscii = false; - boolean kana = false; - int len = jisBytes.length; - for (int i = 0; i < len; i++) { - if (jisBytes[i] == 0x1b) { - if (i + 2 >= len) break; - if (jisBytes[i + 1] == '$' && jisBytes[i + 2] == 'B') { - nonAscii = true; - i += 2; - } else if (jisBytes[i + 1] == '(' && jisBytes[i + 2] == 'I') { - kana = true; - i += 2; - } else if (jisBytes[i + 1] == '(' && jisBytes[i + 2] == 'B') { - nonAscii = false; - kana = false; - i += 2; - } else { - // illegal sequence は当面無視 - nonAscii = false; - kana = false; - } - continue; - } - if (jisBytes[i] == 0x0e) { // SO - kana = true; - continue; - } - if (jisBytes[i] == 0x0f) { // SI - kana = false; - continue; - } - if (kana) { - out.write(jisBytes[i] | 0x80); - } else if (nonAscii) { - i++; - if (i == jisBytes.length) break; - jisToSjis(out, jisBytes[i - 1], jisBytes[i]); - } else { - out.write(jisBytes[i]); - } - } - return out.toByteArray(); - } - /** - * 1文字の2バイト JIS コードを Shift_JIS に変換して書き出します。 - */ - private static void jisToSjis( - ByteArrayOutputStream out, byte bh, byte bl) { - int h = bh & 0xFF; - int l = bl & 0xFF; - if ((h & 0x01) > 0) { - h >>= 1; - if (h < 0x2F) h += 0x71; else h -= 0x4F; - if (l > 0x5F) l += 0x20; else l += 0x1F; - } else { - h >>= 1; - if (h < 0x2F) h += 0x70; else h -= 0x50; - l += 0x7E; - } - out.write(h); - out.write(l); - } -} +/* + * Copyright (c) 2003 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp.io; + +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; + +/** + * 文字関係のコンバータです。 + * 一部コードのオリジナルはJapanese Kanji Codeにて公開されているものです。 + * また、http://www.sk-jp.com/cgi-bin/treebbs.cgi?kako=1&all=644&s=681 + * にて YOSI さんが公開されたコードも参考にしています(というか実質同じです)。 + * + * @author Shin + * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ + */ +public class CharCodeConverter { + public static final byte[] SJIS_KANA; + static { + try { + // 全角への変換テーブル + SJIS_KANA = "。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゛゜".getBytes("Shift_JIS"); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException("CANT HAPPEN"); + } + } + + /** + * Shift_JIS エンコーディングスキームに基づくバイト列を + * ISO-2022-JP エンコーディングスキームに変換します。 + * 「半角カナ」は対応する全角文字に変換します。 + */ + public static byte[] sjisToJis(byte[] sjisBytes) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + boolean nonAscii = false; + int len = sjisBytes.length; + for (int i = 0; i < len; i++ ) { + if (sjisBytes[i] >= 0) { + if (nonAscii) { + nonAscii = false; + out.write(0x1b); + out.write('('); + out.write('B'); + } + out.write(sjisBytes[i]); + } else { + if (!nonAscii) { + nonAscii = true; + out.write(0x1b); + out.write('$'); + out.write('B'); + } + int b = sjisBytes[i] & 0xff; + if (b >= 0xa1 && b <= 0xdf) { + // 半角カナは全角に変換 + int kanaIndex = (b - 0xA1) * 2; + sjisToJis(out, SJIS_KANA[kanaIndex], SJIS_KANA[kanaIndex + 1]); + } else { + i++; + if (i == len) break; + sjisToJis(out, sjisBytes[i - 1], sjisBytes[i]); + } + } + } + if (nonAscii) { + out.write(0x1b); + out.write('('); + out.write('B'); + } + return out.toByteArray(); + } + /** + * 1文字の2バイト Shift_JIS コードを JIS コードに変換して書き出します。 + */ + private static void sjisToJis( + ByteArrayOutputStream out, byte bh, byte bl) { + int h = (bh << 1) & 0xFF; + int l = bl & 0xFF; + if (l < 0x9F) { + if (h < 0x3F) h += 0x1F; else h -= 0x61; + if (l > 0x7E) l -= 0x20; else l -= 0x1F; + } else { + if (h < 0x3F) h += 0x20; else h -= 0x60; + l -= 0x7E; + } + out.write(h); + out.write(l); + } + + /** + * 配列はワイドキャラクタの境界にないことを前提としています。 + * また、エスケープシーケンスが適切に含まれることも前提です。 + * エスケープシーケンスが"(B"/"$B"以外の場合は無視します。 + */ + public byte[] jisTosjis(byte[] jisBytes) { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + boolean nonAscii = false; + boolean kana = false; + int len = jisBytes.length; + for (int i = 0; i < len; i++) { + if (jisBytes[i] == 0x1b) { + if (i + 2 >= len) break; + if (jisBytes[i + 1] == '$' && jisBytes[i + 2] == 'B') { + nonAscii = true; + i += 2; + } else if (jisBytes[i + 1] == '(' && jisBytes[i + 2] == 'I') { + kana = true; + i += 2; + } else if (jisBytes[i + 1] == '(' && jisBytes[i + 2] == 'B') { + nonAscii = false; + kana = false; + i += 2; + } else { + // illegal sequence は当面無視 + nonAscii = false; + kana = false; + } + continue; + } + if (jisBytes[i] == 0x0e) { // SO + kana = true; + continue; + } + if (jisBytes[i] == 0x0f) { // SI + kana = false; + continue; + } + if (kana) { + out.write(jisBytes[i] | 0x80); + } else if (nonAscii) { + i++; + if (i == jisBytes.length) break; + jisToSjis(out, jisBytes[i - 1], jisBytes[i]); + } else { + out.write(jisBytes[i]); + } + } + return out.toByteArray(); + } + /** + * 1文字の2バイト JIS コードを Shift_JIS に変換して書き出します。 + */ + private static void jisToSjis( + ByteArrayOutputStream out, byte bh, byte bl) { + int h = bh & 0xFF; + int l = bl & 0xFF; + if ((h & 0x01) > 0) { + h >>= 1; + if (h < 0x2F) h += 0x71; else h -= 0x4F; + if (l > 0x5F) l += 0x20; else l += 0x1F; + } else { + h >>= 1; + if (h < 0x2F) h += 0x70; else h -= 0x50; + l += 0x7E; + } + out.write(h); + out.write(l); + } +} diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/FromCP932Corrector.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/FromCP932Corrector.java old mode 100755 new mode 100644 index 3657385..cbadf51 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/FromCP932Corrector.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/FromCP932Corrector.java @@ -1,48 +1,48 @@ -/* - * @(#) $Id: FromCP932Corrector.java,v 1.1.2.1 2005/01/18 07:20:36 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp.io; - -/** - * FromCP932Corrector. - *

- * CorrectOutputStreamWriterで用いられる文字列バッファ補正クラスです。
- * 風間一洋さんのJavaHouse-Brewers投稿記事[14452]のCp932クラスから - * 変換表を参考にさせていただいています。
- *

- * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ - * @author Shin - */ -public class FromCP932Corrector extends UnicodeCorrector { - /** - * Unicode文字配列の補正を行います。 - *

- * "MS932""Shift_JIS"エンコーディング以外で出力しようとした際の - * sun.ioやcom.msコンバータでは正常に変換できない部分を補正します。 - *

- * @param c source character - * @return Result character that corrected. - */ - public char correct(char c) { - switch (c) { - // ISO-2022-JPコンバータが正しく解釈しているようだ -// case 0xff3c: // FULLWIDTH REVERSE SOLIDUS -> -// return 0x005c; // REVERSE SOLIDUS - case 0xff5e: // FULLWIDTH TILDE -> - return 0x301c; // WAVE DASH - case 0x2225: // PARALLEL TO -> - return 0x2016; // DOUBLE VERTICAL LINE - case 0xff0d: // FULLWIDTH HYPHEN-MINUS -> - return 0x2212; // MINUS SIGN - case 0xffe0: // FULLWIDTH CENT SIGN -> - return 0x00a2; // CENT SIGN - case 0xffe1: // FULLWIDTH POUND SIGN -> - return 0x00a3; // POUND SIGN - case 0xffe2: // FULLWIDTH NOT SIGN -> - return 0x00ac; // NOT SIGN - } - return c; - } -} +/* + * @(#) $Id: FromCP932Corrector.java,v 1.1.2.1 2005/01/18 07:20:36 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp.io; + +/** + * FromCP932Corrector. + *

+ * CorrectOutputStreamWriterで用いられる文字列バッファ補正クラスです。
+ * 風間一洋さんのJavaHouse-Brewers投稿記事[14452]のCp932クラスから + * 変換表を参考にさせていただいています。
+ *

+ * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ + * @author Shin + */ +public class FromCP932Corrector extends UnicodeCorrector { + /** + * Unicode文字配列の補正を行います。 + *

+ * "MS932""Shift_JIS"エンコーディング以外で出力しようとした際の + * sun.ioやcom.msコンバータでは正常に変換できない部分を補正します。 + *

+ * @param c source character + * @return Result character that corrected. + */ + public char correct(char c) { + switch (c) { + // ISO-2022-JPコンバータが正しく解釈しているようだ +// case 0xff3c: // FULLWIDTH REVERSE SOLIDUS -> +// return 0x005c; // REVERSE SOLIDUS + case 0xff5e: // FULLWIDTH TILDE -> + return 0x301c; // WAVE DASH + case 0x2225: // PARALLEL TO -> + return 0x2016; // DOUBLE VERTICAL LINE + case 0xff0d: // FULLWIDTH HYPHEN-MINUS -> + return 0x2212; // MINUS SIGN + case 0xffe0: // FULLWIDTH CENT SIGN -> + return 0x00a2; // CENT SIGN + case 0xffe1: // FULLWIDTH POUND SIGN -> + return 0x00a3; // POUND SIGN + case 0xffe2: // FULLWIDTH NOT SIGN -> + return 0x00ac; // NOT SIGN + } + return c; + } +} diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ToCP932Corrector.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ToCP932Corrector.java old mode 100755 new mode 100644 index 322b43b..156033a --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ToCP932Corrector.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/ToCP932Corrector.java @@ -1,51 +1,51 @@ -/* - * @(#) $Id: ToCP932Corrector.java,v 1.1.2.1 2005/01/18 07:20:36 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp.io; - -/** - * ToCP932Corrector. - *

- * CorrectOutputStreamWriterで用いられる文字列バッファ補正クラスです。
- * 風間一洋さんのJavaHouse-Brewers投稿記事[14452]のCp932クラス - * (XML日本語プロファイルも同じです)から - * 変換表を参考にさせていただいています。
- *

- * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ - * @author Shin - */ -public class ToCP932Corrector extends UnicodeCorrector { - /** - * Unicode文字の補正を行います。 - *

- * 特定の文字を"MS932""Shift_JIS"エンコーディングで出力しようとした際の - * sun.ioコンバータでは正常に変換できない部分を補正します。 - *

- * @param c source character - * @return Result character that corrected. - */ - public char correct(char c) { - switch (c) { -// case 0x005c: // REVERSE SOLIDUS -> -// return 0xff3c; // FULLWIDTH REVERSE SOLIDUS - case 0x301c: // WAVE DASH -> - return 0xff5e; // FULLWIDTH TILDE - case 0x2016: // DOUBLE VERTICAL LINE -> - return 0x2225; // PARALLEL TO - case 0x2212: // MINUS SIGN -> - return 0xff0d; // FULLWIDTH HYPHEN-MINUS - // MS932コンバータが正しく解釈しているようだ -/* - case 0x00a2: // CENT SIGN -> - return 0xffe0; // FULLWIDTH CENT SIGN - case 0x00a3: // POUND SIGN -> - return 0xffe1; // FULLWIDTH POUND SIGN - case 0x00ac: // NOT SIGN -> - return 0xffe2; // FULLWIDTH NOT SIGN -*/ - } - return c; - } -} +/* + * @(#) $Id: ToCP932Corrector.java,v 1.1.2.1 2005/01/18 07:20:36 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp.io; + +/** + * ToCP932Corrector. + *

+ * CorrectOutputStreamWriterで用いられる文字列バッファ補正クラスです。
+ * 風間一洋さんのJavaHouse-Brewers投稿記事[14452]のCp932クラス + * (XML日本語プロファイルも同じです)から + * 変換表を参考にさせていただいています。
+ *

+ * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ + * @author Shin + */ +public class ToCP932Corrector extends UnicodeCorrector { + /** + * Unicode文字の補正を行います。 + *

+ * 特定の文字を"MS932""Shift_JIS"エンコーディングで出力しようとした際の + * sun.ioコンバータでは正常に変換できない部分を補正します。 + *

+ * @param c source character + * @return Result character that corrected. + */ + public char correct(char c) { + switch (c) { +// case 0x005c: // REVERSE SOLIDUS -> +// return 0xff3c; // FULLWIDTH REVERSE SOLIDUS + case 0x301c: // WAVE DASH -> + return 0xff5e; // FULLWIDTH TILDE + case 0x2016: // DOUBLE VERTICAL LINE -> + return 0x2225; // PARALLEL TO + case 0x2212: // MINUS SIGN -> + return 0xff0d; // FULLWIDTH HYPHEN-MINUS + // MS932コンバータが正しく解釈しているようだ +/* + case 0x00a2: // CENT SIGN -> + return 0xffe0; // FULLWIDTH CENT SIGN + case 0x00a3: // POUND SIGN -> + return 0xffe1; // FULLWIDTH POUND SIGN + case 0x00ac: // NOT SIGN -> + return 0xffe2; // FULLWIDTH NOT SIGN +*/ + } + return c; + } +} diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/UnicodeCorrector.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/UnicodeCorrector.java old mode 100755 new mode 100644 index 4561d36..07affe3 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/UnicodeCorrector.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/io/UnicodeCorrector.java @@ -1,130 +1,130 @@ -/* - * @(#) $Id: UnicodeCorrector.java,v 1.1.2.1 2005/01/18 07:20:36 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ -package com.ozacc.mail.fetch.impl.sk_jp.io; - -import java.io.UnsupportedEncodingException; -import java.util.HashMap; -import java.util.Map; - -/** - * UnicodeCorrector. - *

- * CorrectOutputStreamWriterで用いられる文字列バッファ補正クラスです。
- * 出力エンコーディングによって補正すべき文字コードが異なるので、 - * 実際の補正処理はサブクラスで行います。
- * - * 対応しているのは以下のコンバータ名です。 - *

- *
    - *
  • ISO2022JP - *
  • ISO-2022-JP - *
  • EUC-JP - *
  • EUCJIS - *
  • SJIS - *
  • Shift_JIS - *
  • MS932 - *
  • Windows-31J - *
- * @author Shin - * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ - */ -public abstract class UnicodeCorrector { - private static final Map correctorMap = new HashMap(); - static { - // x-sjis-cp932等でおかしく変換されたUnicodeを他のエンコーディングで - // 出力する場合です - correctorMap.put("iso2022jp", FromCP932Corrector.class); - correctorMap.put("iso-2022-jp", FromCP932Corrector.class); - correctorMap.put("euc-jp", FromCP932Corrector.class); - correctorMap.put("eucjis", FromCP932Corrector.class); - // 同じ"SJIS"でもSunとMS-VMでは異なります。 - // Sun-JDK1.1はSJISはx-sjis-jdk-1.1.7で、MS-VMはx-sjis-cp932です。 - // しかし、MS-JDK中のクラスライブラリだけはx-sjis-jdk-1.1.7相当になるので - // 困ったものです。(ファイル書き出し等のときのみおかしくなる) - // これはWindowsネイティブな変換表で生成されたUnicodeを - // x-sjis-jdk-1.1.7で出力するためのものです。 - correctorMap.put("sjis", FromCP932Corrector.class); - correctorMap.put("shift_jis", FromCP932Corrector.class); - // MS-VMでファイル出力を行う場合に限り、こちらでなければなりません。 - // correctorMap.put("sjis", ToCP932Corrector.class); - // JDK1.2からはWindowsのデフォルトが"MS932"(x-sjis-cp932相当)となりました。 - // これで、他のエンコーディングで変換された(正しい)Unicodeが"ms932" - // での出力時におかしくなってしまいます。 - // これを補正します。 - correctorMap.put("ms932", ToCP932Corrector.class); - correctorMap.put("windows-31j", ToCP932Corrector.class); - } - - /** - * Create an UnicodeCorrector that uses - * the named character encoding. - * @param enc Name of the encoding to be used - * @exception UnsupportedEncodingException - * If the named encoding is not supported - */ - public static UnicodeCorrector getInstance(String enc) - throws UnsupportedEncodingException { - Class correctorClass = (Class)correctorMap.get(enc.toLowerCase()); - if (correctorClass == null) { - throw new UnsupportedEncodingException(enc); - } - try { - return (UnicodeCorrector)correctorClass.newInstance(); - } catch (Exception e) { - throw new UnsupportedEncodingException( - correctorClass + " cannot get newInstance.\n" + e); - } - } - - /** - * Unicode文字配列の補正を行います。 - *

- * 特定の文字を特定エンコーディングで出力しようとした際の - * sun.ioコンバータでは正常に変換できない部分を補正します。 - *

- * @param cbuf Buffer of characters - * @param off Offset from which to start writing characters - * @param len Number of characters to write - * @return Result that corrected. - * Note:Return array is different from cbuf - * in case of different result size. - */ - public char[] correct(char cbuf[], int off, int len) { - StringBuffer buf = new StringBuffer(); - for (int i = off; i < len; i++) { - buf.append(correct(cbuf[i])); - } - return new String(buf).toCharArray(); - } - - public String correct(String s) { - StringBuffer buf = new StringBuffer(); - for (int i = 0; i < s.length(); i++) { - buf.append(correct(s.charAt(i))); - } - return new String(buf); - } - - // 性能的にこれをabstractにするのはためらったが・・・ - public abstract char correct(char c); - - /** - * 新しいUnicodeCorrectorを追加します。 - *

- * このソースコードを変えずに、動的に新たな出力エンコーディングに - * 対応したUnicodeCorrectorを登録したい場合に用います。 - *

- * @param enc 対応するエンコーディング名 - * @param correctorClass UnicodeCorrectorサブクラスのClassオブジェクト - */ - public static void addCorrector(String enc, Class correctorClass) { - if (!correctorClass.isInstance(UnicodeCorrector.class)) { - throw new IllegalArgumentException( - "Corrector is not UnicodeCorrector type."); - } - correctorMap.put(enc, correctorClass); - } +/* + * @(#) $Id: UnicodeCorrector.java,v 1.1.2.1 2005/01/18 07:20:36 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ +package com.ozacc.mail.fetch.impl.sk_jp.io; + +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +/** + * UnicodeCorrector. + *

+ * CorrectOutputStreamWriterで用いられる文字列バッファ補正クラスです。
+ * 出力エンコーディングによって補正すべき文字コードが異なるので、 + * 実際の補正処理はサブクラスで行います。
+ * + * 対応しているのは以下のコンバータ名です。 + *

+ *
    + *
  • ISO2022JP + *
  • ISO-2022-JP + *
  • EUC-JP + *
  • EUCJIS + *
  • SJIS + *
  • Shift_JIS + *
  • MS932 + *
  • Windows-31J + *
+ * @author Shin + * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:36 $ + */ +public abstract class UnicodeCorrector { + private static final Map correctorMap = new HashMap(); + static { + // x-sjis-cp932等でおかしく変換されたUnicodeを他のエンコーディングで + // 出力する場合です + correctorMap.put("iso2022jp", FromCP932Corrector.class); + correctorMap.put("iso-2022-jp", FromCP932Corrector.class); + correctorMap.put("euc-jp", FromCP932Corrector.class); + correctorMap.put("eucjis", FromCP932Corrector.class); + // 同じ"SJIS"でもSunとMS-VMでは異なります。 + // Sun-JDK1.1はSJISはx-sjis-jdk-1.1.7で、MS-VMはx-sjis-cp932です。 + // しかし、MS-JDK中のクラスライブラリだけはx-sjis-jdk-1.1.7相当になるので + // 困ったものです。(ファイル書き出し等のときのみおかしくなる) + // これはWindowsネイティブな変換表で生成されたUnicodeを + // x-sjis-jdk-1.1.7で出力するためのものです。 + correctorMap.put("sjis", FromCP932Corrector.class); + correctorMap.put("shift_jis", FromCP932Corrector.class); + // MS-VMでファイル出力を行う場合に限り、こちらでなければなりません。 + // correctorMap.put("sjis", ToCP932Corrector.class); + // JDK1.2からはWindowsのデフォルトが"MS932"(x-sjis-cp932相当)となりました。 + // これで、他のエンコーディングで変換された(正しい)Unicodeが"ms932" + // での出力時におかしくなってしまいます。 + // これを補正します。 + correctorMap.put("ms932", ToCP932Corrector.class); + correctorMap.put("windows-31j", ToCP932Corrector.class); + } + + /** + * Create an UnicodeCorrector that uses + * the named character encoding. + * @param enc Name of the encoding to be used + * @exception UnsupportedEncodingException + * If the named encoding is not supported + */ + public static UnicodeCorrector getInstance(String enc) + throws UnsupportedEncodingException { + Class correctorClass = (Class)correctorMap.get(enc.toLowerCase()); + if (correctorClass == null) { + throw new UnsupportedEncodingException(enc); + } + try { + return (UnicodeCorrector)correctorClass.newInstance(); + } catch (Exception e) { + throw new UnsupportedEncodingException( + correctorClass + " cannot get newInstance.\n" + e); + } + } + + /** + * Unicode文字配列の補正を行います。 + *

+ * 特定の文字を特定エンコーディングで出力しようとした際の + * sun.ioコンバータでは正常に変換できない部分を補正します。 + *

+ * @param cbuf Buffer of characters + * @param off Offset from which to start writing characters + * @param len Number of characters to write + * @return Result that corrected. + * Note:Return array is different from cbuf + * in case of different result size. + */ + public char[] correct(char cbuf[], int off, int len) { + StringBuffer buf = new StringBuffer(); + for (int i = off; i < len; i++) { + buf.append(correct(cbuf[i])); + } + return new String(buf).toCharArray(); + } + + public String correct(String s) { + StringBuffer buf = new StringBuffer(); + for (int i = 0; i < s.length(); i++) { + buf.append(correct(s.charAt(i))); + } + return new String(buf); + } + + // 性能的にこれをabstractにするのはためらったが・・・ + public abstract char correct(char c); + + /** + * 新しいUnicodeCorrectorを追加します。 + *

+ * このソースコードを変えずに、動的に新たな出力エンコーディングに + * 対応したUnicodeCorrectorを登録したい場合に用います。 + *

+ * @param enc 対応するエンコーディング名 + * @param correctorClass UnicodeCorrectorサブクラスのClassオブジェクト + */ + public static void addCorrector(String enc, Class correctorClass) { + if (!correctorClass.isInstance(UnicodeCorrector.class)) { + throw new IllegalArgumentException( + "Corrector is not UnicodeCorrector type."); + } + correctorMap.put(enc, correctorClass); + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/package.html b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/package.html old mode 100755 new mode 100644 index 7d73505..f15e61d --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/package.html +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/package.html @@ -1,6 +1,6 @@ - - -¼õ¿®¥á¡¼¥ë¤Î²òÀϤ˻ÈÍѤ¹¤ë¥¯¥é¥¹¤òÄ󶡤·¤Þ¤¹¡£ -¤³¤Î¥Ñ¥Ã¥±¡¼¥¸ÇÛ²¼¤Ë¤¢¤ë¥¯¥é¥¹¤Ï¡¢http://www.sk-jp.com/java/library/¤ÇÇÛÉÛ¤µ¤ì¤Æ¤¤¤ë¥é¥¤¥Ö¥é¥ê¤ò°ìÉô²þÊѤ·¤Æ¤¤¤Þ¤¹¡£ - + + +受信メールの解析に使用するクラスを提供します。 +このパッケージ配下にあるクラスは、http://www.sk-jp.com/java/library/で配布されているライブラリを一部改変しています。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/EntityRefEncoder.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/EntityRefEncoder.java old mode 100755 new mode 100644 index 78c3e2f..a53ff4d --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/EntityRefEncoder.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/EntityRefEncoder.java @@ -1,177 +1,177 @@ -/* - * @(#) $Id: EntityRefEncoder.java,v 1.1.2.1 2005/01/18 07:20:43 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ - -package com.ozacc.mail.fetch.impl.sk_jp.text; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; - -/** - * <>&"を&lt;&gt;&amp;&quot;に - * 変換するTranslatorです。 - * リエントラントなので、通常はINSTANCE/CANONICAL_INSTANCEを用いればよいです。 - * またStringオブジェクトに対してはencode()メソッドが使用できます。 - * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:43 $ - * @author Shin - */ -public class EntityRefEncoder implements Translator { - public static final EntityRefEncoder CANONICAL_INSTANCE = - new EntityRefEncoder(true); - public static final EntityRefEncoder INSTANCE = - new EntityRefEncoder(false); - - public EntityRefEncoder() { - this(false); - } - public EntityRefEncoder(boolean canonical) { - setCanonical(canonical); - } - - private boolean canonicalStatus; - private void setCanonical(boolean canonical) { -// public void setCanonical(boolean canonical) { - this.canonicalStatus = canonical; - } - - /** - * 文字ストリームから入力した文字列を任意の変換を - * 行いながら出力ストリームに書き出します。 - *

- *

- */ - public void translate(Reader r, Writer w) throws IOException { - int c; - while ((c = r.read()) != -1) { - translate((char)c, w, canonicalStatus); - } - w.flush(); - } - - public String translate(String source) { - return encode(source); - } -/* - public static String encode(String s) { - if (s == null) return ""; - - StringWriter w = new StringWriter(); - try { - EntityRefEncoder.INSTANCE.translate(new StringReader(s), w); - } catch (IOException e) { - throw new RuntimeException(); - } - return w.toString(); - } -*/ - - /** - * 文字列の実体参照化を行います。 - * @param s 対象文字列 - * @return 変換後文字列 - */ - // 似たようなコードを書きたくは無いが高速化の為… - public static String encode(String s) { - if (s == null) return ""; - - int len = s.length(); - StringBuffer buf = new StringBuffer(len + 128); - char c; - - for (int i = 0; i < len; i++) { - c = s.charAt(i); - switch (c) { - case '<': buf.append("<"); break; - case '>': buf.append(">"); break; - case '&': buf.append("&"); break; - case '"': buf.append("""); break; - default: - buf.append(c); - } - } - return new String(buf); - } - - /** - * 特定の文字を実体参照に変換して書き出します。 - */ - public static void translate(char c, Writer w, boolean canonical) - throws IOException { - switch (c) { - case '<': w.write("<"); break; - case '>': w.write(">"); break; - case '&': w.write("&"); break; - case '"': w.write("""); break; - case '\r': - case '\n': - if (canonical) { - w.write("&#"); - w.write(Integer.toString(c)); - w.write(';'); - } else { - w.write(c); - } - break; - default: - w.write(c); - } - } - - /** - * 実体参照変換されている文字列をもとに戻します。 - * @param s 対象文字列 - * @return 変換後文字列 - */ - public static String decode(String s) { - if (s == null) return ""; - - int len = s.length(); - StringBuffer buf = new StringBuffer(len); - char c; - - for (int i = 0; i < len; i++) { - c = s.charAt(i); - if (c != '&' || i > len - 4) { - buf.append(c); - continue; - } - if ((s.charAt(i + 2) == 't' || s.charAt(i + 2) == 'T') && - s.charAt(i + 3) == ';') { - switch (s.charAt(i + 1)) { - case 'l': - case 'L': - buf.append('<'); - i += 3; - continue; - case 'g': - case 'G': - buf.append('>'); - i += 3; - continue; - } - } else if (i < len - 4 && - (s.charAt(i + 1) == 'a' || s.charAt(i + 1) == 'A') && - (s.charAt(i + 2) == 'm' || s.charAt(i + 2) == 'M') && - (s.charAt(i + 3) == 'p' || s.charAt(i + 3) == 'P') && - s.charAt(i + 4) == ';') { - buf.append('&'); - i += 4; - continue; - } else if (i < len - 5 && - (s.charAt(i + 1) == 'q' || s.charAt(i + 1) == 'Q') && - (s.charAt(i + 2) == 'u' || s.charAt(i + 2) == 'U') && - (s.charAt(i + 3) == 'o' || s.charAt(i + 3) == 'O') && - (s.charAt(i + 4) == 't' || s.charAt(i + 4) == 'T') && - s.charAt(i + 5) == ';') { - buf.append('"'); - i += 5; - continue; - } - buf.append(c); - } - return new String(buf); - } -} +/* + * @(#) $Id: EntityRefEncoder.java,v 1.1.2.1 2005/01/18 07:20:43 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ + +package com.ozacc.mail.fetch.impl.sk_jp.text; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; + +/** + * <>&"を&lt;&gt;&amp;&quot;に + * 変換するTranslatorです。 + * リエントラントなので、通常はINSTANCE/CANONICAL_INSTANCEを用いればよいです。 + * またStringオブジェクトに対してはencode()メソッドが使用できます。 + * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:43 $ + * @author Shin + */ +public class EntityRefEncoder implements Translator { + public static final EntityRefEncoder CANONICAL_INSTANCE = + new EntityRefEncoder(true); + public static final EntityRefEncoder INSTANCE = + new EntityRefEncoder(false); + + public EntityRefEncoder() { + this(false); + } + public EntityRefEncoder(boolean canonical) { + setCanonical(canonical); + } + + private boolean canonicalStatus; + private void setCanonical(boolean canonical) { +// public void setCanonical(boolean canonical) { + this.canonicalStatus = canonical; + } + + /** + * 文字ストリームから入力した文字列を任意の変換を + * 行いながら出力ストリームに書き出します。 + *

+ *

+ */ + public void translate(Reader r, Writer w) throws IOException { + int c; + while ((c = r.read()) != -1) { + translate((char)c, w, canonicalStatus); + } + w.flush(); + } + + public String translate(String source) { + return encode(source); + } +/* + public static String encode(String s) { + if (s == null) return ""; + + StringWriter w = new StringWriter(); + try { + EntityRefEncoder.INSTANCE.translate(new StringReader(s), w); + } catch (IOException e) { + throw new RuntimeException(); + } + return w.toString(); + } +*/ + + /** + * 文字列の実体参照化を行います。 + * @param s 対象文字列 + * @return 変換後文字列 + */ + // 似たようなコードを書きたくは無いが高速化の為… + public static String encode(String s) { + if (s == null) return ""; + + int len = s.length(); + StringBuffer buf = new StringBuffer(len + 128); + char c; + + for (int i = 0; i < len; i++) { + c = s.charAt(i); + switch (c) { + case '<': buf.append("<"); break; + case '>': buf.append(">"); break; + case '&': buf.append("&"); break; + case '"': buf.append("""); break; + default: + buf.append(c); + } + } + return new String(buf); + } + + /** + * 特定の文字を実体参照に変換して書き出します。 + */ + public static void translate(char c, Writer w, boolean canonical) + throws IOException { + switch (c) { + case '<': w.write("<"); break; + case '>': w.write(">"); break; + case '&': w.write("&"); break; + case '"': w.write("""); break; + case '\r': + case '\n': + if (canonical) { + w.write("&#"); + w.write(Integer.toString(c)); + w.write(';'); + } else { + w.write(c); + } + break; + default: + w.write(c); + } + } + + /** + * 実体参照変換されている文字列をもとに戻します。 + * @param s 対象文字列 + * @return 変換後文字列 + */ + public static String decode(String s) { + if (s == null) return ""; + + int len = s.length(); + StringBuffer buf = new StringBuffer(len); + char c; + + for (int i = 0; i < len; i++) { + c = s.charAt(i); + if (c != '&' || i > len - 4) { + buf.append(c); + continue; + } + if ((s.charAt(i + 2) == 't' || s.charAt(i + 2) == 'T') && + s.charAt(i + 3) == ';') { + switch (s.charAt(i + 1)) { + case 'l': + case 'L': + buf.append('<'); + i += 3; + continue; + case 'g': + case 'G': + buf.append('>'); + i += 3; + continue; + } + } else if (i < len - 4 && + (s.charAt(i + 1) == 'a' || s.charAt(i + 1) == 'A') && + (s.charAt(i + 2) == 'm' || s.charAt(i + 2) == 'M') && + (s.charAt(i + 3) == 'p' || s.charAt(i + 3) == 'P') && + s.charAt(i + 4) == ';') { + buf.append('&'); + i += 4; + continue; + } else if (i < len - 5 && + (s.charAt(i + 1) == 'q' || s.charAt(i + 1) == 'Q') && + (s.charAt(i + 2) == 'u' || s.charAt(i + 2) == 'U') && + (s.charAt(i + 3) == 'o' || s.charAt(i + 3) == 'O') && + (s.charAt(i + 4) == 't' || s.charAt(i + 4) == 'T') && + s.charAt(i + 5) == ';') { + buf.append('"'); + i += 5; + continue; + } + buf.append(c); + } + return new String(buf); + } +} diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/Translator.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/Translator.java old mode 100755 new mode 100644 index 24caa92..68f565c --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/Translator.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/text/Translator.java @@ -1,32 +1,32 @@ -/* - * @(#) $Id: Translator.java,v 1.1.2.1 2005/01/18 07:20:43 otsuka Exp $ - * $Revision: 1.1.2.1 $ - * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. - */ - -package com.ozacc.mail.fetch.impl.sk_jp.text; - -import java.io.IOException; -import java.io.Reader; -import java.io.Writer; - -/** - * Character Translatorのインターフェイスです。 - * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:43 $ - * @author Shin - */ -public interface Translator { - /** - * 文字ストリームから入力した文字列を任意の変換を - * 行いながら出力ストリームに書き出します。 - *

- * フィルタとして用いる場合はPipedInput/OutputStreamと併用しましょう。
- * このメソッドの実装者はリエントラントに設計すべきでしょう。 - *

- */ - void translate(Reader r, Writer w) throws IOException; - /** - * 入力文字列に任意の変換を施した文字列を返します。 - */ - String translate(String src); -} +/* + * @(#) $Id: Translator.java,v 1.1.2.1 2005/01/18 07:20:43 otsuka Exp $ + * $Revision: 1.1.2.1 $ + * Copyright (c) 2000 Shin Kinoshita All Rights Reserved. + */ + +package com.ozacc.mail.fetch.impl.sk_jp.text; + +import java.io.IOException; +import java.io.Reader; +import java.io.Writer; + +/** + * Character Translatorのインターフェイスです。 + * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:43 $ + * @author Shin + */ +public interface Translator { + /** + * 文字ストリームから入力した文字列を任意の変換を + * 行いながら出力ストリームに書き出します。 + *

+ * フィルタとして用いる場合はPipedInput/OutputStreamと併用しましょう。
+ * このメソッドの実装者はリエントラントに設計すべきでしょう。 + *

+ */ + void translate(Reader r, Writer w) throws IOException; + /** + * 入力文字列に任意の変換を施した文字列を返します。 + */ + String translate(String src); +} diff --git a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/util/StringValues.java b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/util/StringValues.java old mode 100755 new mode 100644 index bfb425d..7d96355 --- a/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/util/StringValues.java +++ b/src/main/java/com/ozacc/mail/fetch/impl/sk_jp/util/StringValues.java @@ -1,157 +1,157 @@ -/* - * @(#) $Id: StringValues.java,v 1.1.2.1 2005/01/18 07:20:49 otsuka Exp $ - * $Revision: 1.1.2.1 $ - */ -package com.ozacc.mail.fetch.impl.sk_jp.util; - -import java.util.*; - -/** - * StringValues. - *

- * 複数の文字列をカンマやタブ区切りなどの一つの文字列として管理可能とします。 - *
内部的にはListに入れますのでindexによるアクセスも可能ですが、 - * 構築時、及びgetString()時に区切り文字で一本にされた文字列として - * やりとりすることもできます。 - * エスケープ処理がされないので、デリミタを含むトークンを認識できません。 - *

- * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:49 $ - * @author Shin - */ -public class StringValues { - private List src_ = new ArrayList(); - /** - * 複数文字列管理オブジェクトを生成します。 - */ - public StringValues() {} - /** - * 複数文字列管理オブジェクトを生成します。 - * @param str 区切り文字で連結された文字列 - */ - public StringValues(String str) { - parse(str); - } - /** - * 複数文字列管理オブジェクトを生成します。 - * @param str 区切り文字で連結された文字列 - * @param delim デリミタ - */ - public StringValues(String str, String delim) { - parse(str, delim); - } - /** - * 複数文字列管理オブジェクトを生成します。 - * @param strings 文字列の配列 - */ - public StringValues(String[] strings) { - add(strings); - } - /** - * 複数文字列管理オブジェクトを生成します。 - * @param strings 文字列の配列 - */ - public StringValues(Object[] o) { - for (int i = 0; i < o.length; i++) { - add(o[i].toString()); - } - } -////////////////////////////////////////////////////////////////////////////// - /** - * デリミタで区切られた文字列を分割して追加します。 - *

- * デリミタはStringTokenizerの標準のデリミタ - * "\t\n\r\f"が使われます。 - *

- * @param str 区切り文字で連結された文字列 - * @param delim デリミタ - */ - public void parse(String str) { - StringTokenizer st = new StringTokenizer(str); - parse(st); - } - /** - * デリミタで区切られた文字列を分割して追加します。 - *

- *

- * @param str 区切り文字で連結された文字列 - * @param delim デリミタ - */ - public void parse(String str, String delim) { - StringTokenizer st = new StringTokenizer(str, delim); - parse(st); - } - private void parse(StringTokenizer st) { - while (st.hasMoreTokens()) { - add(st.nextToken()); - } - } - /** - * 文字列群へのイテレータを返します。 - * @return Iteratorオブジェクト - */ - public Iterator iterator() { - return src_.iterator(); - } - - /** - * カンマ区切り文字列を得ます。 - *

- * 区切り文字列は文字列同士の間に単純に挿入されます。 - *

- * @return 文字列化したオブジェクト - */ - public String getString() { - return getString(", "); - } - /** - * 指定した区切り文字で連結された文字列を得ます。 - *

- * 区切り文字列は文字列同士の間に単純に挿入されます。 - *

- * @param delim 区切り文字列 - * @return 文字列化したオブジェクト - */ - public String getString(String delim) { - StringBuffer buf = new StringBuffer(); - Iterator iterator = iterator(); - if (iterator.hasNext()) { - buf.append(iterator.next()); - } - while (iterator.hasNext()) { - buf.append(delim).append(iterator.next()); - } - return new String(buf); - } - public String toString() { - return getString(); - } - /** - * 指定indexの文字列を取得します。 - * @param index 文字列群中の位置 - */ - public String get(int index) { - return (String)src_.get(index); - } - /** - * 文字列を追加します。 - * @param str 追加する文字列 - */ - public void add(String str) { - src_.add(str); - } - /** - * 文字列群を追加します。 - * @param str 追加する文字列 - */ - public void add(String[] str) { - for (int i = 0; i < str.length; i++) { - src_.add(str[i]); - } - } - /** - * 管理している文字列を削除します。 - */ - public void clear() { - src_.clear(); - } -} +/* + * @(#) $Id: StringValues.java,v 1.1.2.1 2005/01/18 07:20:49 otsuka Exp $ + * $Revision: 1.1.2.1 $ + */ +package com.ozacc.mail.fetch.impl.sk_jp.util; + +import java.util.*; + +/** + * StringValues. + *

+ * 複数の文字列をカンマやタブ区切りなどの一つの文字列として管理可能とします。 + *
内部的にはListに入れますのでindexによるアクセスも可能ですが、 + * 構築時、及びgetString()時に区切り文字で一本にされた文字列として + * やりとりすることもできます。 + * エスケープ処理がされないので、デリミタを含むトークンを認識できません。 + *

+ * @version $Revision: 1.1.2.1 $ $Date: 2005/01/18 07:20:49 $ + * @author Shin + */ +public class StringValues { + private List src_ = new ArrayList(); + /** + * 複数文字列管理オブジェクトを生成します。 + */ + public StringValues() {} + /** + * 複数文字列管理オブジェクトを生成します。 + * @param str 区切り文字で連結された文字列 + */ + public StringValues(String str) { + parse(str); + } + /** + * 複数文字列管理オブジェクトを生成します。 + * @param str 区切り文字で連結された文字列 + * @param delim デリミタ + */ + public StringValues(String str, String delim) { + parse(str, delim); + } + /** + * 複数文字列管理オブジェクトを生成します。 + * @param strings 文字列の配列 + */ + public StringValues(String[] strings) { + add(strings); + } + /** + * 複数文字列管理オブジェクトを生成します。 + * @param strings 文字列の配列 + */ + public StringValues(Object[] o) { + for (int i = 0; i < o.length; i++) { + add(o[i].toString()); + } + } +////////////////////////////////////////////////////////////////////////////// + /** + * デリミタで区切られた文字列を分割して追加します。 + *

+ * デリミタはStringTokenizerの標準のデリミタ + * "\t\n\r\f"が使われます。 + *

+ * @param str 区切り文字で連結された文字列 + * @param delim デリミタ + */ + public void parse(String str) { + StringTokenizer st = new StringTokenizer(str); + parse(st); + } + /** + * デリミタで区切られた文字列を分割して追加します。 + *

+ *

+ * @param str 区切り文字で連結された文字列 + * @param delim デリミタ + */ + public void parse(String str, String delim) { + StringTokenizer st = new StringTokenizer(str, delim); + parse(st); + } + private void parse(StringTokenizer st) { + while (st.hasMoreTokens()) { + add(st.nextToken()); + } + } + /** + * 文字列群へのイテレータを返します。 + * @return Iteratorオブジェクト + */ + public Iterator iterator() { + return src_.iterator(); + } + + /** + * カンマ区切り文字列を得ます。 + *

+ * 区切り文字列は文字列同士の間に単純に挿入されます。 + *

+ * @return 文字列化したオブジェクト + */ + public String getString() { + return getString(", "); + } + /** + * 指定した区切り文字で連結された文字列を得ます。 + *

+ * 区切り文字列は文字列同士の間に単純に挿入されます。 + *

+ * @param delim 区切り文字列 + * @return 文字列化したオブジェクト + */ + public String getString(String delim) { + StringBuffer buf = new StringBuffer(); + Iterator iterator = iterator(); + if (iterator.hasNext()) { + buf.append(iterator.next()); + } + while (iterator.hasNext()) { + buf.append(delim).append(iterator.next()); + } + return new String(buf); + } + public String toString() { + return getString(); + } + /** + * 指定indexの文字列を取得します。 + * @param index 文字列群中の位置 + */ + public String get(int index) { + return (String)src_.get(index); + } + /** + * 文字列を追加します。 + * @param str 追加する文字列 + */ + public void add(String str) { + src_.add(str); + } + /** + * 文字列群を追加します。 + * @param str 追加する文字列 + */ + public void add(String[] str) { + for (int i = 0; i < str.length; i++) { + src_.add(str[i]); + } + } + /** + * 管理している文字列を削除します。 + */ + public void clear() { + src_.clear(); + } +} diff --git a/src/main/java/com/ozacc/mail/fetch/package.html b/src/main/java/com/ozacc/mail/fetch/package.html old mode 100755 new mode 100644 index 1039956..e7177cf --- a/src/main/java/com/ozacc/mail/fetch/package.html +++ b/src/main/java/com/ozacc/mail/fetch/package.html @@ -1,5 +1,5 @@ - - -¥á¡¼¥ë¤Î¼õ¿®¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤òÄ󶡤·¤Þ¤¹¡£ - + + +メールの受信インターフェースを提供します。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/AbstractXMLMailBuilder.java b/src/main/java/com/ozacc/mail/impl/AbstractXMLMailBuilder.java old mode 100755 new mode 100644 index de31f90..b1040c3 --- a/src/main/java/com/ozacc/mail/impl/AbstractXMLMailBuilder.java +++ b/src/main/java/com/ozacc/mail/impl/AbstractXMLMailBuilder.java @@ -1,274 +1,274 @@ -package com.ozacc.mail.impl; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.xml.sax.SAXException; - -import com.ozacc.mail.Mail; - -/** - * XMLMailBuilder実装が継承する基底クラス。 - * - * @since 1.1 - * - * @author Tomohiro Otsuka - * @version $Id: AbstractXMLMailBuilder.java,v 1.4.2.2 2004/11/25 08:00:49 otsuka Exp $ - */ -public abstract class AbstractXMLMailBuilder { - - protected Map documentBuilderCache; - - /** - * コンストラクタ。 - */ - public AbstractXMLMailBuilder() { - documentBuilderCache = new HashMap(); - } - - /** - * 指定されたXMLファイルを読み込み、DOM Documentを生成します。 - * ignoreCommentが指定されている場合は、XMLのコメントを削除しません。 - * - * @param file XMLファイル - * @return DOM Document - * @throws IOException - * @throws SAXException - */ - protected synchronized Document getDocumentFromFile(File file, boolean ignoreComment) - throws SAXException, - IOException { - DocumentBuilder db = createDocumentBuilder(ignoreComment); - return db.parse(file); - } - - /** - * 指定されたXMLファイルを読み込み、DOM Documentを生成します。 - * XMLのコメントや改行は削除されます。 - * - * @param file XMLファイル - * @return DOM Document - * @throws IOException - * @throws SAXException - */ - protected Document getDocumentFromFile(File file) throws SAXException, IOException { - return getDocumentFromFile(file, true); - } - - /** - * DocumentBuilderインスタンスを生成します。 - * ignoreCommentが指定されている場合は、コメントを削除しないように設定されたDocumentBuilderを生成します。 - * - * @param ignoreComment - * @return DocumentBuilder - * @throws FactoryConfigurationError - */ - protected DocumentBuilder createDocumentBuilder(boolean ignoreComment) - throws FactoryConfigurationError { - Boolean dbKey = Boolean.valueOf(ignoreComment); - DocumentBuilder db = (DocumentBuilder)documentBuilderCache.get(dbKey); - if (db == null) { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setIgnoringComments(ignoreComment); - dbf.setCoalescing(ignoreComment); - dbf.setIgnoringElementContentWhitespace(true); - dbf.setValidating(true); - try { - db = dbf.newDocumentBuilder(); - db.setEntityResolver(new DTDEntityResolver()); - documentBuilderCache.put(dbKey, db); - } catch (ParserConfigurationException e) { - // never be thrown - throw new RuntimeException(e); - } - } - return db; - } - - /** - * DocumentBuilderインスタンスを生成します。 - * このDocumentBuilderを使用して生成されるDOM Documentでは、元のXMLデータにあるコメントは削除されます。 - * - * @return DocumentBuilder - * @throws FactoryConfigurationError - */ - protected DocumentBuilder createDocumentBuilder() throws FactoryConfigurationError { - return createDocumentBuilder(true); - } - - /** - * 指定されたクラスパスのXMLファイルを読み込み、DOM Documentを生成します。 - * ignoreCommentが指定されている場合は、XMLのコメントを削除しません。 - * - * @param ignoreComment - * @param classPath - * @return DOM Document - * @throws IOException - * @throws SAXException - */ - protected synchronized Document getDocumentFromClassPath(String classPath, boolean ignoreComment) - throws SAXException, - IOException { - InputStream is = getClass().getResourceAsStream(classPath); - DocumentBuilder db = createDocumentBuilder(ignoreComment); - try { - return db.parse(is); - } finally { - if (is != null) { - is.close(); - } - } - } - - /** - * 指定されたクラスパスのXMLファイルを読み込み、DOM Documentを生成します。 - * XMLのコメントや改行は削除されます。 - * - * @param classPath - * @return DOM Document - * @throws IOException - * @throws SAXException - */ - protected Document getDocumentFromClassPath(String classPath) throws SAXException, IOException { - return getDocumentFromClassPath(classPath, true); - } - - /** - * @param root - * @param mail - */ - protected void setReplyTo(Element root, Mail mail) { - NodeList nodes = root.getElementsByTagName("replyTo"); - Element replyTo = (Element)nodes.item(0); - if (replyTo != null && replyTo.getAttribute("email").length() > 0) { - mail.setReplyTo(replyTo.getAttribute("email")); - } - } - - /** - * @param root - * @param mail - */ - protected void setText(Element root, Mail mail) { - NodeList nodes = root.getElementsByTagName("body"); - Element bodyElem = (Element)nodes.item(0); - if (bodyElem == null) { - return; - } - String body = bodyElem.getFirstChild().getNodeValue(); - mail.setText(body.trim()); - } - - /** - * HTML本文をセット。 - * - * @param root - * @param mail - */ - protected void setHtml(Element root, Mail mail) { - NodeList nodes = root.getElementsByTagName("html"); - Element htmlElem = (Element)nodes.item(0); - if (htmlElem == null) { - return; - } - String html = htmlElem.getFirstChild().getNodeValue(); - mail.setHtmlText(html.trim()); - } - - /** - * @param root - * @param mail - */ - protected void setSubject(Element root, Mail mail) { - NodeList nodes = root.getElementsByTagName("subject"); - Element subjectElem = (Element)nodes.item(0); - if (subjectElem == null) { - return; - } - String subject = subjectElem.getFirstChild().getNodeValue(); - mail.setSubject(subject.trim()); - } - - /** - * @param root - * @param mail - */ - protected void setRecipients(Element root, Mail mail) { - NodeList nodes = root.getElementsByTagName("recipients"); - Element recipientsElem = (Element)nodes.item(0); - if (recipientsElem == null) { - return; - } - - NodeList recipientElemList = recipientsElem.getChildNodes(); - for (int i = 0, max = recipientElemList.getLength(); i < max; i++) { - Node node = recipientElemList.item(i); - if (node.getNodeType() != Node.ELEMENT_NODE) { - continue; - } - Element e = (Element)node; - if ("to".equals(e.getNodeName())) { // to - if (e.getAttribute("email").length() > 0) { - if (e.getAttribute("name").length() > 0) { - mail.addTo(e.getAttribute("email"), e.getAttribute("name")); - } else { - mail.addTo(e.getAttribute("email")); - } - } - } else if ("cc".equals(e.getNodeName())) { // cc - if (e.getAttribute("email").length() > 0) { - if (e.getAttribute("name").length() > 0) { - mail.addCc(e.getAttribute("email"), e.getAttribute("name")); - } else { - mail.addCc(e.getAttribute("email")); - } - } - } else { - if (e.getAttribute("email").length() > 0) { // bcc - mail.addBcc(e.getAttribute("email")); - } - } - } - } - - /** - * @param root - * @param mail - */ - protected void setReturnPath(Element root, Mail mail) { - NodeList nodes = root.getElementsByTagName("returnPath"); - Element returnPath = (Element)nodes.item(0); - if (returnPath != null && returnPath.getAttribute("email").length() > 0) { - mail.setReturnPath(returnPath.getAttribute("email")); - } - } - - /** - * @param root - * @param mail - */ - protected void setFrom(Element root, Mail mail) { - NodeList nodes = root.getElementsByTagName("from"); - Element from = (Element)nodes.item(0); - if (from != null && from.getAttribute("email").length() > 0) { - if (from.getAttribute("name").length() > 0) { - mail.setFrom(from.getAttribute("email"), from.getAttribute("name")); - } else { - mail.setFrom(from.getAttribute("email")); - } - } - } - +package com.ozacc.mail.impl; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.FactoryConfigurationError; +import javax.xml.parsers.ParserConfigurationException; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import com.ozacc.mail.Mail; + +/** + * XMLMailBuilder実装が継承する基底クラス。 + * + * @since 1.1 + * + * @author Tomohiro Otsuka + * @version $Id: AbstractXMLMailBuilder.java,v 1.4.2.2 2004/11/25 08:00:49 otsuka Exp $ + */ +public abstract class AbstractXMLMailBuilder { + + protected Map documentBuilderCache; + + /** + * コンストラクタ。 + */ + public AbstractXMLMailBuilder() { + documentBuilderCache = new HashMap(); + } + + /** + * 指定されたXMLファイルを読み込み、DOM Documentを生成します。 + * ignoreCommentが指定されている場合は、XMLのコメントを削除しません。 + * + * @param file XMLファイル + * @return DOM Document + * @throws IOException + * @throws SAXException + */ + protected synchronized Document getDocumentFromFile(File file, boolean ignoreComment) + throws SAXException, + IOException { + DocumentBuilder db = createDocumentBuilder(ignoreComment); + return db.parse(file); + } + + /** + * 指定されたXMLファイルを読み込み、DOM Documentを生成します。 + * XMLのコメントや改行は削除されます。 + * + * @param file XMLファイル + * @return DOM Document + * @throws IOException + * @throws SAXException + */ + protected Document getDocumentFromFile(File file) throws SAXException, IOException { + return getDocumentFromFile(file, true); + } + + /** + * DocumentBuilderインスタンスを生成します。 + * ignoreCommentが指定されている場合は、コメントを削除しないように設定されたDocumentBuilderを生成します。 + * + * @param ignoreComment + * @return DocumentBuilder + * @throws FactoryConfigurationError + */ + protected DocumentBuilder createDocumentBuilder(boolean ignoreComment) + throws FactoryConfigurationError { + Boolean dbKey = Boolean.valueOf(ignoreComment); + DocumentBuilder db = (DocumentBuilder)documentBuilderCache.get(dbKey); + if (db == null) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setIgnoringComments(ignoreComment); + dbf.setCoalescing(ignoreComment); + dbf.setIgnoringElementContentWhitespace(true); + dbf.setValidating(true); + try { + db = dbf.newDocumentBuilder(); + db.setEntityResolver(new DTDEntityResolver()); + documentBuilderCache.put(dbKey, db); + } catch (ParserConfigurationException e) { + // never be thrown + throw new RuntimeException(e); + } + } + return db; + } + + /** + * DocumentBuilderインスタンスを生成します。 + * このDocumentBuilderを使用して生成されるDOM Documentでは、元のXMLデータにあるコメントは削除されます。 + * + * @return DocumentBuilder + * @throws FactoryConfigurationError + */ + protected DocumentBuilder createDocumentBuilder() throws FactoryConfigurationError { + return createDocumentBuilder(true); + } + + /** + * 指定されたクラスパスのXMLファイルを読み込み、DOM Documentを生成します。 + * ignoreCommentが指定されている場合は、XMLのコメントを削除しません。 + * + * @param ignoreComment + * @param classPath + * @return DOM Document + * @throws IOException + * @throws SAXException + */ + protected synchronized Document getDocumentFromClassPath(String classPath, boolean ignoreComment) + throws SAXException, + IOException { + InputStream is = getClass().getResourceAsStream(classPath); + DocumentBuilder db = createDocumentBuilder(ignoreComment); + try { + return db.parse(is); + } finally { + if (is != null) { + is.close(); + } + } + } + + /** + * 指定されたクラスパスのXMLファイルを読み込み、DOM Documentを生成します。 + * XMLのコメントや改行は削除されます。 + * + * @param classPath + * @return DOM Document + * @throws IOException + * @throws SAXException + */ + protected Document getDocumentFromClassPath(String classPath) throws SAXException, IOException { + return getDocumentFromClassPath(classPath, true); + } + + /** + * @param root + * @param mail + */ + protected void setReplyTo(Element root, Mail mail) { + NodeList nodes = root.getElementsByTagName("replyTo"); + Element replyTo = (Element)nodes.item(0); + if (replyTo != null && replyTo.getAttribute("email").length() > 0) { + mail.setReplyTo(replyTo.getAttribute("email")); + } + } + + /** + * @param root + * @param mail + */ + protected void setText(Element root, Mail mail) { + NodeList nodes = root.getElementsByTagName("body"); + Element bodyElem = (Element)nodes.item(0); + if (bodyElem == null) { + return; + } + String body = bodyElem.getFirstChild().getNodeValue(); + mail.setText(body.trim()); + } + + /** + * HTML本文をセット。 + * + * @param root + * @param mail + */ + protected void setHtml(Element root, Mail mail) { + NodeList nodes = root.getElementsByTagName("html"); + Element htmlElem = (Element)nodes.item(0); + if (htmlElem == null) { + return; + } + String html = htmlElem.getFirstChild().getNodeValue(); + mail.setHtmlText(html.trim()); + } + + /** + * @param root + * @param mail + */ + protected void setSubject(Element root, Mail mail) { + NodeList nodes = root.getElementsByTagName("subject"); + Element subjectElem = (Element)nodes.item(0); + if (subjectElem == null) { + return; + } + String subject = subjectElem.getFirstChild().getNodeValue(); + mail.setSubject(subject.trim()); + } + + /** + * @param root + * @param mail + */ + protected void setRecipients(Element root, Mail mail) { + NodeList nodes = root.getElementsByTagName("recipients"); + Element recipientsElem = (Element)nodes.item(0); + if (recipientsElem == null) { + return; + } + + NodeList recipientElemList = recipientsElem.getChildNodes(); + for (int i = 0, max = recipientElemList.getLength(); i < max; i++) { + Node node = recipientElemList.item(i); + if (node.getNodeType() != Node.ELEMENT_NODE) { + continue; + } + Element e = (Element)node; + if ("to".equals(e.getNodeName())) { // to + if (e.getAttribute("email").length() > 0) { + if (e.getAttribute("name").length() > 0) { + mail.addTo(e.getAttribute("email"), e.getAttribute("name")); + } else { + mail.addTo(e.getAttribute("email")); + } + } + } else if ("cc".equals(e.getNodeName())) { // cc + if (e.getAttribute("email").length() > 0) { + if (e.getAttribute("name").length() > 0) { + mail.addCc(e.getAttribute("email"), e.getAttribute("name")); + } else { + mail.addCc(e.getAttribute("email")); + } + } + } else { + if (e.getAttribute("email").length() > 0) { // bcc + mail.addBcc(e.getAttribute("email")); + } + } + } + } + + /** + * @param root + * @param mail + */ + protected void setReturnPath(Element root, Mail mail) { + NodeList nodes = root.getElementsByTagName("returnPath"); + Element returnPath = (Element)nodes.item(0); + if (returnPath != null && returnPath.getAttribute("email").length() > 0) { + mail.setReturnPath(returnPath.getAttribute("email")); + } + } + + /** + * @param root + * @param mail + */ + protected void setFrom(Element root, Mail mail) { + NodeList nodes = root.getElementsByTagName("from"); + Element from = (Element)nodes.item(0); + if (from != null && from.getAttribute("email").length() > 0) { + if (from.getAttribute("name").length() > 0) { + mail.setFrom(from.getAttribute("email"), from.getAttribute("name")); + } else { + mail.setFrom(from.getAttribute("email")); + } + } + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/ByteArrayDataSource.java b/src/main/java/com/ozacc/mail/impl/ByteArrayDataSource.java old mode 100755 new mode 100644 index 8aaf795..c766a99 --- a/src/main/java/com/ozacc/mail/impl/ByteArrayDataSource.java +++ b/src/main/java/com/ozacc/mail/impl/ByteArrayDataSource.java @@ -1,122 +1,122 @@ -package com.ozacc.mail.impl; - -/* - * @(#)ByteArrayDataSource.java 1.4 01/05/23 - * - * Copyright 1998-2000 Sun Microsystems, Inc. All Rights Reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistribution in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * Neither the name of Sun Microsystems, Inc. or the names of contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. - * - * This software is provided "AS IS," without a warranty of any kind. ALL - * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, - * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND - * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES - * SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION - * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL - * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR - * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE - * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, - * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS - * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - * - * You acknowledge that Software is not designed, licensed or intended - * for use in the design, construction, operation or maintenance of any - * nuclear facility. - */ - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.UnsupportedEncodingException; - -import javax.activation.DataSource; - -/** - * InputStream、byte array、StringからDataSourceインスタンスを生成するクラス。
- * JavaMailパッケージ付属品。 - *

- * 注: このクラスはpublicですが、ozacc-mail library外からは使用しないでください。 - * - * @since 1.1 - * - * @author John Mani - * @author Bill Shannon - * @author Max Spivak - */ -public class ByteArrayDataSource implements DataSource { - - private byte[] data; // data - - private String type; // content-type - - /* Create a DataSource from an input stream */ - public ByteArrayDataSource(InputStream is, String type) { - this.type = type; - try { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - int ch; - - while ((ch = is.read()) != -1) - // XXX - must be made more efficient by - // doing buffered reads, rather than one byte reads - os.write(ch); - data = os.toByteArray(); - - } catch (IOException ioex) {} - } - - /* Create a DataSource from a byte array */ - public ByteArrayDataSource(byte[] data, String type) { - this.data = data; - this.type = type; - } - - /* Create a DataSource from a String */ - public ByteArrayDataSource(String data, String type) { - try { - // Assumption that the string contains only ASCII - // characters! Otherwise just pass a charset into this - // constructor and use it in getBytes() - this.data = data.getBytes("iso-8859-1"); - } catch (UnsupportedEncodingException uex) {} - this.type = type; - } - - /** - * Return an InputStream for the data. - * Note - a new stream must be returned each time. - */ - public InputStream getInputStream() throws IOException { - if (data == null) - throw new IOException("no data"); - return new ByteArrayInputStream(data); - } - - public OutputStream getOutputStream() throws IOException { - throw new IOException("cannot do this"); - } - - public String getContentType() { - return type; - } - - public String getName() { - return "dummy"; - } +package com.ozacc.mail.impl; + +/* + * @(#)ByteArrayDataSource.java 1.4 01/05/23 + * + * Copyright 1998-2000 Sun Microsystems, Inc. All Rights Reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistribution in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * Neither the name of Sun Microsystems, Inc. or the names of contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * This software is provided "AS IS," without a warranty of any kind. ALL + * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, + * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND + * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES OR LIABILITIES + * SUFFERED BY LICENSEE AS A RESULT OF OR RELATING TO USE, MODIFICATION + * OR DISTRIBUTION OF THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL + * SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR + * FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE + * DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, + * ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS + * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + * + * You acknowledge that Software is not designed, licensed or intended + * for use in the design, construction, operation or maintenance of any + * nuclear facility. + */ + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; + +import javax.activation.DataSource; + +/** + * InputStream、byte array、StringからDataSourceインスタンスを生成するクラス。
+ * JavaMailパッケージ付属品。 + *

+ * 注: このクラスはpublicですが、ozacc-mail library外からは使用しないでください。 + * + * @since 1.1 + * + * @author John Mani + * @author Bill Shannon + * @author Max Spivak + */ +public class ByteArrayDataSource implements DataSource { + + private byte[] data; // data + + private String type; // content-type + + /* Create a DataSource from an input stream */ + public ByteArrayDataSource(InputStream is, String type) { + this.type = type; + try { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + int ch; + + while ((ch = is.read()) != -1) + // XXX - must be made more efficient by + // doing buffered reads, rather than one byte reads + os.write(ch); + data = os.toByteArray(); + + } catch (IOException ioex) {} + } + + /* Create a DataSource from a byte array */ + public ByteArrayDataSource(byte[] data, String type) { + this.data = data; + this.type = type; + } + + /* Create a DataSource from a String */ + public ByteArrayDataSource(String data, String type) { + try { + // Assumption that the string contains only ASCII + // characters! Otherwise just pass a charset into this + // constructor and use it in getBytes() + this.data = data.getBytes("iso-8859-1"); + } catch (UnsupportedEncodingException uex) {} + this.type = type; + } + + /** + * Return an InputStream for the data. + * Note - a new stream must be returned each time. + */ + public InputStream getInputStream() throws IOException { + if (data == null) + throw new IOException("no data"); + return new ByteArrayInputStream(data); + } + + public OutputStream getOutputStream() throws IOException { + throw new IOException("cannot do this"); + } + + public String getContentType() { + return type; + } + + public String getName() { + return "dummy"; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/Cp932.java b/src/main/java/com/ozacc/mail/impl/Cp932.java old mode 100755 new mode 100644 index ae7af34..0048363 --- a/src/main/java/com/ozacc/mail/impl/Cp932.java +++ b/src/main/java/com/ozacc/mail/impl/Cp932.java @@ -1,118 +1,118 @@ -package com.ozacc.mail.impl; - -import java.util.Locale; - -/** - * The Cp932 class contains a utility method for converting Microsoft's - * Cp 932 into JIS. - *

- * 注: このクラスはpublicですが、ozacc-mail library外からは使用しないでください。 - * - * @author Kazuhiro Kazama - * @version 1.0 01/06/97 - * - * @since 1.0.2 - */ -public class Cp932 { - - private static boolean isCp932 = false; - - static { - String p = System.getProperty("iscp932"); - String os = System.getProperty("os.name"); - if (Locale.getDefault().getLanguage().equals("ja")) { - if (p != null && Boolean.getBoolean(p)) - isCp932 = true; - else if (os != null && (os.startsWith("Win"))) - isCp932 = true; - } - } - - /* - * You can't use this constructor. - */ - private Cp932() {} - - /* - * This method converts Cp932 to JIS. - */ - public static String toJIS(String s) { - - /* commented by otsuka - * - * if (!isCp932) - * return s; - */ - - StringBuffer sb = new StringBuffer(); - char c; - for (int i = 0; i < s.length(); i++) { - c = s.charAt(i); - - switch (c) { - case 0xff3c: // FULLWIDTH REVERSE SOLIDUS -> - c = 0x005c; // REVERSE SOLIDUS - break; - case 0xff5e: // FULLWIDTH TILDE -> - c = 0x301c; // WAVE DASH - break; - case 0x2225: // PARALLEL TO -> - c = 0x2016; // DOUBLE VERTICAL LINE - break; - case 0xff0d: // FULLWIDTH HYPHEN-MINUS -> - c = 0x2212; // MINUS SIGN - break; - case 0xffe0: // FULLWIDTH CENT SIGN -> - c = 0x00a2; // CENT SIGN - break; - case 0xffe1: // FULLWIDTH POUND SIGN -> - c = 0x00a3; // POUND SIGN - break; - case 0xffe2: // FULLWIDTH NOT SIGN -> - c = 0x00ac; // NOT SIGN - break; - } - sb.append(c); - } - return new String(sb); - } - - /* - * This method convert JIS to Cp932. - */ - public static String toCp932(String s) { - if (!isCp932) - return s; - StringBuffer sb = new StringBuffer(); - char c; - for (int i = 0; i < s.length(); i++) { - c = s.charAt(i); - - switch (c) { - case 0x005c: // REVERSE SOLIDUS -> - c = 0xff3c; // FULLWIDTH REVERSE SOLIDUS - break; - case 0x301c: // WAVE DASH -> - c = 0xff5e; // FULLWIDTH TILDE - break; - case 0x2016: // DOUBLE VERTICAL LINE -> - c = 0x2225; // PARALLEL TO - break; - case 0x2212: // MINUS SIGN -> - c = 0xff0d; // FULLWIDTH HYPHEN-MINUS - break; - case 0x00a2: // CENT SIGN -> - c = 0xffe0; // FULLWIDTH CENT SIGN - break; - case 0x00a3: // POUND SIGN -> - c = 0xffe1; // FULLWIDTH POUND SIGN - break; - case 0x00ac: // NOT SIGN -> - c = 0xffe2; // FULLWIDTH NOT SIGN - break; - } - sb.append(c); - } - return new String(sb); - } +package com.ozacc.mail.impl; + +import java.util.Locale; + +/** + * The Cp932 class contains a utility method for converting Microsoft's + * Cp 932 into JIS. + *

+ * 注: このクラスはpublicですが、ozacc-mail library外からは使用しないでください。 + * + * @author Kazuhiro Kazama + * @version 1.0 01/06/97 + * + * @since 1.0.2 + */ +public class Cp932 { + + private static boolean isCp932 = false; + + static { + String p = System.getProperty("iscp932"); + String os = System.getProperty("os.name"); + if (Locale.getDefault().getLanguage().equals("ja")) { + if (p != null && Boolean.getBoolean(p)) + isCp932 = true; + else if (os != null && (os.startsWith("Win"))) + isCp932 = true; + } + } + + /* + * You can't use this constructor. + */ + private Cp932() {} + + /* + * This method converts Cp932 to JIS. + */ + public static String toJIS(String s) { + + /* commented by otsuka + * + * if (!isCp932) + * return s; + */ + + StringBuffer sb = new StringBuffer(); + char c; + for (int i = 0; i < s.length(); i++) { + c = s.charAt(i); + + switch (c) { + case 0xff3c: // FULLWIDTH REVERSE SOLIDUS -> + c = 0x005c; // REVERSE SOLIDUS + break; + case 0xff5e: // FULLWIDTH TILDE -> + c = 0x301c; // WAVE DASH + break; + case 0x2225: // PARALLEL TO -> + c = 0x2016; // DOUBLE VERTICAL LINE + break; + case 0xff0d: // FULLWIDTH HYPHEN-MINUS -> + c = 0x2212; // MINUS SIGN + break; + case 0xffe0: // FULLWIDTH CENT SIGN -> + c = 0x00a2; // CENT SIGN + break; + case 0xffe1: // FULLWIDTH POUND SIGN -> + c = 0x00a3; // POUND SIGN + break; + case 0xffe2: // FULLWIDTH NOT SIGN -> + c = 0x00ac; // NOT SIGN + break; + } + sb.append(c); + } + return new String(sb); + } + + /* + * This method convert JIS to Cp932. + */ + public static String toCp932(String s) { + if (!isCp932) + return s; + StringBuffer sb = new StringBuffer(); + char c; + for (int i = 0; i < s.length(); i++) { + c = s.charAt(i); + + switch (c) { + case 0x005c: // REVERSE SOLIDUS -> + c = 0xff3c; // FULLWIDTH REVERSE SOLIDUS + break; + case 0x301c: // WAVE DASH -> + c = 0xff5e; // FULLWIDTH TILDE + break; + case 0x2016: // DOUBLE VERTICAL LINE -> + c = 0x2225; // PARALLEL TO + break; + case 0x2212: // MINUS SIGN -> + c = 0xff0d; // FULLWIDTH HYPHEN-MINUS + break; + case 0x00a2: // CENT SIGN -> + c = 0xffe0; // FULLWIDTH CENT SIGN + break; + case 0x00a3: // POUND SIGN -> + c = 0xffe1; // FULLWIDTH POUND SIGN + break; + case 0x00ac: // NOT SIGN -> + c = 0xffe2; // FULLWIDTH NOT SIGN + break; + } + sb.append(c); + } + return new String(sb); + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/DTDEntityResolver.java b/src/main/java/com/ozacc/mail/impl/DTDEntityResolver.java old mode 100755 new mode 100644 index dccd0da..db5f0c0 --- a/src/main/java/com/ozacc/mail/impl/DTDEntityResolver.java +++ b/src/main/java/com/ozacc/mail/impl/DTDEntityResolver.java @@ -1,58 +1,58 @@ -package com.ozacc.mail.impl; - -import java.io.IOException; -import java.io.InputStream; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.xml.sax.EntityResolver; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * ozacc-mail libraryのDTDファイルをクラスパス上から検出するEntityResolver実装。 - * - * @since 1.1 - * - * @author Tomohiro Otsuka - * @version $Id: DTDEntityResolver.java,v 1.1.2.2 2004/11/25 08:01:07 otsuka Exp $ - */ -public class DTDEntityResolver implements EntityResolver { - - private static Log log = LogFactory.getLog(DTDEntityResolver.class); - - private static final String URL = "http://www.ozacc.com/library/dtd/"; - - /** - * クラスパス「com/ozacc/mail」上で、指定されたsystemIdのファイル名と同じファイルを検出します。 - * もしも検出できなければnullを返します。(必ず検出できるはずです。) - * - * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) - */ - public InputSource resolveEntity(String publicId, String systemId) throws SAXException, - IOException { - if (systemId != null && systemId.startsWith(URL)) { - log.debug("クラスパス[com/ozacc/mail/]上で'" + systemId + "'の取得を試みます。"); - - // Search for DTD - ClassLoader classLoader = this.getClass().getClassLoader(); - InputStream dtdStream = classLoader.getResourceAsStream("com/ozacc/mail/" - + systemId.substring(URL.length())); - - if (dtdStream == null) { - log.debug("'" + systemId + "'はクラスパス上に見つかりませんでした。"); - return null; - } else { - log.debug("'" + systemId + "'をクラスパス上で取得しました。"); - InputSource source = new InputSource(dtdStream); - source.setPublicId(publicId); - source.setSystemId(systemId); - return source; - } - } else { - // use the default behaviour - return null; - } - } - +package com.ozacc.mail.impl; + +import java.io.IOException; +import java.io.InputStream; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.xml.sax.EntityResolver; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +/** + * ozacc-mail libraryのDTDファイルをクラスパス上から検出するEntityResolver実装。 + * + * @since 1.1 + * + * @author Tomohiro Otsuka + * @version $Id: DTDEntityResolver.java,v 1.1.2.2 2004/11/25 08:01:07 otsuka Exp $ + */ +public class DTDEntityResolver implements EntityResolver { + + private static Log log = LogFactory.getLog(DTDEntityResolver.class); + + private static final String URL = "http://www.ozacc.com/library/dtd/"; + + /** + * クラスパス「com/ozacc/mail」上で、指定されたsystemIdのファイル名と同じファイルを検出します。 + * もしも検出できなければnullを返します。(必ず検出できるはずです。) + * + * @see org.xml.sax.EntityResolver#resolveEntity(java.lang.String, java.lang.String) + */ + public InputSource resolveEntity(String publicId, String systemId) throws SAXException, + IOException { + if (systemId != null && systemId.startsWith(URL)) { + log.debug("クラスパス[com/ozacc/mail/]上で'" + systemId + "'の取得を試みます。"); + + // Search for DTD + ClassLoader classLoader = this.getClass().getClassLoader(); + InputStream dtdStream = classLoader.getResourceAsStream("com/ozacc/mail/" + + systemId.substring(URL.length())); + + if (dtdStream == null) { + log.debug("'" + systemId + "'はクラスパス上に見つかりませんでした。"); + return null; + } else { + log.debug("'" + systemId + "'をクラスパス上で取得しました。"); + InputSource source = new InputSource(dtdStream); + source.setPublicId(publicId); + source.setSystemId(systemId); + return source; + } + } else { + // use the default behaviour + return null; + } + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/JDomXMLMailBuilder.java b/src/main/java/com/ozacc/mail/impl/JDomXMLMailBuilder.java old mode 100755 new mode 100644 index 8d87272..b277363 --- a/src/main/java/com/ozacc/mail/impl/JDomXMLMailBuilder.java +++ b/src/main/java/com/ozacc/mail/impl/JDomXMLMailBuilder.java @@ -1,504 +1,504 @@ -package com.ozacc.mail.impl; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.apache.velocity.exception.MethodInvocationException; -import org.apache.velocity.exception.ParseErrorException; -import org.apache.velocity.exception.ResourceNotFoundException; -import org.apache.velocity.runtime.log.LogSystem; -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.input.SAXBuilder; -import org.jdom.output.XMLOutputter; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.MultipleMailBuilder; -import com.ozacc.mail.VelocityMultipleMailBuilder; - -/** - * JDOMを利用してXMLファイルからMailインスタンスを生成するクラス。 - *

- * ソースXMLを読み込む際に、DTDバリデーションが実行されますので妥当なXMLデータ(Valid XML Document)でなければいけません。 - * - * @since 1.0 - * - * @author Tomohiro Otsuka - * @version $Id: JDomXMLMailBuilder.java,v 1.10.2.5 2005/02/01 20:37:49 otsuka Exp $ - */ -public class JDomXMLMailBuilder implements MultipleMailBuilder, VelocityMultipleMailBuilder { - - private static Log log = LogFactory.getLog(JDomXMLMailBuilder.class); - - private static String CACHE_KEY_SEPARATOR = "#"; - - private static String DEFAULT_MAIL_ID = "DEFAULT"; - - protected LogSystem velocityLogSystem = new VelocityLogSystem(); - - private boolean cacheEnabled = false; - - protected Map templateCache = new HashMap(); - - /** - * コンストラクタ。 - */ - public JDomXMLMailBuilder() {} - - /** - * 指定されたクラスパス上のXMLファイルからMailインスタンスを生成します。 - * - * @param classPath メール内容を記述したXMLファイルのパス - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - public Mail buildMail(String classPath) throws MailBuildException { - Document doc = getDocumentFromClassPath(classPath); - return build(doc.getRootElement()); - } - - /** - * 指定されたクラスパス上のXMLファイルからMailインスタンスを生成します。 - * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 - * - * @param classPath メール内容を記述したXMLファイルのパス - * @param context VelocityContext - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - public Mail buildMail(String classPath, VelocityContext context) throws MailBuildException { - String cacheKey = classPath + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc = getDocumentFromClassPath(classPath); - templateXmlText = cacheTemplateText(doc, cacheKey); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - - /** - * 指定されたXMLファイルからMailインスタンスを生成します。 - * - * @param file メール内容を記述したXMLファイル - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - public Mail buildMail(File file) throws MailBuildException { - Document doc = getDocumentFromFile(file); - return build(doc.getRootElement()); - } - - /** - * 指定されたXMLファイルからMailインスタンスを生成します。 - * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 - * - * @param file メール内容を記述したXMLファイル - * @param context VelocityContext - * @return 生成されたMailインスタンス - * @throws MailBuildException Mailインスタンスの生成に失敗した場合 - */ - public Mail buildMail(File file, VelocityContext context) throws MailBuildException { - String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc = getDocumentFromFile(file); - templateXmlText = cacheTemplateText(doc, cacheKey); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - - private String cacheTemplateText(Document doc, String cacheKey) { - XMLOutputter output = new XMLOutputter(); - String templateXmlText = "\n" + output.outputString(doc.getRootElement()); - log.debug("以下のXMLデータをキャッシュします。\n" + templateXmlText); - putTemplateCache(cacheKey, templateXmlText); - return templateXmlText; - } - - /** - * 指定されたクラスパス上のファイルを読み込んで、XMLドキュメントを生成します。 - * - * @param classPath - * @return JDOM Document - */ - protected Document getDocumentFromClassPath(String classPath) throws MailBuildException { - InputStream is = getClass().getResourceAsStream(classPath); - SAXBuilder builder = new SAXBuilder(true); - builder.setEntityResolver(new DTDEntityResolver()); - Document doc; - try { - doc = builder.build(is); - } catch (JDOMException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - // ignore - } - } - } - return doc; - } - - /** - * 指定されたファイルを読み込んで、XMLドキュメントを生成します。 - * - * @param file - * @return JDOM Document - */ - protected Document getDocumentFromFile(File file) { - SAXBuilder builder = new SAXBuilder(true); - builder.setEntityResolver(new DTDEntityResolver()); - Document doc; - try { - doc = builder.build(file); - } catch (JDOMException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } - return doc; - } - - /** - * XMLのmailルートエレメントからMailインスタンスを生成します。 - * - * @param mailElement mail要素を示すElementインスタンス - * @return Mail 生成されたMail - */ - protected Mail build(Element mailElement) { - Mail mail = new Mail(); - setFrom(mailElement, mail); - setRecipients(mailElement, mail); - setSubject(mailElement, mail); - setBody(mailElement, mail); - setReplyTo(mailElement, mail); - setReturnPath(mailElement, mail); - - setHtml(mailElement, mail); - - return mail; - } - - /** - * VelocityContextとXMLテンプレートをマージさせ、Mailインスタンスを生成します。 - * - * @param templateText マージするXMLテンプレートの文字列 - * @param context マージするVelocityContext - * @return Mail - * - * @throws Exception - * @throws ParseErrorException - * @throws MethodInvocationException - * @throws ResourceNotFoundException - * @throws IOException - * @throws JDOMException - */ - protected Mail build(String templateText, VelocityContext context) throws Exception, - ParseErrorException, - MethodInvocationException, - ResourceNotFoundException, - IOException, JDOMException { - if (log.isDebugEnabled()) { - log.debug("ソースXMLデータ\n" + templateText); - } - - Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, velocityLogSystem); - Velocity.init(); - StringWriter w = new StringWriter(); - Velocity.evaluate(context, w, "XML Mail Data", templateText); - - if (log.isDebugEnabled()) { - log.debug("VelocityContextとマージ後のXMLデータ\n" + w.toString()); - } - - StringReader reader = new StringReader(w.toString()); - SAXBuilder builder = new SAXBuilder(true); - builder.setEntityResolver(new DTDEntityResolver()); - Document mergedDoc = builder.build(reader); - - return build(mergedDoc.getRootElement()); - } - - /** - * @param root - * @param mail - */ - protected void setReturnPath(Element root, Mail mail) { - Element returnPathElem = root.getChild("returnPath"); - if (returnPathElem != null && returnPathElem.getAttributeValue("email") != null) { - mail.setReturnPath(returnPathElem.getAttributeValue("email")); - } - } - - /** - * @param root - * @param mail - */ - protected void setReplyTo(Element root, Mail mail) { - Element replyToElem = root.getChild("replyTo"); - if (replyToElem != null && replyToElem.getAttributeValue("email") != null) { - mail.setReplyTo(replyToElem.getAttributeValue("email")); - } - } - - /** - * @param root - * @param mail - */ - protected void setBody(Element root, Mail mail) { - Element bodyElem = root.getChild("body"); - if (bodyElem != null) { - mail.setText(bodyElem.getTextTrim()); - } - } - - /** - * @param root - * @param mail - */ - protected void setHtml(Element root, Mail mail) { - Element htmlElem = root.getChild("html"); - if (htmlElem != null) { - mail.setHtmlText(htmlElem.getTextTrim()); - } - } - - /** - * @param root - * @param mail - */ - protected void setSubject(Element root, Mail mail) { - Element subjectElem = root.getChild("subject"); - if (subjectElem != null) { - mail.setSubject(subjectElem.getTextTrim()); - } - } - - /** - * @param root - * @param mail - */ - protected void setRecipients(Element root, Mail mail) { - Element recipientsElem = root.getChild("recipients"); - if (recipientsElem == null) { - return; - } - - List recipientElemList = recipientsElem.getChildren(); - for (int i = 0, max = recipientElemList.size(); i < max; i++) { - Element e = (Element)recipientElemList.get(i); - if ("to".equals(e.getName())) { // to - if (e.getAttributeValue("email") != null) { - if (e.getAttributeValue("name") != null) { - mail.addTo(e.getAttributeValue("email"), e.getAttributeValue("name")); - } else { - mail.addTo(e.getAttributeValue("email")); - } - } - } else if ("cc".equals(e.getName())) { // cc - if (e.getAttributeValue("email") != null) { - if (e.getAttributeValue("name") != null) { - mail.addCc(e.getAttributeValue("email"), e.getAttributeValue("name")); - } else { - mail.addCc(e.getAttributeValue("email")); - } - } - } else { - if (e.getAttributeValue("email") != null) { // bcc - mail.addBcc(e.getAttributeValue("email")); - } - } - } - } - - /** - * @param root - * @param mail - */ - protected void setFrom(Element root, Mail mail) { - Element fromElem = root.getChild("from"); - if (fromElem != null && fromElem.getAttributeValue("email") != null) { - if (fromElem.getAttributeValue("name") != null) { - mail.setFrom(fromElem.getAttributeValue("email"), fromElem - .getAttributeValue("name")); - } else { - mail.setFrom(fromElem.getAttributeValue("email")); - } - } - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#clearCache() - */ - public synchronized void clearCache() { - log.debug("テンプレートキャッシュをクリアします。"); - templateCache.clear(); - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#isCacheEnabled() - */ - public boolean isCacheEnabled() { - return cacheEnabled; - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#setCacheEnabled(boolean) - */ - public void setCacheEnabled(boolean cacheEnabled) { - if (!cacheEnabled) { - clearCache(); - } - this.cacheEnabled = cacheEnabled; - } - - protected boolean hasTemplateCache(String key) { - if (cacheEnabled) { - return templateCache.containsKey(key); - } - return false; - } - - protected void putTemplateCache(String key, String templateXmlText) { - if (cacheEnabled) { - log.debug("テンプレートをキャッシュします。[key='" + key + "']"); - templateCache.put(key, templateXmlText); - } - } - - protected String getTemplateCache(String key) { - if (hasTemplateCache(key)) { - log.debug("テンプレートキャッシュを返します。[key='" + key + "']"); - return (String)templateCache.get(key); - } - return null; - } - - /** - * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.lang.String, org.apache.velocity.VelocityContext, java.lang.String) - */ - public Mail buildMail(String classPath, VelocityContext context, String mailId) - throws MailBuildException { - if (mailId == null || "".equals(mailId)) { - throw new IllegalArgumentException("メールIDが指定されていません。"); - } - - String cacheKey = classPath + CACHE_KEY_SEPARATOR + mailId; - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc = getDocumentFromClassPath(classPath); - templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - - private String getAndCacheTemplateText(Document doc, String mailId, String cacheKey) - throws MailBuildException { - Element mailElem = getElementById(doc, mailId); - XMLOutputter output = new XMLOutputter(); - String templateXmlText = output.outputString(mailElem); - - putTemplateCache(cacheKey, templateXmlText); - return templateXmlText; - } - - /** - * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.io.File, org.apache.velocity.VelocityContext, java.lang.String) - */ - public Mail buildMail(File file, VelocityContext context, String mailId) - throws MailBuildException { - if (mailId == null || "".equals(mailId)) { - throw new IllegalArgumentException("メールIDが指定されていません。"); - } - - String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + mailId; - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc = getDocumentFromFile(file); - templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - - /** - * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.lang.String, java.lang.String) - */ - public Mail buildMail(String classPath, String mailId) throws MailBuildException { - Document doc = getDocumentFromClassPath(classPath); - Element mailElem = getElementById(doc, mailId); - return build(mailElem); - } - - /** - * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.io.File, java.lang.String) - */ - public Mail buildMail(File file, String mailId) throws MailBuildException { - Document doc = getDocumentFromFile(file); - Element mailElem = getElementById(doc, mailId); - return build(mailElem); - } - - /** - * 指定されたXMLドキュメントの中から、指定されたid属性がセットされている要素を取得します。 - * - * @param doc XMLドキュメント - * @param id 抽出する要素のid属性値 - * @return XMLドキュメントで見つかったid属性を持つ要素 - */ - private Element getElementById(Document doc, String id) { - Element mailsElem = doc.getRootElement(); // - List mailElemList = mailsElem.getChildren("mail"); - for (Iterator itr = mailElemList.iterator(); itr.hasNext();) { - Element mailElem = (Element)itr.next(); - String mailId = mailElem.getAttributeValue("id"); - if (mailId.equals(id)) { - return mailElem; - } - } - throw new MailBuildException("指定されたID[" + id + "]のメールデータは見つかりませんでした。"); - } - +package com.ozacc.mail.impl; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.apache.velocity.exception.MethodInvocationException; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.log.LogSystem; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.input.SAXBuilder; +import org.jdom.output.XMLOutputter; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.MultipleMailBuilder; +import com.ozacc.mail.VelocityMultipleMailBuilder; + +/** + * JDOMを利用してXMLファイルからMailインスタンスを生成するクラス。 + *

+ * ソースXMLを読み込む際に、DTDバリデーションが実行されますので妥当なXMLデータ(Valid XML Document)でなければいけません。 + * + * @since 1.0 + * + * @author Tomohiro Otsuka + * @version $Id: JDomXMLMailBuilder.java,v 1.10.2.5 2005/02/01 20:37:49 otsuka Exp $ + */ +public class JDomXMLMailBuilder implements MultipleMailBuilder, VelocityMultipleMailBuilder { + + private static Log log = LogFactory.getLog(JDomXMLMailBuilder.class); + + private static String CACHE_KEY_SEPARATOR = "#"; + + private static String DEFAULT_MAIL_ID = "DEFAULT"; + + protected LogSystem velocityLogSystem = new VelocityLogSystem(); + + private boolean cacheEnabled = false; + + protected Map templateCache = new HashMap(); + + /** + * コンストラクタ。 + */ + public JDomXMLMailBuilder() {} + + /** + * 指定されたクラスパス上のXMLファイルからMailインスタンスを生成します。 + * + * @param classPath メール内容を記述したXMLファイルのパス + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + public Mail buildMail(String classPath) throws MailBuildException { + Document doc = getDocumentFromClassPath(classPath); + return build(doc.getRootElement()); + } + + /** + * 指定されたクラスパス上のXMLファイルからMailインスタンスを生成します。 + * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 + * + * @param classPath メール内容を記述したXMLファイルのパス + * @param context VelocityContext + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + public Mail buildMail(String classPath, VelocityContext context) throws MailBuildException { + String cacheKey = classPath + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc = getDocumentFromClassPath(classPath); + templateXmlText = cacheTemplateText(doc, cacheKey); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + + /** + * 指定されたXMLファイルからMailインスタンスを生成します。 + * + * @param file メール内容を記述したXMLファイル + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + public Mail buildMail(File file) throws MailBuildException { + Document doc = getDocumentFromFile(file); + return build(doc.getRootElement()); + } + + /** + * 指定されたXMLファイルからMailインスタンスを生成します。 + * 指定されたVelocityContextを使って、XMLファイルの内容を動的に生成できます。 + * + * @param file メール内容を記述したXMLファイル + * @param context VelocityContext + * @return 生成されたMailインスタンス + * @throws MailBuildException Mailインスタンスの生成に失敗した場合 + */ + public Mail buildMail(File file, VelocityContext context) throws MailBuildException { + String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc = getDocumentFromFile(file); + templateXmlText = cacheTemplateText(doc, cacheKey); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + + private String cacheTemplateText(Document doc, String cacheKey) { + XMLOutputter output = new XMLOutputter(); + String templateXmlText = "\n" + output.outputString(doc.getRootElement()); + log.debug("以下のXMLデータをキャッシュします。\n" + templateXmlText); + putTemplateCache(cacheKey, templateXmlText); + return templateXmlText; + } + + /** + * 指定されたクラスパス上のファイルを読み込んで、XMLドキュメントを生成します。 + * + * @param classPath + * @return JDOM Document + */ + protected Document getDocumentFromClassPath(String classPath) throws MailBuildException { + InputStream is = getClass().getResourceAsStream(classPath); + SAXBuilder builder = new SAXBuilder(true); + builder.setEntityResolver(new DTDEntityResolver()); + Document doc; + try { + doc = builder.build(is); + } catch (JDOMException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException e) { + // ignore + } + } + } + return doc; + } + + /** + * 指定されたファイルを読み込んで、XMLドキュメントを生成します。 + * + * @param file + * @return JDOM Document + */ + protected Document getDocumentFromFile(File file) { + SAXBuilder builder = new SAXBuilder(true); + builder.setEntityResolver(new DTDEntityResolver()); + Document doc; + try { + doc = builder.build(file); + } catch (JDOMException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } + return doc; + } + + /** + * XMLのmailルートエレメントからMailインスタンスを生成します。 + * + * @param mailElement mail要素を示すElementインスタンス + * @return Mail 生成されたMail + */ + protected Mail build(Element mailElement) { + Mail mail = new Mail(); + setFrom(mailElement, mail); + setRecipients(mailElement, mail); + setSubject(mailElement, mail); + setBody(mailElement, mail); + setReplyTo(mailElement, mail); + setReturnPath(mailElement, mail); + + setHtml(mailElement, mail); + + return mail; + } + + /** + * VelocityContextとXMLテンプレートをマージさせ、Mailインスタンスを生成します。 + * + * @param templateText マージするXMLテンプレートの文字列 + * @param context マージするVelocityContext + * @return Mail + * + * @throws Exception + * @throws ParseErrorException + * @throws MethodInvocationException + * @throws ResourceNotFoundException + * @throws IOException + * @throws JDOMException + */ + protected Mail build(String templateText, VelocityContext context) throws Exception, + ParseErrorException, + MethodInvocationException, + ResourceNotFoundException, + IOException, JDOMException { + if (log.isDebugEnabled()) { + log.debug("ソースXMLデータ\n" + templateText); + } + + Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, velocityLogSystem); + Velocity.init(); + StringWriter w = new StringWriter(); + Velocity.evaluate(context, w, "XML Mail Data", templateText); + + if (log.isDebugEnabled()) { + log.debug("VelocityContextとマージ後のXMLデータ\n" + w.toString()); + } + + StringReader reader = new StringReader(w.toString()); + SAXBuilder builder = new SAXBuilder(true); + builder.setEntityResolver(new DTDEntityResolver()); + Document mergedDoc = builder.build(reader); + + return build(mergedDoc.getRootElement()); + } + + /** + * @param root + * @param mail + */ + protected void setReturnPath(Element root, Mail mail) { + Element returnPathElem = root.getChild("returnPath"); + if (returnPathElem != null && returnPathElem.getAttributeValue("email") != null) { + mail.setReturnPath(returnPathElem.getAttributeValue("email")); + } + } + + /** + * @param root + * @param mail + */ + protected void setReplyTo(Element root, Mail mail) { + Element replyToElem = root.getChild("replyTo"); + if (replyToElem != null && replyToElem.getAttributeValue("email") != null) { + mail.setReplyTo(replyToElem.getAttributeValue("email")); + } + } + + /** + * @param root + * @param mail + */ + protected void setBody(Element root, Mail mail) { + Element bodyElem = root.getChild("body"); + if (bodyElem != null) { + mail.setText(bodyElem.getTextTrim()); + } + } + + /** + * @param root + * @param mail + */ + protected void setHtml(Element root, Mail mail) { + Element htmlElem = root.getChild("html"); + if (htmlElem != null) { + mail.setHtmlText(htmlElem.getTextTrim()); + } + } + + /** + * @param root + * @param mail + */ + protected void setSubject(Element root, Mail mail) { + Element subjectElem = root.getChild("subject"); + if (subjectElem != null) { + mail.setSubject(subjectElem.getTextTrim()); + } + } + + /** + * @param root + * @param mail + */ + protected void setRecipients(Element root, Mail mail) { + Element recipientsElem = root.getChild("recipients"); + if (recipientsElem == null) { + return; + } + + List recipientElemList = recipientsElem.getChildren(); + for (int i = 0, max = recipientElemList.size(); i < max; i++) { + Element e = (Element)recipientElemList.get(i); + if ("to".equals(e.getName())) { // to + if (e.getAttributeValue("email") != null) { + if (e.getAttributeValue("name") != null) { + mail.addTo(e.getAttributeValue("email"), e.getAttributeValue("name")); + } else { + mail.addTo(e.getAttributeValue("email")); + } + } + } else if ("cc".equals(e.getName())) { // cc + if (e.getAttributeValue("email") != null) { + if (e.getAttributeValue("name") != null) { + mail.addCc(e.getAttributeValue("email"), e.getAttributeValue("name")); + } else { + mail.addCc(e.getAttributeValue("email")); + } + } + } else { + if (e.getAttributeValue("email") != null) { // bcc + mail.addBcc(e.getAttributeValue("email")); + } + } + } + } + + /** + * @param root + * @param mail + */ + protected void setFrom(Element root, Mail mail) { + Element fromElem = root.getChild("from"); + if (fromElem != null && fromElem.getAttributeValue("email") != null) { + if (fromElem.getAttributeValue("name") != null) { + mail.setFrom(fromElem.getAttributeValue("email"), fromElem + .getAttributeValue("name")); + } else { + mail.setFrom(fromElem.getAttributeValue("email")); + } + } + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#clearCache() + */ + public synchronized void clearCache() { + log.debug("テンプレートキャッシュをクリアします。"); + templateCache.clear(); + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#isCacheEnabled() + */ + public boolean isCacheEnabled() { + return cacheEnabled; + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#setCacheEnabled(boolean) + */ + public void setCacheEnabled(boolean cacheEnabled) { + if (!cacheEnabled) { + clearCache(); + } + this.cacheEnabled = cacheEnabled; + } + + protected boolean hasTemplateCache(String key) { + if (cacheEnabled) { + return templateCache.containsKey(key); + } + return false; + } + + protected void putTemplateCache(String key, String templateXmlText) { + if (cacheEnabled) { + log.debug("テンプレートをキャッシュします。[key='" + key + "']"); + templateCache.put(key, templateXmlText); + } + } + + protected String getTemplateCache(String key) { + if (hasTemplateCache(key)) { + log.debug("テンプレートキャッシュを返します。[key='" + key + "']"); + return (String)templateCache.get(key); + } + return null; + } + + /** + * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.lang.String, org.apache.velocity.VelocityContext, java.lang.String) + */ + public Mail buildMail(String classPath, VelocityContext context, String mailId) + throws MailBuildException { + if (mailId == null || "".equals(mailId)) { + throw new IllegalArgumentException("メールIDが指定されていません。"); + } + + String cacheKey = classPath + CACHE_KEY_SEPARATOR + mailId; + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc = getDocumentFromClassPath(classPath); + templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + + private String getAndCacheTemplateText(Document doc, String mailId, String cacheKey) + throws MailBuildException { + Element mailElem = getElementById(doc, mailId); + XMLOutputter output = new XMLOutputter(); + String templateXmlText = output.outputString(mailElem); + + putTemplateCache(cacheKey, templateXmlText); + return templateXmlText; + } + + /** + * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.io.File, org.apache.velocity.VelocityContext, java.lang.String) + */ + public Mail buildMail(File file, VelocityContext context, String mailId) + throws MailBuildException { + if (mailId == null || "".equals(mailId)) { + throw new IllegalArgumentException("メールIDが指定されていません。"); + } + + String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + mailId; + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc = getDocumentFromFile(file); + templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + + /** + * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.lang.String, java.lang.String) + */ + public Mail buildMail(String classPath, String mailId) throws MailBuildException { + Document doc = getDocumentFromClassPath(classPath); + Element mailElem = getElementById(doc, mailId); + return build(mailElem); + } + + /** + * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.io.File, java.lang.String) + */ + public Mail buildMail(File file, String mailId) throws MailBuildException { + Document doc = getDocumentFromFile(file); + Element mailElem = getElementById(doc, mailId); + return build(mailElem); + } + + /** + * 指定されたXMLドキュメントの中から、指定されたid属性がセットされている要素を取得します。 + * + * @param doc XMLドキュメント + * @param id 抽出する要素のid属性値 + * @return XMLドキュメントで見つかったid属性を持つ要素 + */ + private Element getElementById(Document doc, String id) { + Element mailsElem = doc.getRootElement(); // + List mailElemList = mailsElem.getChildren("mail"); + for (Iterator itr = mailElemList.iterator(); itr.hasNext();) { + Element mailElem = (Element)itr.next(); + String mailId = mailElem.getAttributeValue("id"); + if (mailId.equals(id)) { + return mailElem; + } + } + throw new MailBuildException("指定されたID[" + id + "]のメールデータは見つかりませんでした。"); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/MimeMessageBuilder.java b/src/main/java/com/ozacc/mail/impl/MimeMessageBuilder.java old mode 100755 new mode 100644 index 4a2eaf7..b5cc40b --- a/src/main/java/com/ozacc/mail/impl/MimeMessageBuilder.java +++ b/src/main/java/com/ozacc/mail/impl/MimeMessageBuilder.java @@ -1,431 +1,431 @@ -package com.ozacc.mail.impl; - -import java.io.UnsupportedEncodingException; -import java.util.Iterator; -import java.util.Map; - -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.mail.MessagingException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import javax.mail.internet.MimePart; -import javax.mail.internet.MimeUtility; - -import com.ozacc.mail.Mail; - -/** - * MimeMessageインスタンスを生成するクラス。Mail一通毎に生成されます。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MimeMessageBuilder.java,v 1.11.2.2 2007/03/30 13:03:44 otsuka Exp $ - */ -public class MimeMessageBuilder { - - private MimeMessage mimeMessage; - - private String charset = Mail.JIS_CHARSET; - - private boolean hasRecipient = false; - - /** - * コンストラクタ。 - * デフォルトの文字コード ISO-2022-JP がエンコーディングに使用されます。 - * - * @param mimeMessage - */ - public MimeMessageBuilder(MimeMessage mimeMessage) { - this.mimeMessage = mimeMessage; - } - - /** - * コンストラクタ。 - * 本文や件名のエンコーディングに使用する文字コードを指定します。 - * - * @param mimeMessage - * @param charset エンコーディングに使用する文字コード - */ - public MimeMessageBuilder(MimeMessage mimeMessage, String charset) { - this.mimeMessage = mimeMessage; - this.charset = charset; - } - - /** - * コンストラクタの引数で渡されたMimeMessageをそのまま返します。 - * - * @return MimeMessage - */ - public MimeMessage getMimeMessage() { - return this.mimeMessage; - } - - /** - * 指定されたメールからMimeMessageを生成します。 - * - * @param mail MimeMessageのソースとなるMail - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - public void buildMimeMessage(Mail mail) throws UnsupportedEncodingException, MessagingException { - setCharset(mail); - - setTo(mail); - setCc(mail); - setBcc(mail); - // 宛先の指定がない場合エラー - if (!hasRecipient) { - throw new MessagingException("宛先の指定がありません。To、Cc、Bccのいずれか一つは指定する必要があります。"); - } - setFrom(mail); - setSubject(mail); - setReplyTo(mail); - setXHeaders(mail); - setImportance(mail); - - if (mail.isMultipartMail()) { - - if (!mail.isFileAttached() && mail.isHtmlMail()) { // Plain text, HTML - - if (mail.getText() != null && mail.getText().length() > 0) { // Plain text, HTML - - MimeMultipart textAndHtmlMultipart = new MimeMultipart("alternative"); - setPlainText(mail, textAndHtmlMultipart); - setHtmlText(mail, textAndHtmlMultipart); - this.mimeMessage.setContent(textAndHtmlMultipart); - - } else { // HTML Only マルチパートは使用しない - - setHtmlText(mail.getHtmlText(), this.mimeMessage); - - } - - } else if (mail.isFileAttached() && mail.isHtmlMail()) { // Plain text, HMTL, File - - MimeMultipart textAndHtmlMultipart = new MimeMultipart("alternative"); - setPlainText(mail, textAndHtmlMultipart); - setHtmlText(mail, textAndHtmlMultipart); - - MimeMultipart containingMultipart = new MimeMultipart(); - MimeBodyPart textBodyPart = createMimeBodyPart(containingMultipart); - textBodyPart.setContent(textAndHtmlMultipart); - setAttachmentFiles(mail, containingMultipart); - - this.mimeMessage.setContent(containingMultipart); - - } else if (mail.isFileAttached() && !mail.isHtmlMail()) { // Plain text, File - - MimeMultipart textAndFileMultipart = new MimeMultipart(); - setPlainText(mail, textAndFileMultipart); - setAttachmentFiles(mail, textAndFileMultipart); - this.mimeMessage.setContent(textAndFileMultipart); - - } else { // Plain text only マルチパートは使用しない - - setText(mail.getText(), this.mimeMessage); - - } - - } else { - - setText(mail.getText(), this.mimeMessage); - - } - - } - - /** - * メールに使用するcharsetを決定します。 - * Mail#charsetが設定されている場合、その値が優先されます。 - * - * @since 1.2.1 - * @param mail - */ - private void setCharset(Mail mail) { - if (mail.getCharset() != null && !"".equals(mail.getCharset())) { - charset = mail.getCharset(); - } - } - - /** - * - * @since 1.1 - * - * @param mail - * @param mimeMultipart - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - private void setAttachmentFiles(Mail mail, MimeMultipart mimeMultipart) - throws MessagingException, - UnsupportedEncodingException { - Mail.AttachmentFile[] files = mail.getAttachmentFiles(); - for (int i = 0; i < files.length; i++) { - MimeBodyPart bodyPart = createMimeBodyPart(mimeMultipart); - Mail.AttachmentFile attachmentFile = files[i]; - addAttachment(attachmentFile.getName(), attachmentFile.getDataSource(), bodyPart); - } - } - - /** - * - * @since 1.1 - * - * @param mail - * @param mimeMultipart - * @throws MessagingException - */ - private void setHtmlText(Mail mail, MimeMultipart mimeMultipart) throws MessagingException { - if (mail.isHtmlMail()) { - MimeBodyPart bodyPart = createMimeBodyPart(mimeMultipart); - setHtmlText(mail.getHtmlText(), bodyPart); - } - } - - /** - * - * @since 1.1 - * - * @param mail - * @param mimeMultipart - * @throws MessagingException - */ - private void setPlainText(Mail mail, MimeMultipart mimeMultipart) throws MessagingException { - if (mail.getText() != null && mail.getText().length() > 0) { - MimeBodyPart bodyPart = createMimeBodyPart(mimeMultipart); - setText(mail.getText(), bodyPart); - } - } - - /** - * 新しいMimeBodyPartインスタンスを生成し、指定されたMimeMultipartに登録します。 - * - * このメソッドはマルチパートメール生成時にのみ呼び出すことができます。 - * プレーンテキストメール生成時には、mimeMulipartがnullなので、 - * NullPointerExceptionがスローされます。 - * - * @since 1.1 - * - * @param mm - * @return 生成されたMimeBodyPart - * @throws MessagingException - */ - private MimeBodyPart createMimeBodyPart(MimeMultipart mm) throws MessagingException { - MimeBodyPart bodyPart = new MimeBodyPart(); - mm.addBodyPart(bodyPart); - return bodyPart; - } - - /** - * @since 1.1 - * - * @param htmlText - * @param mimePart - * @throws MessagingException - */ - private void setHtmlText(final String htmlText, MimePart mimePart) throws MessagingException { - if (charset != null) { - mimePart.setContent(htmlText, "text/html; charset=" + charset); - } else { - mimePart.setContent(htmlText, "text/html"); - } - setContentTransferEncoding(mimePart); - } - - /** - * @param mail - * @throws MessagingException - */ - private void setXHeaders(Mail mail) throws MessagingException { - Map headers = mail.getHeaders(); - if (headers == null) { - return; - } - - Iterator itr = headers.keySet().iterator(); - while (itr.hasNext()) { - String key = (String)itr.next(); - String value = (String)headers.get(key); - mimeMessage.setHeader(key, value); - } - } - - /** - * @param mail - * @throws MessagingException - */ - private void setImportance(Mail mail) throws MessagingException { - if (mail.getImportance() != null) { - mimeMessage.setHeader("Importance", mail.getImportance()); - - int level = 3; - if (Mail.Importance.HIGH.equals(mail.getImportance())) { - level = 1; - } else if (Mail.Importance.LOW.equals(mail.getImportance())) { - level = 5; - } - mimeMessage.setHeader("X-Priority", String.valueOf(level)); - } - } - - /** - * @param mail - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - private void setReplyTo(Mail mail) throws MessagingException, UnsupportedEncodingException { - if (mail.getReplyTo() != null) { - mimeMessage.setReplyTo(new InternetAddress[] { convertCharset(mail.getReplyTo()) }); - } - } - - /** - * @param mail - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - private void setBcc(Mail mail) throws MessagingException, UnsupportedEncodingException { - if (mail.getBcc().length > 0) { - mimeMessage.setRecipients(MimeMessage.RecipientType.BCC, convertCharset(mail.getBcc())); - hasRecipient = true; - } - } - - /** - * @param mail - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - private void setCc(Mail mail) throws MessagingException, UnsupportedEncodingException { - if (mail.getCc().length > 0) { - mimeMessage.setRecipients(MimeMessage.RecipientType.CC, convertCharset(mail.getCc())); - hasRecipient = true; - } - } - - /** - * @param mail - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - private void setTo(Mail mail) throws MessagingException, UnsupportedEncodingException { - if (mail.getTo().length > 0) { - mimeMessage.setRecipients(MimeMessage.RecipientType.TO, convertCharset(mail.getTo())); - hasRecipient = true; - } - } - - /** - * 本文をセット。 - *

- * NOTE: 本文の最後に改行がないとMozilla系のメーラーで最終行の日本語が文字化けしてしまう為、 - * message.setTextの引数で最後に\nを追加している。 - * - * @since 1.1 - * - * @param text 本文 - * @param mimePart 本文をセットするMimePart - * @throws MessagingException - */ - private void setText(String text, MimePart mimePart) throws MessagingException { - if (charset != null) { - if (charset.equalsIgnoreCase(Mail.JIS_CHARSET)) { - // Cp932クラスを使用して、怪しい記号を強制的にJIS変換 - mimePart.setText(Cp932.toJIS(text) + "\n", charset); - } else { - mimePart.setText(text + "\n", charset); - } - } else { - mimePart.setText(text + "\n"); - } - setContentTransferEncoding(mimePart); - } - - /** - * charsetに応じてContent-Trnasfer-Encodingを設定します。 - * が、UTF-8の時に8bitになること以外分かりません。。。 - * - * @since 1.2.1 - * @param mimePart - * @throws MessagingException - */ - private void setContentTransferEncoding(MimePart mimePart) throws MessagingException { - String contentTransferEncoding = "7bit"; - if ("UTF-8".equalsIgnoreCase(charset)) { - contentTransferEncoding = "8bit"; - } - mimePart.setHeader("Content-Transfer-Encoding", contentTransferEncoding); - } - - /** - * @param mail - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - private void setSubject(Mail mail) throws UnsupportedEncodingException, MessagingException { - if (charset != null) { - if (Mail.JIS_CHARSET.equalsIgnoreCase(charset)) { - String subject = Cp932.toJIS(mail.getSubject()); - mimeMessage.setSubject(MimeUtility.encodeText(subject, charset, "B")); - } else { - mimeMessage.setSubject(mail.getSubject(), charset); - } - } else { - mimeMessage.setSubject(mail.getSubject()); - } - } - - /** - * @param mail - * @throws MessagingException - * @throws UnsupportedEncodingException - */ - private void setFrom(Mail mail) throws MessagingException, UnsupportedEncodingException { - InternetAddress address = convertCharset(mail.getFrom()); - mimeMessage.setFrom(address); - } - - private InternetAddress convertCharset(InternetAddress address) - throws UnsupportedEncodingException { - String name = address.getPersonal(); - if (name != null && !"".equals(name) && Mail.JIS_CHARSET.equalsIgnoreCase(charset)) { - name = Cp932.toJIS(name); - } - return new InternetAddress(address.getAddress(), name, charset); - } - - private InternetAddress[] convertCharset(InternetAddress[] addresses) - throws UnsupportedEncodingException { - for (int i = 0; i < addresses.length; i++) { - addresses[i] = convertCharset(addresses[i]); - } - return addresses; - } - - /** - * 添付ファイルデータを指定されたMimeBodyPartにセットします。 - * - * @since 1.1 - * - * @param fileName - * @param dataSource - * @param mimeBodyPart ファイルデータをセットするMimeBodyPart - * @throws UnsupportedEncodingException - * @throws MessagingException - */ - private void addAttachment(String fileName, DataSource dataSource, MimeBodyPart mimeBodyPart) - throws UnsupportedEncodingException, - MessagingException { - if (charset != null) { - // ファイル名のエンコード - mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, charset, "B")); - } else { - mimeBodyPart.setFileName(fileName); - } - - mimeBodyPart.setDataHandler(new DataHandler(dataSource)); - } - +package com.ozacc.mail.impl; + +import java.io.UnsupportedEncodingException; +import java.util.Iterator; +import java.util.Map; + +import javax.activation.DataHandler; +import javax.activation.DataSource; +import javax.mail.MessagingException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeBodyPart; +import javax.mail.internet.MimeMessage; +import javax.mail.internet.MimeMultipart; +import javax.mail.internet.MimePart; +import javax.mail.internet.MimeUtility; + +import com.ozacc.mail.Mail; + +/** + * MimeMessageインスタンスを生成するクラス。Mail一通毎に生成されます。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MimeMessageBuilder.java,v 1.11.2.2 2007/03/30 13:03:44 otsuka Exp $ + */ +public class MimeMessageBuilder { + + private MimeMessage mimeMessage; + + private String charset = Mail.JIS_CHARSET; + + private boolean hasRecipient = false; + + /** + * コンストラクタ。 + * デフォルトの文字コード ISO-2022-JP がエンコーディングに使用されます。 + * + * @param mimeMessage + */ + public MimeMessageBuilder(MimeMessage mimeMessage) { + this.mimeMessage = mimeMessage; + } + + /** + * コンストラクタ。 + * 本文や件名のエンコーディングに使用する文字コードを指定します。 + * + * @param mimeMessage + * @param charset エンコーディングに使用する文字コード + */ + public MimeMessageBuilder(MimeMessage mimeMessage, String charset) { + this.mimeMessage = mimeMessage; + this.charset = charset; + } + + /** + * コンストラクタの引数で渡されたMimeMessageをそのまま返します。 + * + * @return MimeMessage + */ + public MimeMessage getMimeMessage() { + return this.mimeMessage; + } + + /** + * 指定されたメールからMimeMessageを生成します。 + * + * @param mail MimeMessageのソースとなるMail + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + public void buildMimeMessage(Mail mail) throws UnsupportedEncodingException, MessagingException { + setCharset(mail); + + setTo(mail); + setCc(mail); + setBcc(mail); + // 宛先の指定がない場合エラー + if (!hasRecipient) { + throw new MessagingException("宛先の指定がありません。To、Cc、Bccのいずれか一つは指定する必要があります。"); + } + setFrom(mail); + setSubject(mail); + setReplyTo(mail); + setXHeaders(mail); + setImportance(mail); + + if (mail.isMultipartMail()) { + + if (!mail.isFileAttached() && mail.isHtmlMail()) { // Plain text, HTML + + if (mail.getText() != null && mail.getText().length() > 0) { // Plain text, HTML + + MimeMultipart textAndHtmlMultipart = new MimeMultipart("alternative"); + setPlainText(mail, textAndHtmlMultipart); + setHtmlText(mail, textAndHtmlMultipart); + this.mimeMessage.setContent(textAndHtmlMultipart); + + } else { // HTML Only マルチパートは使用しない + + setHtmlText(mail.getHtmlText(), this.mimeMessage); + + } + + } else if (mail.isFileAttached() && mail.isHtmlMail()) { // Plain text, HMTL, File + + MimeMultipart textAndHtmlMultipart = new MimeMultipart("alternative"); + setPlainText(mail, textAndHtmlMultipart); + setHtmlText(mail, textAndHtmlMultipart); + + MimeMultipart containingMultipart = new MimeMultipart(); + MimeBodyPart textBodyPart = createMimeBodyPart(containingMultipart); + textBodyPart.setContent(textAndHtmlMultipart); + setAttachmentFiles(mail, containingMultipart); + + this.mimeMessage.setContent(containingMultipart); + + } else if (mail.isFileAttached() && !mail.isHtmlMail()) { // Plain text, File + + MimeMultipart textAndFileMultipart = new MimeMultipart(); + setPlainText(mail, textAndFileMultipart); + setAttachmentFiles(mail, textAndFileMultipart); + this.mimeMessage.setContent(textAndFileMultipart); + + } else { // Plain text only マルチパートは使用しない + + setText(mail.getText(), this.mimeMessage); + + } + + } else { + + setText(mail.getText(), this.mimeMessage); + + } + + } + + /** + * メールに使用するcharsetを決定します。 + * Mail#charsetが設定されている場合、その値が優先されます。 + * + * @since 1.2.1 + * @param mail + */ + private void setCharset(Mail mail) { + if (mail.getCharset() != null && !"".equals(mail.getCharset())) { + charset = mail.getCharset(); + } + } + + /** + * + * @since 1.1 + * + * @param mail + * @param mimeMultipart + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + private void setAttachmentFiles(Mail mail, MimeMultipart mimeMultipart) + throws MessagingException, + UnsupportedEncodingException { + Mail.AttachmentFile[] files = mail.getAttachmentFiles(); + for (int i = 0; i < files.length; i++) { + MimeBodyPart bodyPart = createMimeBodyPart(mimeMultipart); + Mail.AttachmentFile attachmentFile = files[i]; + addAttachment(attachmentFile.getName(), attachmentFile.getDataSource(), bodyPart); + } + } + + /** + * + * @since 1.1 + * + * @param mail + * @param mimeMultipart + * @throws MessagingException + */ + private void setHtmlText(Mail mail, MimeMultipart mimeMultipart) throws MessagingException { + if (mail.isHtmlMail()) { + MimeBodyPart bodyPart = createMimeBodyPart(mimeMultipart); + setHtmlText(mail.getHtmlText(), bodyPart); + } + } + + /** + * + * @since 1.1 + * + * @param mail + * @param mimeMultipart + * @throws MessagingException + */ + private void setPlainText(Mail mail, MimeMultipart mimeMultipart) throws MessagingException { + if (mail.getText() != null && mail.getText().length() > 0) { + MimeBodyPart bodyPart = createMimeBodyPart(mimeMultipart); + setText(mail.getText(), bodyPart); + } + } + + /** + * 新しいMimeBodyPartインスタンスを生成し、指定されたMimeMultipartに登録します。 + * + * このメソッドはマルチパートメール生成時にのみ呼び出すことができます。 + * プレーンテキストメール生成時には、mimeMulipartがnullなので、 + * NullPointerExceptionがスローされます。 + * + * @since 1.1 + * + * @param mm + * @return 生成されたMimeBodyPart + * @throws MessagingException + */ + private MimeBodyPart createMimeBodyPart(MimeMultipart mm) throws MessagingException { + MimeBodyPart bodyPart = new MimeBodyPart(); + mm.addBodyPart(bodyPart); + return bodyPart; + } + + /** + * @since 1.1 + * + * @param htmlText + * @param mimePart + * @throws MessagingException + */ + private void setHtmlText(final String htmlText, MimePart mimePart) throws MessagingException { + if (charset != null) { + mimePart.setContent(htmlText, "text/html; charset=" + charset); + } else { + mimePart.setContent(htmlText, "text/html"); + } + setContentTransferEncoding(mimePart); + } + + /** + * @param mail + * @throws MessagingException + */ + private void setXHeaders(Mail mail) throws MessagingException { + Map headers = mail.getHeaders(); + if (headers == null) { + return; + } + + Iterator itr = headers.keySet().iterator(); + while (itr.hasNext()) { + String key = (String)itr.next(); + String value = (String)headers.get(key); + mimeMessage.setHeader(key, value); + } + } + + /** + * @param mail + * @throws MessagingException + */ + private void setImportance(Mail mail) throws MessagingException { + if (mail.getImportance() != null) { + mimeMessage.setHeader("Importance", mail.getImportance()); + + int level = 3; + if (Mail.Importance.HIGH.equals(mail.getImportance())) { + level = 1; + } else if (Mail.Importance.LOW.equals(mail.getImportance())) { + level = 5; + } + mimeMessage.setHeader("X-Priority", String.valueOf(level)); + } + } + + /** + * @param mail + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + private void setReplyTo(Mail mail) throws MessagingException, UnsupportedEncodingException { + if (mail.getReplyTo() != null) { + mimeMessage.setReplyTo(new InternetAddress[] { convertCharset(mail.getReplyTo()) }); + } + } + + /** + * @param mail + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + private void setBcc(Mail mail) throws MessagingException, UnsupportedEncodingException { + if (mail.getBcc().length > 0) { + mimeMessage.setRecipients(MimeMessage.RecipientType.BCC, convertCharset(mail.getBcc())); + hasRecipient = true; + } + } + + /** + * @param mail + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + private void setCc(Mail mail) throws MessagingException, UnsupportedEncodingException { + if (mail.getCc().length > 0) { + mimeMessage.setRecipients(MimeMessage.RecipientType.CC, convertCharset(mail.getCc())); + hasRecipient = true; + } + } + + /** + * @param mail + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + private void setTo(Mail mail) throws MessagingException, UnsupportedEncodingException { + if (mail.getTo().length > 0) { + mimeMessage.setRecipients(MimeMessage.RecipientType.TO, convertCharset(mail.getTo())); + hasRecipient = true; + } + } + + /** + * 本文をセット。 + *

+ * NOTE: 本文の最後に改行がないとMozilla系のメーラーで最終行の日本語が文字化けしてしまう為、 + * message.setTextの引数で最後に\nを追加している。 + * + * @since 1.1 + * + * @param text 本文 + * @param mimePart 本文をセットするMimePart + * @throws MessagingException + */ + private void setText(String text, MimePart mimePart) throws MessagingException { + if (charset != null) { + if (charset.equalsIgnoreCase(Mail.JIS_CHARSET)) { + // Cp932クラスを使用して、怪しい記号を強制的にJIS変換 + mimePart.setText(Cp932.toJIS(text) + "\n", charset); + } else { + mimePart.setText(text + "\n", charset); + } + } else { + mimePart.setText(text + "\n"); + } + setContentTransferEncoding(mimePart); + } + + /** + * charsetに応じてContent-Trnasfer-Encodingを設定します。 + * が、UTF-8の時に8bitになること以外分かりません。。。 + * + * @since 1.2.1 + * @param mimePart + * @throws MessagingException + */ + private void setContentTransferEncoding(MimePart mimePart) throws MessagingException { + String contentTransferEncoding = "7bit"; + if ("UTF-8".equalsIgnoreCase(charset)) { + contentTransferEncoding = "8bit"; + } + mimePart.setHeader("Content-Transfer-Encoding", contentTransferEncoding); + } + + /** + * @param mail + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + private void setSubject(Mail mail) throws UnsupportedEncodingException, MessagingException { + if (charset != null) { + if (Mail.JIS_CHARSET.equalsIgnoreCase(charset)) { + String subject = Cp932.toJIS(mail.getSubject()); + mimeMessage.setSubject(MimeUtility.encodeText(subject, charset, "B")); + } else { + mimeMessage.setSubject(mail.getSubject(), charset); + } + } else { + mimeMessage.setSubject(mail.getSubject()); + } + } + + /** + * @param mail + * @throws MessagingException + * @throws UnsupportedEncodingException + */ + private void setFrom(Mail mail) throws MessagingException, UnsupportedEncodingException { + InternetAddress address = convertCharset(mail.getFrom()); + mimeMessage.setFrom(address); + } + + private InternetAddress convertCharset(InternetAddress address) + throws UnsupportedEncodingException { + String name = address.getPersonal(); + if (name != null && !"".equals(name) && Mail.JIS_CHARSET.equalsIgnoreCase(charset)) { + name = Cp932.toJIS(name); + } + return new InternetAddress(address.getAddress(), name, charset); + } + + private InternetAddress[] convertCharset(InternetAddress[] addresses) + throws UnsupportedEncodingException { + for (int i = 0; i < addresses.length; i++) { + addresses[i] = convertCharset(addresses[i]); + } + return addresses; + } + + /** + * 添付ファイルデータを指定されたMimeBodyPartにセットします。 + * + * @since 1.1 + * + * @param fileName + * @param dataSource + * @param mimeBodyPart ファイルデータをセットするMimeBodyPart + * @throws UnsupportedEncodingException + * @throws MessagingException + */ + private void addAttachment(String fileName, DataSource dataSource, MimeBodyPart mimeBodyPart) + throws UnsupportedEncodingException, + MessagingException { + if (charset != null) { + // ファイル名のエンコード + mimeBodyPart.setFileName(MimeUtility.encodeText(fileName, charset, "B")); + } else { + mimeBodyPart.setFileName(fileName); + } + + mimeBodyPart.setDataHandler(new DataHandler(dataSource)); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/OMLMimeMessage.java b/src/main/java/com/ozacc/mail/impl/OMLMimeMessage.java old mode 100755 new mode 100644 index 7647111..88d6ad3 --- a/src/main/java/com/ozacc/mail/impl/OMLMimeMessage.java +++ b/src/main/java/com/ozacc/mail/impl/OMLMimeMessage.java @@ -1,86 +1,86 @@ -package com.ozacc.mail.impl; - -import java.util.Random; - -import javax.mail.MessagingException; -import javax.mail.Session; -import javax.mail.internet.MimeMessage; - -/** - * Message-Idヘッダがカスタマイズ可能なMimeMessageのサブクラス。 - * - * @since 1.1 - * - * @author Tomohiro Otsuka - * @version $Id: OMLMimeMessage.java,v 1.3.2.3 2006/01/20 10:57:50 otsuka Exp $ - */ -public class OMLMimeMessage extends MimeMessage { - - private static Random random = new Random(); - - private String domainPartOfMessageId; - - private String messageId; - - /** - * コンストラクタ。 - * - * @param session - * @param domainPartOfMessageId Message-Idヘッダのドメイン部分に使用する文字列 - */ - public OMLMimeMessage(Session session, String domainPartOfMessageId) { - super(session); - - String[] parts = domainPartOfMessageId.split("@"); - if (parts.length == 1) { - this.domainPartOfMessageId = "@" + domainPartOfMessageId; - } else if (parts.length == 2) { - if (parts[0].length() > 0 && !parts[0].startsWith(".")) { - this.domainPartOfMessageId = "." + domainPartOfMessageId; - } else { - this.domainPartOfMessageId = domainPartOfMessageId; - } - } - messageId = generateRandomMessageId(); - } - - /** - * Message-Idヘッダをここでセットします。 - *

- * 参考ページ
- * http://java.sun.com/products/javamail/FAQ.html#msgid - * - * @see javax.mail.internet.MimeMessage#updateHeaders() - */ - protected void updateHeaders() throws MessagingException { - super.updateHeaders(); - setHeader("Message-ID", messageId); - } - - /** - * タイムスタンプ + 16桁の乱数 + messageIdプロパティを連結した文字列を返します。 - * - * @return タイムスタンプ + 16桁の乱数 + messageIdプロパティを連結した文字列 - */ - protected String generateRandomMessageId() { - StringBuffer buf = new StringBuffer(); - buf.append("<"); - buf.append(System.currentTimeMillis()).append("."); - for (int i = 0; i < 16; i++) { - long num = Math.abs(random.nextInt(10)); - buf.append(num); - } - buf.append(domainPartOfMessageId); - buf.append(">"); - return buf.toString(); - } - - /** - * 生成されたMessage-Idを返します。 - * - * @return 生成されたMessage-Id - */ - public String getMessageId() { - return messageId; - } +package com.ozacc.mail.impl; + +import java.util.Random; + +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.internet.MimeMessage; + +/** + * Message-Idヘッダがカスタマイズ可能なMimeMessageのサブクラス。 + * + * @since 1.1 + * + * @author Tomohiro Otsuka + * @version $Id: OMLMimeMessage.java,v 1.3.2.3 2006/01/20 10:57:50 otsuka Exp $ + */ +public class OMLMimeMessage extends MimeMessage { + + private static Random random = new Random(); + + private String domainPartOfMessageId; + + private String messageId; + + /** + * コンストラクタ。 + * + * @param session + * @param domainPartOfMessageId Message-Idヘッダのドメイン部分に使用する文字列 + */ + public OMLMimeMessage(Session session, String domainPartOfMessageId) { + super(session); + + String[] parts = domainPartOfMessageId.split("@"); + if (parts.length == 1) { + this.domainPartOfMessageId = "@" + domainPartOfMessageId; + } else if (parts.length == 2) { + if (parts[0].length() > 0 && !parts[0].startsWith(".")) { + this.domainPartOfMessageId = "." + domainPartOfMessageId; + } else { + this.domainPartOfMessageId = domainPartOfMessageId; + } + } + messageId = generateRandomMessageId(); + } + + /** + * Message-Idヘッダをここでセットします。 + *

+ * 参考ページ
+ * http://java.sun.com/products/javamail/FAQ.html#msgid + * + * @see javax.mail.internet.MimeMessage#updateHeaders() + */ + protected void updateHeaders() throws MessagingException { + super.updateHeaders(); + setHeader("Message-ID", messageId); + } + + /** + * タイムスタンプ + 16桁の乱数 + messageIdプロパティを連結した文字列を返します。 + * + * @return タイムスタンプ + 16桁の乱数 + messageIdプロパティを連結した文字列 + */ + protected String generateRandomMessageId() { + StringBuffer buf = new StringBuffer(); + buf.append("<"); + buf.append(System.currentTimeMillis()).append("."); + for (int i = 0; i < 16; i++) { + long num = Math.abs(random.nextInt(10)); + buf.append(num); + } + buf.append(domainPartOfMessageId); + buf.append(">"); + return buf.toString(); + } + + /** + * 生成されたMessage-Idを返します。 + * + * @return 生成されたMessage-Id + */ + public String getMessageId() { + return messageId; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/SendMailImpl.java b/src/main/java/com/ozacc/mail/impl/SendMailImpl.java old mode 100755 new mode 100644 index 396b925..aef932a --- a/src/main/java/com/ozacc/mail/impl/SendMailImpl.java +++ b/src/main/java/com/ozacc/mail/impl/SendMailImpl.java @@ -1,475 +1,475 @@ -package com.ozacc.mail.impl; - -import java.io.UnsupportedEncodingException; -import java.util.Date; -import java.util.Properties; - -import javax.mail.AuthenticationFailedException; -import javax.mail.MessagingException; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailAuthenticationException; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.MailException; -import com.ozacc.mail.MailSendException; -import com.ozacc.mail.SendMail; - -/** - * SendMailインターフェースの実装クラス。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: SendMailImpl.java,v 1.7.2.6 2007/03/30 13:03:44 otsuka Exp $ - */ -public class SendMailImpl implements SendMail { - - private static Log log = LogFactory.getLog(SendMailImpl.class); - - /** デフォルトのプロトコル。「smtp」 */ - public static final String DEFAULT_PROTOCOL = "smtp"; - - /** - * デフォルトのポート。「-1」
- * -1はプロトコルに応じた適切なポートを設定する特別な値。 - * */ - public static final int DEFAULT_PORT = -1; - - /** デフォルトのSMTPサーバ。「localhost」 */ - public static final String DEFAULT_HOST = "localhost"; - - /** ISO-2022-JP */ - public static final String JIS_CHARSET = "ISO-2022-JP"; - - private static final String RETURN_PATH_KEY = "mail.smtp.from"; - - /** 接続タイムアウト */ - private static final int DEFAULT_CONNECTION_TIMEOUT = 5000; - - /** 読込タイムアウト */ - private static final int DEFAULT_READ_TIMEOUT = 5000; - - private String protocol = DEFAULT_PROTOCOL; - - private String host = DEFAULT_HOST; - - private int port = DEFAULT_PORT; - - private String username; - - private String password; - - private String charset = JIS_CHARSET; - - private String returnPath; - - private String messageId; - - private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; - - private int readTimeout = DEFAULT_READ_TIMEOUT; - - /** - * コンストラクタ。 - */ - public SendMailImpl() {} - - /** - * コンストラクタ。使用するSMTPサーバを指定します。 - * - * @param host SMTPサーバのホスト名、またはIPアドレス - */ - public SendMailImpl(String host) { - this(); - setHost(host); - } - - /** - * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail) - */ - public void send(Mail mail) throws MailException { - send(new Mail[] { mail }); - } - - /** - * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail[]) - */ - public void send(Mail[] mails) throws MailException { - MimeMessageWrapper[] mmws = new MimeMessageWrapper[mails.length]; - Session session = Session.getInstance(new Properties()); - for (int i = 0; i < mails.length; i++) { - Mail mail = mails[i]; - - // MimeMessageを生成 - MimeMessage message = createMimeMessage(session); - if (isMessageIdCustomized()) { - mail.addHeader("Message-ID", ((OMLMimeMessage)message).getMessageId()); - } - MimeMessageBuilder builder = new MimeMessageBuilder(message, charset); - try { - builder.buildMimeMessage(mail); - } catch (UnsupportedEncodingException e) { - throw new MailBuildException("サポートされていない文字コードが指定されました。", e); - } catch (MessagingException e) { - throw new MailBuildException("MimeMessageの生成に失敗しました。", e); - } - - // Return-Pathを取得 - String returnPath; - if (mail.getReturnPath() != null) { - returnPath = mail.getReturnPath().getAddress(); - } else { - returnPath = this.returnPath; - } - - mmws[i] = new MimeMessageWrapper(message, returnPath, mail.getEnvelopeTo()); - } - processSend(mmws); - } - - /** - * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage) - */ - public void send(MimeMessage message) throws MailException { - send(new MimeMessage[] { message }); - } - - /** - * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage[]) - */ - public void send(MimeMessage[] messages) throws MailException { - MimeMessageWrapper[] mmws = new MimeMessageWrapper[messages.length]; - for (int i = 0; i < messages.length; i++) { - mmws[i] = new MimeMessageWrapper(messages[i], returnPath); - } - processSend(mmws); - } - - private void processSend(MimeMessageWrapper[] mmws) throws MailException { - - Properties prop = new Properties(); - // タイムアウトの設定 - prop.put("mail.smtp.connectiontimeout", String.valueOf(connectionTimeout)); - prop.put("mail.smtp.timeout", String.valueOf(readTimeout)); - // mail.smtp.authプロパティの設定 - if (username != null && !"".equals(username) && password != null && !"".equals(password)) { - prop.put("mail.smtp.auth", "true"); - } - Session session = Session.getInstance(prop); - - Transport transport = null; - try { - // SMTPサーバに接続 - log.debug("SMTPサーバ[" + host + "]に接続します。"); - transport = session.getTransport(protocol); - transport.connect(host, port, username, password); - log.debug("SMTPサーバ[" + host + "]に接続しました。"); - - for (int i = 0; i < mmws.length; i++) { - MimeMessage mimeMessage = mmws[i].getMimeMessage(); - // Return-Pathをセット - String returnPath = mmws[i].getReturnPath(); - if (returnPath != null) { - session.getProperties().put(RETURN_PATH_KEY, returnPath); - log.debug("Return-Path[" + returnPath + "]を設定しました。"); - } - // 送信日時をセット - mimeMessage.setSentDate(new Date()); - mimeMessage.saveChanges(); - - // 送信 - log.debug("メールを送信します。"); - if (mmws[i].hasEnvelopeTo()) { - log.debug("メールはenvelope-toアドレスに送信されます。"); - transport.sendMessage(mimeMessage, mmws[i].getEnvelopeTo()); - } else { - transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); - } - log.debug("メールを送信しました。"); - - // Return-Pathを解除 - if (returnPath != null) { - session.getProperties().remove(RETURN_PATH_KEY); - log.debug("Return-Path設定をクリアしました。"); - } - } - } catch (AuthenticationFailedException ex) { - log.error("SMTPサーバ[" + host + "]への接続認証に失敗しました。", ex); - throw new MailAuthenticationException(ex); - } catch (MessagingException ex) { - log.error("メールの送信に失敗しました。", ex); - throw new MailSendException("メールの送信に失敗しました。", ex); - } finally { - if (transport != null && transport.isConnected()) { - log.debug("SMTPサーバ[" + host + "]との接続を切断します。"); - try { - // SMTPサーバとの接続を切断 - transport.close(); - } catch (MessagingException e) { - log.error("SMTPサーバ[" + host + "]との接続切断に失敗しました。", e); - throw new MailException("SMTPサーバ[" + host + "]との接続切断に失敗しました。"); - } - log.debug("SMTPサーバ[" + host + "]との接続を切断しました。"); - } - } - } - - /** - * 新しいMimeMessageオブジェクトを生成します。
- * messageIdプロパティがセットされている場合、OMLMimeMessageのインスタンスを生成します。 - * - * @return 新しいMimeMessageオブジェクト - */ - private MimeMessage createMimeMessage(Session session) { - if (isMessageIdCustomized()) { - return new OMLMimeMessage(session, messageId); - } - return new MimeMessage(session); - } - - /** - * Message-Idヘッダのドメイン部分を独自にセットしているかどうか判定します。 - * - * @return Message-Idヘッダのドメイン部分を独自にセットしている場合 true - */ - private boolean isMessageIdCustomized() { - return messageId != null; - } - - /** - * エンコーディングに使用する文字コードを返します。 - * - * @return エンコーディングに使用する文字コード - */ - public String getCharset() { - return charset; - } - - /** - * メールの件名や本文のエンコーディングに使用する文字コードを指定します。 - * デフォルトはISO-2022-JPです。 - *

- * 日本語環境で利用する場合は通常変更する必要はありません。 - * - * @param charset エンコーディングに使用する文字コード - */ - public void setCharset(String charset) { - this.charset = charset; - } - - /** - * セットされたSMTPサーバのホスト名、またはIPアドレスを返します。 - * - * @return SMTPサーバのホスト名、またはIPアドレス - */ - public String getHost() { - return host; - } - - /** - * SMTPサーバのホスト名、またはIPアドレスをセットします。 - * デフォルトは localhost です。 - * - * @param host SMTPサーバのホスト名、またはIPアドレス - */ - public void setHost(String host) { - this.host = host; - } - - /** - * @return SMTPサーバ認証パスワード - */ - public String getPassword() { - return password; - } - - /** - * SMTPサーバの接続認証が必要な場合にパスワードをセットします。 - * - * @param password SMTPサーバ認証パスワード - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return SMTPサーバのポート番号 - */ - public int getPort() { - return port; - } - - /** - * SMTPサーバのポート番号をセットします。 - * - * @param port SMTPサーバのポート番号 - */ - public void setPort(int port) { - this.port = port; - } - - /** - * プロトコルを返します。 - * - * @return プロトコル - */ - public String getProtocol() { - return protocol; - } - - /** - * プロトコルをセットします。デフォルトは「smtp」。 - * - * @param protocol プロトコル - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * @return Return-Pathアドレス - */ - public String getReturnPath() { - return returnPath; - } - - /** - * Return-Pathアドレスをセットします。 - *

- * 送信するMailインスタンスに指定されたFromアドレス以外のアドレスをReturn-Pathとしたい場合に使用します。 - * ここでセットされたReturn-Pathより、MailインスタンスにセットされたReturn-Pathが優先されます。 - * - * @param returnPath Return-Pathアドレス - */ - public void setReturnPath(String returnPath) { - this.returnPath = returnPath; - } - - /** - * @return SMTPサーバ認証ユーザ名 - */ - public String getUsername() { - return username; - } - - /** - * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。 - * - * @param username SMTPサーバ認証ユーザ名 - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * SMTPサーバとの接続タイムアウトをセットします。 - * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。 - *

- * -1を指定すると無限大になりますが、お薦めしません。 - * - * @since 1.1.4 - * @param connectionTimeout SMTPサーバとの接続タイムアウト - */ - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - /** - * SMTPサーバへの送信時のタイムアウトをセットします。 - * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。
- * 送信時にタイムアウトすると、com.ozacc.mail.MailSendExceptionがスローされます。 - *

- * -1を指定すると無限大になりますが、お薦めしません。 - * - * @since 1.1.4 - * @param readTimeout SMTPサーバへの送受信時のタイムアウト - */ - public void setReadTimeout(int readTimeout) { - this.readTimeout = readTimeout; - } - - /** - * 生成されるMimeMessageに付けられるMessage-Idヘッダのドメイン部分を指定します。
- * 指定されない場合(nullや空文字列の場合)は、JavaMailがMessage-Idヘッダを生成します。 - * JavaMailが生成する「JavaMail.実行ユーザ名@ホスト名」のMessage-Idを避けたい場合に、このメソッドを使用します。 - *

- * messageIdプロパティがセットされている場合、Mailから生成されるMimeMessageのMessage-Idには - * タイムスタンプ + ランダムに生成される16桁の数値 + ここでセットされた値 - * が使用されます。 - *

- * 生成されるMessage-Idの例。 (実際の数値部分は送信メール毎に変わります)

    - *
  • messageIdに'example.com'を指定した場合・・・1095714924963.5619528074501343@example.com
  • - *
  • messageIdに'@example.com'を指定した場合・・・1095714924963.5619528074501343@example.com (上と同じ)
  • - *
  • messageIdに'OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com
  • - *
  • messageIdに'.OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com (上と同じ)
  • - *
- *

- * 注: このMessage-Idはsend(Mail)かsend(Mail[])メソッドが呼びだれた時にのみ有効です。MimeMessageを直接送信する場合には適用されません。 - * - * @param messageId メールに付けられるMessage-Idヘッダのドメイン部分 - * @throws IllegalArgumentException @を複数含んだ文字列を指定した場合 - */ - public void setMessageId(String messageId) { - if (messageId == null || messageId.length() < 1) { - return; - } - - String[] parts = messageId.split("@"); - if (parts.length > 2) { - throw new IllegalArgumentException("messageIdプロパティに'@'を複数含むことはできません。[" + messageId - + "]"); - } - - this.messageId = messageId; - } - - /** - * MimeMessageインスタンスと、そのメールに対応するReturn-Path、envelope-toアドレスをラップするクラス。 - * - * @author Tomohiro Otsuka - * @version $Id: SendMailImpl.java,v 1.7.2.6 2007/03/30 13:03:44 otsuka Exp $ - */ - private static class MimeMessageWrapper { - - private MimeMessage mimeMessage; - - private String returnPath; - - private InternetAddress[] envelopeTo; - - public MimeMessageWrapper(MimeMessage mimeMessage, String returnPath) { - this.mimeMessage = mimeMessage; - this.returnPath = returnPath; - } - - public MimeMessageWrapper(MimeMessage mimeMessage, String returnPath, - InternetAddress[] envelopeTo) { - this.mimeMessage = mimeMessage; - this.returnPath = returnPath; - this.envelopeTo = envelopeTo; - } - - public MimeMessage getMimeMessage() { - return mimeMessage; - } - - public String getReturnPath() { - return returnPath; - } - - public boolean hasEnvelopeTo() { - return envelopeTo.length > 0; - } - - public InternetAddress[] getEnvelopeTo() { - return envelopeTo; - } - } - +package com.ozacc.mail.impl; + +import java.io.UnsupportedEncodingException; +import java.util.Date; +import java.util.Properties; + +import javax.mail.AuthenticationFailedException; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailAuthenticationException; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.MailException; +import com.ozacc.mail.MailSendException; +import com.ozacc.mail.SendMail; + +/** + * SendMailインターフェースの実装クラス。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: SendMailImpl.java,v 1.7.2.6 2007/03/30 13:03:44 otsuka Exp $ + */ +public class SendMailImpl implements SendMail { + + private static Log log = LogFactory.getLog(SendMailImpl.class); + + /** デフォルトのプロトコル。「smtp」 */ + public static final String DEFAULT_PROTOCOL = "smtp"; + + /** + * デフォルトのポート。「-1」
+ * -1はプロトコルに応じた適切なポートを設定する特別な値。 + * */ + public static final int DEFAULT_PORT = -1; + + /** デフォルトのSMTPサーバ。「localhost」 */ + public static final String DEFAULT_HOST = "localhost"; + + /** ISO-2022-JP */ + public static final String JIS_CHARSET = "ISO-2022-JP"; + + private static final String RETURN_PATH_KEY = "mail.smtp.from"; + + /** 接続タイムアウト */ + private static final int DEFAULT_CONNECTION_TIMEOUT = 5000; + + /** 読込タイムアウト */ + private static final int DEFAULT_READ_TIMEOUT = 5000; + + private String protocol = DEFAULT_PROTOCOL; + + private String host = DEFAULT_HOST; + + private int port = DEFAULT_PORT; + + private String username; + + private String password; + + private String charset = JIS_CHARSET; + + private String returnPath; + + private String messageId; + + private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; + + private int readTimeout = DEFAULT_READ_TIMEOUT; + + /** + * コンストラクタ。 + */ + public SendMailImpl() {} + + /** + * コンストラクタ。使用するSMTPサーバを指定します。 + * + * @param host SMTPサーバのホスト名、またはIPアドレス + */ + public SendMailImpl(String host) { + this(); + setHost(host); + } + + /** + * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail) + */ + public void send(Mail mail) throws MailException { + send(new Mail[] { mail }); + } + + /** + * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail[]) + */ + public void send(Mail[] mails) throws MailException { + MimeMessageWrapper[] mmws = new MimeMessageWrapper[mails.length]; + Session session = Session.getInstance(new Properties()); + for (int i = 0; i < mails.length; i++) { + Mail mail = mails[i]; + + // MimeMessageを生成 + MimeMessage message = createMimeMessage(session); + if (isMessageIdCustomized()) { + mail.addHeader("Message-ID", ((OMLMimeMessage)message).getMessageId()); + } + MimeMessageBuilder builder = new MimeMessageBuilder(message, charset); + try { + builder.buildMimeMessage(mail); + } catch (UnsupportedEncodingException e) { + throw new MailBuildException("サポートされていない文字コードが指定されました。", e); + } catch (MessagingException e) { + throw new MailBuildException("MimeMessageの生成に失敗しました。", e); + } + + // Return-Pathを取得 + String returnPath; + if (mail.getReturnPath() != null) { + returnPath = mail.getReturnPath().getAddress(); + } else { + returnPath = this.returnPath; + } + + mmws[i] = new MimeMessageWrapper(message, returnPath, mail.getEnvelopeTo()); + } + processSend(mmws); + } + + /** + * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage) + */ + public void send(MimeMessage message) throws MailException { + send(new MimeMessage[] { message }); + } + + /** + * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage[]) + */ + public void send(MimeMessage[] messages) throws MailException { + MimeMessageWrapper[] mmws = new MimeMessageWrapper[messages.length]; + for (int i = 0; i < messages.length; i++) { + mmws[i] = new MimeMessageWrapper(messages[i], returnPath); + } + processSend(mmws); + } + + private void processSend(MimeMessageWrapper[] mmws) throws MailException { + + Properties prop = new Properties(); + // タイムアウトの設定 + prop.put("mail.smtp.connectiontimeout", String.valueOf(connectionTimeout)); + prop.put("mail.smtp.timeout", String.valueOf(readTimeout)); + // mail.smtp.authプロパティの設定 + if (username != null && !"".equals(username) && password != null && !"".equals(password)) { + prop.put("mail.smtp.auth", "true"); + } + Session session = Session.getInstance(prop); + + Transport transport = null; + try { + // SMTPサーバに接続 + log.debug("SMTPサーバ[" + host + "]に接続します。"); + transport = session.getTransport(protocol); + transport.connect(host, port, username, password); + log.debug("SMTPサーバ[" + host + "]に接続しました。"); + + for (int i = 0; i < mmws.length; i++) { + MimeMessage mimeMessage = mmws[i].getMimeMessage(); + // Return-Pathをセット + String returnPath = mmws[i].getReturnPath(); + if (returnPath != null) { + session.getProperties().put(RETURN_PATH_KEY, returnPath); + log.debug("Return-Path[" + returnPath + "]を設定しました。"); + } + // 送信日時をセット + mimeMessage.setSentDate(new Date()); + mimeMessage.saveChanges(); + + // 送信 + log.debug("メールを送信します。"); + if (mmws[i].hasEnvelopeTo()) { + log.debug("メールはenvelope-toアドレスに送信されます。"); + transport.sendMessage(mimeMessage, mmws[i].getEnvelopeTo()); + } else { + transport.sendMessage(mimeMessage, mimeMessage.getAllRecipients()); + } + log.debug("メールを送信しました。"); + + // Return-Pathを解除 + if (returnPath != null) { + session.getProperties().remove(RETURN_PATH_KEY); + log.debug("Return-Path設定をクリアしました。"); + } + } + } catch (AuthenticationFailedException ex) { + log.error("SMTPサーバ[" + host + "]への接続認証に失敗しました。", ex); + throw new MailAuthenticationException(ex); + } catch (MessagingException ex) { + log.error("メールの送信に失敗しました。", ex); + throw new MailSendException("メールの送信に失敗しました。", ex); + } finally { + if (transport != null && transport.isConnected()) { + log.debug("SMTPサーバ[" + host + "]との接続を切断します。"); + try { + // SMTPサーバとの接続を切断 + transport.close(); + } catch (MessagingException e) { + log.error("SMTPサーバ[" + host + "]との接続切断に失敗しました。", e); + throw new MailException("SMTPサーバ[" + host + "]との接続切断に失敗しました。"); + } + log.debug("SMTPサーバ[" + host + "]との接続を切断しました。"); + } + } + } + + /** + * 新しいMimeMessageオブジェクトを生成します。
+ * messageIdプロパティがセットされている場合、OMLMimeMessageのインスタンスを生成します。 + * + * @return 新しいMimeMessageオブジェクト + */ + private MimeMessage createMimeMessage(Session session) { + if (isMessageIdCustomized()) { + return new OMLMimeMessage(session, messageId); + } + return new MimeMessage(session); + } + + /** + * Message-Idヘッダのドメイン部分を独自にセットしているかどうか判定します。 + * + * @return Message-Idヘッダのドメイン部分を独自にセットしている場合 true + */ + private boolean isMessageIdCustomized() { + return messageId != null; + } + + /** + * エンコーディングに使用する文字コードを返します。 + * + * @return エンコーディングに使用する文字コード + */ + public String getCharset() { + return charset; + } + + /** + * メールの件名や本文のエンコーディングに使用する文字コードを指定します。 + * デフォルトはISO-2022-JPです。 + *

+ * 日本語環境で利用する場合は通常変更する必要はありません。 + * + * @param charset エンコーディングに使用する文字コード + */ + public void setCharset(String charset) { + this.charset = charset; + } + + /** + * セットされたSMTPサーバのホスト名、またはIPアドレスを返します。 + * + * @return SMTPサーバのホスト名、またはIPアドレス + */ + public String getHost() { + return host; + } + + /** + * SMTPサーバのホスト名、またはIPアドレスをセットします。 + * デフォルトは localhost です。 + * + * @param host SMTPサーバのホスト名、またはIPアドレス + */ + public void setHost(String host) { + this.host = host; + } + + /** + * @return SMTPサーバ認証パスワード + */ + public String getPassword() { + return password; + } + + /** + * SMTPサーバの接続認証が必要な場合にパスワードをセットします。 + * + * @param password SMTPサーバ認証パスワード + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return SMTPサーバのポート番号 + */ + public int getPort() { + return port; + } + + /** + * SMTPサーバのポート番号をセットします。 + * + * @param port SMTPサーバのポート番号 + */ + public void setPort(int port) { + this.port = port; + } + + /** + * プロトコルを返します。 + * + * @return プロトコル + */ + public String getProtocol() { + return protocol; + } + + /** + * プロトコルをセットします。デフォルトは「smtp」。 + * + * @param protocol プロトコル + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return Return-Pathアドレス + */ + public String getReturnPath() { + return returnPath; + } + + /** + * Return-Pathアドレスをセットします。 + *

+ * 送信するMailインスタンスに指定されたFromアドレス以外のアドレスをReturn-Pathとしたい場合に使用します。 + * ここでセットされたReturn-Pathより、MailインスタンスにセットされたReturn-Pathが優先されます。 + * + * @param returnPath Return-Pathアドレス + */ + public void setReturnPath(String returnPath) { + this.returnPath = returnPath; + } + + /** + * @return SMTPサーバ認証ユーザ名 + */ + public String getUsername() { + return username; + } + + /** + * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。 + * + * @param username SMTPサーバ認証ユーザ名 + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * SMTPサーバとの接続タイムアウトをセットします。 + * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。 + *

+ * -1を指定すると無限大になりますが、お薦めしません。 + * + * @since 1.1.4 + * @param connectionTimeout SMTPサーバとの接続タイムアウト + */ + public void setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + /** + * SMTPサーバへの送信時のタイムアウトをセットします。 + * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。
+ * 送信時にタイムアウトすると、com.ozacc.mail.MailSendExceptionがスローされます。 + *

+ * -1を指定すると無限大になりますが、お薦めしません。 + * + * @since 1.1.4 + * @param readTimeout SMTPサーバへの送受信時のタイムアウト + */ + public void setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + } + + /** + * 生成されるMimeMessageに付けられるMessage-Idヘッダのドメイン部分を指定します。
+ * 指定されない場合(nullや空文字列の場合)は、JavaMailがMessage-Idヘッダを生成します。 + * JavaMailが生成する「JavaMail.実行ユーザ名@ホスト名」のMessage-Idを避けたい場合に、このメソッドを使用します。 + *

+ * messageIdプロパティがセットされている場合、Mailから生成されるMimeMessageのMessage-Idには + * タイムスタンプ + ランダムに生成される16桁の数値 + ここでセットされた値 + * が使用されます。 + *

+ * 生成されるMessage-Idの例。 (実際の数値部分は送信メール毎に変わります)

    + *
  • messageIdに'example.com'を指定した場合・・・1095714924963.5619528074501343@example.com
  • + *
  • messageIdに'@example.com'を指定した場合・・・1095714924963.5619528074501343@example.com (上と同じ)
  • + *
  • messageIdに'OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com
  • + *
  • messageIdに'.OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com (上と同じ)
  • + *
+ *

+ * 注: このMessage-Idはsend(Mail)かsend(Mail[])メソッドが呼びだれた時にのみ有効です。MimeMessageを直接送信する場合には適用されません。 + * + * @param messageId メールに付けられるMessage-Idヘッダのドメイン部分 + * @throws IllegalArgumentException @を複数含んだ文字列を指定した場合 + */ + public void setMessageId(String messageId) { + if (messageId == null || messageId.length() < 1) { + return; + } + + String[] parts = messageId.split("@"); + if (parts.length > 2) { + throw new IllegalArgumentException("messageIdプロパティに'@'を複数含むことはできません。[" + messageId + + "]"); + } + + this.messageId = messageId; + } + + /** + * MimeMessageインスタンスと、そのメールに対応するReturn-Path、envelope-toアドレスをラップするクラス。 + * + * @author Tomohiro Otsuka + * @version $Id: SendMailImpl.java,v 1.7.2.6 2007/03/30 13:03:44 otsuka Exp $ + */ + private static class MimeMessageWrapper { + + private MimeMessage mimeMessage; + + private String returnPath; + + private InternetAddress[] envelopeTo; + + public MimeMessageWrapper(MimeMessage mimeMessage, String returnPath) { + this.mimeMessage = mimeMessage; + this.returnPath = returnPath; + } + + public MimeMessageWrapper(MimeMessage mimeMessage, String returnPath, + InternetAddress[] envelopeTo) { + this.mimeMessage = mimeMessage; + this.returnPath = returnPath; + this.envelopeTo = envelopeTo; + } + + public MimeMessage getMimeMessage() { + return mimeMessage; + } + + public String getReturnPath() { + return returnPath; + } + + public boolean hasEnvelopeTo() { + return envelopeTo.length > 0; + } + + public InternetAddress[] getEnvelopeTo() { + return envelopeTo; + } + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/SendMailProImpl.java b/src/main/java/com/ozacc/mail/impl/SendMailProImpl.java old mode 100755 new mode 100644 index 2e1ca8e..c69d9a6 --- a/src/main/java/com/ozacc/mail/impl/SendMailProImpl.java +++ b/src/main/java/com/ozacc/mail/impl/SendMailProImpl.java @@ -1,501 +1,501 @@ -package com.ozacc.mail.impl; - -import java.io.UnsupportedEncodingException; -import java.util.Date; -import java.util.Properties; - -import javax.mail.Address; -import javax.mail.AuthenticationFailedException; -import javax.mail.MessagingException; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.MimeMessage; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailAuthenticationException; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.MailException; -import com.ozacc.mail.MailSendException; -import com.ozacc.mail.NotConnectedException; -import com.ozacc.mail.SendMailPro; - -/** - * SendMailProインターフェースの実装クラス。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: SendMailProImpl.java,v 1.4.2.5 2006/08/07 13:45:22 otsuka Exp $ - */ -public class SendMailProImpl implements SendMailPro { - - /** smtp */ - public static final String DEFAULT_PROTOCOL = "smtp"; - - /** -1 */ - public static final int DEFAULT_PORT = -1; - - /** localhost */ - public static final String DEFAULT_HOST = "localhost"; - - /** ISO-2022-JP */ - public static final String JIS_CHARSET = "ISO-2022-JP"; - - private static final String RETURN_PATH_KEY = "mail.smtp.from"; - - private static Log log = LogFactory.getLog(SendMailProImpl.class); - - /** 接続タイムアウト */ - private static final int DEFAULT_CONNECTION_TIMEOUT = 5000; - - /** 読込タイムアウト */ - private static final int DEFAULT_READ_TIMEOUT = 5000; - - private String protocol = DEFAULT_PROTOCOL; - - private String host = DEFAULT_HOST; - - private int port = DEFAULT_PORT; - - private String username; - - private String password; - - private String charset = JIS_CHARSET; - - private String returnPath; - - private Session session; - - private Transport transport; - - private boolean connected; - - private String messageId; - - private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; - - private int readTimeout = DEFAULT_READ_TIMEOUT; - - /** - * コンストラクタ。 - */ - public SendMailProImpl() {} - - /** - * コンストラクタ。使用するSMTPサーバを指定します。 - * - * @param host SMTPサーバのホスト名、またはIPアドレス - */ - public SendMailProImpl(String host) { - this(); - setHost(host); - } - - /** - * @see com.ozacc.mail.SendMailPro#connect() - */ - public synchronized void connect() throws MailException { - if (session == null) { - initSession(); - } - - // グローバルReturn-Pathの設定 - putOnReturnPath(this.returnPath); - - try { - // SMTPサーバに接続 - log.debug("SMTPサーバ[" + host + "]に接続します。"); - - transport = session.getTransport(protocol); - transport.connect(host, port, username, password); - } catch (AuthenticationFailedException ex) { - log.error("SMTPサーバ[" + host + "]への接続認証に失敗しました。", ex); - throw new MailAuthenticationException(ex); - } catch (MessagingException ex) { - log.error("SMTPサーバ[" + host + "]への接続に失敗しました。", ex); - throw new MailSendException("SMTPサーバ[" + host + "]への接続に失敗しました。", ex); - } - - log.debug("SMTPサーバ[" + host + "]に接続しました。"); - - connected = true; - } - - /** - * Sessionの初期化を行います。 - * タイムアウト値を設定したPropertiesをセットします。 - */ - private void initSession() { - Properties prop = new Properties(); - // タイムアウトの設定 - prop.put("mail.smtp.connectiontimeout", String.valueOf(connectionTimeout)); - prop.put("mail.smtp.timeout", String.valueOf(readTimeout)); - // mail.smtp.authプロパティの設定 - if (username != null && !"".equals(username) && password != null && !"".equals(password)) { - prop.put("mail.smtp.auth", "true"); - } - session = Session.getInstance(prop); - } - - /** - * @see com.ozacc.mail.SendMailPro#disconnect() - */ - public synchronized void disconnect() throws MailException { - if (connected) { - try { - log.debug("SMTPサーバ[" + host + "]との接続を切断します。"); - - // SMTPサーバとの接続を切断 - transport.close(); - connected = false; - - log.debug("SMTPサーバ[" + host + "]との接続を切断しました。"); - } catch (MessagingException ex) { - log.error("SMTPサーバ[" + host + "]との接続切断に失敗しました。", ex); - throw new MailException("SMTPサーバ[" + host + "]との接続切断に失敗しました。"); - } finally { - // グローバルReturn-Pathの解除 - releaseReturnPath(false); - } - } else { - log.warn("SMTPサーバ[" + host + "]との接続が確立されていない状態で、接続の切断がリクエストされました。"); - } - } - - /** - * ReturnPathをセットします。 - * - * @param returnPath - */ - private void putOnReturnPath(String returnPath) { - if (returnPath != null) { - session.getProperties().put(RETURN_PATH_KEY, returnPath); - log.debug("Return-Path[" + returnPath + "]を設定しました。"); - } - } - - /** - * ReturnPathの設定をクリアします。 - *

- * setGlobalReturnPathAgainがtrueに指定されている場合、一旦Return-Path設定をクリアした後に、 - * グローバルなReturn-Path(setReturnPath()メソッドで、このインスタンスにセットされたReturn-Pathアドレス)を設定します。 - * グローバルなReturn-PathがセットされていなければReturn-Pathはクリアされたままになります。 - *

- * クリアされた状態でsend()メソッドが実行されると、Fromの値がReturn-Pathに使用されます。 - * - * @param setGlobalReturnPathAgain Return-Path設定をクリアした後、再度グローバルなReturn-Pathをセットする場合 true - */ - private void releaseReturnPath(boolean setGlobalReturnPathAgain) { - session.getProperties().remove(RETURN_PATH_KEY); - log.debug("Return-Path設定をクリアしました。"); - - if (setGlobalReturnPathAgain && this.returnPath != null) { - putOnReturnPath(this.returnPath); - } - } - - /** - * @see com.ozacc.mail.SendMailPro#send(javax.mail.internet.MimeMessage) - */ - public void send(MimeMessage mimeMessage) throws MailException { - Address[] addresses; - try { - addresses = mimeMessage.getAllRecipients(); - } catch (MessagingException ex) { - log.error("メールの送信に失敗しました。", ex); - throw new MailSendException("メールの送信に失敗しました。", ex); - } - processSend(mimeMessage, addresses); - } - - /** - * @param mimeMessage - */ - private void processSend(MimeMessage mimeMessage, Address[] addresses) { - if (!connected) { - log.error("SMTPサーバへの接続が確立されていません。"); - throw new NotConnectedException("SMTPサーバへの接続が確立されていません。"); - } - - try { - // 送信日時をセット - mimeMessage.setSentDate(new Date()); - mimeMessage.saveChanges(); - // 送信 - log.debug("メールを送信します。"); - transport.sendMessage(mimeMessage, addresses); - log.debug("メールを送信しました。"); - } catch (MessagingException ex) { - log.error("メールの送信に失敗しました。", ex); - throw new MailSendException("メールの送信に失敗しました。", ex); - } - } - - /** - * @see com.ozacc.mail.SendMailPro#send(com.ozacc.mail.Mail) - */ - public void send(Mail mail) throws MailException { - if (mail.getReturnPath() != null) { - sendMailWithReturnPath(mail); - } else { - sendMail(mail); - } - } - - /** - * 指定されたMailからMimeMessageを生成し、send(MimeMessage)メソッドに渡します。 - * - * @param mail - * @throws MailException - */ - private void sendMail(Mail mail) throws MailException { - // MimeMessageの生成 - MimeMessage message = createMimeMessage(); - if (isMessageIdCustomized()) { - mail.addHeader("Message-ID", ((OMLMimeMessage)message).getMessageId()); - } - MimeMessageBuilder builder = new MimeMessageBuilder(message, charset); - try { - builder.buildMimeMessage(mail); - } catch (UnsupportedEncodingException e) { - throw new MailBuildException("サポートされていない文字コードが指定されました。", e); - } catch (MessagingException e) { - throw new MailBuildException("MimeMessageの生成に失敗しました。", e); - } - // 送信 - if (mail.getEnvelopeTo().length > 0) { - log.debug("メールはenvelope-toアドレスに送信されます。"); - processSend(message, mail.getEnvelopeTo()); - } else { - send(message); - } - } - - /** - * 指定されたMailにセットされたReturn-Pathを設定して、メールを送信します。 - * 同期メソッドです。 - * - * @param mail - * @throws MailException - */ - private synchronized void sendMailWithReturnPath(Mail mail) throws MailException { - putOnReturnPath(mail.getReturnPath().getAddress()); - - sendMail(mail); - - releaseReturnPath(true); - } - - /** - * 新しいMimeMessageオブジェクトを生成します。 - * - * @return 新しいMimeMessageオブジェクト - */ - public MimeMessage createMimeMessage() { - if (isMessageIdCustomized()) { - return new OMLMimeMessage(session, messageId); - } - return new MimeMessage(session); - } - - /** - * Message-Idヘッダのドメイン部分を独自にセットしているかどうか判定します。 - * - * @return Message-Idヘッダのドメイン部分を独自にセットしている場合 true - */ - private boolean isMessageIdCustomized() { - return messageId != null; - } - - /** - * @return Sessionインスタンス - */ - protected Session getSession() { - return session; - } - - /** - * エンコーディングに使用する文字コードを返します。 - * - * @return エンコーディングに使用する文字コード - */ - public String getCharset() { - return charset; - } - - /** - * メールの件名や本文のエンコーディングに使用する文字コードを指定します。 - * デフォルトは ISO-2022-JP です。 - *

- * 日本語環境で利用する場合は通常変更する必要はありません。 - * - * @param charset エンコーディングに使用する文字コード - */ - public void setCharset(String charset) { - this.charset = charset; - } - - /** - * @return Returns the host. - */ - public String getHost() { - return host; - } - - /** - * SMTPサーバのホスト名、またはIPアドレスをセットします。 - * デフォルトは localhost です。 - * - * @param host SMTPサーバのホスト名、またはIPアドレス - */ - public void setHost(String host) { - this.host = host; - } - - /** - * @return SMTPサーバ認証パスワード - */ - public String getPassword() { - return password; - } - - /** - * SMTPサーバの接続認証が必要な場合にパスワードをセットします。 - * - * @param password SMTPサーバ認証パスワード - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return SMTPサーバのポート番号 - */ - public int getPort() { - return port; - } - - /** - * SMTPサーバのポート番号をセットします。 - * - * @param port SMTPサーバのポート番号 - */ - public void setPort(int port) { - this.port = port; - } - - /** - * プロトコルを返します。 - * - * @return プロトコル - */ - public String getProtocol() { - return protocol; - } - - /** - * プロトコルをセットします。デフォルトは「smtp」。 - * - * @param protocol プロトコル - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * @return Return-Pathアドレス - */ - public String getReturnPath() { - return returnPath; - } - - /** - * Return-Pathアドレスをセットします。 - *

- * 送信するMailインスタンスに指定されたFromアドレス以外のアドレスをReturn-Pathとしたい場合に使用します。 - * ここでセットされたReturn-Pathより、MailインスタンスにセットされたReturn-Pathが優先されます。 - * - * @param returnPath Return-Pathアドレス - */ - public void setReturnPath(String returnPath) { - this.returnPath = returnPath; - } - - /** - * @return SMTPサーバ認証ユーザ名 - */ - public String getUsername() { - return username; - } - - /** - * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。 - * - * @param username SMTPサーバ認証ユーザ名 - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * 生成されるMimeMessageに付けられるMessage-Idヘッダのドメイン部分を指定します。
- * 指定されない場合(nullや空文字列の場合)は、JavaMailがMessage-Idヘッダを生成します。 - * JavaMailが生成する「JavaMail.実行ユーザ名@ホスト名」のMessage-Idを避けたい場合に、このメソッドを使用します。 - *

- * messageIdプロパティがセットされている場合、Mailから生成されるMimeMessageのMessage-Idには - * タイムスタンプ + ランダムに生成される16桁の数値 + ここでセットされた値 - * が使用されます。 - *

- * 生成されるMessage-Idの例。 (実際の数値部分は送信メール毎に変わります)

    - *
  • messageIdに'example.com'を指定した場合・・・1095714924963.5619528074501343@example.com
  • - *
  • messageIdに'@example.com'を指定した場合・・・1095714924963.5619528074501343@example.com (上と同じ)
  • - *
  • messageIdに'OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com
  • - *
  • messageIdに'.OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com (上と同じ)
  • - *
- *

- * 注: このMessage-Idはsend(Mail)かsend(Mail[])メソッドが呼びだれた時にのみ有効です。MimeMessageを直接送信する場合には適用されません。 - * - * @param messageId メールに付けられるMessage-Idヘッダのドメイン部分 - * @throws IllegalArgumentException @を複数含んだ文字列を指定した場合 - */ - public void setMessageId(String messageId) { - if (messageId == null || messageId.length() < 1) { - return; - } - String[] parts = messageId.split("@"); - if (parts.length > 2) { - throw new IllegalArgumentException("messageIdプロパティに'@'を複数含むことはできません。[" + messageId - + "]"); - } - this.messageId = messageId; - } - - /** - * SMTPサーバとの接続タイムアウトをセットします。 - * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。 - *

- * -1を指定すると無限大になりますが、お薦めしません。 - * - * @since 1.1.4 - * @param connectionTimeout SMTPサーバとの接続タイムアウト - */ - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - /** - * SMTPサーバへの送受信時のタイムアウトをセットします。 - * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。 - *

- * -1を指定すると無限大になりますが、お薦めしません。 - * - * @since 1.1.4 - * @param readTimeout SMTPサーバへの送受信時のタイムアウト - */ - public void setReadTimeout(int readTimeout) { - this.readTimeout = readTimeout; - } +package com.ozacc.mail.impl; + +import java.io.UnsupportedEncodingException; +import java.util.Date; +import java.util.Properties; + +import javax.mail.Address; +import javax.mail.AuthenticationFailedException; +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.Transport; +import javax.mail.internet.MimeMessage; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailAuthenticationException; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.MailException; +import com.ozacc.mail.MailSendException; +import com.ozacc.mail.NotConnectedException; +import com.ozacc.mail.SendMailPro; + +/** + * SendMailProインターフェースの実装クラス。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: SendMailProImpl.java,v 1.4.2.5 2006/08/07 13:45:22 otsuka Exp $ + */ +public class SendMailProImpl implements SendMailPro { + + /** smtp */ + public static final String DEFAULT_PROTOCOL = "smtp"; + + /** -1 */ + public static final int DEFAULT_PORT = -1; + + /** localhost */ + public static final String DEFAULT_HOST = "localhost"; + + /** ISO-2022-JP */ + public static final String JIS_CHARSET = "ISO-2022-JP"; + + private static final String RETURN_PATH_KEY = "mail.smtp.from"; + + private static Log log = LogFactory.getLog(SendMailProImpl.class); + + /** 接続タイムアウト */ + private static final int DEFAULT_CONNECTION_TIMEOUT = 5000; + + /** 読込タイムアウト */ + private static final int DEFAULT_READ_TIMEOUT = 5000; + + private String protocol = DEFAULT_PROTOCOL; + + private String host = DEFAULT_HOST; + + private int port = DEFAULT_PORT; + + private String username; + + private String password; + + private String charset = JIS_CHARSET; + + private String returnPath; + + private Session session; + + private Transport transport; + + private boolean connected; + + private String messageId; + + private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; + + private int readTimeout = DEFAULT_READ_TIMEOUT; + + /** + * コンストラクタ。 + */ + public SendMailProImpl() {} + + /** + * コンストラクタ。使用するSMTPサーバを指定します。 + * + * @param host SMTPサーバのホスト名、またはIPアドレス + */ + public SendMailProImpl(String host) { + this(); + setHost(host); + } + + /** + * @see com.ozacc.mail.SendMailPro#connect() + */ + public synchronized void connect() throws MailException { + if (session == null) { + initSession(); + } + + // グローバルReturn-Pathの設定 + putOnReturnPath(this.returnPath); + + try { + // SMTPサーバに接続 + log.debug("SMTPサーバ[" + host + "]に接続します。"); + + transport = session.getTransport(protocol); + transport.connect(host, port, username, password); + } catch (AuthenticationFailedException ex) { + log.error("SMTPサーバ[" + host + "]への接続認証に失敗しました。", ex); + throw new MailAuthenticationException(ex); + } catch (MessagingException ex) { + log.error("SMTPサーバ[" + host + "]への接続に失敗しました。", ex); + throw new MailSendException("SMTPサーバ[" + host + "]への接続に失敗しました。", ex); + } + + log.debug("SMTPサーバ[" + host + "]に接続しました。"); + + connected = true; + } + + /** + * Sessionの初期化を行います。 + * タイムアウト値を設定したPropertiesをセットします。 + */ + private void initSession() { + Properties prop = new Properties(); + // タイムアウトの設定 + prop.put("mail.smtp.connectiontimeout", String.valueOf(connectionTimeout)); + prop.put("mail.smtp.timeout", String.valueOf(readTimeout)); + // mail.smtp.authプロパティの設定 + if (username != null && !"".equals(username) && password != null && !"".equals(password)) { + prop.put("mail.smtp.auth", "true"); + } + session = Session.getInstance(prop); + } + + /** + * @see com.ozacc.mail.SendMailPro#disconnect() + */ + public synchronized void disconnect() throws MailException { + if (connected) { + try { + log.debug("SMTPサーバ[" + host + "]との接続を切断します。"); + + // SMTPサーバとの接続を切断 + transport.close(); + connected = false; + + log.debug("SMTPサーバ[" + host + "]との接続を切断しました。"); + } catch (MessagingException ex) { + log.error("SMTPサーバ[" + host + "]との接続切断に失敗しました。", ex); + throw new MailException("SMTPサーバ[" + host + "]との接続切断に失敗しました。"); + } finally { + // グローバルReturn-Pathの解除 + releaseReturnPath(false); + } + } else { + log.warn("SMTPサーバ[" + host + "]との接続が確立されていない状態で、接続の切断がリクエストされました。"); + } + } + + /** + * ReturnPathをセットします。 + * + * @param returnPath + */ + private void putOnReturnPath(String returnPath) { + if (returnPath != null) { + session.getProperties().put(RETURN_PATH_KEY, returnPath); + log.debug("Return-Path[" + returnPath + "]を設定しました。"); + } + } + + /** + * ReturnPathの設定をクリアします。 + *

+ * setGlobalReturnPathAgainがtrueに指定されている場合、一旦Return-Path設定をクリアした後に、 + * グローバルなReturn-Path(setReturnPath()メソッドで、このインスタンスにセットされたReturn-Pathアドレス)を設定します。 + * グローバルなReturn-PathがセットされていなければReturn-Pathはクリアされたままになります。 + *

+ * クリアされた状態でsend()メソッドが実行されると、Fromの値がReturn-Pathに使用されます。 + * + * @param setGlobalReturnPathAgain Return-Path設定をクリアした後、再度グローバルなReturn-Pathをセットする場合 true + */ + private void releaseReturnPath(boolean setGlobalReturnPathAgain) { + session.getProperties().remove(RETURN_PATH_KEY); + log.debug("Return-Path設定をクリアしました。"); + + if (setGlobalReturnPathAgain && this.returnPath != null) { + putOnReturnPath(this.returnPath); + } + } + + /** + * @see com.ozacc.mail.SendMailPro#send(javax.mail.internet.MimeMessage) + */ + public void send(MimeMessage mimeMessage) throws MailException { + Address[] addresses; + try { + addresses = mimeMessage.getAllRecipients(); + } catch (MessagingException ex) { + log.error("メールの送信に失敗しました。", ex); + throw new MailSendException("メールの送信に失敗しました。", ex); + } + processSend(mimeMessage, addresses); + } + + /** + * @param mimeMessage + */ + private void processSend(MimeMessage mimeMessage, Address[] addresses) { + if (!connected) { + log.error("SMTPサーバへの接続が確立されていません。"); + throw new NotConnectedException("SMTPサーバへの接続が確立されていません。"); + } + + try { + // 送信日時をセット + mimeMessage.setSentDate(new Date()); + mimeMessage.saveChanges(); + // 送信 + log.debug("メールを送信します。"); + transport.sendMessage(mimeMessage, addresses); + log.debug("メールを送信しました。"); + } catch (MessagingException ex) { + log.error("メールの送信に失敗しました。", ex); + throw new MailSendException("メールの送信に失敗しました。", ex); + } + } + + /** + * @see com.ozacc.mail.SendMailPro#send(com.ozacc.mail.Mail) + */ + public void send(Mail mail) throws MailException { + if (mail.getReturnPath() != null) { + sendMailWithReturnPath(mail); + } else { + sendMail(mail); + } + } + + /** + * 指定されたMailからMimeMessageを生成し、send(MimeMessage)メソッドに渡します。 + * + * @param mail + * @throws MailException + */ + private void sendMail(Mail mail) throws MailException { + // MimeMessageの生成 + MimeMessage message = createMimeMessage(); + if (isMessageIdCustomized()) { + mail.addHeader("Message-ID", ((OMLMimeMessage)message).getMessageId()); + } + MimeMessageBuilder builder = new MimeMessageBuilder(message, charset); + try { + builder.buildMimeMessage(mail); + } catch (UnsupportedEncodingException e) { + throw new MailBuildException("サポートされていない文字コードが指定されました。", e); + } catch (MessagingException e) { + throw new MailBuildException("MimeMessageの生成に失敗しました。", e); + } + // 送信 + if (mail.getEnvelopeTo().length > 0) { + log.debug("メールはenvelope-toアドレスに送信されます。"); + processSend(message, mail.getEnvelopeTo()); + } else { + send(message); + } + } + + /** + * 指定されたMailにセットされたReturn-Pathを設定して、メールを送信します。 + * 同期メソッドです。 + * + * @param mail + * @throws MailException + */ + private synchronized void sendMailWithReturnPath(Mail mail) throws MailException { + putOnReturnPath(mail.getReturnPath().getAddress()); + + sendMail(mail); + + releaseReturnPath(true); + } + + /** + * 新しいMimeMessageオブジェクトを生成します。 + * + * @return 新しいMimeMessageオブジェクト + */ + public MimeMessage createMimeMessage() { + if (isMessageIdCustomized()) { + return new OMLMimeMessage(session, messageId); + } + return new MimeMessage(session); + } + + /** + * Message-Idヘッダのドメイン部分を独自にセットしているかどうか判定します。 + * + * @return Message-Idヘッダのドメイン部分を独自にセットしている場合 true + */ + private boolean isMessageIdCustomized() { + return messageId != null; + } + + /** + * @return Sessionインスタンス + */ + protected Session getSession() { + return session; + } + + /** + * エンコーディングに使用する文字コードを返します。 + * + * @return エンコーディングに使用する文字コード + */ + public String getCharset() { + return charset; + } + + /** + * メールの件名や本文のエンコーディングに使用する文字コードを指定します。 + * デフォルトは ISO-2022-JP です。 + *

+ * 日本語環境で利用する場合は通常変更する必要はありません。 + * + * @param charset エンコーディングに使用する文字コード + */ + public void setCharset(String charset) { + this.charset = charset; + } + + /** + * @return Returns the host. + */ + public String getHost() { + return host; + } + + /** + * SMTPサーバのホスト名、またはIPアドレスをセットします。 + * デフォルトは localhost です。 + * + * @param host SMTPサーバのホスト名、またはIPアドレス + */ + public void setHost(String host) { + this.host = host; + } + + /** + * @return SMTPサーバ認証パスワード + */ + public String getPassword() { + return password; + } + + /** + * SMTPサーバの接続認証が必要な場合にパスワードをセットします。 + * + * @param password SMTPサーバ認証パスワード + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return SMTPサーバのポート番号 + */ + public int getPort() { + return port; + } + + /** + * SMTPサーバのポート番号をセットします。 + * + * @param port SMTPサーバのポート番号 + */ + public void setPort(int port) { + this.port = port; + } + + /** + * プロトコルを返します。 + * + * @return プロトコル + */ + public String getProtocol() { + return protocol; + } + + /** + * プロトコルをセットします。デフォルトは「smtp」。 + * + * @param protocol プロトコル + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return Return-Pathアドレス + */ + public String getReturnPath() { + return returnPath; + } + + /** + * Return-Pathアドレスをセットします。 + *

+ * 送信するMailインスタンスに指定されたFromアドレス以外のアドレスをReturn-Pathとしたい場合に使用します。 + * ここでセットされたReturn-Pathより、MailインスタンスにセットされたReturn-Pathが優先されます。 + * + * @param returnPath Return-Pathアドレス + */ + public void setReturnPath(String returnPath) { + this.returnPath = returnPath; + } + + /** + * @return SMTPサーバ認証ユーザ名 + */ + public String getUsername() { + return username; + } + + /** + * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。 + * + * @param username SMTPサーバ認証ユーザ名 + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * 生成されるMimeMessageに付けられるMessage-Idヘッダのドメイン部分を指定します。
+ * 指定されない場合(nullや空文字列の場合)は、JavaMailがMessage-Idヘッダを生成します。 + * JavaMailが生成する「JavaMail.実行ユーザ名@ホスト名」のMessage-Idを避けたい場合に、このメソッドを使用します。 + *

+ * messageIdプロパティがセットされている場合、Mailから生成されるMimeMessageのMessage-Idには + * タイムスタンプ + ランダムに生成される16桁の数値 + ここでセットされた値 + * が使用されます。 + *

+ * 生成されるMessage-Idの例。 (実際の数値部分は送信メール毎に変わります)

    + *
  • messageIdに'example.com'を指定した場合・・・1095714924963.5619528074501343@example.com
  • + *
  • messageIdに'@example.com'を指定した場合・・・1095714924963.5619528074501343@example.com (上と同じ)
  • + *
  • messageIdに'OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com
  • + *
  • messageIdに'.OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com (上と同じ)
  • + *
+ *

+ * 注: このMessage-Idはsend(Mail)かsend(Mail[])メソッドが呼びだれた時にのみ有効です。MimeMessageを直接送信する場合には適用されません。 + * + * @param messageId メールに付けられるMessage-Idヘッダのドメイン部分 + * @throws IllegalArgumentException @を複数含んだ文字列を指定した場合 + */ + public void setMessageId(String messageId) { + if (messageId == null || messageId.length() < 1) { + return; + } + String[] parts = messageId.split("@"); + if (parts.length > 2) { + throw new IllegalArgumentException("messageIdプロパティに'@'を複数含むことはできません。[" + messageId + + "]"); + } + this.messageId = messageId; + } + + /** + * SMTPサーバとの接続タイムアウトをセットします。 + * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。 + *

+ * -1を指定すると無限大になりますが、お薦めしません。 + * + * @since 1.1.4 + * @param connectionTimeout SMTPサーバとの接続タイムアウト + */ + public void setConnectionTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + } + + /** + * SMTPサーバへの送受信時のタイムアウトをセットします。 + * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。 + *

+ * -1を指定すると無限大になりますが、お薦めしません。 + * + * @since 1.1.4 + * @param readTimeout SMTPサーバへの送受信時のタイムアウト + */ + public void setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/VelocityLogSystem.java b/src/main/java/com/ozacc/mail/impl/VelocityLogSystem.java old mode 100755 new mode 100644 index 295f560..546bed4 --- a/src/main/java/com/ozacc/mail/impl/VelocityLogSystem.java +++ b/src/main/java/com/ozacc/mail/impl/VelocityLogSystem.java @@ -1,52 +1,52 @@ -package com.ozacc.mail.impl; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.velocity.app.Velocity; -import org.apache.velocity.runtime.RuntimeServices; -import org.apache.velocity.runtime.log.LogSystem; - -/** - * VelocityのログメッセージをCommonsLoggingを通して出力させるクラス。 - * - * - * @see XMLVelocityMailBuilderImpl - * @see JDomXMLMailBuilder - * - * @since 1.0.3 - * - * @author Tomohiro Otsuka - * @version $Id: VelocityLogSystem.java,v 1.2.2.1 2004/11/25 08:01:07 otsuka Exp $ - */ -public class VelocityLogSystem implements LogSystem { - - private static Log log = LogFactory.getLog(Velocity.class); - - /** - * @see org.apache.velocity.runtime.log.LogSystem#init(org.apache.velocity.runtime.RuntimeServices) - */ - public void init(RuntimeServices rsvc) throws Exception { - // do nothing - } - - /** - * @see org.apache.velocity.runtime.log.LogSystem#logVelocityMessage(int, java.lang.String) - */ - public void logVelocityMessage(int level, String message) { - switch (level) { - case DEBUG_ID: - log.debug(message); - break; - case INFO_ID: - log.info(message); - break; - case WARN_ID: - log.warn(message); - break; - case ERROR_ID: - log.error(message); - break; - } - } - +package com.ozacc.mail.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.velocity.app.Velocity; +import org.apache.velocity.runtime.RuntimeServices; +import org.apache.velocity.runtime.log.LogSystem; + +/** + * VelocityのログメッセージをCommonsLoggingを通して出力させるクラス。 + * + * + * @see XMLVelocityMailBuilderImpl + * @see JDomXMLMailBuilder + * + * @since 1.0.3 + * + * @author Tomohiro Otsuka + * @version $Id: VelocityLogSystem.java,v 1.2.2.1 2004/11/25 08:01:07 otsuka Exp $ + */ +public class VelocityLogSystem implements LogSystem { + + private static Log log = LogFactory.getLog(Velocity.class); + + /** + * @see org.apache.velocity.runtime.log.LogSystem#init(org.apache.velocity.runtime.RuntimeServices) + */ + public void init(RuntimeServices rsvc) throws Exception { + // do nothing + } + + /** + * @see org.apache.velocity.runtime.log.LogSystem#logVelocityMessage(int, java.lang.String) + */ + public void logVelocityMessage(int level, String message) { + switch (level) { + case DEBUG_ID: + log.debug(message); + break; + case INFO_ID: + log.info(message); + break; + case WARN_ID: + log.warn(message); + break; + case ERROR_ID: + log.error(message); + break; + } + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/XMLMailBuilderImpl.java b/src/main/java/com/ozacc/mail/impl/XMLMailBuilderImpl.java old mode 100755 new mode 100644 index b7adf07..4b837d5 --- a/src/main/java/com/ozacc/mail/impl/XMLMailBuilderImpl.java +++ b/src/main/java/com/ozacc/mail/impl/XMLMailBuilderImpl.java @@ -1,151 +1,151 @@ -package com.ozacc.mail.impl; - -import java.io.File; -import java.io.IOException; - -import javax.xml.parsers.FactoryConfigurationError; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.SAXException; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.MultipleMailBuilder; - -/** - * メールデータのXMLファイルからMailインスタンスを生成するクラス。 - *

- * ソースXMLを読み込む際に、DTDバリデーションが実行されますので妥当なXMLデータ(Valid XML Document)でなければいけません。 - * メールデータXMLのDTDは、http://www.ozacc.com/library/dtd/ozacc-mail.dtdを参照。 - * - * @since 1.0.1 - * @author Tomohiro Otsuka - * @version $Id: XMLMailBuilderImpl.java,v 1.5.2.1 2005/01/21 22:16:31 otsuka Exp $ - */ -public class XMLMailBuilderImpl extends AbstractXMLMailBuilder implements MultipleMailBuilder { - - private static Log log = LogFactory.getLog(XMLMailBuilderImpl.class); - - /** - * コンストラクタ。 - */ - public XMLMailBuilderImpl() { - super(); - } - - /** - * @see com.ozacc.mail.MailBuilder#buildMail(java.lang.String) - */ - public Mail buildMail(String classPath) throws MailBuildException { - Document doc = retrieveDocument(classPath); - return buildMail(doc.getDocumentElement()); - } - - /** - * @see com.ozacc.mail.MailBuilder#buildMail(java.io.File) - */ - public Mail buildMail(File file) throws MailBuildException { - Document doc = retrieveDocument(file); - return buildMail(doc.getDocumentElement()); - } - - /** - * @param classPath - * @return - * @throws MailBuildException - */ - private Document retrieveDocument(String classPath) throws MailBuildException { - try { - return getDocumentFromClassPath(classPath); - } catch (SAXException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } - } - - /** - * @param file - * @return - * @throws MailBuildException - */ - private Document retrieveDocument(File file) throws MailBuildException { - try { - return getDocumentFromFile(file); - } catch (SAXException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } - } - - /** - * 指定されたXMLのmail要素からMailインスタンスを生成します。 - * - * @param root メールデータのmail要素 - * @return 生成されたMailインスタンス - */ - protected Mail buildMail(Element root) { - Mail mail = new Mail(); - setReturnPath(root, mail); - setFrom(root, mail); - setRecipients(root, mail); - setReplyTo(root, mail); - setSubject(root, mail); - setText(root, mail); - setHtml(root, mail); - return mail; - } - - /** - * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.lang.String, java.lang.String) - */ - public Mail buildMail(String classPath, String mailId) throws MailBuildException { - if (mailId == null || "".equals(mailId)) { - throw new IllegalArgumentException("メールIDが指定されていません。"); - } - Document doc = retrieveDocument(classPath); - if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { - throw new MailBuildException("指定されたクラスパスのXMLはシングルメールテンプレートです。[classPath='" + classPath - + "']"); - } - Element mailElem = doc.getElementById(mailId); - return buildMail(mailElem); - } - - /** - * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.io.File, java.lang.String) - */ - public Mail buildMail(File file, String mailId) throws MailBuildException { - if (mailId == null || "".equals(mailId)) { - throw new IllegalArgumentException("メールIDが指定されていません。"); - } - Document doc = retrieveDocument(file); - if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { - throw new MailBuildException("指定されたファイルのXMLはシングルメールテンプレートです。[filePath='" - + file.getAbsolutePath() + "']"); - } - return buildMail(doc, mailId); - } - - /** - * マルチプルメールテンプレートのXMLドキュメント上の指定されたIDが示すメールテンプレートからMailインスタンスを生成して返します。 - * - * @param doc - * @param mailId - * @return 生成されたMailインスタンス - * @throws FactoryConfigurationError - */ - protected Mail buildMail(Document doc, String mailId) throws FactoryConfigurationError { - Element mailElem = doc.getElementById(mailId); - if (mailElem == null) { - throw new MailBuildException("指定されたID[" + mailId + "]のメールデータは見つかりませんでした。"); - } - log.debug(mailElem); - return buildMail(mailElem); - } - +package com.ozacc.mail.impl; + +import java.io.File; +import java.io.IOException; + +import javax.xml.parsers.FactoryConfigurationError; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.MultipleMailBuilder; + +/** + * メールデータのXMLファイルからMailインスタンスを生成するクラス。 + *

+ * ソースXMLを読み込む際に、DTDバリデーションが実行されますので妥当なXMLデータ(Valid XML Document)でなければいけません。 + * メールデータXMLのDTDは、http://www.ozacc.com/library/dtd/ozacc-mail.dtdを参照。 + * + * @since 1.0.1 + * @author Tomohiro Otsuka + * @version $Id: XMLMailBuilderImpl.java,v 1.5.2.1 2005/01/21 22:16:31 otsuka Exp $ + */ +public class XMLMailBuilderImpl extends AbstractXMLMailBuilder implements MultipleMailBuilder { + + private static Log log = LogFactory.getLog(XMLMailBuilderImpl.class); + + /** + * コンストラクタ。 + */ + public XMLMailBuilderImpl() { + super(); + } + + /** + * @see com.ozacc.mail.MailBuilder#buildMail(java.lang.String) + */ + public Mail buildMail(String classPath) throws MailBuildException { + Document doc = retrieveDocument(classPath); + return buildMail(doc.getDocumentElement()); + } + + /** + * @see com.ozacc.mail.MailBuilder#buildMail(java.io.File) + */ + public Mail buildMail(File file) throws MailBuildException { + Document doc = retrieveDocument(file); + return buildMail(doc.getDocumentElement()); + } + + /** + * @param classPath + * @return + * @throws MailBuildException + */ + private Document retrieveDocument(String classPath) throws MailBuildException { + try { + return getDocumentFromClassPath(classPath); + } catch (SAXException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } + } + + /** + * @param file + * @return + * @throws MailBuildException + */ + private Document retrieveDocument(File file) throws MailBuildException { + try { + return getDocumentFromFile(file); + } catch (SAXException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } + } + + /** + * 指定されたXMLのmail要素からMailインスタンスを生成します。 + * + * @param root メールデータのmail要素 + * @return 生成されたMailインスタンス + */ + protected Mail buildMail(Element root) { + Mail mail = new Mail(); + setReturnPath(root, mail); + setFrom(root, mail); + setRecipients(root, mail); + setReplyTo(root, mail); + setSubject(root, mail); + setText(root, mail); + setHtml(root, mail); + return mail; + } + + /** + * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.lang.String, java.lang.String) + */ + public Mail buildMail(String classPath, String mailId) throws MailBuildException { + if (mailId == null || "".equals(mailId)) { + throw new IllegalArgumentException("メールIDが指定されていません。"); + } + Document doc = retrieveDocument(classPath); + if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { + throw new MailBuildException("指定されたクラスパスのXMLはシングルメールテンプレートです。[classPath='" + classPath + + "']"); + } + Element mailElem = doc.getElementById(mailId); + return buildMail(mailElem); + } + + /** + * @see com.ozacc.mail.MultipleMailBuilder#buildMail(java.io.File, java.lang.String) + */ + public Mail buildMail(File file, String mailId) throws MailBuildException { + if (mailId == null || "".equals(mailId)) { + throw new IllegalArgumentException("メールIDが指定されていません。"); + } + Document doc = retrieveDocument(file); + if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { + throw new MailBuildException("指定されたファイルのXMLはシングルメールテンプレートです。[filePath='" + + file.getAbsolutePath() + "']"); + } + return buildMail(doc, mailId); + } + + /** + * マルチプルメールテンプレートのXMLドキュメント上の指定されたIDが示すメールテンプレートからMailインスタンスを生成して返します。 + * + * @param doc + * @param mailId + * @return 生成されたMailインスタンス + * @throws FactoryConfigurationError + */ + protected Mail buildMail(Document doc, String mailId) throws FactoryConfigurationError { + Element mailElem = doc.getElementById(mailId); + if (mailElem == null) { + throw new MailBuildException("指定されたID[" + mailId + "]のメールデータは見つかりませんでした。"); + } + log.debug(mailElem); + return buildMail(mailElem); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImpl.java b/src/main/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImpl.java old mode 100755 new mode 100644 index 81908ab..b86e4af --- a/src/main/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImpl.java +++ b/src/main/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImpl.java @@ -1,340 +1,340 @@ -package com.ozacc.mail.impl; - -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerConfigurationException; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.TransformerFactoryConfigurationError; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.velocity.VelocityContext; -import org.apache.velocity.app.Velocity; -import org.apache.velocity.exception.MethodInvocationException; -import org.apache.velocity.exception.ParseErrorException; -import org.apache.velocity.exception.ResourceNotFoundException; -import org.apache.velocity.runtime.log.LogSystem; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.VelocityMultipleMailBuilder; - -/** - * XMLファイルを読み込み、Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成するクラス。 - * - * @since 1.0.1 - * @author Tomohiro Otsuka - * @version $Id: XMLVelocityMailBuilderImpl.java,v 1.4.2.4 2005/01/23 06:13:10 otsuka Exp $ - */ -public class XMLVelocityMailBuilderImpl extends XMLMailBuilderImpl implements - VelocityMultipleMailBuilder { - - private static Log log = LogFactory.getLog(XMLVelocityMailBuilderImpl.class); - - private static String CACHE_KEY_SEPARATOR = "#"; - - private static String DEFAULT_MAIL_ID = "DEFAULT"; - - protected String charset = "UTF-8"; - - protected LogSystem velocityLogSystem = new VelocityLogSystem(); - - protected Map templateCache = new HashMap(); - - private boolean cacheEnabled = false; - - protected boolean hasTemplateCache(String key) { - if (cacheEnabled) { - return templateCache.containsKey(key); - } - return false; - } - - protected void putTemplateCache(String key, String templateXmlText) { - if (cacheEnabled) { - log.debug("テンプレートをキャッシュします。[key='" + key + "']"); - templateCache.put(key, templateXmlText); - } - } - - protected String getTemplateCache(String key) { - if (hasTemplateCache(key)) { - log.debug("テンプレートキャッシュを返します。[key='" + key + "']"); - return (String)templateCache.get(key); - } - return null; - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#clearCache() - */ - public synchronized void clearCache() { - log.debug("テンプレートキャッシュをクリアします。"); - templateCache.clear(); - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#isCacheEnabled() - */ - public boolean isCacheEnabled() { - return cacheEnabled; - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#setCacheEnabled(boolean) - */ - public void setCacheEnabled(boolean cacheEnabled) { - if (!cacheEnabled) { - clearCache(); - } - this.cacheEnabled = cacheEnabled; - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#buildMail(java.lang.String, org.apache.velocity.VelocityContext) - */ - public Mail buildMail(String classPath, VelocityContext context) throws MailBuildException { - String cacheKey = classPath + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; - - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc; - try { - // Velocityマージ前のXMLではコメントを許可する - doc = getDocumentFromClassPath(classPath, false); - } catch (SAXException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } - templateXmlText = convertDocumentIntoString(doc.getDocumentElement()); - putTemplateCache(cacheKey, templateXmlText); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - - /** - * @see com.ozacc.mail.VelocityMailBuilder#buildMail(java.io.File, org.apache.velocity.VelocityContext) - */ - public Mail buildMail(File file, VelocityContext context) throws MailBuildException { - String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; - - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc; - try { - // Velocityマージ前のXMLではコメントを許可する - doc = getDocumentFromFile(file, false); - } catch (SAXException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } - templateXmlText = convertDocumentIntoString(doc.getDocumentElement()); - putTemplateCache(cacheKey, templateXmlText); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - - /** - * メールデータをVelocityContextとマージして生成されたXMLからMailインスタンスを生成します。 - * - * @param templateXmlText メールデータのテンプレート - * @param context テンプレートにマージする内容を格納したVelocityContext - * @return VelocityContextをテンプレートにマージして生成されたXMLから生成されたMailインスタンス - * @throws TransformerFactoryConfigurationError - * @throws Exception - * @throws ParseErrorException - * @throws MethodInvocationException - * @throws ResourceNotFoundException - * @throws IOException - */ - protected synchronized Mail build(String templateXmlText, VelocityContext context) - throws TransformerFactoryConfigurationError, - Exception, - ParseErrorException, - MethodInvocationException, - ResourceNotFoundException, - IOException { - if (log.isDebugEnabled()) { - log.debug("Source XML Mail Data\n" + templateXmlText); - } - - Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, velocityLogSystem); - Velocity.init(); - StringWriter w = new StringWriter(); - Velocity.evaluate(context, w, "XML Mail Data", templateXmlText); - StringReader reader = new StringReader(w.toString()); - - DocumentBuilder db = createDocumentBuilder(); - InputSource source = new InputSource(reader); - Document newDoc = db.parse(source); - - if (log.isDebugEnabled()) { - String newXmlContent = convertDocumentIntoString(newDoc.getDocumentElement()); - log.debug("VelocityContext-merged XML Mail Data\n" + newXmlContent); - } - - return buildMail(newDoc.getDocumentElement()); - } - - /** - * 指定されたDOM Documentを文字列に変換します。 - * - * @param mailElement - * @return XMLドキュメントの文字列 - * @throws TransformerFactoryConfigurationError - */ - protected String convertDocumentIntoString(Element mailElement) - throws TransformerFactoryConfigurationError { - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer t; - try { - t = tf.newTransformer(); - } catch (TransformerConfigurationException e) { - throw new MailBuildException(e.getMessage(), e); - } - t.setOutputProperties(getOutputProperties()); - - DOMSource source = new DOMSource(mailElement); - StringWriter w = new StringWriter(); - StreamResult result = new StreamResult(w); - try { - t.transform(source, result); - } catch (TransformerException e) { - throw new MailBuildException(e.getMessage(), e); - } - - return w.toString(); - } - - /** - * 出力プロパティを生成。 - * @return 出力プロパティを設定したPropertiesインスタンス - */ - protected Properties getOutputProperties() { - Properties p = new Properties(); - p.put(OutputKeys.ENCODING, charset); - p.put(OutputKeys.DOCTYPE_PUBLIC, Mail.DOCTYPE_PUBLIC); - p.put(OutputKeys.DOCTYPE_SYSTEM, Mail.DOCTYPE_SYSTEM); - return p; - } - - /** - * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.lang.String, org.apache.velocity.VelocityContext, java.lang.String) - */ - public Mail buildMail(String classPath, VelocityContext context, String mailId) - throws MailBuildException { - if (mailId == null || "".equals(mailId)) { - throw new IllegalArgumentException("メールIDが指定されていません。"); - } - - String cacheKey = classPath + CACHE_KEY_SEPARATOR + mailId; - - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc; - try { - // Velocityマージ前のXMLではコメントを許可する - doc = getDocumentFromClassPath(classPath, false); - } catch (SAXException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } - if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { - throw new MailBuildException("指定されたクラスパスのXMLはシングルメールテンプレートです。[classPath='" - + classPath + "']"); - } - templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - - private String getAndCacheTemplateText(Document doc, String mailId, String cacheKey) - throws TransformerFactoryConfigurationError { - Element mailElem = doc.getElementById(mailId); - if (mailElem == null) { - throw new MailBuildException("指定されたID[" + mailId + "]のメールデータは見つかりませんでした。"); - } - String templateXmlText = convertDocumentIntoString(mailElem); - putTemplateCache(cacheKey, templateXmlText); - return templateXmlText; - } - - /** - * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.io.File, org.apache.velocity.VelocityContext, java.lang.String) - */ - public Mail buildMail(File file, VelocityContext context, String mailId) - throws MailBuildException { - if (mailId == null || "".equals(mailId)) { - throw new IllegalArgumentException("メールIDが指定されていません。"); - } - - String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + mailId; - - String templateXmlText; - if (!hasTemplateCache(cacheKey)) { - Document doc; - try { - // Velocityマージ前のXMLではコメントを許可する - doc = getDocumentFromFile(file, false); - } catch (SAXException e) { - throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); - } catch (IOException e) { - throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); - } - if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { - throw new MailBuildException("指定されたファイルのXMLはシングルメールテンプレートです。[filePath='" - + file.getAbsolutePath() + "']"); - } - templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); - } else { - templateXmlText = getTemplateCache(cacheKey); - } - - try { - return build(templateXmlText, context); - } catch (Exception e) { - throw new MailBuildException("メールの生成に失敗しました。", e); - } - } - +package com.ozacc.mail.impl; + +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.TransformerFactoryConfigurationError; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; +import org.apache.velocity.exception.MethodInvocationException; +import org.apache.velocity.exception.ParseErrorException; +import org.apache.velocity.exception.ResourceNotFoundException; +import org.apache.velocity.runtime.log.LogSystem; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.VelocityMultipleMailBuilder; + +/** + * XMLファイルを読み込み、Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成するクラス。 + * + * @since 1.0.1 + * @author Tomohiro Otsuka + * @version $Id: XMLVelocityMailBuilderImpl.java,v 1.4.2.4 2005/01/23 06:13:10 otsuka Exp $ + */ +public class XMLVelocityMailBuilderImpl extends XMLMailBuilderImpl implements + VelocityMultipleMailBuilder { + + private static Log log = LogFactory.getLog(XMLVelocityMailBuilderImpl.class); + + private static String CACHE_KEY_SEPARATOR = "#"; + + private static String DEFAULT_MAIL_ID = "DEFAULT"; + + protected String charset = "UTF-8"; + + protected LogSystem velocityLogSystem = new VelocityLogSystem(); + + protected Map templateCache = new HashMap(); + + private boolean cacheEnabled = false; + + protected boolean hasTemplateCache(String key) { + if (cacheEnabled) { + return templateCache.containsKey(key); + } + return false; + } + + protected void putTemplateCache(String key, String templateXmlText) { + if (cacheEnabled) { + log.debug("テンプレートをキャッシュします。[key='" + key + "']"); + templateCache.put(key, templateXmlText); + } + } + + protected String getTemplateCache(String key) { + if (hasTemplateCache(key)) { + log.debug("テンプレートキャッシュを返します。[key='" + key + "']"); + return (String)templateCache.get(key); + } + return null; + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#clearCache() + */ + public synchronized void clearCache() { + log.debug("テンプレートキャッシュをクリアします。"); + templateCache.clear(); + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#isCacheEnabled() + */ + public boolean isCacheEnabled() { + return cacheEnabled; + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#setCacheEnabled(boolean) + */ + public void setCacheEnabled(boolean cacheEnabled) { + if (!cacheEnabled) { + clearCache(); + } + this.cacheEnabled = cacheEnabled; + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#buildMail(java.lang.String, org.apache.velocity.VelocityContext) + */ + public Mail buildMail(String classPath, VelocityContext context) throws MailBuildException { + String cacheKey = classPath + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; + + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc; + try { + // Velocityマージ前のXMLではコメントを許可する + doc = getDocumentFromClassPath(classPath, false); + } catch (SAXException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } + templateXmlText = convertDocumentIntoString(doc.getDocumentElement()); + putTemplateCache(cacheKey, templateXmlText); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + + /** + * @see com.ozacc.mail.VelocityMailBuilder#buildMail(java.io.File, org.apache.velocity.VelocityContext) + */ + public Mail buildMail(File file, VelocityContext context) throws MailBuildException { + String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + DEFAULT_MAIL_ID; + + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc; + try { + // Velocityマージ前のXMLではコメントを許可する + doc = getDocumentFromFile(file, false); + } catch (SAXException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } + templateXmlText = convertDocumentIntoString(doc.getDocumentElement()); + putTemplateCache(cacheKey, templateXmlText); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + + /** + * メールデータをVelocityContextとマージして生成されたXMLからMailインスタンスを生成します。 + * + * @param templateXmlText メールデータのテンプレート + * @param context テンプレートにマージする内容を格納したVelocityContext + * @return VelocityContextをテンプレートにマージして生成されたXMLから生成されたMailインスタンス + * @throws TransformerFactoryConfigurationError + * @throws Exception + * @throws ParseErrorException + * @throws MethodInvocationException + * @throws ResourceNotFoundException + * @throws IOException + */ + protected synchronized Mail build(String templateXmlText, VelocityContext context) + throws TransformerFactoryConfigurationError, + Exception, + ParseErrorException, + MethodInvocationException, + ResourceNotFoundException, + IOException { + if (log.isDebugEnabled()) { + log.debug("Source XML Mail Data\n" + templateXmlText); + } + + Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, velocityLogSystem); + Velocity.init(); + StringWriter w = new StringWriter(); + Velocity.evaluate(context, w, "XML Mail Data", templateXmlText); + StringReader reader = new StringReader(w.toString()); + + DocumentBuilder db = createDocumentBuilder(); + InputSource source = new InputSource(reader); + Document newDoc = db.parse(source); + + if (log.isDebugEnabled()) { + String newXmlContent = convertDocumentIntoString(newDoc.getDocumentElement()); + log.debug("VelocityContext-merged XML Mail Data\n" + newXmlContent); + } + + return buildMail(newDoc.getDocumentElement()); + } + + /** + * 指定されたDOM Documentを文字列に変換します。 + * + * @param mailElement + * @return XMLドキュメントの文字列 + * @throws TransformerFactoryConfigurationError + */ + protected String convertDocumentIntoString(Element mailElement) + throws TransformerFactoryConfigurationError { + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t; + try { + t = tf.newTransformer(); + } catch (TransformerConfigurationException e) { + throw new MailBuildException(e.getMessage(), e); + } + t.setOutputProperties(getOutputProperties()); + + DOMSource source = new DOMSource(mailElement); + StringWriter w = new StringWriter(); + StreamResult result = new StreamResult(w); + try { + t.transform(source, result); + } catch (TransformerException e) { + throw new MailBuildException(e.getMessage(), e); + } + + return w.toString(); + } + + /** + * 出力プロパティを生成。 + * @return 出力プロパティを設定したPropertiesインスタンス + */ + protected Properties getOutputProperties() { + Properties p = new Properties(); + p.put(OutputKeys.ENCODING, charset); + p.put(OutputKeys.DOCTYPE_PUBLIC, Mail.DOCTYPE_PUBLIC); + p.put(OutputKeys.DOCTYPE_SYSTEM, Mail.DOCTYPE_SYSTEM); + return p; + } + + /** + * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.lang.String, org.apache.velocity.VelocityContext, java.lang.String) + */ + public Mail buildMail(String classPath, VelocityContext context, String mailId) + throws MailBuildException { + if (mailId == null || "".equals(mailId)) { + throw new IllegalArgumentException("メールIDが指定されていません。"); + } + + String cacheKey = classPath + CACHE_KEY_SEPARATOR + mailId; + + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc; + try { + // Velocityマージ前のXMLではコメントを許可する + doc = getDocumentFromClassPath(classPath, false); + } catch (SAXException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } + if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { + throw new MailBuildException("指定されたクラスパスのXMLはシングルメールテンプレートです。[classPath='" + + classPath + "']"); + } + templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + + private String getAndCacheTemplateText(Document doc, String mailId, String cacheKey) + throws TransformerFactoryConfigurationError { + Element mailElem = doc.getElementById(mailId); + if (mailElem == null) { + throw new MailBuildException("指定されたID[" + mailId + "]のメールデータは見つかりませんでした。"); + } + String templateXmlText = convertDocumentIntoString(mailElem); + putTemplateCache(cacheKey, templateXmlText); + return templateXmlText; + } + + /** + * @see com.ozacc.mail.VelocityMultipleMailBuilder#buildMail(java.io.File, org.apache.velocity.VelocityContext, java.lang.String) + */ + public Mail buildMail(File file, VelocityContext context, String mailId) + throws MailBuildException { + if (mailId == null || "".equals(mailId)) { + throw new IllegalArgumentException("メールIDが指定されていません。"); + } + + String cacheKey = file.getAbsolutePath() + CACHE_KEY_SEPARATOR + mailId; + + String templateXmlText; + if (!hasTemplateCache(cacheKey)) { + Document doc; + try { + // Velocityマージ前のXMLではコメントを許可する + doc = getDocumentFromFile(file, false); + } catch (SAXException e) { + throw new MailBuildException("XMLのパースに失敗しました。" + e.getMessage(), e); + } catch (IOException e) { + throw new MailBuildException("XMLファイルの読み込みに失敗しました。", e); + } + if (Mail.DOCTYPE_PUBLIC.equals(doc.getDoctype().getPublicId())) { + throw new MailBuildException("指定されたファイルのXMLはシングルメールテンプレートです。[filePath='" + + file.getAbsolutePath() + "']"); + } + templateXmlText = getAndCacheTemplateText(doc, mailId, cacheKey); + } else { + templateXmlText = getTemplateCache(cacheKey); + } + + try { + return build(templateXmlText, context); + } catch (Exception e) { + throw new MailBuildException("メールの生成に失敗しました。", e); + } + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/impl/package.html b/src/main/java/com/ozacc/mail/impl/package.html old mode 100755 new mode 100644 index c31c337..6445031 --- a/src/main/java/com/ozacc/mail/impl/package.html +++ b/src/main/java/com/ozacc/mail/impl/package.html @@ -1,38 +1,38 @@ - - -com.ozacc.mail¥Ñ¥Ã¥±¡¼¥¸¤Î¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤ò¼ÂÁõ¤·¤¿¥¯¥é¥¹¤òÄ󶡤·¤Þ¤¹¡£ -

-¤³¤Î¥Ñ¥Ã¥±¡¼¥¸¤Ë¤Ï¡¢¼ÂÁõ¥¯¥é¥¹¤¬ÍøÍѤ¹¤ëÊä½õŪÌò³ä¤Î¥¯¥é¥¹¤¬´Þ¤Þ¤ì¤Æ¤¤¤Þ¤¹¡£Ä̾¥¢¥×¥ê¥±¡¼¥·¥ç¥ó¤¬ÍøÍѤ¹¤ë¥¯¥é¥¹¤Ï¡¢²¼É½¤Ç¼¨¤¹¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤Î¼ÂÁõ¥¯¥é¥¹¤À¤±¤Ç¤¹¡£ - - - - - - - - - - - - - - - - - - - - - - - - - - - -
¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¼ÂÁõ¥¯¥é¥¹
SendMailSendMailImpl
SendMailProSendMailProImpl
MailBuilderXMLMailBuilderImpl
JDomXMLMailBuilder
VelocityMailBuilderXMLVelocityMailBuilderImpl
JDomXMLMailBuilder
- - - - + + +com.ozacc.mailパッケージのインターフェースを実装したクラスを提供します。 +

+このパッケージには、実装クラスが利用する補助的役割のクラスが含まれています。通常、アプリケーションが利用するクラスは、下表で示すインターフェースの実装クラスだけです。 + + + + + + + + + + + + + + + + + + + + + + + + + + + +
インターフェース実装クラス
SendMailSendMailImpl
SendMailProSendMailProImpl
MailBuilderXMLMailBuilderImpl
JDomXMLMailBuilder
VelocityMailBuilderXMLVelocityMailBuilderImpl
JDomXMLMailBuilder
+ + + + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mailet/Mailet.java b/src/main/java/com/ozacc/mail/mailet/Mailet.java old mode 100755 new mode 100644 index ec38690..b7b3fca --- a/src/main/java/com/ozacc/mail/mailet/Mailet.java +++ b/src/main/java/com/ozacc/mail/mailet/Mailet.java @@ -1,16 +1,16 @@ -package com.ozacc.mail.mailet; - -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * Mailetインターフェース。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: Mailet.java,v 1.1.2.2 2005/01/23 06:46:54 otsuka Exp $ - */ -public interface Mailet { - - void service(ReceivedMail mail); - +package com.ozacc.mail.mailet; + +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * Mailetインターフェース。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: Mailet.java,v 1.1.2.2 2005/01/23 06:46:54 otsuka Exp $ + */ +public interface Mailet { + + void service(ReceivedMail mail); + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mailet/MailetRunner.java b/src/main/java/com/ozacc/mail/mailet/MailetRunner.java old mode 100755 new mode 100644 index c72709f..1aa7fb7 --- a/src/main/java/com/ozacc/mail/mailet/MailetRunner.java +++ b/src/main/java/com/ozacc/mail/mailet/MailetRunner.java @@ -1,75 +1,75 @@ -package com.ozacc.mail.mailet; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.ozacc.mail.fetch.FetchMailPro; -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * メールの受信とMailetの起動を行うクラス。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: MailetRunner.java,v 1.1.2.5 2005/04/19 14:51:55 otsuka Exp $ - */ -public class MailetRunner { - - private List mailetWrapperList; - - private FetchMailPro fetchMailPro; - - /** - * コンストラクタ。 - */ - public MailetRunner() { - mailetWrapperList = new ArrayList(); - } - - /** - * メール受信とMailetの起動を行います。 - */ - public void run() { - fetchMailPro.connect(); - try { - int count = fetchMailPro.getMailCount(); - for (int i = 1; i <= count; i++) { - ReceivedMail mail = fetchMailPro.getMail(i); - processMail(mail); - } - } finally { - fetchMailPro.disconnect(); - } - } - - /** - * 指定された受信メールに対してMailetを適用します。 - * - * @param mail MailetWrapperに渡す受信メール - */ - private void processMail(ReceivedMail mail) { - for (Iterator itr = mailetWrapperList.iterator(); itr.hasNext();) { - MailetWrapper mailetWrapper = (MailetWrapper)itr.next(); - mailetWrapper.execute(mail); - } - } - - /** - * メールの受信に使用するFetchMailProインターフェースの実装インスタンスをセットします。 - * - * @param fetchMailPro FetchMailProインターフェースの実装インスタンス - */ - public void setFetchMailPro(FetchMailPro fetchMailPro) { - this.fetchMailPro = fetchMailPro; - } - - /** - * 実行するMailetのMailetWrapperリストをセットします。 - * - * @param mailetWrapperList 実行するMailetのMailetWrapperリスト - */ - public void setMailetWrapperList(List mailetWrapperList) { - this.mailetWrapperList = mailetWrapperList; - } +package com.ozacc.mail.mailet; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.ozacc.mail.fetch.FetchMailPro; +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * メールの受信とMailetの起動を行うクラス。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: MailetRunner.java,v 1.1.2.5 2005/04/19 14:51:55 otsuka Exp $ + */ +public class MailetRunner { + + private List mailetWrapperList; + + private FetchMailPro fetchMailPro; + + /** + * コンストラクタ。 + */ + public MailetRunner() { + mailetWrapperList = new ArrayList(); + } + + /** + * メール受信とMailetの起動を行います。 + */ + public void run() { + fetchMailPro.connect(); + try { + int count = fetchMailPro.getMailCount(); + for (int i = 1; i <= count; i++) { + ReceivedMail mail = fetchMailPro.getMail(i); + processMail(mail); + } + } finally { + fetchMailPro.disconnect(); + } + } + + /** + * 指定された受信メールに対してMailetを適用します。 + * + * @param mail MailetWrapperに渡す受信メール + */ + private void processMail(ReceivedMail mail) { + for (Iterator itr = mailetWrapperList.iterator(); itr.hasNext();) { + MailetWrapper mailetWrapper = (MailetWrapper)itr.next(); + mailetWrapper.execute(mail); + } + } + + /** + * メールの受信に使用するFetchMailProインターフェースの実装インスタンスをセットします。 + * + * @param fetchMailPro FetchMailProインターフェースの実装インスタンス + */ + public void setFetchMailPro(FetchMailPro fetchMailPro) { + this.fetchMailPro = fetchMailPro; + } + + /** + * 実行するMailetのMailetWrapperリストをセットします。 + * + * @param mailetWrapperList 実行するMailetのMailetWrapperリスト + */ + public void setMailetWrapperList(List mailetWrapperList) { + this.mailetWrapperList = mailetWrapperList; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mailet/MailetWrapper.java b/src/main/java/com/ozacc/mail/mailet/MailetWrapper.java old mode 100755 new mode 100644 index 9198793..95b100e --- a/src/main/java/com/ozacc/mail/mailet/MailetWrapper.java +++ b/src/main/java/com/ozacc/mail/mailet/MailetWrapper.java @@ -1,91 +1,91 @@ -package com.ozacc.mail.mailet; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * MailetインスタンスとMatcherインスタンスのリストを持つMailetの実行単位となるクラス。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: MailetWrapper.java,v 1.1.2.2 2005/01/23 06:47:01 otsuka Exp $ - */ -public class MailetWrapper { - - private Mailet mailet; - - private List matcherList; - - /** - * コンストラクタ。 - */ - public MailetWrapper() { - matcherList = new ArrayList(); - } - - /** - * コンストラクタ。 - * - * @param mailet Mailetインスタンス - * @param matcherList Matcherインスタンスのリスト - */ - public MailetWrapper(Mailet mailet, List matcherList) { - this(); - this.mailet = mailet; - this.matcherList = matcherList; - } - - /** - * リストされているMatcherの条件をクリアしたMailetを実行します。 - * - * @param mail 受信メール - */ - public void execute(ReceivedMail mail) { - for (Iterator itr = matcherList.iterator(); itr.hasNext();) { - Matcher m = (Matcher)itr.next(); - if (!m.match(mail)) { - return; - } - } - mailet.service(mail); - } - - /** - * Mailetインスタンスを返します。 - * - * @return Mailetインスタンス - */ - public Mailet getMailet() { - return mailet; - } - - /** - * Mailetインスタンスをセットします。 - * - * @param mailet Mailetインスタンス - */ - public void setMailet(Mailet mailet) { - this.mailet = mailet; - } - - /** - * Matcherインスタンスのリストを返します。 - * - * @return Matcherインスタンスのリスト - */ - public List getMatcherList() { - return matcherList; - } - - /** - * Matcherインスタンスのリストをセットします。 - * - * @param matcherList Matcherインスタンスのリスト - */ - public void setMatcherList(List matcherList) { - this.matcherList = matcherList; - } +package com.ozacc.mail.mailet; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * MailetインスタンスとMatcherインスタンスのリストを持つMailetの実行単位となるクラス。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: MailetWrapper.java,v 1.1.2.2 2005/01/23 06:47:01 otsuka Exp $ + */ +public class MailetWrapper { + + private Mailet mailet; + + private List matcherList; + + /** + * コンストラクタ。 + */ + public MailetWrapper() { + matcherList = new ArrayList(); + } + + /** + * コンストラクタ。 + * + * @param mailet Mailetインスタンス + * @param matcherList Matcherインスタンスのリスト + */ + public MailetWrapper(Mailet mailet, List matcherList) { + this(); + this.mailet = mailet; + this.matcherList = matcherList; + } + + /** + * リストされているMatcherの条件をクリアしたMailetを実行します。 + * + * @param mail 受信メール + */ + public void execute(ReceivedMail mail) { + for (Iterator itr = matcherList.iterator(); itr.hasNext();) { + Matcher m = (Matcher)itr.next(); + if (!m.match(mail)) { + return; + } + } + mailet.service(mail); + } + + /** + * Mailetインスタンスを返します。 + * + * @return Mailetインスタンス + */ + public Mailet getMailet() { + return mailet; + } + + /** + * Mailetインスタンスをセットします。 + * + * @param mailet Mailetインスタンス + */ + public void setMailet(Mailet mailet) { + this.mailet = mailet; + } + + /** + * Matcherインスタンスのリストを返します。 + * + * @return Matcherインスタンスのリスト + */ + public List getMatcherList() { + return matcherList; + } + + /** + * Matcherインスタンスのリストをセットします。 + * + * @param matcherList Matcherインスタンスのリスト + */ + public void setMatcherList(List matcherList) { + this.matcherList = matcherList; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mailet/Matcher.java b/src/main/java/com/ozacc/mail/mailet/Matcher.java old mode 100755 new mode 100644 index 7c3a239..3074c15 --- a/src/main/java/com/ozacc/mail/mailet/Matcher.java +++ b/src/main/java/com/ozacc/mail/mailet/Matcher.java @@ -1,22 +1,22 @@ -package com.ozacc.mail.mailet; - -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * Mailetの実行条件を満たすかどうか判定するインターフェース。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: Matcher.java,v 1.1.2.2 2005/01/23 06:47:01 otsuka Exp $ - */ -public interface Matcher { - - /** - * 指定された受信メールがMailet実行条件を満たすかどうか判定します。 - * - * @param mail 受信メール - * @return 受信メールMailet実行条件を満たす場合 true - */ - boolean match(ReceivedMail mail); - +package com.ozacc.mail.mailet; + +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * Mailetの実行条件を満たすかどうか判定するインターフェース。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: Matcher.java,v 1.1.2.2 2005/01/23 06:47:01 otsuka Exp $ + */ +public interface Matcher { + + /** + * 指定された受信メールがMailet実行条件を満たすかどうか判定します。 + * + * @param mail 受信メール + * @return 受信メールMailet実行条件を満たす場合 true + */ + boolean match(ReceivedMail mail); + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mailet/package.html b/src/main/java/com/ozacc/mail/mailet/package.html old mode 100755 new mode 100644 index 589ba0c..d5ccf7a --- a/src/main/java/com/ozacc/mail/mailet/package.html +++ b/src/main/java/com/ozacc/mail/mailet/package.html @@ -1,5 +1,5 @@ - - -Mailet¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤È¼Â¹Ô´Ä¶­¤òÄ󶡤·¤Þ¤¹¡£ - + + +Mailetインターフェースと実行環境を提供します。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mock/AssertionFailedException.java b/src/main/java/com/ozacc/mail/mock/AssertionFailedException.java old mode 100755 new mode 100644 index b55e44e..ad24992 --- a/src/main/java/com/ozacc/mail/mock/AssertionFailedException.java +++ b/src/main/java/com/ozacc/mail/mock/AssertionFailedException.java @@ -1,28 +1,28 @@ -package com.ozacc.mail.mock; - -/** - * MockSendMailで期待メールと送信メールが一致しなかった時にスローされる非チェック例外。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: AssertionFailedException.java,v 1.2 2004/09/13 07:07:42 otsuka Exp $ - */ -public class AssertionFailedException extends RuntimeException { - - public AssertionFailedException() { - super(); - } - - public AssertionFailedException(String message) { - super(message); - } - - public AssertionFailedException(Throwable cause) { - super(cause); - } - - public AssertionFailedException(String message, Throwable cause) { - super(message, cause); - } - +package com.ozacc.mail.mock; + +/** + * MockSendMailで期待メールと送信メールが一致しなかった時にスローされる非チェック例外。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: AssertionFailedException.java,v 1.2 2004/09/13 07:07:42 otsuka Exp $ + */ +public class AssertionFailedException extends RuntimeException { + + public AssertionFailedException() { + super(); + } + + public AssertionFailedException(String message) { + super(message); + } + + public AssertionFailedException(Throwable cause) { + super(cause); + } + + public AssertionFailedException(String message, Throwable cause) { + super(message, cause); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mock/EqualityCheck.java b/src/main/java/com/ozacc/mail/mock/EqualityCheck.java old mode 100755 new mode 100644 index 854ecc4..33491be --- a/src/main/java/com/ozacc/mail/mock/EqualityCheck.java +++ b/src/main/java/com/ozacc/mail/mock/EqualityCheck.java @@ -1,166 +1,166 @@ -package com.ozacc.mail.mock; - -import javax.mail.internet.InternetAddress; - -import com.ozacc.mail.Mail; - -/** - * メールが同値であることを調べるメソッドを提供。 - *

- * 注: 添付ファイルは比較対象になりません。 - * - * @since 1.1 - * - * @author Tomohiro Otsuka - * @version $Id: EqualityCheck.java,v 1.3.2.1 2004/11/25 08:01:18 otsuka Exp $ - */ -public class EqualityCheck { - - private EqualityCheck() {} - - /** - * expectedとsentのメール内容が同一であるかどうかを判定します。
- * MultipartMailのインスタンスも指定できます。但し、添付ファイルはチェックされません。 - * - * @param expected - * @param sent - * @return expectedとsentのメール内容が同一である場合 true - */ - public static boolean equals(Mail expected, Mail sent) { - boolean mockMode = (expected instanceof MockMail); - - // マルチパートメールの場合 - if (expected.isMultipartMail()) { - - // HTML - if (!mockMode) { - if ((expected.getHtmlText() == null && sent.getHtmlText() != null) - || (expected.getHtmlText() != null && sent.getHtmlText() == null) - || (!expected.getHtmlText().equals(sent.getHtmlText()))) { - return false; - } - } else if (mockMode && expected.getHtmlText() != null) { - if (!expected.getHtmlText().equals(sent.getHtmlText())) { - return false; - } - } - } - - // Return-Path - if (!mockMode || (mockMode && expected.getReturnPath() != null)) { - if (expected.getReturnPath() != null && sent.getReturnPath() != null) { - if (!expected.getReturnPath().equals(sent.getReturnPath())) { - return false; - } - } else if ((expected.getReturnPath() != null && sent.getReturnPath() == null) - || (expected.getReturnPath() == null && sent.getReturnPath() != null)) { - return false; - } - } - - // From - if (!mockMode || (mockMode && expected.getFrom() != null)) { - if (expected.getFrom() != null && sent.getFrom() != null) { - if (!equals(expected.getFrom(), sent.getFrom())) { - return false; - } - } else if ((expected.getFrom() != null && sent.getFrom() == null) - || (expected.getFrom() == null && sent.getFrom() != null)) { - return false; - } - } - - // to - InternetAddress[] expectedAddresses = expected.getTo(); - InternetAddress[] sentAddresses = sent.getTo(); - if (!mockMode || (mockMode && expectedAddresses.length > 0)) { - if (expectedAddresses.length != sentAddresses.length) { - return false; - } - for (int i = 0; i < expectedAddresses.length; i++) { - if (!equals(expectedAddresses[i], sentAddresses[i])) { - return false; - } - } - } - - // cc - expectedAddresses = expected.getCc(); - sentAddresses = sent.getCc(); - if (!mockMode || (mockMode && expectedAddresses.length > 0)) { - if (expectedAddresses.length != sentAddresses.length) { - return false; - } - for (int i = 0; i < expectedAddresses.length; i++) { - if (!equals(expectedAddresses[i], sentAddresses[i])) { - return false; - } - } - } - - // bcc - expectedAddresses = expected.getBcc(); - sentAddresses = sent.getBcc(); - if (!mockMode || (mockMode && expectedAddresses.length > 0)) { - if (expectedAddresses.length != sentAddresses.length) { - return false; - } - for (int i = 0; i < expectedAddresses.length; i++) { - if (!equals(expectedAddresses[i], sentAddresses[i])) { - return false; - } - } - } - - // Reply-To - if (!mockMode || (mockMode && expected.getReplyTo() != null)) { - if (expected.getReplyTo() != null && sent.getReplyTo() != null) { - if (!equals(expected.getReplyTo(), sent.getReplyTo())) { - return false; - } - } else if ((expected.getReplyTo() != null && sent.getReplyTo() == null) - || (expected.getReplyTo() == null && sent.getReplyTo() != null)) { - return false; - } - } - - // 件名 - if (!mockMode || (mockMode && expected.getSubject().length() > 0)) { - if (!expected.getSubject().equals(sent.getSubject())) { - return false; - } - } - - // 本文 - if (!mockMode || (mockMode && expected.getText().length() > 0)) { - if (!expected.getText().equals(sent.getText())) { - return false; - } - } - - return true; - } - - /** - * 指定された二つのInternetAddressインスタンスが等しいかどうか判定します。 - *

- * InternetAddress#equals()メソッドでは、メールアドレスしか検査しないため、 - * このメソッドではInternetAddressに名前が含まれている場合、その名前も - * 等しいかどうか検査します。 - * - * @since 1.1.3 - * @param a 比較するInternetAddressインスタンス - * @param b 比較するInternetAddressインスタンス - * @return 二つのInternetAddressインスタンスが等しい場合 true - */ - public static boolean equals(InternetAddress a, InternetAddress b) { - if (a.equals(b)) { - if (a.getPersonal() != null || b.getPersonal() != null) { - return a.getPersonal().equals(b.getPersonal()); - } else { - return true; - } - } - return false; - } +package com.ozacc.mail.mock; + +import javax.mail.internet.InternetAddress; + +import com.ozacc.mail.Mail; + +/** + * メールが同値であることを調べるメソッドを提供。 + *

+ * 注: 添付ファイルは比較対象になりません。 + * + * @since 1.1 + * + * @author Tomohiro Otsuka + * @version $Id: EqualityCheck.java,v 1.3.2.1 2004/11/25 08:01:18 otsuka Exp $ + */ +public class EqualityCheck { + + private EqualityCheck() {} + + /** + * expectedとsentのメール内容が同一であるかどうかを判定します。
+ * MultipartMailのインスタンスも指定できます。但し、添付ファイルはチェックされません。 + * + * @param expected + * @param sent + * @return expectedとsentのメール内容が同一である場合 true + */ + public static boolean equals(Mail expected, Mail sent) { + boolean mockMode = (expected instanceof MockMail); + + // マルチパートメールの場合 + if (expected.isMultipartMail()) { + + // HTML + if (!mockMode) { + if ((expected.getHtmlText() == null && sent.getHtmlText() != null) + || (expected.getHtmlText() != null && sent.getHtmlText() == null) + || (!expected.getHtmlText().equals(sent.getHtmlText()))) { + return false; + } + } else if (mockMode && expected.getHtmlText() != null) { + if (!expected.getHtmlText().equals(sent.getHtmlText())) { + return false; + } + } + } + + // Return-Path + if (!mockMode || (mockMode && expected.getReturnPath() != null)) { + if (expected.getReturnPath() != null && sent.getReturnPath() != null) { + if (!expected.getReturnPath().equals(sent.getReturnPath())) { + return false; + } + } else if ((expected.getReturnPath() != null && sent.getReturnPath() == null) + || (expected.getReturnPath() == null && sent.getReturnPath() != null)) { + return false; + } + } + + // From + if (!mockMode || (mockMode && expected.getFrom() != null)) { + if (expected.getFrom() != null && sent.getFrom() != null) { + if (!equals(expected.getFrom(), sent.getFrom())) { + return false; + } + } else if ((expected.getFrom() != null && sent.getFrom() == null) + || (expected.getFrom() == null && sent.getFrom() != null)) { + return false; + } + } + + // to + InternetAddress[] expectedAddresses = expected.getTo(); + InternetAddress[] sentAddresses = sent.getTo(); + if (!mockMode || (mockMode && expectedAddresses.length > 0)) { + if (expectedAddresses.length != sentAddresses.length) { + return false; + } + for (int i = 0; i < expectedAddresses.length; i++) { + if (!equals(expectedAddresses[i], sentAddresses[i])) { + return false; + } + } + } + + // cc + expectedAddresses = expected.getCc(); + sentAddresses = sent.getCc(); + if (!mockMode || (mockMode && expectedAddresses.length > 0)) { + if (expectedAddresses.length != sentAddresses.length) { + return false; + } + for (int i = 0; i < expectedAddresses.length; i++) { + if (!equals(expectedAddresses[i], sentAddresses[i])) { + return false; + } + } + } + + // bcc + expectedAddresses = expected.getBcc(); + sentAddresses = sent.getBcc(); + if (!mockMode || (mockMode && expectedAddresses.length > 0)) { + if (expectedAddresses.length != sentAddresses.length) { + return false; + } + for (int i = 0; i < expectedAddresses.length; i++) { + if (!equals(expectedAddresses[i], sentAddresses[i])) { + return false; + } + } + } + + // Reply-To + if (!mockMode || (mockMode && expected.getReplyTo() != null)) { + if (expected.getReplyTo() != null && sent.getReplyTo() != null) { + if (!equals(expected.getReplyTo(), sent.getReplyTo())) { + return false; + } + } else if ((expected.getReplyTo() != null && sent.getReplyTo() == null) + || (expected.getReplyTo() == null && sent.getReplyTo() != null)) { + return false; + } + } + + // 件名 + if (!mockMode || (mockMode && expected.getSubject().length() > 0)) { + if (!expected.getSubject().equals(sent.getSubject())) { + return false; + } + } + + // 本文 + if (!mockMode || (mockMode && expected.getText().length() > 0)) { + if (!expected.getText().equals(sent.getText())) { + return false; + } + } + + return true; + } + + /** + * 指定された二つのInternetAddressインスタンスが等しいかどうか判定します。 + *

+ * InternetAddress#equals()メソッドでは、メールアドレスしか検査しないため、 + * このメソッドではInternetAddressに名前が含まれている場合、その名前も + * 等しいかどうか検査します。 + * + * @since 1.1.3 + * @param a 比較するInternetAddressインスタンス + * @param b 比較するInternetAddressインスタンス + * @return 二つのInternetAddressインスタンスが等しい場合 true + */ + public static boolean equals(InternetAddress a, InternetAddress b) { + if (a.equals(b)) { + if (a.getPersonal() != null || b.getPersonal() != null) { + return a.getPersonal().equals(b.getPersonal()); + } else { + return true; + } + } + return false; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mock/MockFetchMail.java b/src/main/java/com/ozacc/mail/mock/MockFetchMail.java old mode 100755 new mode 100644 index 0e3ae56..628ede7 --- a/src/main/java/com/ozacc/mail/mock/MockFetchMail.java +++ b/src/main/java/com/ozacc/mail/mock/MockFetchMail.java @@ -1,182 +1,182 @@ -package com.ozacc.mail.mock; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.ozacc.mail.MailException; -import com.ozacc.mail.fetch.FetchMail; -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * FetchMailImplクラスのMock。
- * setupGetMails()メソッドでReceivedMailインスタンスをセットすると、getMails()メソッドがそのインスタンスを返します。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: MockFetchMail.java,v 1.1.2.3 2005/02/05 09:25:25 otsuka Exp $ - */ -public class MockFetchMail implements FetchMail { - - private static Log log = LogFactory.getLog(MockFetchMail.class); - - /** デフォルトのSMTPサーバ。「localhost」 */ - public static final String DEFAULT_HOST = "localhost"; - - /** デフォルトのプロトコル。「pop3」 */ - public static final String DEFAULT_PROTOCOL = "pop3"; - - /** - * デフォルトのポート。「-1」
- * -1はプロトコルに応じた適切なポートを設定する特別な値。 - */ - public static final int DEFAULT_PORT = -1; - - private static final String INBOX_NAME = "INBOX"; - - private String host = DEFAULT_HOST; - - private String protocol = DEFAULT_PROTOCOL; - - private int port = DEFAULT_PORT; - - private String username; - - private String password; - - private List receivedMails; - - /** - * コンストラクタ。 - */ - public MockFetchMail() { - super(); - receivedMails = new ArrayList(); - } - - /** - * MockFetchMailのgetMails()メソッドが返す - * ReceivedMailインスタンスをセットします。 - * - * @param mail getMails()メソッドが返すReceivedMailインスタンス - */ - public void setupGetMails(ReceivedMail mail) { - receivedMails.add(mail); - } - - /** - * MockFetchMailのgetMails()メソッドが返す - * ReceivedMailインスタンスをセットします。 - * - * @param mails getMails()メソッドが返すReceivedMailインスタンス配列 - */ - public void setupGetMails(ReceivedMail[] mails) { - for (int i = 0; i < mails.length; i++) { - ReceivedMail mail = mails[i]; - setupGetMails(mail); - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMail#getMails() - */ - public ReceivedMail[] getMails() throws MailException { - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続しるフリ。"); - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続したフリ。"); - - if (receivedMails.size() > 0) { - log.debug(receivedMails.size() + "通のメールを受信するフリ。"); - } else { - log.debug("受信するフリをするメールはありません。"); - } - try { - return (ReceivedMail[])receivedMails.toArray(new ReceivedMail[receivedMails.size()]); - } finally { - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断するフリ。"); - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断したフリ。"); - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMail#getMails(boolean) - */ - public ReceivedMail[] getMails(boolean delete) throws MailException { - ReceivedMail[] result = getMails(); - if (delete) { - receivedMails.clear(); - } - return result; - } - - /** - * @return Returns the host. - */ - public String getHost() { - return host; - } - - /** - * @param host The host to set. - */ - public void setHost(String host) { - this.host = host; - } - - /** - * @return Returns the password. - */ - public String getPassword() { - return password; - } - - /** - * @param password The password to set. - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return Returns the port. - */ - public int getPort() { - return port; - } - - /** - * @param port The port to set. - */ - public void setPort(int port) { - this.port = port; - } - - /** - * @return Returns the protocol. - */ - public String getProtocol() { - return protocol; - } - - /** - * @param protocol The protocol to set. - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * @return Returns the username. - */ - public String getUsername() { - return username; - } - - /** - * @param username The username to set. - */ - public void setUsername(String username) { - this.username = username; - } +package com.ozacc.mail.mock; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.ozacc.mail.MailException; +import com.ozacc.mail.fetch.FetchMail; +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * FetchMailImplクラスのMock。
+ * setupGetMails()メソッドでReceivedMailインスタンスをセットすると、getMails()メソッドがそのインスタンスを返します。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: MockFetchMail.java,v 1.1.2.3 2005/02/05 09:25:25 otsuka Exp $ + */ +public class MockFetchMail implements FetchMail { + + private static Log log = LogFactory.getLog(MockFetchMail.class); + + /** デフォルトのSMTPサーバ。「localhost」 */ + public static final String DEFAULT_HOST = "localhost"; + + /** デフォルトのプロトコル。「pop3」 */ + public static final String DEFAULT_PROTOCOL = "pop3"; + + /** + * デフォルトのポート。「-1」
+ * -1はプロトコルに応じた適切なポートを設定する特別な値。 + */ + public static final int DEFAULT_PORT = -1; + + private static final String INBOX_NAME = "INBOX"; + + private String host = DEFAULT_HOST; + + private String protocol = DEFAULT_PROTOCOL; + + private int port = DEFAULT_PORT; + + private String username; + + private String password; + + private List receivedMails; + + /** + * コンストラクタ。 + */ + public MockFetchMail() { + super(); + receivedMails = new ArrayList(); + } + + /** + * MockFetchMailのgetMails()メソッドが返す + * ReceivedMailインスタンスをセットします。 + * + * @param mail getMails()メソッドが返すReceivedMailインスタンス + */ + public void setupGetMails(ReceivedMail mail) { + receivedMails.add(mail); + } + + /** + * MockFetchMailのgetMails()メソッドが返す + * ReceivedMailインスタンスをセットします。 + * + * @param mails getMails()メソッドが返すReceivedMailインスタンス配列 + */ + public void setupGetMails(ReceivedMail[] mails) { + for (int i = 0; i < mails.length; i++) { + ReceivedMail mail = mails[i]; + setupGetMails(mail); + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMail#getMails() + */ + public ReceivedMail[] getMails() throws MailException { + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続しるフリ。"); + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続したフリ。"); + + if (receivedMails.size() > 0) { + log.debug(receivedMails.size() + "通のメールを受信するフリ。"); + } else { + log.debug("受信するフリをするメールはありません。"); + } + try { + return (ReceivedMail[])receivedMails.toArray(new ReceivedMail[receivedMails.size()]); + } finally { + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断するフリ。"); + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断したフリ。"); + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMail#getMails(boolean) + */ + public ReceivedMail[] getMails(boolean delete) throws MailException { + ReceivedMail[] result = getMails(); + if (delete) { + receivedMails.clear(); + } + return result; + } + + /** + * @return Returns the host. + */ + public String getHost() { + return host; + } + + /** + * @param host The host to set. + */ + public void setHost(String host) { + this.host = host; + } + + /** + * @return Returns the password. + */ + public String getPassword() { + return password; + } + + /** + * @param password The password to set. + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return Returns the port. + */ + public int getPort() { + return port; + } + + /** + * @param port The port to set. + */ + public void setPort(int port) { + this.port = port; + } + + /** + * @return Returns the protocol. + */ + public String getProtocol() { + return protocol; + } + + /** + * @param protocol The protocol to set. + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return Returns the username. + */ + public String getUsername() { + return username; + } + + /** + * @param username The username to set. + */ + public void setUsername(String username) { + this.username = username; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mock/MockFetchMailPro.java b/src/main/java/com/ozacc/mail/mock/MockFetchMailPro.java old mode 100755 new mode 100644 index 8a5f4e9..be21375 --- a/src/main/java/com/ozacc/mail/mock/MockFetchMailPro.java +++ b/src/main/java/com/ozacc/mail/mock/MockFetchMailPro.java @@ -1,276 +1,276 @@ -package com.ozacc.mail.mock; - -import java.util.ArrayList; -import java.util.List; - -import javax.mail.internet.MimeMessage; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.ozacc.mail.MailException; -import com.ozacc.mail.NotConnectedException; -import com.ozacc.mail.fetch.FetchMailPro; -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * FetchMailProImplクラスのMock。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: MockFetchMailPro.java,v 1.1.2.2 2005/04/10 05:22:34 otsuka Exp $ - */ -public class MockFetchMailPro implements FetchMailPro { - - private static Log log = LogFactory.getLog(MockFetchMailPro.class); - - /** デフォルトのSMTPサーバ。「localhost」 */ - public static final String DEFAULT_HOST = "localhost"; - - /** デフォルトのプロトコル。「pop3」 */ - public static final String DEFAULT_PROTOCOL = "pop3"; - - /** - * デフォルトのポート。「-1」
- * -1はプロトコルに応じた適切なポートを設定する特別な値。 - */ - public static final int DEFAULT_PORT = -1; - - private static final String INBOX_NAME = "INBOX"; - - private String host = DEFAULT_HOST; - - private String protocol = DEFAULT_PROTOCOL; - - private int port = DEFAULT_PORT; - - private String username; - - private String password; - - private boolean javaMailLogEnabled; - - private boolean connected = false; - - private List receivedMails; - - /** - * コンストラクタ。 - */ - public MockFetchMailPro() { - super(); - receivedMails = new ArrayList(); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#connect() - */ - public synchronized void connect() throws MailException { - if (isConnected()) { - log.warn("既にサーバ[" + host + "]に接続されています。再接続するには先に接続を切断する必要があります。"); - return; - } - - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続するフリ。"); - connected = true; - log.info(protocol.toUpperCase() + "サーバ[" + host + "]に接続したフリ。"); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#disconnect() - */ - public synchronized void disconnect() throws MailException { - if (isConnected()) { - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断するフリ。"); - connected = false; - log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断したフリ。"); - } - } - - /** - * MockFetchMailProのgetMails()メソッドが返す - * ReceivedMailインスタンスをセットします。 - * - * @param mail getMails()メソッドが返すReceivedMailインスタンス - */ - public void setupGetMails(ReceivedMail mail) { - receivedMails.add(mail); - } - - /** - * MockFetchMailProのgetMails()メソッドが返す - * ReceivedMailインスタンスをセットします。 - * - * @param mails getMails()メソッドが返すReceivedMailインスタンス配列 - */ - public void setupGetMails(ReceivedMail[] mails) { - for (int i = 0; i < mails.length; i++) { - ReceivedMail mail = mails[i]; - setupGetMails(mail); - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMailCount() - */ - public int getMailCount() throws MailException { - return receivedMails.size(); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int) - */ - public synchronized ReceivedMail getMail(int num) throws MailException { - return getMail(num, false); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int, boolean) - */ - public synchronized ReceivedMail getMail(int num, boolean delete) throws MailException { - if (isConnected()) { - if (delete) { - return (ReceivedMail)receivedMails.remove(num - 1); - } else { - return (ReceivedMail)receivedMails.get(num - 1); - } - } else { - throw new NotConnectedException(protocol.toUpperCase() + "サーバ[" + host + "]に接続されていません。"); - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMails(boolean) - */ - public synchronized ReceivedMail[] getMails(boolean delete) throws MailException { - if (isConnected()) { - ReceivedMail[] results = (ReceivedMail[])receivedMails - .toArray(new ReceivedMail[receivedMails.size()]); - if (delete) { - receivedMails.clear(); - } - return results; - } else { - throw new NotConnectedException(protocol.toUpperCase() + "サーバ[" + host + "]に接続されていません。"); - } - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMessage(int) - */ - public MimeMessage getMessage(int num) throws MailException { - throw new UnsupportedOperationException("申し訳ございません。MockFetchMailProでは、このメソッドをサポートしていません。"); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#getMessages(boolean) - */ - public MimeMessage[] getMessages(boolean delete) throws MailException { - throw new UnsupportedOperationException("申し訳ございません。MockFetchMailProでは、このメソッドをサポートしていません。"); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#changeFolder(java.lang.String) - */ - public synchronized void changeFolder(String folderName) throws MailException { - if (!isConnected()) { - log.warn("メールサーバに接続されていません。"); - return; - } - - log.debug("メッセージフォルダ[" + folderName + "]をオープンするフリ。"); - log.debug("メッセージフォルダ[" + folderName + "]をオープンしたフリ。"); - } - - /** - * @see com.ozacc.mail.fetch.FetchMailPro#isConnected() - */ - public boolean isConnected() { - return connected; - } - - /** - * @return Returns the host. - */ - public String getHost() { - return host; - } - - /** - * @param host The host to set. - */ - public void setHost(String host) { - this.host = host; - } - - /** - * @return Returns the javaMailLogEnabled. - */ - public boolean isJavaMailLogEnabled() { - return javaMailLogEnabled; - } - - /** - * @param javaMailLogEnabled The javaMailLogEnabled to set. - */ - public void setJavaMailLogEnabled(boolean javaMailLogEnabled) { - this.javaMailLogEnabled = javaMailLogEnabled; - } - - /** - * @return Returns the password. - */ - public String getPassword() { - return password; - } - - /** - * @param password The password to set. - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return Returns the port. - */ - public int getPort() { - return port; - } - - /** - * @param port The port to set. - */ - public void setPort(int port) { - this.port = port; - } - - /** - * @return Returns the protocol. - */ - public String getProtocol() { - return protocol; - } - - /** - * @param protocol The protocol to set. - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * @return Returns the username. - */ - public String getUsername() { - return username; - } - - /** - * @param username The username to set. - */ - public void setUsername(String username) { - this.username = username; - } - +package com.ozacc.mail.mock; + +import java.util.ArrayList; +import java.util.List; + +import javax.mail.internet.MimeMessage; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.ozacc.mail.MailException; +import com.ozacc.mail.NotConnectedException; +import com.ozacc.mail.fetch.FetchMailPro; +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * FetchMailProImplクラスのMock。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: MockFetchMailPro.java,v 1.1.2.2 2005/04/10 05:22:34 otsuka Exp $ + */ +public class MockFetchMailPro implements FetchMailPro { + + private static Log log = LogFactory.getLog(MockFetchMailPro.class); + + /** デフォルトのSMTPサーバ。「localhost」 */ + public static final String DEFAULT_HOST = "localhost"; + + /** デフォルトのプロトコル。「pop3」 */ + public static final String DEFAULT_PROTOCOL = "pop3"; + + /** + * デフォルトのポート。「-1」
+ * -1はプロトコルに応じた適切なポートを設定する特別な値。 + */ + public static final int DEFAULT_PORT = -1; + + private static final String INBOX_NAME = "INBOX"; + + private String host = DEFAULT_HOST; + + private String protocol = DEFAULT_PROTOCOL; + + private int port = DEFAULT_PORT; + + private String username; + + private String password; + + private boolean javaMailLogEnabled; + + private boolean connected = false; + + private List receivedMails; + + /** + * コンストラクタ。 + */ + public MockFetchMailPro() { + super(); + receivedMails = new ArrayList(); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#connect() + */ + public synchronized void connect() throws MailException { + if (isConnected()) { + log.warn("既にサーバ[" + host + "]に接続されています。再接続するには先に接続を切断する必要があります。"); + return; + } + + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]に接続するフリ。"); + connected = true; + log.info(protocol.toUpperCase() + "サーバ[" + host + "]に接続したフリ。"); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#disconnect() + */ + public synchronized void disconnect() throws MailException { + if (isConnected()) { + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断するフリ。"); + connected = false; + log.debug(protocol.toUpperCase() + "サーバ[" + host + "]との接続を切断したフリ。"); + } + } + + /** + * MockFetchMailProのgetMails()メソッドが返す + * ReceivedMailインスタンスをセットします。 + * + * @param mail getMails()メソッドが返すReceivedMailインスタンス + */ + public void setupGetMails(ReceivedMail mail) { + receivedMails.add(mail); + } + + /** + * MockFetchMailProのgetMails()メソッドが返す + * ReceivedMailインスタンスをセットします。 + * + * @param mails getMails()メソッドが返すReceivedMailインスタンス配列 + */ + public void setupGetMails(ReceivedMail[] mails) { + for (int i = 0; i < mails.length; i++) { + ReceivedMail mail = mails[i]; + setupGetMails(mail); + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMailCount() + */ + public int getMailCount() throws MailException { + return receivedMails.size(); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int) + */ + public synchronized ReceivedMail getMail(int num) throws MailException { + return getMail(num, false); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMail(int, boolean) + */ + public synchronized ReceivedMail getMail(int num, boolean delete) throws MailException { + if (isConnected()) { + if (delete) { + return (ReceivedMail)receivedMails.remove(num - 1); + } else { + return (ReceivedMail)receivedMails.get(num - 1); + } + } else { + throw new NotConnectedException(protocol.toUpperCase() + "サーバ[" + host + "]に接続されていません。"); + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMails(boolean) + */ + public synchronized ReceivedMail[] getMails(boolean delete) throws MailException { + if (isConnected()) { + ReceivedMail[] results = (ReceivedMail[])receivedMails + .toArray(new ReceivedMail[receivedMails.size()]); + if (delete) { + receivedMails.clear(); + } + return results; + } else { + throw new NotConnectedException(protocol.toUpperCase() + "サーバ[" + host + "]に接続されていません。"); + } + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMessage(int) + */ + public MimeMessage getMessage(int num) throws MailException { + throw new UnsupportedOperationException("申し訳ございません。MockFetchMailProでは、このメソッドをサポートしていません。"); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#getMessages(boolean) + */ + public MimeMessage[] getMessages(boolean delete) throws MailException { + throw new UnsupportedOperationException("申し訳ございません。MockFetchMailProでは、このメソッドをサポートしていません。"); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#changeFolder(java.lang.String) + */ + public synchronized void changeFolder(String folderName) throws MailException { + if (!isConnected()) { + log.warn("メールサーバに接続されていません。"); + return; + } + + log.debug("メッセージフォルダ[" + folderName + "]をオープンするフリ。"); + log.debug("メッセージフォルダ[" + folderName + "]をオープンしたフリ。"); + } + + /** + * @see com.ozacc.mail.fetch.FetchMailPro#isConnected() + */ + public boolean isConnected() { + return connected; + } + + /** + * @return Returns the host. + */ + public String getHost() { + return host; + } + + /** + * @param host The host to set. + */ + public void setHost(String host) { + this.host = host; + } + + /** + * @return Returns the javaMailLogEnabled. + */ + public boolean isJavaMailLogEnabled() { + return javaMailLogEnabled; + } + + /** + * @param javaMailLogEnabled The javaMailLogEnabled to set. + */ + public void setJavaMailLogEnabled(boolean javaMailLogEnabled) { + this.javaMailLogEnabled = javaMailLogEnabled; + } + + /** + * @return Returns the password. + */ + public String getPassword() { + return password; + } + + /** + * @param password The password to set. + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return Returns the port. + */ + public int getPort() { + return port; + } + + /** + * @param port The port to set. + */ + public void setPort(int port) { + this.port = port; + } + + /** + * @return Returns the protocol. + */ + public String getProtocol() { + return protocol; + } + + /** + * @param protocol The protocol to set. + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return Returns the username. + */ + public String getUsername() { + return username; + } + + /** + * @param username The username to set. + */ + public void setUsername(String username) { + this.username = username; + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mock/MockMail.java b/src/main/java/com/ozacc/mail/mock/MockMail.java old mode 100755 new mode 100644 index 2e17eb9..eb813c4 --- a/src/main/java/com/ozacc/mail/mock/MockMail.java +++ b/src/main/java/com/ozacc/mail/mock/MockMail.java @@ -1,31 +1,31 @@ -package com.ozacc.mail.mock; - -import com.ozacc.mail.Mail; - -/** - * 値がセットされた項目だけ送信メールと比較する、MockSendMailでのテスト用Mailクラス。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MockMail.java,v 1.5 2004/09/16 04:52:45 otsuka Exp $ - */ -public class MockMail extends Mail { - - /** - * コンストラクタ。 - */ - public MockMail() {} - - /** - * コピーコンストラクタ。 - * シャローコピー(shallow copy)です。 - * - * @since 1.0.2 - * - * @param original コピー元のMailインスタンス - */ - public MockMail(Mail original) { - super(original); - } - +package com.ozacc.mail.mock; + +import com.ozacc.mail.Mail; + +/** + * 値がセットされた項目だけ送信メールと比較する、MockSendMailでのテスト用Mailクラス。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MockMail.java,v 1.5 2004/09/16 04:52:45 otsuka Exp $ + */ +public class MockMail extends Mail { + + /** + * コンストラクタ。 + */ + public MockMail() {} + + /** + * コピーコンストラクタ。 + * シャローコピー(shallow copy)です。 + * + * @since 1.0.2 + * + * @param original コピー元のMailインスタンス + */ + public MockMail(Mail original) { + super(original); + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mock/MockSendMail.java b/src/main/java/com/ozacc/mail/mock/MockSendMail.java old mode 100755 new mode 100644 index 29c52c7..f1c6b8e --- a/src/main/java/com/ozacc/mail/mock/MockSendMail.java +++ b/src/main/java/com/ozacc/mail/mock/MockSendMail.java @@ -1,536 +1,536 @@ -package com.ozacc.mail.mock; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.mail.MessagingException; -import javax.mail.Session; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeMessage; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.MailException; -import com.ozacc.mail.SendMail; -import com.ozacc.mail.impl.MimeMessageBuilder; - -/** - * SendMailImplクラスのMock。
- * 実存するSMTPサーバを設定しても、実際には送信されません。 - * デバッグモードを有効にすると、メールを送信するタイミングでコンソールに送信メール内容が出力されます。 - *

- * Mailインスタンスを addExpectedMail() にセットし verify() メソッドを実行すると、send() されたMailインスタンスと全てのプロパティ(XHeader、添付ファイルを除く)が一致しなければAssertionFailedExceptionがスローされます。 - *

- * 例えば、send() されたMailインスタンスのFromアドレスと件名だけチェックし、その他のプロパティはチェックしたくない場合は、MockMailインスタンスを使用します。 - *

Mail sentMail = new Mail();
- *sentMail.setFrom("from@example.com");
- *sentMail.setSubject("件名");
- *sentMail.addTo("to@example.com");
- *sentMail.setText("動的生成される本文");
- *
- *Mail expectedMail = new Mail();
- *expectedMail.setFrom("from@example.com");
- *expectedMail.setSubject("件名");
- *
- *MockMail mockMail = new MockMail();
- *mockMail.setFrom("from@example.com");
- *mockMail.setSubject("件名");
- *
- *MockSendMail sendMail = new MockSendMail();
- *sendMail.addExpectedMail(expectedMail);
- *sendMail.send(sentMail);
- *sendMail.verify(); // 失敗 AssertionFailedException
- *
- *sendMail = new MockSendMail();
- *sendMail.addExpectedMail(mockMail);
- *sendMail.send(sentMail);
- *sendMail.verify(); // 成功
- *

- * 注: 添付ファイルは比較対象になりません。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: MockSendMail.java,v 1.10.2.1 2004/11/25 08:01:47 otsuka Exp $ - */ -public class MockSendMail implements SendMail { - - /** デフォルトのプロトコル。「smtp」 */ - public static final String DEFAULT_PROTOCOL = "smtp"; - - /** デフォルトのポート。「-1」 */ - public static final int DEFAULT_PORT = -1; - - /** デフォルトのSMTPサーバ。「localhost」 */ - public static final String DEFAULT_HOST = "localhost"; - - /** ISO-2022-JP */ - public static final String JIS_CHARSET = "ISO-2022-JP"; - - private static final String RETURN_PATH_KEY = "mail.smtp.from"; - - private String protocol = DEFAULT_PROTOCOL; - - private String host = DEFAULT_HOST; - - private int port = DEFAULT_PORT; - - private String username; - - private String password; - - private String charset = JIS_CHARSET; - - private String returnPath; - - private List sentMails; - - private List mimeMessages; - - private List expectedMails; - - private boolean debug; - - /** - * コンストラクタ。 - */ - public MockSendMail() { - super(); - initialize(); - } - - /** - * MockSendMailインスタンスを初期化します。 - */ - public void initialize() { - sentMails = new ArrayList(); - expectedMails = new ArrayList(); - mimeMessages = new ArrayList(); - } - - /** - * 送信されたメールのMimeMessageインスタンスを返します。 - * 送信順の配列です。 - * - * @return 送信メールのMimeMessageインスタンス配列 - */ - public MimeMessage[] getMimeMessages() { - return (MimeMessage[])mimeMessages.toArray(new MimeMessage[mimeMessages.size()]); - } - - /** - * 送信されたMailインスタンスを返します。送信順の配列です。 - * - * @return 送信メールのMailインスタンス配列 - */ - public Mail[] getSentMails() { - return (Mail[])sentMails.toArray(new Mail[sentMails.size()]); - } - - /** - * デバッグモードが有効になっているか判定します。 - * - * @return Returns 有効になっている場合 true - */ - public boolean isDebug() { - return debug; - } - - /** - * デバッグモード(コンソールにログを出力)を有効にします。 - * デフォルトは無効です。 - * - * @param debug デバッグモードを有効にする場合 true - */ - public void setDebug(boolean debug) { - this.debug = debug; - } - - /** - * デバッグモードが有効のとき、指定されたメッセージをコンソールに出力します。 - * - * @param message コンソール出力するメッセージ - */ - private void debug(String message) { - if (debug) { - System.out.println("[" + Thread.currentThread().getName() + "] DEBUG " - + getClass().getName() + " - " + message); - } - } - - /** - * - * @param expectedMail - */ - public void addExpectedMail(Mail expectedMail) { - expectedMails.add(expectedMail); - } - - /** - * - * @param expectedMails - */ - public void addExpectedMail(Mail[] expectedMails) { - for (int i = 0; i < expectedMails.length; i++) { - addExpectedMail(expectedMails[i]); - } - } - - /** - * - * @throws AssertionFailedException - */ - public void verify() throws AssertionFailedException { - debug("======================================================"); - debug(" verify() "); - debug("======================================================"); - - // メールの数を比較 - int numOfExpectedMails = expectedMails.size(); - int numOfSentMails = sentMails.size(); - if (numOfExpectedMails != numOfSentMails) { - throw new AssertionFailedException("期待メール数<" + numOfExpectedMails + ">と送信メール数<" - + numOfSentMails + ">が一致しませんでした。"); - } - - debug("期待メール数と送信メール数は一致しました。[" + numOfExpectedMails + "通]"); - - // メール内容を比較 - for (int i = 0; i < numOfExpectedMails; i++) { - Mail expected = (Mail)expectedMails.get(i); - Mail sent = (Mail)sentMails.get(i); - debug((i + 1) + "通目のチェックを開始します。(" - + ((expected instanceof MockMail) ? "MockMail" : "Mail") + " - Mail)"); - checkEquality(expected, sent, i + 1); - debug((i + 1) + "通目の期待メールと送信メール内容は一致しました。"); - } - - debug("verifyプロセスは全て成功しました。"); - debug("======================================================"); - } - - /** - * @param expected - * @param sent - * @throws AssertionFailedException - */ - public void checkEquality(Mail expected, Mail sent, int num) throws AssertionFailedException { - boolean mockMode = (expected instanceof MockMail); - - // マルチパートメールの場合 - if (expected.isMultipartMail()) { - - // HTML - if (!mockMode) { - if ((expected.getHtmlText() == null && sent.getHtmlText() != null) - || (expected.getHtmlText() != null && sent.getHtmlText() == null) - || (!expected.getHtmlText().equals(sent.getHtmlText()))) { - throwExceptioWithMessage("HTML本文", expected.getHtmlText(), sent.getHtmlText(), - num); - } - } else if (mockMode && expected.getHtmlText() != null) { - if (!expected.getHtmlText().equals(sent.getHtmlText())) { - throwExceptioWithMessage("HTML本文", expected.getHtmlText(), sent.getHtmlText(), - num); - } - } - } - - // Return-Path - if (!mockMode || (mockMode && expected.getReturnPath() != null)) { - if (expected.getReturnPath() != null && sent.getReturnPath() != null) { - if (!expected.getReturnPath().equals(sent.getReturnPath())) { - throwExceptioWithMessage("Return-Pathアドレス", expected.getReturnPath() - .toUnicodeString(), sent.getReturnPath().toUnicodeString(), num); - } - } else if ((expected.getReturnPath() != null && sent.getReturnPath() == null) - || (expected.getReturnPath() == null && sent.getReturnPath() != null)) { - throw new AssertionFailedException(); - } - } - - // From - if (!mockMode || (mockMode && expected.getFrom() != null)) { - if (expected.getFrom() != null && sent.getFrom() != null) { - if (!EqualityCheck.equals(expected.getFrom(), sent.getFrom())) { - throwExceptioWithMessage("Fromアドレス", expected.getFrom().toUnicodeString(), sent - .getFrom().toUnicodeString(), num); - } - } else if ((expected.getFrom() != null && sent.getFrom() == null) - || (expected.getFrom() == null && sent.getFrom() != null)) { - throw new AssertionFailedException(); - } - } - - // to - InternetAddress[] expectedAddresses = expected.getTo(); - InternetAddress[] sentAddresses = sent.getTo(); - if (!mockMode || (mockMode && expectedAddresses.length > 0)) { - if (expectedAddresses.length != sentAddresses.length) { - throwExceptioWithMessage("Toアドレス数", Integer.toString(expectedAddresses.length), - Integer.toString(sentAddresses.length), num); - } - for (int i = 0; i < expectedAddresses.length; i++) { - if (!EqualityCheck.equals(expectedAddresses[i], sentAddresses[i])) { - throwExceptioWithMessage("Toアドレス", expectedAddresses[i].toUnicodeString(), - sentAddresses[i].toUnicodeString(), num); - } - } - } - - // cc - expectedAddresses = expected.getCc(); - sentAddresses = sent.getCc(); - if (!mockMode || (mockMode && expectedAddresses.length > 0)) { - if (expectedAddresses.length != sentAddresses.length) { - throwExceptioWithMessage("Ccアドレス数", Integer.toString(expectedAddresses.length), - Integer.toString(sentAddresses.length), num); - } - for (int i = 0; i < expectedAddresses.length; i++) { - if (!EqualityCheck.equals(expectedAddresses[i], sentAddresses[i])) { - throwExceptioWithMessage("Ccアドレス", expectedAddresses[i].toUnicodeString(), - sentAddresses[i].toUnicodeString(), num); - } - } - } - - // bcc - expectedAddresses = expected.getBcc(); - sentAddresses = sent.getBcc(); - if (!mockMode || (mockMode && expectedAddresses.length > 0)) { - if (expectedAddresses.length != sentAddresses.length) { - throwExceptioWithMessage("Bccアドレス数", Integer.toString(expectedAddresses.length), - Integer.toString(sentAddresses.length), num); - } - for (int i = 0; i < expectedAddresses.length; i++) { - if (!EqualityCheck.equals(expectedAddresses[i], sentAddresses[i])) { - throwExceptioWithMessage("Bccアドレス", expectedAddresses[i].toUnicodeString(), - sentAddresses[i].toUnicodeString(), num); - } - } - } - - // Reply-To - if (!mockMode || (mockMode && expected.getReplyTo() != null)) { - if (expected.getReplyTo() != null && sent.getReplyTo() != null) { - if (!EqualityCheck.equals(expected.getReplyTo(), sent.getReplyTo())) { - throwExceptioWithMessage("ReplyToアドレス", - expected.getReplyTo().toUnicodeString(), sent.getReplyTo() - .toUnicodeString(), num); - } - } else if ((expected.getReplyTo() != null && sent.getReplyTo() == null) - || (expected.getReplyTo() == null && sent.getReplyTo() != null)) { - throw new AssertionFailedException(); - } - } - - // 件名 - if (!mockMode || (mockMode && expected.getSubject().length() > 0)) { - if (!expected.getSubject().equals(sent.getSubject())) { - throwExceptioWithMessage("件名", expected.getSubject(), sent.getSubject(), num); - } - } - - // 本文 - if (!mockMode || (mockMode && expected.getText().length() > 0)) { - if (!expected.getText().equals(sent.getText())) { - throwExceptioWithMessage("本文", expected.getText(), sent.getText(), num); - } - } - - } - - /** - * 引数の値を受けてエラーメッセージを生成し、AssertionFailedErrorをスローします。 - * - * @param name 一致しなかった項目名 - * @param expectedValue 期待値 - * @param sentValue 実際値 - * @param num N番目のメール - * @throws AssertionFailedException 生成された例外 - */ - protected void throwExceptioWithMessage(String name, String expectedValue, String sentValue, - int num) throws AssertionFailedException { - String message = num + "番目のメッセージで、「" + name + "」が一致しませんでした。期待値='" + expectedValue - + "', 送信値='" + sentValue + "'"; - - debug(message); - debug("verifyプロセスは失敗しました。"); - debug("******************************************************"); - - throw new AssertionFailedException(message); - } - - /** - * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail) - */ - public void send(Mail mail) throws MailException { - send(new Mail[] { mail }); - } - - /** - * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail[]) - */ - public void send(Mail[] mails) throws MailException { - debug("SMTPサーバ[" + host + "]に接続するフリ。"); - debug("SMTPサーバ[" + host + "]に接続したフリ。"); - - Session session = Session.getInstance(new Properties()); - for (int i = 0; i < mails.length; i++) { - - Mail mail = mails[i]; - - // MimeMessageを生成 - MimeMessage message = new MimeMessage(session); - MimeMessageBuilder builder = new MimeMessageBuilder(message); - try { - builder.buildMimeMessage(mail); - } catch (UnsupportedEncodingException e) { - throw new MailBuildException("サポートされていない文字コードが指定されました。", e); - } catch (MessagingException e) { - throw new MailBuildException("MimeMessageの生成に失敗しました。", e); - } - mimeMessages.add(message); - - debug("メールを送信するフリ。"); - sentMails.add(mail); - debug(mail.toString()); - debug("メールを送信したフリ。"); - } - - debug("SMTPサーバ[" + host + "]との接続を切断するフリ。"); - debug("SMTPサーバ[" + host + "]との接続を切断したフリ。"); - } - - /** - * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage) - */ - public void send(MimeMessage mimeMessage) throws MailException { - throw new UnsupportedOperationException("申し訳ございません。MockSendMailでは、このメソッドをサポートしていません。"); - } - - /** - * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage[]) - */ - public void send(MimeMessage[] mimeMessages) throws MailException { - throw new UnsupportedOperationException("申し訳ございません。MockSendMailでは、このメソッドをサポートしていません。"); - } - - /** - * エンコーディングに使用する文字コードを返します。 - * - * @return エンコーディングに使用する文字コード - */ - public String getCharset() { - return charset; - } - - /** - * メールの件名や本文のエンコーディングに使用する文字コードを指定します。 - * デフォルトは ISO-2022-JP です。 - * - * @param charset エンコーディングに使用する文字コード - */ - public void setCharset(String charset) { - this.charset = charset; - } - - /** - * セットされたSMTPサーバのホスト名、またはIPアドレスを返します。 - * - * @return SMTPサーバのホスト名、またはIPアドレス - */ - public String getHost() { - return host; - } - - /** - * SMTPサーバのホスト名、またはIPアドレスをセットします。 - * デフォルトは localhost です。 - * - * @param host SMTPサーバのホスト名、またはIPアドレス - */ - public void setHost(String host) { - this.host = host; - } - - /** - * @return SMTPサーバ認証パスワード - */ - public String getPassword() { - return password; - } - - /** - * SMTPサーバの接続認証が必要な場合にパスワードをセットします。 - * - * @param password SMTPサーバ認証パスワード - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * @return SMTPサーバのポート番号 - */ - public int getPort() { - return port; - } - - /** - * SMTPサーバのポート番号をセットします。 - * - * @param port SMTPサーバのポート番号 - */ - public void setPort(int port) { - this.port = port; - } - - /** - * @return Returns the protocol. - */ - public String getProtocol() { - return protocol; - } - - /** - * @param protocol The protocol to set. - */ - public void setProtocol(String protocol) { - this.protocol = protocol; - } - - /** - * @return Return-Pathアドレス - */ - public String getReturnPath() { - return returnPath; - } - - /** - * Return-Pathアドレスをセットします。 - * - * @param returnPath Return-Pathアドレス - */ - public void setReturnPath(String returnPath) { - this.returnPath = returnPath; - } - - /** - * @return SMTPサーバ認証ユーザ名 - */ - public String getUsername() { - return username; - } - - /** - * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。 - * - * @param username SMTPサーバ認証ユーザ名 - */ - public void setUsername(String username) { - this.username = username; - } - +package com.ozacc.mail.mock; + +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +import javax.mail.MessagingException; +import javax.mail.Session; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.MailException; +import com.ozacc.mail.SendMail; +import com.ozacc.mail.impl.MimeMessageBuilder; + +/** + * SendMailImplクラスのMock。
+ * 実存するSMTPサーバを設定しても、実際には送信されません。 + * デバッグモードを有効にすると、メールを送信するタイミングでコンソールに送信メール内容が出力されます。 + *

+ * Mailインスタンスを addExpectedMail() にセットし verify() メソッドを実行すると、send() されたMailインスタンスと全てのプロパティ(XHeader、添付ファイルを除く)が一致しなければAssertionFailedExceptionがスローされます。 + *

+ * 例えば、send() されたMailインスタンスのFromアドレスと件名だけチェックし、その他のプロパティはチェックしたくない場合は、MockMailインスタンスを使用します。 + *

Mail sentMail = new Mail();
+ *sentMail.setFrom("from@example.com");
+ *sentMail.setSubject("件名");
+ *sentMail.addTo("to@example.com");
+ *sentMail.setText("動的生成される本文");
+ *
+ *Mail expectedMail = new Mail();
+ *expectedMail.setFrom("from@example.com");
+ *expectedMail.setSubject("件名");
+ *
+ *MockMail mockMail = new MockMail();
+ *mockMail.setFrom("from@example.com");
+ *mockMail.setSubject("件名");
+ *
+ *MockSendMail sendMail = new MockSendMail();
+ *sendMail.addExpectedMail(expectedMail);
+ *sendMail.send(sentMail);
+ *sendMail.verify(); // 失敗 AssertionFailedException
+ *
+ *sendMail = new MockSendMail();
+ *sendMail.addExpectedMail(mockMail);
+ *sendMail.send(sentMail);
+ *sendMail.verify(); // 成功
+ *

+ * 注: 添付ファイルは比較対象になりません。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: MockSendMail.java,v 1.10.2.1 2004/11/25 08:01:47 otsuka Exp $ + */ +public class MockSendMail implements SendMail { + + /** デフォルトのプロトコル。「smtp」 */ + public static final String DEFAULT_PROTOCOL = "smtp"; + + /** デフォルトのポート。「-1」 */ + public static final int DEFAULT_PORT = -1; + + /** デフォルトのSMTPサーバ。「localhost」 */ + public static final String DEFAULT_HOST = "localhost"; + + /** ISO-2022-JP */ + public static final String JIS_CHARSET = "ISO-2022-JP"; + + private static final String RETURN_PATH_KEY = "mail.smtp.from"; + + private String protocol = DEFAULT_PROTOCOL; + + private String host = DEFAULT_HOST; + + private int port = DEFAULT_PORT; + + private String username; + + private String password; + + private String charset = JIS_CHARSET; + + private String returnPath; + + private List sentMails; + + private List mimeMessages; + + private List expectedMails; + + private boolean debug; + + /** + * コンストラクタ。 + */ + public MockSendMail() { + super(); + initialize(); + } + + /** + * MockSendMailインスタンスを初期化します。 + */ + public void initialize() { + sentMails = new ArrayList(); + expectedMails = new ArrayList(); + mimeMessages = new ArrayList(); + } + + /** + * 送信されたメールのMimeMessageインスタンスを返します。 + * 送信順の配列です。 + * + * @return 送信メールのMimeMessageインスタンス配列 + */ + public MimeMessage[] getMimeMessages() { + return (MimeMessage[])mimeMessages.toArray(new MimeMessage[mimeMessages.size()]); + } + + /** + * 送信されたMailインスタンスを返します。送信順の配列です。 + * + * @return 送信メールのMailインスタンス配列 + */ + public Mail[] getSentMails() { + return (Mail[])sentMails.toArray(new Mail[sentMails.size()]); + } + + /** + * デバッグモードが有効になっているか判定します。 + * + * @return Returns 有効になっている場合 true + */ + public boolean isDebug() { + return debug; + } + + /** + * デバッグモード(コンソールにログを出力)を有効にします。 + * デフォルトは無効です。 + * + * @param debug デバッグモードを有効にする場合 true + */ + public void setDebug(boolean debug) { + this.debug = debug; + } + + /** + * デバッグモードが有効のとき、指定されたメッセージをコンソールに出力します。 + * + * @param message コンソール出力するメッセージ + */ + private void debug(String message) { + if (debug) { + System.out.println("[" + Thread.currentThread().getName() + "] DEBUG " + + getClass().getName() + " - " + message); + } + } + + /** + * + * @param expectedMail + */ + public void addExpectedMail(Mail expectedMail) { + expectedMails.add(expectedMail); + } + + /** + * + * @param expectedMails + */ + public void addExpectedMail(Mail[] expectedMails) { + for (int i = 0; i < expectedMails.length; i++) { + addExpectedMail(expectedMails[i]); + } + } + + /** + * + * @throws AssertionFailedException + */ + public void verify() throws AssertionFailedException { + debug("======================================================"); + debug(" verify() "); + debug("======================================================"); + + // メールの数を比較 + int numOfExpectedMails = expectedMails.size(); + int numOfSentMails = sentMails.size(); + if (numOfExpectedMails != numOfSentMails) { + throw new AssertionFailedException("期待メール数<" + numOfExpectedMails + ">と送信メール数<" + + numOfSentMails + ">が一致しませんでした。"); + } + + debug("期待メール数と送信メール数は一致しました。[" + numOfExpectedMails + "通]"); + + // メール内容を比較 + for (int i = 0; i < numOfExpectedMails; i++) { + Mail expected = (Mail)expectedMails.get(i); + Mail sent = (Mail)sentMails.get(i); + debug((i + 1) + "通目のチェックを開始します。(" + + ((expected instanceof MockMail) ? "MockMail" : "Mail") + " - Mail)"); + checkEquality(expected, sent, i + 1); + debug((i + 1) + "通目の期待メールと送信メール内容は一致しました。"); + } + + debug("verifyプロセスは全て成功しました。"); + debug("======================================================"); + } + + /** + * @param expected + * @param sent + * @throws AssertionFailedException + */ + public void checkEquality(Mail expected, Mail sent, int num) throws AssertionFailedException { + boolean mockMode = (expected instanceof MockMail); + + // マルチパートメールの場合 + if (expected.isMultipartMail()) { + + // HTML + if (!mockMode) { + if ((expected.getHtmlText() == null && sent.getHtmlText() != null) + || (expected.getHtmlText() != null && sent.getHtmlText() == null) + || (!expected.getHtmlText().equals(sent.getHtmlText()))) { + throwExceptioWithMessage("HTML本文", expected.getHtmlText(), sent.getHtmlText(), + num); + } + } else if (mockMode && expected.getHtmlText() != null) { + if (!expected.getHtmlText().equals(sent.getHtmlText())) { + throwExceptioWithMessage("HTML本文", expected.getHtmlText(), sent.getHtmlText(), + num); + } + } + } + + // Return-Path + if (!mockMode || (mockMode && expected.getReturnPath() != null)) { + if (expected.getReturnPath() != null && sent.getReturnPath() != null) { + if (!expected.getReturnPath().equals(sent.getReturnPath())) { + throwExceptioWithMessage("Return-Pathアドレス", expected.getReturnPath() + .toUnicodeString(), sent.getReturnPath().toUnicodeString(), num); + } + } else if ((expected.getReturnPath() != null && sent.getReturnPath() == null) + || (expected.getReturnPath() == null && sent.getReturnPath() != null)) { + throw new AssertionFailedException(); + } + } + + // From + if (!mockMode || (mockMode && expected.getFrom() != null)) { + if (expected.getFrom() != null && sent.getFrom() != null) { + if (!EqualityCheck.equals(expected.getFrom(), sent.getFrom())) { + throwExceptioWithMessage("Fromアドレス", expected.getFrom().toUnicodeString(), sent + .getFrom().toUnicodeString(), num); + } + } else if ((expected.getFrom() != null && sent.getFrom() == null) + || (expected.getFrom() == null && sent.getFrom() != null)) { + throw new AssertionFailedException(); + } + } + + // to + InternetAddress[] expectedAddresses = expected.getTo(); + InternetAddress[] sentAddresses = sent.getTo(); + if (!mockMode || (mockMode && expectedAddresses.length > 0)) { + if (expectedAddresses.length != sentAddresses.length) { + throwExceptioWithMessage("Toアドレス数", Integer.toString(expectedAddresses.length), + Integer.toString(sentAddresses.length), num); + } + for (int i = 0; i < expectedAddresses.length; i++) { + if (!EqualityCheck.equals(expectedAddresses[i], sentAddresses[i])) { + throwExceptioWithMessage("Toアドレス", expectedAddresses[i].toUnicodeString(), + sentAddresses[i].toUnicodeString(), num); + } + } + } + + // cc + expectedAddresses = expected.getCc(); + sentAddresses = sent.getCc(); + if (!mockMode || (mockMode && expectedAddresses.length > 0)) { + if (expectedAddresses.length != sentAddresses.length) { + throwExceptioWithMessage("Ccアドレス数", Integer.toString(expectedAddresses.length), + Integer.toString(sentAddresses.length), num); + } + for (int i = 0; i < expectedAddresses.length; i++) { + if (!EqualityCheck.equals(expectedAddresses[i], sentAddresses[i])) { + throwExceptioWithMessage("Ccアドレス", expectedAddresses[i].toUnicodeString(), + sentAddresses[i].toUnicodeString(), num); + } + } + } + + // bcc + expectedAddresses = expected.getBcc(); + sentAddresses = sent.getBcc(); + if (!mockMode || (mockMode && expectedAddresses.length > 0)) { + if (expectedAddresses.length != sentAddresses.length) { + throwExceptioWithMessage("Bccアドレス数", Integer.toString(expectedAddresses.length), + Integer.toString(sentAddresses.length), num); + } + for (int i = 0; i < expectedAddresses.length; i++) { + if (!EqualityCheck.equals(expectedAddresses[i], sentAddresses[i])) { + throwExceptioWithMessage("Bccアドレス", expectedAddresses[i].toUnicodeString(), + sentAddresses[i].toUnicodeString(), num); + } + } + } + + // Reply-To + if (!mockMode || (mockMode && expected.getReplyTo() != null)) { + if (expected.getReplyTo() != null && sent.getReplyTo() != null) { + if (!EqualityCheck.equals(expected.getReplyTo(), sent.getReplyTo())) { + throwExceptioWithMessage("ReplyToアドレス", + expected.getReplyTo().toUnicodeString(), sent.getReplyTo() + .toUnicodeString(), num); + } + } else if ((expected.getReplyTo() != null && sent.getReplyTo() == null) + || (expected.getReplyTo() == null && sent.getReplyTo() != null)) { + throw new AssertionFailedException(); + } + } + + // 件名 + if (!mockMode || (mockMode && expected.getSubject().length() > 0)) { + if (!expected.getSubject().equals(sent.getSubject())) { + throwExceptioWithMessage("件名", expected.getSubject(), sent.getSubject(), num); + } + } + + // 本文 + if (!mockMode || (mockMode && expected.getText().length() > 0)) { + if (!expected.getText().equals(sent.getText())) { + throwExceptioWithMessage("本文", expected.getText(), sent.getText(), num); + } + } + + } + + /** + * 引数の値を受けてエラーメッセージを生成し、AssertionFailedErrorをスローします。 + * + * @param name 一致しなかった項目名 + * @param expectedValue 期待値 + * @param sentValue 実際値 + * @param num N番目のメール + * @throws AssertionFailedException 生成された例外 + */ + protected void throwExceptioWithMessage(String name, String expectedValue, String sentValue, + int num) throws AssertionFailedException { + String message = num + "番目のメッセージで、「" + name + "」が一致しませんでした。期待値='" + expectedValue + + "', 送信値='" + sentValue + "'"; + + debug(message); + debug("verifyプロセスは失敗しました。"); + debug("******************************************************"); + + throw new AssertionFailedException(message); + } + + /** + * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail) + */ + public void send(Mail mail) throws MailException { + send(new Mail[] { mail }); + } + + /** + * @see com.ozacc.mail.SendMail#send(com.ozacc.mail.Mail[]) + */ + public void send(Mail[] mails) throws MailException { + debug("SMTPサーバ[" + host + "]に接続するフリ。"); + debug("SMTPサーバ[" + host + "]に接続したフリ。"); + + Session session = Session.getInstance(new Properties()); + for (int i = 0; i < mails.length; i++) { + + Mail mail = mails[i]; + + // MimeMessageを生成 + MimeMessage message = new MimeMessage(session); + MimeMessageBuilder builder = new MimeMessageBuilder(message); + try { + builder.buildMimeMessage(mail); + } catch (UnsupportedEncodingException e) { + throw new MailBuildException("サポートされていない文字コードが指定されました。", e); + } catch (MessagingException e) { + throw new MailBuildException("MimeMessageの生成に失敗しました。", e); + } + mimeMessages.add(message); + + debug("メールを送信するフリ。"); + sentMails.add(mail); + debug(mail.toString()); + debug("メールを送信したフリ。"); + } + + debug("SMTPサーバ[" + host + "]との接続を切断するフリ。"); + debug("SMTPサーバ[" + host + "]との接続を切断したフリ。"); + } + + /** + * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage) + */ + public void send(MimeMessage mimeMessage) throws MailException { + throw new UnsupportedOperationException("申し訳ございません。MockSendMailでは、このメソッドをサポートしていません。"); + } + + /** + * @see com.ozacc.mail.SendMail#send(javax.mail.internet.MimeMessage[]) + */ + public void send(MimeMessage[] mimeMessages) throws MailException { + throw new UnsupportedOperationException("申し訳ございません。MockSendMailでは、このメソッドをサポートしていません。"); + } + + /** + * エンコーディングに使用する文字コードを返します。 + * + * @return エンコーディングに使用する文字コード + */ + public String getCharset() { + return charset; + } + + /** + * メールの件名や本文のエンコーディングに使用する文字コードを指定します。 + * デフォルトは ISO-2022-JP です。 + * + * @param charset エンコーディングに使用する文字コード + */ + public void setCharset(String charset) { + this.charset = charset; + } + + /** + * セットされたSMTPサーバのホスト名、またはIPアドレスを返します。 + * + * @return SMTPサーバのホスト名、またはIPアドレス + */ + public String getHost() { + return host; + } + + /** + * SMTPサーバのホスト名、またはIPアドレスをセットします。 + * デフォルトは localhost です。 + * + * @param host SMTPサーバのホスト名、またはIPアドレス + */ + public void setHost(String host) { + this.host = host; + } + + /** + * @return SMTPサーバ認証パスワード + */ + public String getPassword() { + return password; + } + + /** + * SMTPサーバの接続認証が必要な場合にパスワードをセットします。 + * + * @param password SMTPサーバ認証パスワード + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * @return SMTPサーバのポート番号 + */ + public int getPort() { + return port; + } + + /** + * SMTPサーバのポート番号をセットします。 + * + * @param port SMTPサーバのポート番号 + */ + public void setPort(int port) { + this.port = port; + } + + /** + * @return Returns the protocol. + */ + public String getProtocol() { + return protocol; + } + + /** + * @param protocol The protocol to set. + */ + public void setProtocol(String protocol) { + this.protocol = protocol; + } + + /** + * @return Return-Pathアドレス + */ + public String getReturnPath() { + return returnPath; + } + + /** + * Return-Pathアドレスをセットします。 + * + * @param returnPath Return-Pathアドレス + */ + public void setReturnPath(String returnPath) { + this.returnPath = returnPath; + } + + /** + * @return SMTPサーバ認証ユーザ名 + */ + public String getUsername() { + return username; + } + + /** + * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。 + * + * @param username SMTPサーバ認証ユーザ名 + */ + public void setUsername(String username) { + this.username = username; + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/mock/package.html b/src/main/java/com/ozacc/mail/mock/package.html old mode 100755 new mode 100644 index 1f2c878..fb80598 --- a/src/main/java/com/ozacc/mail/mock/package.html +++ b/src/main/java/com/ozacc/mail/mock/package.html @@ -1,5 +1,5 @@ - - -SendMail¤Î¥â¥Ã¥¯¼ÂÁõ¥¯¥é¥¹¤Ç¤¹¡£ - + + +SendMailのモック実装クラスです。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/ozacc-mail.dtd b/src/main/java/com/ozacc/mail/ozacc-mail.dtd old mode 100755 new mode 100644 index 4dab370..02416b7 --- a/src/main/java/com/ozacc/mail/ozacc-mail.dtd +++ b/src/main/java/com/ozacc/mail/ozacc-mail.dtd @@ -1,59 +1,59 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/ozacc/mail/ozacc-multiple-mails.dtd b/src/main/java/com/ozacc/mail/ozacc-multiple-mails.dtd old mode 100755 new mode 100644 index 9ec85a3..1f736b4 --- a/src/main/java/com/ozacc/mail/ozacc-multiple-mails.dtd +++ b/src/main/java/com/ozacc/mail/ozacc-multiple-mails.dtd @@ -1,64 +1,64 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/ozacc/mail/package.html b/src/main/java/com/ozacc/mail/package.html old mode 100755 new mode 100644 index b9d7581..10c0f8d --- a/src/main/java/com/ozacc/mail/package.html +++ b/src/main/java/com/ozacc/mail/package.html @@ -1,5 +1,5 @@ - - -¥á¡¼¥ë¤ÎÁ÷¿®¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤È¡¢XML¥É¥­¥å¥á¥ó¥È¤«¤é¥á¡¼¥ë¤òÀ¸À®¤¹¤ë¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤òÄ󶡤·¤Þ¤¹¡£ - + + +メールの送信インターフェースと、XMLドキュメントからメールを生成するインターフェースを提供します。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/spring/MailetRunnerJob.java b/src/main/java/com/ozacc/mail/spring/MailetRunnerJob.java old mode 100755 new mode 100644 index e7593ce..7bced28 --- a/src/main/java/com/ozacc/mail/spring/MailetRunnerJob.java +++ b/src/main/java/com/ozacc/mail/spring/MailetRunnerJob.java @@ -1,85 +1,85 @@ -package com.ozacc.mail.spring; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.quartz.JobExecutionContext; -import org.quartz.JobExecutionException; -import org.springframework.scheduling.quartz.QuartzJobBean; - -import com.ozacc.mail.fetch.FetchMailPro; -import com.ozacc.mail.fetch.ReceivedMail; -import com.ozacc.mail.mailet.MailetWrapper; - -/** - * Spring FrameworkのQuartz実行用MailetRunner。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: MailetRunnerJob.java,v 1.1.2.3 2005/01/23 06:47:16 otsuka Exp $ - */ -public class MailetRunnerJob extends QuartzJobBean { - - private List mailetWrapperList; - - private FetchMailPro fetchMailPro; - - /** - * コンストラクタ。 - */ - public MailetRunnerJob() { - mailetWrapperList = new ArrayList(); - } - - /** - * メール受信とMailetの起動を行います。 - * - * @see org.springframework.scheduling.quartz.QuartzJobBean#executeInternal(org.quartz.JobExecutionContext) - */ - protected void executeInternal(JobExecutionContext context) throws JobExecutionException { - fetchMailPro.connect(); - try { - int count = fetchMailPro.getMailCount(); - for (int i = 1; i <= count; i++) { - ReceivedMail mail = fetchMailPro.getMail(i); - processMail(mail); - } - } finally { - if (fetchMailPro.isConnected()) { - fetchMailPro.disconnect(); - } - } - } - - /** - * 指定された受信メールに対してMailetを適用します。 - * - * @param mail MailetUnitに渡す受信メール - */ - private void processMail(ReceivedMail mail) { - for (Iterator itr = mailetWrapperList.iterator(); itr.hasNext();) { - MailetWrapper mailetWrapper = (MailetWrapper)itr.next(); - mailetWrapper.execute(mail); - } - } - - /** - * メールの受信に使用するFetchMailProインターフェースの実装インスタンスをセットします。 - * - * @param fetchMailPro FetchMailProインターフェースの実装インスタンス - */ - public void setFetchMailPro(FetchMailPro fetchMailPro) { - this.fetchMailPro = fetchMailPro; - } - - /** - * 実行するMailetのMailetWrapperリストをセットします。 - * - * @param mailetWrapperList 実行するMailetのMailetWrapperリスト - */ - public void setMailetWrapperList(List mailetWrapperList) { - this.mailetWrapperList = mailetWrapperList; - } - +package com.ozacc.mail.spring; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.quartz.JobExecutionContext; +import org.quartz.JobExecutionException; +import org.springframework.scheduling.quartz.QuartzJobBean; + +import com.ozacc.mail.fetch.FetchMailPro; +import com.ozacc.mail.fetch.ReceivedMail; +import com.ozacc.mail.mailet.MailetWrapper; + +/** + * Spring FrameworkのQuartz実行用MailetRunner。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: MailetRunnerJob.java,v 1.1.2.3 2005/01/23 06:47:16 otsuka Exp $ + */ +public class MailetRunnerJob extends QuartzJobBean { + + private List mailetWrapperList; + + private FetchMailPro fetchMailPro; + + /** + * コンストラクタ。 + */ + public MailetRunnerJob() { + mailetWrapperList = new ArrayList(); + } + + /** + * メール受信とMailetの起動を行います。 + * + * @see org.springframework.scheduling.quartz.QuartzJobBean#executeInternal(org.quartz.JobExecutionContext) + */ + protected void executeInternal(JobExecutionContext context) throws JobExecutionException { + fetchMailPro.connect(); + try { + int count = fetchMailPro.getMailCount(); + for (int i = 1; i <= count; i++) { + ReceivedMail mail = fetchMailPro.getMail(i); + processMail(mail); + } + } finally { + if (fetchMailPro.isConnected()) { + fetchMailPro.disconnect(); + } + } + } + + /** + * 指定された受信メールに対してMailetを適用します。 + * + * @param mail MailetUnitに渡す受信メール + */ + private void processMail(ReceivedMail mail) { + for (Iterator itr = mailetWrapperList.iterator(); itr.hasNext();) { + MailetWrapper mailetWrapper = (MailetWrapper)itr.next(); + mailetWrapper.execute(mail); + } + } + + /** + * メールの受信に使用するFetchMailProインターフェースの実装インスタンスをセットします。 + * + * @param fetchMailPro FetchMailProインターフェースの実装インスタンス + */ + public void setFetchMailPro(FetchMailPro fetchMailPro) { + this.fetchMailPro = fetchMailPro; + } + + /** + * 実行するMailetのMailetWrapperリストをセットします。 + * + * @param mailetWrapperList 実行するMailetのMailetWrapperリスト + */ + public void setMailetWrapperList(List mailetWrapperList) { + this.mailetWrapperList = mailetWrapperList; + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/spring/XMLMailFactoryBean.java b/src/main/java/com/ozacc/mail/spring/XMLMailFactoryBean.java old mode 100755 new mode 100644 index 5b54331..0a7ffee --- a/src/main/java/com/ozacc/mail/spring/XMLMailFactoryBean.java +++ b/src/main/java/com/ozacc/mail/spring/XMLMailFactoryBean.java @@ -1,131 +1,131 @@ -package com.ozacc.mail.spring; - -import java.io.File; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.springframework.core.io.Resource; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.MailBuilder; -import com.ozacc.mail.impl.XMLMailBuilderImpl; - -/** - * Springの設定ファイルで指定されたロケーションのXMLファイルからMailインスタンスを生成するFactoryBean。 - * デフォルトでは、singletonプロパティはfalseに設定されます。 - *

- * location、classPath、filePathの順で、一番先にセットされているプロパティ値がXMLファイルのパスとして使われます。 - * - * @see com.ozacc.mail.impl.XMLMailBuilderImpl - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: XMLMailFactoryBean.java,v 1.4 2004/09/13 19:48:16 otsuka Exp $ - */ -public class XMLMailFactoryBean extends AbstractFactoryBean { - - private String classPath; - - private String filePath; - - private Resource location; - - private MailBuilder mailBuilder; - - /** - * コンストラクタ。 - */ - public XMLMailFactoryBean() { - setSingleton(false); - } - - /** - * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() - */ - protected Object createInstance() throws Exception { - if (mailBuilder == null) { - init(); - } - - if (getLocation() != null && getLocation().getFile() != null) { - return mailBuilder.buildMail(getLocation().getFile()); - } - if (getClassPath() != null) { - return mailBuilder.buildMail(getClassPath()); - } - if (getFilePath() != null) { - return mailBuilder.buildMail(new File(getFilePath())); - } - throw new MailBuildException("Mailインスタンスの生成に失敗しました。XMLデータのロケーションが指定されていません。"); - } - - /** - * mailBuilderインスタンスを生成します。 - */ - private void init() { - mailBuilder = new XMLMailBuilderImpl(); - } - - /** - * @see org.springframework.beans.factory.FactoryBean#getObjectType() - */ - public Class getObjectType() { - return Mail.class; - } - - /** - * MailBuilderインターフェースの実装クラスのインスタンスをセットします。 - * デフォルトでは、XMLMailBuilderImplが使用されます。 - *

- * ただし、ここでセットしない場合は、XMLMailFactoryBeanひとつに付き、 - * XMLMailBuilderImplインスタンス一つが保持されます。 - * シングルトンのMailBuilderインスタンスをセットすることを推奨します。 - * - * @param mailBuilder MailBuilderインスタンス - */ - public void setMailBuilder(MailBuilder mailBuilder) { - this.mailBuilder = mailBuilder; - } - - /** - * @return Returns the classPath. - */ - public String getClassPath() { - return classPath; - } - - /** - * @param classPath The classPath to set. - */ - public void setClassPath(String classPath) { - this.classPath = classPath; - } - - /** - * @return Returns the filePath. - */ - public String getFilePath() { - return filePath; - } - - /** - * @param filePath The filePath to set. - */ - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - /** - * @return Returns the location. - */ - public Resource getLocation() { - return location; - } - - /** - * @param location The location to set. - */ - public void setLocation(Resource location) { - this.location = location; - } +package com.ozacc.mail.spring; + +import java.io.File; + +import org.springframework.beans.factory.config.AbstractFactoryBean; +import org.springframework.core.io.Resource; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.MailBuilder; +import com.ozacc.mail.impl.XMLMailBuilderImpl; + +/** + * Springの設定ファイルで指定されたロケーションのXMLファイルからMailインスタンスを生成するFactoryBean。 + * デフォルトでは、singletonプロパティはfalseに設定されます。 + *

+ * location、classPath、filePathの順で、一番先にセットされているプロパティ値がXMLファイルのパスとして使われます。 + * + * @see com.ozacc.mail.impl.XMLMailBuilderImpl + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: XMLMailFactoryBean.java,v 1.4 2004/09/13 19:48:16 otsuka Exp $ + */ +public class XMLMailFactoryBean extends AbstractFactoryBean { + + private String classPath; + + private String filePath; + + private Resource location; + + private MailBuilder mailBuilder; + + /** + * コンストラクタ。 + */ + public XMLMailFactoryBean() { + setSingleton(false); + } + + /** + * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() + */ + protected Object createInstance() throws Exception { + if (mailBuilder == null) { + init(); + } + + if (getLocation() != null && getLocation().getFile() != null) { + return mailBuilder.buildMail(getLocation().getFile()); + } + if (getClassPath() != null) { + return mailBuilder.buildMail(getClassPath()); + } + if (getFilePath() != null) { + return mailBuilder.buildMail(new File(getFilePath())); + } + throw new MailBuildException("Mailインスタンスの生成に失敗しました。XMLデータのロケーションが指定されていません。"); + } + + /** + * mailBuilderインスタンスを生成します。 + */ + private void init() { + mailBuilder = new XMLMailBuilderImpl(); + } + + /** + * @see org.springframework.beans.factory.FactoryBean#getObjectType() + */ + public Class getObjectType() { + return Mail.class; + } + + /** + * MailBuilderインターフェースの実装クラスのインスタンスをセットします。 + * デフォルトでは、XMLMailBuilderImplが使用されます。 + *

+ * ただし、ここでセットしない場合は、XMLMailFactoryBeanひとつに付き、 + * XMLMailBuilderImplインスタンス一つが保持されます。 + * シングルトンのMailBuilderインスタンスをセットすることを推奨します。 + * + * @param mailBuilder MailBuilderインスタンス + */ + public void setMailBuilder(MailBuilder mailBuilder) { + this.mailBuilder = mailBuilder; + } + + /** + * @return Returns the classPath. + */ + public String getClassPath() { + return classPath; + } + + /** + * @param classPath The classPath to set. + */ + public void setClassPath(String classPath) { + this.classPath = classPath; + } + + /** + * @return Returns the filePath. + */ + public String getFilePath() { + return filePath; + } + + /** + * @param filePath The filePath to set. + */ + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + /** + * @return Returns the location. + */ + public Resource getLocation() { + return location; + } + + /** + * @param location The location to set. + */ + public void setLocation(Resource location) { + this.location = location; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/spring/package.html b/src/main/java/com/ozacc/mail/spring/package.html old mode 100755 new mode 100644 index e7eae9a..0aa1175 --- a/src/main/java/com/ozacc/mail/spring/package.html +++ b/src/main/java/com/ozacc/mail/spring/package.html @@ -1,5 +1,5 @@ - - -Spring Framework¤ÇÍøÍѤǤ­¤ë¥¯¥é¥¹¤òÄ󶡤·¤Þ¤¹¡£ - + + +Spring Frameworkで利用できるクラスを提供します。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/xml/XMLBuildException.java b/src/main/java/com/ozacc/mail/xml/XMLBuildException.java old mode 100755 new mode 100644 index 2a27a5e..54a625a --- a/src/main/java/com/ozacc/mail/xml/XMLBuildException.java +++ b/src/main/java/com/ozacc/mail/xml/XMLBuildException.java @@ -1,26 +1,26 @@ -package com.ozacc.mail.xml; - -/** - * XMLドキュメントの生成に失敗した時にスローされる例外。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: XMLBuildException.java,v 1.2 2004/09/13 07:08:11 otsuka Exp $ - */ -public class XMLBuildException extends RuntimeException { - - /** - * @param message - */ - public XMLBuildException(String message) { - super(message); - } - - /** - * @param message - * @param cause - */ - public XMLBuildException(String message, Throwable cause) { - super(message, cause); - } +package com.ozacc.mail.xml; + +/** + * XMLドキュメントの生成に失敗した時にスローされる例外。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: XMLBuildException.java,v 1.2 2004/09/13 07:08:11 otsuka Exp $ + */ +public class XMLBuildException extends RuntimeException { + + /** + * @param message + */ + public XMLBuildException(String message) { + super(message); + } + + /** + * @param message + * @param cause + */ + public XMLBuildException(String message, Throwable cause) { + super(message, cause); + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/xml/XMLBuilder.java b/src/main/java/com/ozacc/mail/xml/XMLBuilder.java old mode 100755 new mode 100644 index 91e49be..0f65b26 --- a/src/main/java/com/ozacc/mail/xml/XMLBuilder.java +++ b/src/main/java/com/ozacc/mail/xml/XMLBuilder.java @@ -1,40 +1,40 @@ -package com.ozacc.mail.xml; - -import java.io.File; - -import org.w3c.dom.Document; - -import com.ozacc.mail.Mail; - -/** - * MailインスタンスからXMLドキュメントを生成します。 - * - * @see com.ozacc.mail.xml.impl.XMLBuilderImpl - * @see com.ozacc.mail.xml.impl.JDomXMLBuilder - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: XMLBuilder.java,v 1.2 2004/09/13 07:13:31 otsuka Exp $ - */ -public interface XMLBuilder { - - /** - * 指定されたMailインスタンスからXMLドキュメントを生成します。 - * - * @param mail - * @return DOM Document - * @throws XMLBuildException - */ - Document buildDocument(Mail mail) throws XMLBuildException; - - /** - * 指定されたMailインスタンスからXMLドキュメントを生成し、 - * 指定されたファイルに保存します。 - * - * @param mail - * @param destFile MailデータXMLの保存先ファイル - * @throws XMLBuildException - */ - void saveDocument(Mail mail, File destFile) throws XMLBuildException; - +package com.ozacc.mail.xml; + +import java.io.File; + +import org.w3c.dom.Document; + +import com.ozacc.mail.Mail; + +/** + * MailインスタンスからXMLドキュメントを生成します。 + * + * @see com.ozacc.mail.xml.impl.XMLBuilderImpl + * @see com.ozacc.mail.xml.impl.JDomXMLBuilder + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: XMLBuilder.java,v 1.2 2004/09/13 07:13:31 otsuka Exp $ + */ +public interface XMLBuilder { + + /** + * 指定されたMailインスタンスからXMLドキュメントを生成します。 + * + * @param mail + * @return DOM Document + * @throws XMLBuildException + */ + Document buildDocument(Mail mail) throws XMLBuildException; + + /** + * 指定されたMailインスタンスからXMLドキュメントを生成し、 + * 指定されたファイルに保存します。 + * + * @param mail + * @param destFile MailデータXMLの保存先ファイル + * @throws XMLBuildException + */ + void saveDocument(Mail mail, File destFile) throws XMLBuildException; + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/xml/impl/JDomXMLBuilder.java b/src/main/java/com/ozacc/mail/xml/impl/JDomXMLBuilder.java old mode 100755 new mode 100644 index 7e0bad3..0b507ef --- a/src/main/java/com/ozacc/mail/xml/impl/JDomXMLBuilder.java +++ b/src/main/java/com/ozacc/mail/xml/impl/JDomXMLBuilder.java @@ -1,210 +1,210 @@ -package com.ozacc.mail.xml.impl; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; - -import javax.mail.internet.InternetAddress; - -import org.jdom.CDATA; -import org.jdom.DocType; -import org.jdom.Document; -import org.jdom.Element; -import org.jdom.JDOMException; -import org.jdom.output.DOMOutputter; -import org.jdom.output.Format; -import org.jdom.output.XMLOutputter; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.xml.XMLBuildException; -import com.ozacc.mail.xml.XMLBuilder; - -/** - * XMLBuilderの実装クラス。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: JDomXMLBuilder.java,v 1.6 2004/09/18 00:39:17 otsuka Exp $ - */ -public class JDomXMLBuilder implements XMLBuilder { - - public static final String DOCTYPE_PUBLIC = "-//OZACC//DTD MAIL//EN"; - - public static final String DOCTYPE_SYSTEM = "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"; - - private String charset = "UTF-8"; - - /** - * コンストラクタ。 - */ - public JDomXMLBuilder() {} - - /** - * コンストラクタ。 - * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 - * - * @param charset 出力XMLファイルの文字コード - */ - public JDomXMLBuilder(String charset) { - this(); - setCharset(charset); - } - - /** - * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 - * - * @param charset 出力XMLファイルの文字コード - */ - public void setCharset(String charset) { - this.charset = charset; - } - - /** - * 出力XMLファイルの文字コードを返します。 - * - * @return 出力XMLファイルの文字コード - */ - public String getCharset() { - return charset; - } - - /** - * @see com.ozacc.mail.xml.XMLBuilder#buildDocument(com.ozacc.mail.Mail) - */ - public org.w3c.dom.Document buildDocument(Mail mail) throws XMLBuildException { - Document doc = buildJDomDocument(mail); - DOMOutputter outputter = new DOMOutputter(); - try { - return outputter.output(doc); - } catch (JDOMException e) { - throw new XMLBuildException("DOM Documentの生成に失敗しました。", e); - } - } - - /** - * 指定されたMailインスタンスからJDOMドキュメントを生成します。 - * - * @return 生成されたJDOMドキュメント - */ - public Document buildJDomDocument(Mail mail) { - - Element mailElem = new Element("mail"); - - // Return-Path - if (mail.getReturnPath() != null) { - InternetAddress returnPath = mail.getReturnPath(); - Element returnPathElem = convertInternetAddressIntoElement(returnPath, "returnPath"); - mailElem.addContent(returnPathElem); - } - - // From - if (mail.getFrom() != null) { - InternetAddress from = mail.getFrom(); - Element fromElem = convertInternetAddressIntoElement(from, "from"); - mailElem.addContent(fromElem); - } - - if (mail.getTo().length > 0 || mail.getCc().length > 0 || mail.getBcc().length > 0) { - Element recipientsElem = new Element("recipients"); - - // To - if (mail.getTo().length > 0) { - for (int i = 0; i < mail.getTo().length; i++) { - InternetAddress to = mail.getTo()[i]; - Element toElem = convertInternetAddressIntoElement(to, "to"); - recipientsElem.addContent(toElem); - } - } - // Cc - if (mail.getCc().length > 0) { - for (int i = 0; i < mail.getCc().length; i++) { - InternetAddress cc = mail.getCc()[i]; - Element ccElem = convertInternetAddressIntoElement(cc, "cc"); - recipientsElem.addContent(ccElem); - } - } - // Bcc - if (mail.getBcc().length > 0) { - for (int i = 0; i < mail.getBcc().length; i++) { - InternetAddress bcc = mail.getBcc()[i]; - Element bccElem = convertInternetAddressIntoElement(bcc, "bcc"); - recipientsElem.addContent(bccElem); - } - } - mailElem.addContent(recipientsElem); - } - - // Reply-To - if (mail.getReplyTo() != null) { - InternetAddress replyTo = mail.getReplyTo(); - Element replyToElem = convertInternetAddressIntoElement(replyTo, "replyTo"); - mailElem.addContent(replyToElem); - } - - // Subject - if (mail.getSubject() != null) { - Element subjectElem = new Element("subject"); - subjectElem.setText(mail.getSubject()); - mailElem.addContent(subjectElem); - } - - // Body - if (mail.getText() != null) { - Element textElem = new Element("body"); - textElem.setText(mail.getText()); - mailElem.addContent(textElem); - } - - // Html - if (mail.isHtmlMail()) { - Element htmlElem = new Element("html"); - htmlElem.setContent(new CDATA(mail.getHtmlText())); - mailElem.addContent(htmlElem); - } - - Document doc = new Document(mailElem); - DocType docType = new DocType("mail", DOCTYPE_PUBLIC, DOCTYPE_SYSTEM); - doc.setDocType(docType); - return doc; - } - - /** - * - * @param address - * @param elemName - * @return - */ - private Element convertInternetAddressIntoElement(InternetAddress address, String elemName) { - Element element = new Element(elemName); - element.setAttribute("email", address.getAddress()); - if (address.getPersonal() != null) { - element.setAttribute("name", address.getPersonal()); - } - return element; - } - - /** - * @see com.ozacc.mail.xml.XMLBuilder#saveDocument(com.ozacc.mail.Mail, java.io.File) - */ - public void saveDocument(Mail mail, File destFile) throws XMLBuildException { - // JDOM Documentを生成 - Document doc = buildJDomDocument(mail); - - // ファイル出力 - try { - FileOutputStream fos = new FileOutputStream(destFile); - XMLOutputter outputter = getXMLOutputter(); - outputter.output(doc, fos); - fos.close(); - } catch (IOException e) { - throw new XMLBuildException("DOM Documentのファイル出力に失敗しました。", e); - } - } - - public XMLOutputter getXMLOutputter() { - Format format = Format.getPrettyFormat(); - format.setEncoding(charset); - XMLOutputter outputter = new XMLOutputter(format); - return outputter; - } +package com.ozacc.mail.xml.impl; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; + +import javax.mail.internet.InternetAddress; + +import org.jdom.CDATA; +import org.jdom.DocType; +import org.jdom.Document; +import org.jdom.Element; +import org.jdom.JDOMException; +import org.jdom.output.DOMOutputter; +import org.jdom.output.Format; +import org.jdom.output.XMLOutputter; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.xml.XMLBuildException; +import com.ozacc.mail.xml.XMLBuilder; + +/** + * XMLBuilderの実装クラス。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: JDomXMLBuilder.java,v 1.6 2004/09/18 00:39:17 otsuka Exp $ + */ +public class JDomXMLBuilder implements XMLBuilder { + + public static final String DOCTYPE_PUBLIC = "-//OZACC//DTD MAIL//EN"; + + public static final String DOCTYPE_SYSTEM = "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"; + + private String charset = "UTF-8"; + + /** + * コンストラクタ。 + */ + public JDomXMLBuilder() {} + + /** + * コンストラクタ。 + * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 + * + * @param charset 出力XMLファイルの文字コード + */ + public JDomXMLBuilder(String charset) { + this(); + setCharset(charset); + } + + /** + * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 + * + * @param charset 出力XMLファイルの文字コード + */ + public void setCharset(String charset) { + this.charset = charset; + } + + /** + * 出力XMLファイルの文字コードを返します。 + * + * @return 出力XMLファイルの文字コード + */ + public String getCharset() { + return charset; + } + + /** + * @see com.ozacc.mail.xml.XMLBuilder#buildDocument(com.ozacc.mail.Mail) + */ + public org.w3c.dom.Document buildDocument(Mail mail) throws XMLBuildException { + Document doc = buildJDomDocument(mail); + DOMOutputter outputter = new DOMOutputter(); + try { + return outputter.output(doc); + } catch (JDOMException e) { + throw new XMLBuildException("DOM Documentの生成に失敗しました。", e); + } + } + + /** + * 指定されたMailインスタンスからJDOMドキュメントを生成します。 + * + * @return 生成されたJDOMドキュメント + */ + public Document buildJDomDocument(Mail mail) { + + Element mailElem = new Element("mail"); + + // Return-Path + if (mail.getReturnPath() != null) { + InternetAddress returnPath = mail.getReturnPath(); + Element returnPathElem = convertInternetAddressIntoElement(returnPath, "returnPath"); + mailElem.addContent(returnPathElem); + } + + // From + if (mail.getFrom() != null) { + InternetAddress from = mail.getFrom(); + Element fromElem = convertInternetAddressIntoElement(from, "from"); + mailElem.addContent(fromElem); + } + + if (mail.getTo().length > 0 || mail.getCc().length > 0 || mail.getBcc().length > 0) { + Element recipientsElem = new Element("recipients"); + + // To + if (mail.getTo().length > 0) { + for (int i = 0; i < mail.getTo().length; i++) { + InternetAddress to = mail.getTo()[i]; + Element toElem = convertInternetAddressIntoElement(to, "to"); + recipientsElem.addContent(toElem); + } + } + // Cc + if (mail.getCc().length > 0) { + for (int i = 0; i < mail.getCc().length; i++) { + InternetAddress cc = mail.getCc()[i]; + Element ccElem = convertInternetAddressIntoElement(cc, "cc"); + recipientsElem.addContent(ccElem); + } + } + // Bcc + if (mail.getBcc().length > 0) { + for (int i = 0; i < mail.getBcc().length; i++) { + InternetAddress bcc = mail.getBcc()[i]; + Element bccElem = convertInternetAddressIntoElement(bcc, "bcc"); + recipientsElem.addContent(bccElem); + } + } + mailElem.addContent(recipientsElem); + } + + // Reply-To + if (mail.getReplyTo() != null) { + InternetAddress replyTo = mail.getReplyTo(); + Element replyToElem = convertInternetAddressIntoElement(replyTo, "replyTo"); + mailElem.addContent(replyToElem); + } + + // Subject + if (mail.getSubject() != null) { + Element subjectElem = new Element("subject"); + subjectElem.setText(mail.getSubject()); + mailElem.addContent(subjectElem); + } + + // Body + if (mail.getText() != null) { + Element textElem = new Element("body"); + textElem.setText(mail.getText()); + mailElem.addContent(textElem); + } + + // Html + if (mail.isHtmlMail()) { + Element htmlElem = new Element("html"); + htmlElem.setContent(new CDATA(mail.getHtmlText())); + mailElem.addContent(htmlElem); + } + + Document doc = new Document(mailElem); + DocType docType = new DocType("mail", DOCTYPE_PUBLIC, DOCTYPE_SYSTEM); + doc.setDocType(docType); + return doc; + } + + /** + * + * @param address + * @param elemName + * @return + */ + private Element convertInternetAddressIntoElement(InternetAddress address, String elemName) { + Element element = new Element(elemName); + element.setAttribute("email", address.getAddress()); + if (address.getPersonal() != null) { + element.setAttribute("name", address.getPersonal()); + } + return element; + } + + /** + * @see com.ozacc.mail.xml.XMLBuilder#saveDocument(com.ozacc.mail.Mail, java.io.File) + */ + public void saveDocument(Mail mail, File destFile) throws XMLBuildException { + // JDOM Documentを生成 + Document doc = buildJDomDocument(mail); + + // ファイル出力 + try { + FileOutputStream fos = new FileOutputStream(destFile); + XMLOutputter outputter = getXMLOutputter(); + outputter.output(doc, fos); + fos.close(); + } catch (IOException e) { + throw new XMLBuildException("DOM Documentのファイル出力に失敗しました。", e); + } + } + + public XMLOutputter getXMLOutputter() { + Format format = Format.getPrettyFormat(); + format.setEncoding(charset); + XMLOutputter outputter = new XMLOutputter(format); + return outputter; + } } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/xml/impl/XMLBuilderImpl.java b/src/main/java/com/ozacc/mail/xml/impl/XMLBuilderImpl.java old mode 100755 new mode 100644 index fd0c4a2..80c9edc --- a/src/main/java/com/ozacc/mail/xml/impl/XMLBuilderImpl.java +++ b/src/main/java/com/ozacc/mail/xml/impl/XMLBuilderImpl.java @@ -1,225 +1,225 @@ -package com.ozacc.mail.xml.impl; - -import java.io.File; -import java.util.Properties; - -import javax.mail.internet.InternetAddress; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.FactoryConfigurationError; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; - -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.xml.XMLBuildException; -import com.ozacc.mail.xml.XMLBuilder; - -/** - * JDK 1.4以降の標準XMLライブラリを使用して実装されたXMLBuilder。 - * - * @since 1.0 - * @author Tomohiro Otsuka - * @version $Id: XMLBuilderImpl.java,v 1.4.2.1 2005/01/21 22:15:07 otsuka Exp $ - */ -public class XMLBuilderImpl implements XMLBuilder { - - private String charset = "UTF-8"; - - /** - * コンストラクタ。 - */ - public XMLBuilderImpl() {} - - /** - * コンストラクタ。 - * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 - * - * @param charset 出力XMLファイルの文字コード - */ - public XMLBuilderImpl(String charset) { - super(); - this.charset = charset; - } - - /** - * 出力XMLファイルの文字コードを返します。 - * - * @return 出力XMLファイルの文字コード - */ - public String getCharset() { - return charset; - } - - /** - * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 - * - * @param charset 出力XMLファイルの文字コード - */ - public void setCharset(String charset) { - this.charset = charset; - } - - /** - * @see com.ozacc.mail.xml.XMLBuilder#buildDocument(com.ozacc.mail.Mail) - */ - public Document buildDocument(Mail mail) throws XMLBuildException { - Document doc = createNewDocument(); - - /*DOMImplementation domImpl = doc.getImplementation(); - DocumentType docType = domImpl.createDocumentType("mail", Mail.DOCTYPE_PUBLIC, Mail.DOCTYPE_SYSTEM); - doc.appendChild(docType);*/ - - Element mailElem = doc.createElement("mail"); - - // Return-Path - if (mail.getReturnPath() != null) { - InternetAddress returnPath = mail.getReturnPath(); - Element returnPathElem = convertInternetAddressIntoElement(returnPath, "returnPath", - doc); - mailElem.appendChild(returnPathElem); - } - - // From - if (mail.getFrom() != null) { - InternetAddress from = mail.getFrom(); - Element fromElem = convertInternetAddressIntoElement(from, "from", doc); - mailElem.appendChild(fromElem); - } - - if (mail.getTo().length > 0 || mail.getCc().length > 0 || mail.getBcc().length > 0) { - Element recipientsElem = doc.createElement("recipients"); - - // To - if (mail.getTo().length > 0) { - for (int i = 0; i < mail.getTo().length; i++) { - InternetAddress to = mail.getTo()[i]; - Element toElem = convertInternetAddressIntoElement(to, "to", doc); - recipientsElem.appendChild(toElem); - } - } - // Cc - if (mail.getCc().length > 0) { - for (int i = 0; i < mail.getCc().length; i++) { - InternetAddress cc = mail.getCc()[i]; - Element ccElem = convertInternetAddressIntoElement(cc, "cc", doc); - recipientsElem.appendChild(ccElem); - } - } - // Bcc - if (mail.getBcc().length > 0) { - for (int i = 0; i < mail.getBcc().length; i++) { - InternetAddress bcc = mail.getBcc()[i]; - Element bccElem = convertInternetAddressIntoElement(bcc, "bcc", doc); - recipientsElem.appendChild(bccElem); - } - } - mailElem.appendChild(recipientsElem); - } - - // Reply-To - if (mail.getReplyTo() != null) { - InternetAddress replyTo = mail.getReplyTo(); - Element replyToElem = convertInternetAddressIntoElement(replyTo, "replyTo", doc); - mailElem.appendChild(replyToElem); - } - - // Subject - if (mail.getSubject() != null) { - Element subjectElem = doc.createElement("subject"); - subjectElem.appendChild(doc.createTextNode(mail.getSubject())); - mailElem.appendChild(subjectElem); - } - - // Body - if (mail.getText() != null) { - Element bodyElem = doc.createElement("body"); - bodyElem.appendChild(doc.createTextNode(mail.getText())); - mailElem.appendChild(bodyElem); - } - - // Html - if (mail.isHtmlMail()) { - Element htmlElem = doc.createElement("html"); - htmlElem.appendChild(doc.createCDATASection(mail.getHtmlText())); - mailElem.appendChild(htmlElem); - } - - doc.appendChild(mailElem); - - return doc; - } - - public static Document createNewDocument() throws FactoryConfigurationError { - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - try { - DocumentBuilder db = dbf.newDocumentBuilder(); - Document doc = db.newDocument(); - return doc; - } catch (ParserConfigurationException e) { - // never be thrown - throw new XMLBuildException("", e); - } - } - - private Element convertInternetAddressIntoElement(InternetAddress address, String elemName, - Document doc) { - Element element = doc.createElement(elemName); - element.setAttribute("email", address.getAddress()); - if (address.getPersonal() != null) { - element.setAttribute("name", address.getPersonal()); - } - return element; - } - - /** - * 指定されたMailインスタンスからXMLドキュメントを生成し、 - * 指定されたファイルに保存します。 - * - * このメソッド内部で使用されるTransformerFactoryがスレッドセーフではないため、synchronzedメソッドになっています。 - * - * @see com.ozacc.mail.xml.XMLBuilder#saveDocument(com.ozacc.mail.Mail, java.io.File) - * @see TransformerFactory - */ - public synchronized void saveDocument(Mail mail, File destFile) throws XMLBuildException { - Document doc = buildDocument(mail); - - Transformer t; - try { - t = TransformerFactory.newInstance().newTransformer(); - } catch (Exception e) { - // never be thrown - throw new XMLBuildException(e.getMessage()); - } - t.setOutputProperties(getOutputProperties()); - - DOMSource source = new DOMSource(doc); - StreamResult result = new StreamResult(destFile); - try { - t.transform(source, result); - } catch (TransformerException e) { - throw new XMLBuildException("XMLファイルの保存に失敗しました。", e); - } - } - - /** - * 出力プロパティを生成。 - * @return 出力プロパティを設定したPropertiesインスタンス - */ - private Properties getOutputProperties() { - Properties p = new Properties(); - p.put(OutputKeys.ENCODING, charset); - p.put(OutputKeys.INDENT, "yes"); - p.put(OutputKeys.DOCTYPE_PUBLIC, Mail.DOCTYPE_PUBLIC); - p.put(OutputKeys.DOCTYPE_SYSTEM, Mail.DOCTYPE_SYSTEM); - return p; - } - +package com.ozacc.mail.xml.impl; + +import java.io.File; +import java.util.Properties; + +import javax.mail.internet.InternetAddress; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.FactoryConfigurationError; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.xml.XMLBuildException; +import com.ozacc.mail.xml.XMLBuilder; + +/** + * JDK 1.4以降の標準XMLライブラリを使用して実装されたXMLBuilder。 + * + * @since 1.0 + * @author Tomohiro Otsuka + * @version $Id: XMLBuilderImpl.java,v 1.4.2.1 2005/01/21 22:15:07 otsuka Exp $ + */ +public class XMLBuilderImpl implements XMLBuilder { + + private String charset = "UTF-8"; + + /** + * コンストラクタ。 + */ + public XMLBuilderImpl() {} + + /** + * コンストラクタ。 + * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 + * + * @param charset 出力XMLファイルの文字コード + */ + public XMLBuilderImpl(String charset) { + super(); + this.charset = charset; + } + + /** + * 出力XMLファイルの文字コードを返します。 + * + * @return 出力XMLファイルの文字コード + */ + public String getCharset() { + return charset; + } + + /** + * 出力XMLファイルの文字コードを指定します。デフォルトはUTF-8。 + * + * @param charset 出力XMLファイルの文字コード + */ + public void setCharset(String charset) { + this.charset = charset; + } + + /** + * @see com.ozacc.mail.xml.XMLBuilder#buildDocument(com.ozacc.mail.Mail) + */ + public Document buildDocument(Mail mail) throws XMLBuildException { + Document doc = createNewDocument(); + + /*DOMImplementation domImpl = doc.getImplementation(); + DocumentType docType = domImpl.createDocumentType("mail", Mail.DOCTYPE_PUBLIC, Mail.DOCTYPE_SYSTEM); + doc.appendChild(docType);*/ + + Element mailElem = doc.createElement("mail"); + + // Return-Path + if (mail.getReturnPath() != null) { + InternetAddress returnPath = mail.getReturnPath(); + Element returnPathElem = convertInternetAddressIntoElement(returnPath, "returnPath", + doc); + mailElem.appendChild(returnPathElem); + } + + // From + if (mail.getFrom() != null) { + InternetAddress from = mail.getFrom(); + Element fromElem = convertInternetAddressIntoElement(from, "from", doc); + mailElem.appendChild(fromElem); + } + + if (mail.getTo().length > 0 || mail.getCc().length > 0 || mail.getBcc().length > 0) { + Element recipientsElem = doc.createElement("recipients"); + + // To + if (mail.getTo().length > 0) { + for (int i = 0; i < mail.getTo().length; i++) { + InternetAddress to = mail.getTo()[i]; + Element toElem = convertInternetAddressIntoElement(to, "to", doc); + recipientsElem.appendChild(toElem); + } + } + // Cc + if (mail.getCc().length > 0) { + for (int i = 0; i < mail.getCc().length; i++) { + InternetAddress cc = mail.getCc()[i]; + Element ccElem = convertInternetAddressIntoElement(cc, "cc", doc); + recipientsElem.appendChild(ccElem); + } + } + // Bcc + if (mail.getBcc().length > 0) { + for (int i = 0; i < mail.getBcc().length; i++) { + InternetAddress bcc = mail.getBcc()[i]; + Element bccElem = convertInternetAddressIntoElement(bcc, "bcc", doc); + recipientsElem.appendChild(bccElem); + } + } + mailElem.appendChild(recipientsElem); + } + + // Reply-To + if (mail.getReplyTo() != null) { + InternetAddress replyTo = mail.getReplyTo(); + Element replyToElem = convertInternetAddressIntoElement(replyTo, "replyTo", doc); + mailElem.appendChild(replyToElem); + } + + // Subject + if (mail.getSubject() != null) { + Element subjectElem = doc.createElement("subject"); + subjectElem.appendChild(doc.createTextNode(mail.getSubject())); + mailElem.appendChild(subjectElem); + } + + // Body + if (mail.getText() != null) { + Element bodyElem = doc.createElement("body"); + bodyElem.appendChild(doc.createTextNode(mail.getText())); + mailElem.appendChild(bodyElem); + } + + // Html + if (mail.isHtmlMail()) { + Element htmlElem = doc.createElement("html"); + htmlElem.appendChild(doc.createCDATASection(mail.getHtmlText())); + mailElem.appendChild(htmlElem); + } + + doc.appendChild(mailElem); + + return doc; + } + + public static Document createNewDocument() throws FactoryConfigurationError { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + try { + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.newDocument(); + return doc; + } catch (ParserConfigurationException e) { + // never be thrown + throw new XMLBuildException("", e); + } + } + + private Element convertInternetAddressIntoElement(InternetAddress address, String elemName, + Document doc) { + Element element = doc.createElement(elemName); + element.setAttribute("email", address.getAddress()); + if (address.getPersonal() != null) { + element.setAttribute("name", address.getPersonal()); + } + return element; + } + + /** + * 指定されたMailインスタンスからXMLドキュメントを生成し、 + * 指定されたファイルに保存します。 + * + * このメソッド内部で使用されるTransformerFactoryがスレッドセーフではないため、synchronzedメソッドになっています。 + * + * @see com.ozacc.mail.xml.XMLBuilder#saveDocument(com.ozacc.mail.Mail, java.io.File) + * @see TransformerFactory + */ + public synchronized void saveDocument(Mail mail, File destFile) throws XMLBuildException { + Document doc = buildDocument(mail); + + Transformer t; + try { + t = TransformerFactory.newInstance().newTransformer(); + } catch (Exception e) { + // never be thrown + throw new XMLBuildException(e.getMessage()); + } + t.setOutputProperties(getOutputProperties()); + + DOMSource source = new DOMSource(doc); + StreamResult result = new StreamResult(destFile); + try { + t.transform(source, result); + } catch (TransformerException e) { + throw new XMLBuildException("XMLファイルの保存に失敗しました。", e); + } + } + + /** + * 出力プロパティを生成。 + * @return 出力プロパティを設定したPropertiesインスタンス + */ + private Properties getOutputProperties() { + Properties p = new Properties(); + p.put(OutputKeys.ENCODING, charset); + p.put(OutputKeys.INDENT, "yes"); + p.put(OutputKeys.DOCTYPE_PUBLIC, Mail.DOCTYPE_PUBLIC); + p.put(OutputKeys.DOCTYPE_SYSTEM, Mail.DOCTYPE_SYSTEM); + return p; + } + } \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/xml/impl/package.html b/src/main/java/com/ozacc/mail/xml/impl/package.html old mode 100755 new mode 100644 index 6f3b665..40d0ca5 --- a/src/main/java/com/ozacc/mail/xml/impl/package.html +++ b/src/main/java/com/ozacc/mail/xml/impl/package.html @@ -1,5 +1,5 @@ - - -com.ozacc.mail.xml¥Ñ¥Ã¥±¡¼¥¸¤Î¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤ò¼ÂÁõ¤·¤¿¥¯¥é¥¹¤òÄ󶡤·¤Þ¤¹¡£ - + + +com.ozacc.mail.xmlパッケージのインターフェースを実装したクラスを提供します。 + \ No newline at end of file diff --git a/src/main/java/com/ozacc/mail/xml/package.html b/src/main/java/com/ozacc/mail/xml/package.html old mode 100755 new mode 100644 index d90d912..1452ee6 --- a/src/main/java/com/ozacc/mail/xml/package.html +++ b/src/main/java/com/ozacc/mail/xml/package.html @@ -1,5 +1,5 @@ - - -Mail¥¤¥ó¥¹¥¿¥ó¥¹¤«¤éXML¥É¥­¥å¥á¥ó¥È¤òÀ¸À®¤¹¤ë¥¤¥ó¥¿¡¼¥Õ¥§¡¼¥¹¤òÄ󶡤·¤Þ¤¹¡£ - + + +MailインスタンスからXMLドキュメントを生成するインターフェースを提供します。 + \ No newline at end of file diff --git a/src/test/java/com/dumbster/smtp/SimpleSmtpServer.java b/src/test/java/com/dumbster/smtp/SimpleSmtpServer.java old mode 100755 new mode 100644 index 4a08baf..654502c --- a/src/test/java/com/dumbster/smtp/SimpleSmtpServer.java +++ b/src/test/java/com/dumbster/smtp/SimpleSmtpServer.java @@ -1,201 +1,201 @@ -/* - * Dumbster: a dummy SMTP server. - * Copyright (C) 2003, Jason Paul Kitchen - * lilnottsman@yahoo.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.dumbster.smtp; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.InterruptedIOException; -import java.io.PrintWriter; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -/** - * Dummy SMTP server for testing purposes. - */ -public class SimpleSmtpServer implements Runnable { - - /** Stores all of the email received since this instance started up. */ - private List receivedMail; - - /** Default SMTP port is 25. */ - public static final int DEFAULT_SMTP_PORT = 25; - - /** Indicates whether this server is stopped or not. */ - private volatile boolean stopped = true; - - /** Indicates if a stop request has been sent to this server. */ - private volatile boolean doStop = false; - - /** Port the server listens on - set to the default SMTP port initially. */ - private int port = DEFAULT_SMTP_PORT; - - /** - * Constructor. - */ - public SimpleSmtpServer(int port) { - receivedMail = new ArrayList(); - this.port = port; - } - - /** - * Main loop of the SMTP server. - */ - public void run() { - stopped = false; - ServerSocket serverSocket = null; - try { - serverSocket = new ServerSocket(port); - serverSocket.setSoTimeout(500); // Block for maximum of 1.5 seconds - - // Server: loop until stopped - while (!doStop) { - Socket socket = null; - try { - socket = serverSocket.accept(); - } catch (InterruptedIOException iioe) { - if (socket != null) { - socket.close(); - } - continue; // Non-blocking socket timeout occurred: try accept() again - } - - // Get the input and output streams - BufferedReader input = new BufferedReader(new InputStreamReader(socket - .getInputStream())); - PrintWriter out = new PrintWriter(socket.getOutputStream()); - - // Initialize the state machine - SmtpState smtpState = SmtpState.CONNECT; - SmtpRequest smtpRequest = new SmtpRequest(SmtpActionType.CONNECT, "", smtpState); - - // Execute the connection request - SmtpResponse smtpResponse = smtpRequest.execute(); - - // Send initial response - sendResponse(out, smtpResponse); - smtpState = smtpResponse.getNextState(); - - SmtpMessage msg = new SmtpMessage(); - - while (smtpState != SmtpState.CONNECT) { - String line = input.readLine(); - - if (line == null) { - break; - } - // Create request from client input and current state - SmtpRequest request = SmtpRequest.createRequest(line, smtpState); - // Execute request and create response object - SmtpResponse response = request.execute(); - // Move to next internal state - smtpState = response.getNextState(); - // Send reponse to client - sendResponse(out, response); - - // Store input in message - msg.store(response, request.getParams()); - } - - receivedMail.add(msg); - socket.close(); - } - } catch (Exception e) { - // e.printStackTrace(); - } finally { - if (serverSocket != null) { - try { - serverSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - stopped = true; - } - - /** - * Send response to client. - * @param out socket output stream - * @param smtpResponse response object - */ - private void sendResponse(PrintWriter out, SmtpResponse smtpResponse) { - if (smtpResponse.getCode() > 0) { - out.print(smtpResponse.getCode() + " " + smtpResponse.getMessage() + "\r\n"); - out.flush(); - } - } - - /** - * Get email received by this instance since start up. - * @return List of String - */ - public Iterator getReceivedEmail() { - return receivedMail.iterator(); - } - - /** - * Get the number of messages received. - * @return size of received email list - */ - public int getReceievedEmailSize() { - return receivedMail.size(); - } - - /** - * Forces the server to stop after processing the current request. - */ - public void stop() { - doStop = true; - while (!isStopped()) {} // Wait for email server to stop - } - - /** - * Indicates whether this server is stopped or not. - * @return true iff this server is stopped - */ - public boolean isStopped() { - return stopped; - } - - /** - * Creates an instance of SimpleSmtpServer and starts it. Will listen on the default port. - * @return a reference to the SMTP server - */ - public static SimpleSmtpServer start() { - return start(DEFAULT_SMTP_PORT); - } - - /** - * Creates an instance of SimpleSmtpServer and starts it. - * @param port port number the server should listen to - * @return a reference to the SMTP server - */ - public static SimpleSmtpServer start(int port) { - SimpleSmtpServer server = new SimpleSmtpServer(port); - Thread t = new Thread(server); - t.start(); - return server; - } - +/* + * Dumbster: a dummy SMTP server. + * Copyright (C) 2003, Jason Paul Kitchen + * lilnottsman@yahoo.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package com.dumbster.smtp; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.InterruptedIOException; +import java.io.PrintWriter; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +/** + * Dummy SMTP server for testing purposes. + */ +public class SimpleSmtpServer implements Runnable { + + /** Stores all of the email received since this instance started up. */ + private List receivedMail; + + /** Default SMTP port is 25. */ + public static final int DEFAULT_SMTP_PORT = 25; + + /** Indicates whether this server is stopped or not. */ + private volatile boolean stopped = true; + + /** Indicates if a stop request has been sent to this server. */ + private volatile boolean doStop = false; + + /** Port the server listens on - set to the default SMTP port initially. */ + private int port = DEFAULT_SMTP_PORT; + + /** + * Constructor. + */ + public SimpleSmtpServer(int port) { + receivedMail = new ArrayList(); + this.port = port; + } + + /** + * Main loop of the SMTP server. + */ + public void run() { + stopped = false; + ServerSocket serverSocket = null; + try { + serverSocket = new ServerSocket(port); + serverSocket.setSoTimeout(500); // Block for maximum of 1.5 seconds + + // Server: loop until stopped + while (!doStop) { + Socket socket = null; + try { + socket = serverSocket.accept(); + } catch (InterruptedIOException iioe) { + if (socket != null) { + socket.close(); + } + continue; // Non-blocking socket timeout occurred: try accept() again + } + + // Get the input and output streams + BufferedReader input = new BufferedReader(new InputStreamReader(socket + .getInputStream())); + PrintWriter out = new PrintWriter(socket.getOutputStream()); + + // Initialize the state machine + SmtpState smtpState = SmtpState.CONNECT; + SmtpRequest smtpRequest = new SmtpRequest(SmtpActionType.CONNECT, "", smtpState); + + // Execute the connection request + SmtpResponse smtpResponse = smtpRequest.execute(); + + // Send initial response + sendResponse(out, smtpResponse); + smtpState = smtpResponse.getNextState(); + + SmtpMessage msg = new SmtpMessage(); + + while (smtpState != SmtpState.CONNECT) { + String line = input.readLine(); + + if (line == null) { + break; + } + // Create request from client input and current state + SmtpRequest request = SmtpRequest.createRequest(line, smtpState); + // Execute request and create response object + SmtpResponse response = request.execute(); + // Move to next internal state + smtpState = response.getNextState(); + // Send reponse to client + sendResponse(out, response); + + // Store input in message + msg.store(response, request.getParams()); + } + + receivedMail.add(msg); + socket.close(); + } + } catch (Exception e) { + // e.printStackTrace(); + } finally { + if (serverSocket != null) { + try { + serverSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + stopped = true; + } + + /** + * Send response to client. + * @param out socket output stream + * @param smtpResponse response object + */ + private void sendResponse(PrintWriter out, SmtpResponse smtpResponse) { + if (smtpResponse.getCode() > 0) { + out.print(smtpResponse.getCode() + " " + smtpResponse.getMessage() + "\r\n"); + out.flush(); + } + } + + /** + * Get email received by this instance since start up. + * @return List of String + */ + public Iterator getReceivedEmail() { + return receivedMail.iterator(); + } + + /** + * Get the number of messages received. + * @return size of received email list + */ + public int getReceievedEmailSize() { + return receivedMail.size(); + } + + /** + * Forces the server to stop after processing the current request. + */ + public void stop() { + doStop = true; + while (!isStopped()) {} // Wait for email server to stop + } + + /** + * Indicates whether this server is stopped or not. + * @return true iff this server is stopped + */ + public boolean isStopped() { + return stopped; + } + + /** + * Creates an instance of SimpleSmtpServer and starts it. Will listen on the default port. + * @return a reference to the SMTP server + */ + public static SimpleSmtpServer start() { + return start(DEFAULT_SMTP_PORT); + } + + /** + * Creates an instance of SimpleSmtpServer and starts it. + * @param port port number the server should listen to + * @return a reference to the SMTP server + */ + public static SimpleSmtpServer start(int port) { + SimpleSmtpServer server = new SimpleSmtpServer(port); + Thread t = new Thread(server); + t.start(); + return server; + } + } \ No newline at end of file diff --git a/src/test/java/com/dumbster/smtp/SmtpActionType.java b/src/test/java/com/dumbster/smtp/SmtpActionType.java old mode 100755 new mode 100644 index 4357764..88e99f4 --- a/src/test/java/com/dumbster/smtp/SmtpActionType.java +++ b/src/test/java/com/dumbster/smtp/SmtpActionType.java @@ -1,168 +1,168 @@ -/* - * Dumbster: a dummy SMTP server. - * Copyright (C) 2003, Jason Paul Kitchen - * lilnottsman@yahoo.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.dumbster.smtp; - -/** - * Represents an SMTP action or command. - */ -public class SmtpActionType { - - /** Internal value for the action type. */ - private byte value; - - /** Internal representation of the CONNECT action. */ - private static final byte CONNECT_BYTE = 1; - - /** Internal representation of the EHLO action. */ - private static final byte EHLO_BYTE = 2; - - /** Internal representation of the MAIL FROM action. */ - private static final byte MAIL_BYTE = 3; - - /** Internal representation of the RCPT action. */ - private static final byte RCPT_BYTE = 4; - - /** Internal representation of the DATA action. */ - private static final byte DATA_BYTE = 5; - - /** Internal representation of the DATA END (.) action. */ - private static final byte DATA_END_BYTE = 6; - - /** Internal representation of the QUIT action. */ - private static final byte QUIT_BYTE = 7; - - /** Internal representation of an unrecognized action: body text gets this action type. */ - private static final byte UNREC_BYTE = 8; - - /** Internal representation of the blank line action: separates headers and body text. */ - private static final byte BLANK_LINE_BYTE = 9; - - /** Internal representation of the stateless RSET action. */ - private static final byte RSET_BYTE = -1; - - /** Internal representation of the stateless VRFY action. */ - private static final byte VRFY_BYTE = -2; - - /** Internal representation of the stateless EXPN action. */ - private static final byte EXPN_BYTE = -3; - - /** Internal representation of the stateless HELP action. */ - private static final byte HELP_BYTE = -4; - - /** Internal representation of the stateless NOOP action. */ - private static final byte NOOP_BYTE = -5; - - /** CONNECT action. */ - public static final SmtpActionType CONNECT = new SmtpActionType(CONNECT_BYTE); - - /** EHLO action. */ - public static final SmtpActionType EHLO = new SmtpActionType(EHLO_BYTE); - - /** MAIL action. */ - public static final SmtpActionType MAIL = new SmtpActionType(MAIL_BYTE); - - /** RCPT action. */ - public static final SmtpActionType RCPT = new SmtpActionType(RCPT_BYTE); - - /** DATA action. */ - public static final SmtpActionType DATA = new SmtpActionType(DATA_BYTE); - - /** "." action. */ - public static final SmtpActionType DATA_END = new SmtpActionType(DATA_END_BYTE); - - /** Body text action. */ - public static final SmtpActionType UNRECOG = new SmtpActionType(UNREC_BYTE); - - /** QUIT action. */ - public static final SmtpActionType QUIT = new SmtpActionType(QUIT_BYTE); - - /** Header/body separator action. */ - public static final SmtpActionType BLANK_LINE = new SmtpActionType(BLANK_LINE_BYTE); - - /** Stateless RSET action. */ - public static final SmtpActionType RSET = new SmtpActionType(RSET_BYTE); - - /** Stateless VRFY action. */ - public static final SmtpActionType VRFY = new SmtpActionType(VRFY_BYTE); - - /** Stateless EXPN action. */ - public static final SmtpActionType EXPN = new SmtpActionType(EXPN_BYTE); - - /** Stateless HELP action. */ - public static final SmtpActionType HELP = new SmtpActionType(HELP_BYTE); - - /** Stateless NOOP action. */ - public static final SmtpActionType NOOP = new SmtpActionType(NOOP_BYTE); - - /** - * Create a new SMTP action type. Private to ensure no invalid values. - * @param value one of the _BYTE values - */ - private SmtpActionType(byte value) { - this.value = value; - } - - /** - * Indicates whether the action is stateless or not. - * @return true iff the action is stateless - */ - public boolean isStateless() { - return value < 0; - } - - /** - * String representation of this SMTP action type. - * @return a String - */ - public String toString() { - switch (value) { - case CONNECT_BYTE: - return "Connect"; - case EHLO_BYTE: - return "EHLO"; - case MAIL_BYTE: - return "MAIL"; - case RCPT_BYTE: - return "RCPT"; - case DATA_BYTE: - return "DATA"; - case DATA_END_BYTE: - return "."; - case QUIT_BYTE: - return "QUIT"; - case RSET_BYTE: - return "RSET"; - case VRFY_BYTE: - return "VRFY"; - case EXPN_BYTE: - return "EXPN"; - case HELP_BYTE: - return "HELP"; - case NOOP_BYTE: - return "NOOP"; - case UNREC_BYTE: - return "Unrecognized command / data"; - case BLANK_LINE_BYTE: - return "Blank line"; - default: - return "Unknown"; - } - } +/* + * Dumbster: a dummy SMTP server. + * Copyright (C) 2003, Jason Paul Kitchen + * lilnottsman@yahoo.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package com.dumbster.smtp; + +/** + * Represents an SMTP action or command. + */ +public class SmtpActionType { + + /** Internal value for the action type. */ + private byte value; + + /** Internal representation of the CONNECT action. */ + private static final byte CONNECT_BYTE = 1; + + /** Internal representation of the EHLO action. */ + private static final byte EHLO_BYTE = 2; + + /** Internal representation of the MAIL FROM action. */ + private static final byte MAIL_BYTE = 3; + + /** Internal representation of the RCPT action. */ + private static final byte RCPT_BYTE = 4; + + /** Internal representation of the DATA action. */ + private static final byte DATA_BYTE = 5; + + /** Internal representation of the DATA END (.) action. */ + private static final byte DATA_END_BYTE = 6; + + /** Internal representation of the QUIT action. */ + private static final byte QUIT_BYTE = 7; + + /** Internal representation of an unrecognized action: body text gets this action type. */ + private static final byte UNREC_BYTE = 8; + + /** Internal representation of the blank line action: separates headers and body text. */ + private static final byte BLANK_LINE_BYTE = 9; + + /** Internal representation of the stateless RSET action. */ + private static final byte RSET_BYTE = -1; + + /** Internal representation of the stateless VRFY action. */ + private static final byte VRFY_BYTE = -2; + + /** Internal representation of the stateless EXPN action. */ + private static final byte EXPN_BYTE = -3; + + /** Internal representation of the stateless HELP action. */ + private static final byte HELP_BYTE = -4; + + /** Internal representation of the stateless NOOP action. */ + private static final byte NOOP_BYTE = -5; + + /** CONNECT action. */ + public static final SmtpActionType CONNECT = new SmtpActionType(CONNECT_BYTE); + + /** EHLO action. */ + public static final SmtpActionType EHLO = new SmtpActionType(EHLO_BYTE); + + /** MAIL action. */ + public static final SmtpActionType MAIL = new SmtpActionType(MAIL_BYTE); + + /** RCPT action. */ + public static final SmtpActionType RCPT = new SmtpActionType(RCPT_BYTE); + + /** DATA action. */ + public static final SmtpActionType DATA = new SmtpActionType(DATA_BYTE); + + /** "." action. */ + public static final SmtpActionType DATA_END = new SmtpActionType(DATA_END_BYTE); + + /** Body text action. */ + public static final SmtpActionType UNRECOG = new SmtpActionType(UNREC_BYTE); + + /** QUIT action. */ + public static final SmtpActionType QUIT = new SmtpActionType(QUIT_BYTE); + + /** Header/body separator action. */ + public static final SmtpActionType BLANK_LINE = new SmtpActionType(BLANK_LINE_BYTE); + + /** Stateless RSET action. */ + public static final SmtpActionType RSET = new SmtpActionType(RSET_BYTE); + + /** Stateless VRFY action. */ + public static final SmtpActionType VRFY = new SmtpActionType(VRFY_BYTE); + + /** Stateless EXPN action. */ + public static final SmtpActionType EXPN = new SmtpActionType(EXPN_BYTE); + + /** Stateless HELP action. */ + public static final SmtpActionType HELP = new SmtpActionType(HELP_BYTE); + + /** Stateless NOOP action. */ + public static final SmtpActionType NOOP = new SmtpActionType(NOOP_BYTE); + + /** + * Create a new SMTP action type. Private to ensure no invalid values. + * @param value one of the _BYTE values + */ + private SmtpActionType(byte value) { + this.value = value; + } + + /** + * Indicates whether the action is stateless or not. + * @return true iff the action is stateless + */ + public boolean isStateless() { + return value < 0; + } + + /** + * String representation of this SMTP action type. + * @return a String + */ + public String toString() { + switch (value) { + case CONNECT_BYTE: + return "Connect"; + case EHLO_BYTE: + return "EHLO"; + case MAIL_BYTE: + return "MAIL"; + case RCPT_BYTE: + return "RCPT"; + case DATA_BYTE: + return "DATA"; + case DATA_END_BYTE: + return "."; + case QUIT_BYTE: + return "QUIT"; + case RSET_BYTE: + return "RSET"; + case VRFY_BYTE: + return "VRFY"; + case EXPN_BYTE: + return "EXPN"; + case HELP_BYTE: + return "HELP"; + case NOOP_BYTE: + return "NOOP"; + case UNREC_BYTE: + return "Unrecognized command / data"; + case BLANK_LINE_BYTE: + return "Blank line"; + default: + return "Unknown"; + } + } } \ No newline at end of file diff --git a/src/test/java/com/dumbster/smtp/SmtpMessage.java b/src/test/java/com/dumbster/smtp/SmtpMessage.java old mode 100755 new mode 100644 index 03ff977..a2c4bae --- a/src/test/java/com/dumbster/smtp/SmtpMessage.java +++ b/src/test/java/com/dumbster/smtp/SmtpMessage.java @@ -1,147 +1,147 @@ -/* - * Dumbster: a dummy SMTP server. - * Copyright (C) 2003, Jason Paul Kitchen - * lilnottsman@yahoo.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.dumbster.smtp; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * Container for a complete SMTP message - headers and message body. - */ -public class SmtpMessage { - - /** Headers: Map of List of String hashed on header name. */ - private Map headers; - - /** Message body. */ - private StringBuffer body; - - /** - * Constructor. Initializes headers Map and body buffer. - */ - public SmtpMessage() { - headers = new HashMap(); - body = new StringBuffer(); - } - - /** - * Update the headers or body depending on the SmtpResponse object and line of input. - * @param response SmtpResponse object - * @param params remainder of input line after SMTP command has been removed - */ - public void store(SmtpResponse response, String params) { - if (params != null) { - if (SmtpState.DATA_HDR == response.getNextState()) { - int headerNameEnd = params.indexOf(':'); - if (headerNameEnd >= 0) { - String name = params.substring(0, headerNameEnd).trim(); - String value = params.substring(headerNameEnd + 1).trim(); - addHeader(name, value); - } - } else if (SmtpState.DATA_BODY == response.getNextState()) { - body.append(params); - } - } - } - - /** - * Get an Iterator over the header names. - * @return an Iterator over the set of header names (String) - */ - public Iterator getHeaderNames() { - return headers.keySet().iterator(); - } - - /** - * Get the value(s) associated with the given header name. - * @param name header name - * @return value(s) associated with the header name - */ - public String[] getHeaderValues(String name) { - List values = (List)headers.get(name); - if (values == null) { - return new String[0]; - } else { - return (String[])values.toArray(new String[0]); - } - } - - /** - * Get the first values associated with a given header name. - * @param name header name - * @return first value associated with the header name - */ - public String getHeaderValue(String name) { - List values = (List)headers.get(name); - if (values == null) { - return null; - } else { - return (String)values.iterator().next(); - } - } - - /** - * Get the message body. - * @return message body - */ - public String getBody() { - return body.toString(); - } - - /** - * Adds a header to the Map. - * @param name header name - * @param value header value - */ - private void addHeader(String name, String value) { - List valueList = (List)headers.get(name); - if (valueList == null) { - valueList = new ArrayList(); - headers.put(name, valueList); - } - valueList.add(value); - } - - /** - * String representation of the SmtpMessage. - * @return a String - */ - public String toString() { - StringBuffer msg = new StringBuffer(); - for (Iterator i = headers.keySet().iterator(); i.hasNext();) { - String name = (String)i.next(); - List values = (List)headers.get(name); - for (Iterator j = values.iterator(); j.hasNext();) { - String value = (String)j.next(); - msg.append(name); - msg.append(": "); - msg.append(value); - msg.append('\n'); - } - } - msg.append('\n'); - msg.append(body); - msg.append('\n'); - return msg.toString(); - } +/* + * Dumbster: a dummy SMTP server. + * Copyright (C) 2003, Jason Paul Kitchen + * lilnottsman@yahoo.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package com.dumbster.smtp; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * Container for a complete SMTP message - headers and message body. + */ +public class SmtpMessage { + + /** Headers: Map of List of String hashed on header name. */ + private Map headers; + + /** Message body. */ + private StringBuffer body; + + /** + * Constructor. Initializes headers Map and body buffer. + */ + public SmtpMessage() { + headers = new HashMap(); + body = new StringBuffer(); + } + + /** + * Update the headers or body depending on the SmtpResponse object and line of input. + * @param response SmtpResponse object + * @param params remainder of input line after SMTP command has been removed + */ + public void store(SmtpResponse response, String params) { + if (params != null) { + if (SmtpState.DATA_HDR == response.getNextState()) { + int headerNameEnd = params.indexOf(':'); + if (headerNameEnd >= 0) { + String name = params.substring(0, headerNameEnd).trim(); + String value = params.substring(headerNameEnd + 1).trim(); + addHeader(name, value); + } + } else if (SmtpState.DATA_BODY == response.getNextState()) { + body.append(params); + } + } + } + + /** + * Get an Iterator over the header names. + * @return an Iterator over the set of header names (String) + */ + public Iterator getHeaderNames() { + return headers.keySet().iterator(); + } + + /** + * Get the value(s) associated with the given header name. + * @param name header name + * @return value(s) associated with the header name + */ + public String[] getHeaderValues(String name) { + List values = (List)headers.get(name); + if (values == null) { + return new String[0]; + } else { + return (String[])values.toArray(new String[0]); + } + } + + /** + * Get the first values associated with a given header name. + * @param name header name + * @return first value associated with the header name + */ + public String getHeaderValue(String name) { + List values = (List)headers.get(name); + if (values == null) { + return null; + } else { + return (String)values.iterator().next(); + } + } + + /** + * Get the message body. + * @return message body + */ + public String getBody() { + return body.toString(); + } + + /** + * Adds a header to the Map. + * @param name header name + * @param value header value + */ + private void addHeader(String name, String value) { + List valueList = (List)headers.get(name); + if (valueList == null) { + valueList = new ArrayList(); + headers.put(name, valueList); + } + valueList.add(value); + } + + /** + * String representation of the SmtpMessage. + * @return a String + */ + public String toString() { + StringBuffer msg = new StringBuffer(); + for (Iterator i = headers.keySet().iterator(); i.hasNext();) { + String name = (String)i.next(); + List values = (List)headers.get(name); + for (Iterator j = values.iterator(); j.hasNext();) { + String value = (String)j.next(); + msg.append(name); + msg.append(": "); + msg.append(value); + msg.append('\n'); + } + } + msg.append('\n'); + msg.append(body); + msg.append('\n'); + return msg.toString(); + } } \ No newline at end of file diff --git a/src/test/java/com/dumbster/smtp/SmtpRequest.java b/src/test/java/com/dumbster/smtp/SmtpRequest.java old mode 100755 new mode 100644 index dbb34a8..2a80d71 --- a/src/test/java/com/dumbster/smtp/SmtpRequest.java +++ b/src/test/java/com/dumbster/smtp/SmtpRequest.java @@ -1,212 +1,212 @@ -/* - * Dumbster: a dummy SMTP server. - * Copyright (C) 2003, Jason Paul Kitchen - * lilnottsman@yahoo.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.dumbster.smtp; - -/** - * Contains an SMTP client request. - */ -public class SmtpRequest { - - /** SMTP action received from client. */ - private SmtpActionType action; - - /** Current state of the SMTP state table. */ - private SmtpState state; - - /** Additional information passed from the client with the SMTP action. */ - private String params; - - /** - * Create a new SMTP client request. - * @param actionType type of action/command - * @param params remainder of command line once command is removed - * @param state current SMTP server state - */ - public SmtpRequest(SmtpActionType actionType, String params, SmtpState state) { - this.action = actionType; - this.state = state; - this.params = params; - } - - /** - * Execute the SMTP request returning a response. This method models the state transition table for the SMTP server. - * @return reponse to the request - */ - public SmtpResponse execute() { - SmtpResponse response = null; - if (action.isStateless()) { - if (SmtpActionType.EXPN == action || SmtpActionType.VRFY == action) { - response = new SmtpResponse(252, "Not supported", this.state); - } else if (SmtpActionType.HELP == action) { - response = new SmtpResponse(211, "No help available", this.state); - } else if (SmtpActionType.NOOP == action) { - response = new SmtpResponse(250, "OK", this.state); - } else if (SmtpActionType.VRFY == action) { - response = new SmtpResponse(252, "Not supported", this.state); - } else if (SmtpActionType.RSET == action) { - response = new SmtpResponse(250, "OK", SmtpState.GREET); - } else { - response = new SmtpResponse(500, "Command not recognized", this.state); - } - } else { // Stateful commands - if (SmtpActionType.CONNECT == action) { - if (SmtpState.CONNECT == state) { - response = new SmtpResponse(220, "localhost Dumbster SMTP service ready", - SmtpState.GREET); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.EHLO == action) { - if (SmtpState.GREET == state) { - response = new SmtpResponse(250, "OK", SmtpState.MAIL); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.MAIL == action) { - if (SmtpState.MAIL == state) { - response = new SmtpResponse(250, "OK", SmtpState.RCPT); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.RCPT == action) { - if (SmtpState.RCPT == state) { - response = new SmtpResponse(250, "OK", this.state); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.DATA == action) { - if (SmtpState.RCPT == state) { - response = new SmtpResponse(354, "Start mail input; end with .", - SmtpState.DATA_HDR); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.UNRECOG == action) { - if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state) { - response = new SmtpResponse(-1, "", this.state); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.DATA_END == action) { - if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state) { - response = new SmtpResponse(250, "OK", SmtpState.QUIT); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.BLANK_LINE == action) { - if (SmtpState.DATA_HDR == state) { - response = new SmtpResponse(-1, "", SmtpState.DATA_BODY); - } else if (SmtpState.DATA_BODY == state) { - response = new SmtpResponse(-1, "", this.state); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else if (SmtpActionType.QUIT == action) { - if (SmtpState.QUIT == state) { - response = new SmtpResponse(250, "OK", SmtpState.CONNECT); - } else { - response = new SmtpResponse(503, "Bad sequence of commands: " + action, - this.state); - } - } else { - response = new SmtpResponse(500, "Command not recognized", this.state); - } - } - return response; - } - - /** - * Create an SMTP request object given a line of the input stream from the client and the current internal state. - * @param s line of input - * @param state current state - * @return a populated SmtpRequest object - */ - public static SmtpRequest createRequest(String s, SmtpState state) { - SmtpActionType action = null; - String params = null; - - if (state == SmtpState.DATA_HDR) { - if (s.equals(".")) { - action = SmtpActionType.DATA_END; - } else if (s.length() < 1) { - action = SmtpActionType.BLANK_LINE; - } else { - action = SmtpActionType.UNRECOG; - params = s; - } - } else if (state == SmtpState.DATA_BODY) { - if (s.equals(".")) { - action = SmtpActionType.DATA_END; - } else { - action = SmtpActionType.UNRECOG; - if (s.length() < 1) { - params = "\n"; - } else { - params = s; - } - } - } else { - String su = s.toUpperCase(); - if (su.startsWith("EHLO ") || su.startsWith("HELO")) { - action = SmtpActionType.EHLO; - params = s.substring(5); - } else if (su.startsWith("MAIL FROM:")) { - action = SmtpActionType.MAIL; - params = s.substring(10); - } else if (su.startsWith("RCPT TO:")) { - action = SmtpActionType.RCPT; - params = s.substring(8); - } else if (su.startsWith("DATA")) { - action = SmtpActionType.DATA; - } else if (su.startsWith("QUIT")) { - action = SmtpActionType.QUIT; - } else if (su.startsWith("RSET")) { - action = SmtpActionType.RSET; - } else if (su.startsWith("NOOP")) { - action = SmtpActionType.NOOP; - } else if (su.startsWith("EXPN")) { - action = SmtpActionType.EXPN; - } else if (su.startsWith("VRFY")) { - action = SmtpActionType.VRFY; - } else if (su.startsWith("HELP")) { - action = SmtpActionType.HELP; - } - } - - SmtpRequest req = new SmtpRequest(action, params, state); - return req; - } - - /** - * Get the parameters of this request (remainder of command line once the command is removed. - * @return parameters - */ - public String getParams() { - return params; - } +/* + * Dumbster: a dummy SMTP server. + * Copyright (C) 2003, Jason Paul Kitchen + * lilnottsman@yahoo.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package com.dumbster.smtp; + +/** + * Contains an SMTP client request. + */ +public class SmtpRequest { + + /** SMTP action received from client. */ + private SmtpActionType action; + + /** Current state of the SMTP state table. */ + private SmtpState state; + + /** Additional information passed from the client with the SMTP action. */ + private String params; + + /** + * Create a new SMTP client request. + * @param actionType type of action/command + * @param params remainder of command line once command is removed + * @param state current SMTP server state + */ + public SmtpRequest(SmtpActionType actionType, String params, SmtpState state) { + this.action = actionType; + this.state = state; + this.params = params; + } + + /** + * Execute the SMTP request returning a response. This method models the state transition table for the SMTP server. + * @return reponse to the request + */ + public SmtpResponse execute() { + SmtpResponse response = null; + if (action.isStateless()) { + if (SmtpActionType.EXPN == action || SmtpActionType.VRFY == action) { + response = new SmtpResponse(252, "Not supported", this.state); + } else if (SmtpActionType.HELP == action) { + response = new SmtpResponse(211, "No help available", this.state); + } else if (SmtpActionType.NOOP == action) { + response = new SmtpResponse(250, "OK", this.state); + } else if (SmtpActionType.VRFY == action) { + response = new SmtpResponse(252, "Not supported", this.state); + } else if (SmtpActionType.RSET == action) { + response = new SmtpResponse(250, "OK", SmtpState.GREET); + } else { + response = new SmtpResponse(500, "Command not recognized", this.state); + } + } else { // Stateful commands + if (SmtpActionType.CONNECT == action) { + if (SmtpState.CONNECT == state) { + response = new SmtpResponse(220, "localhost Dumbster SMTP service ready", + SmtpState.GREET); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.EHLO == action) { + if (SmtpState.GREET == state) { + response = new SmtpResponse(250, "OK", SmtpState.MAIL); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.MAIL == action) { + if (SmtpState.MAIL == state) { + response = new SmtpResponse(250, "OK", SmtpState.RCPT); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.RCPT == action) { + if (SmtpState.RCPT == state) { + response = new SmtpResponse(250, "OK", this.state); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.DATA == action) { + if (SmtpState.RCPT == state) { + response = new SmtpResponse(354, "Start mail input; end with .", + SmtpState.DATA_HDR); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.UNRECOG == action) { + if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state) { + response = new SmtpResponse(-1, "", this.state); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.DATA_END == action) { + if (SmtpState.DATA_HDR == state || SmtpState.DATA_BODY == state) { + response = new SmtpResponse(250, "OK", SmtpState.QUIT); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.BLANK_LINE == action) { + if (SmtpState.DATA_HDR == state) { + response = new SmtpResponse(-1, "", SmtpState.DATA_BODY); + } else if (SmtpState.DATA_BODY == state) { + response = new SmtpResponse(-1, "", this.state); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else if (SmtpActionType.QUIT == action) { + if (SmtpState.QUIT == state) { + response = new SmtpResponse(250, "OK", SmtpState.CONNECT); + } else { + response = new SmtpResponse(503, "Bad sequence of commands: " + action, + this.state); + } + } else { + response = new SmtpResponse(500, "Command not recognized", this.state); + } + } + return response; + } + + /** + * Create an SMTP request object given a line of the input stream from the client and the current internal state. + * @param s line of input + * @param state current state + * @return a populated SmtpRequest object + */ + public static SmtpRequest createRequest(String s, SmtpState state) { + SmtpActionType action = null; + String params = null; + + if (state == SmtpState.DATA_HDR) { + if (s.equals(".")) { + action = SmtpActionType.DATA_END; + } else if (s.length() < 1) { + action = SmtpActionType.BLANK_LINE; + } else { + action = SmtpActionType.UNRECOG; + params = s; + } + } else if (state == SmtpState.DATA_BODY) { + if (s.equals(".")) { + action = SmtpActionType.DATA_END; + } else { + action = SmtpActionType.UNRECOG; + if (s.length() < 1) { + params = "\n"; + } else { + params = s; + } + } + } else { + String su = s.toUpperCase(); + if (su.startsWith("EHLO ") || su.startsWith("HELO")) { + action = SmtpActionType.EHLO; + params = s.substring(5); + } else if (su.startsWith("MAIL FROM:")) { + action = SmtpActionType.MAIL; + params = s.substring(10); + } else if (su.startsWith("RCPT TO:")) { + action = SmtpActionType.RCPT; + params = s.substring(8); + } else if (su.startsWith("DATA")) { + action = SmtpActionType.DATA; + } else if (su.startsWith("QUIT")) { + action = SmtpActionType.QUIT; + } else if (su.startsWith("RSET")) { + action = SmtpActionType.RSET; + } else if (su.startsWith("NOOP")) { + action = SmtpActionType.NOOP; + } else if (su.startsWith("EXPN")) { + action = SmtpActionType.EXPN; + } else if (su.startsWith("VRFY")) { + action = SmtpActionType.VRFY; + } else if (su.startsWith("HELP")) { + action = SmtpActionType.HELP; + } + } + + SmtpRequest req = new SmtpRequest(action, params, state); + return req; + } + + /** + * Get the parameters of this request (remainder of command line once the command is removed. + * @return parameters + */ + public String getParams() { + return params; + } } \ No newline at end of file diff --git a/src/test/java/com/dumbster/smtp/SmtpResponse.java b/src/test/java/com/dumbster/smtp/SmtpResponse.java old mode 100755 new mode 100644 index f7a036c..cacc6f1 --- a/src/test/java/com/dumbster/smtp/SmtpResponse.java +++ b/src/test/java/com/dumbster/smtp/SmtpResponse.java @@ -1,71 +1,71 @@ -/* - * Dumbster: a dummy SMTP server. - * Copyright (C) 2003, Jason Paul Kitchen - * lilnottsman@yahoo.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.dumbster.smtp; - -/** - * SMTP response container. - */ -public class SmtpResponse { - - /** Response code - see RFC-2821. */ - private int code; - - /** Response message. */ - private String message; - - /** New state of the SMTP server once the request has been executed. */ - private SmtpState nextState; - - /** - * Constructor. - * @param code response code - * @param message response message - * @param next next state of the SMTP server - */ - public SmtpResponse(int code, String message, SmtpState next) { - this.code = code; - this.message = message; - this.nextState = next; - } - - /** - * Get the response code. - * @return response code - */ - public int getCode() { - return code; - } - - /** - * Get the response message. - * @return response message - */ - public String getMessage() { - return message; - } - - /** - * Get the next SMTP server state. - * @return state - */ - public SmtpState getNextState() { - return nextState; - } +/* + * Dumbster: a dummy SMTP server. + * Copyright (C) 2003, Jason Paul Kitchen + * lilnottsman@yahoo.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package com.dumbster.smtp; + +/** + * SMTP response container. + */ +public class SmtpResponse { + + /** Response code - see RFC-2821. */ + private int code; + + /** Response message. */ + private String message; + + /** New state of the SMTP server once the request has been executed. */ + private SmtpState nextState; + + /** + * Constructor. + * @param code response code + * @param message response message + * @param next next state of the SMTP server + */ + public SmtpResponse(int code, String message, SmtpState next) { + this.code = code; + this.message = message; + this.nextState = next; + } + + /** + * Get the response code. + * @return response code + */ + public int getCode() { + return code; + } + + /** + * Get the response message. + * @return response message + */ + public String getMessage() { + return message; + } + + /** + * Get the next SMTP server state. + * @return state + */ + public SmtpState getNextState() { + return nextState; + } } \ No newline at end of file diff --git a/src/test/java/com/dumbster/smtp/SmtpState.java b/src/test/java/com/dumbster/smtp/SmtpState.java old mode 100755 new mode 100644 index da9c8e5..bff284d --- a/src/test/java/com/dumbster/smtp/SmtpState.java +++ b/src/test/java/com/dumbster/smtp/SmtpState.java @@ -1,104 +1,104 @@ -/* - * Dumbster: a dummy SMTP server. - * Copyright (C) 2003, Jason Paul Kitchen - * lilnottsman@yahoo.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - */ -package com.dumbster.smtp; - -/** - * SMTP server state. - */ -public class SmtpState { - - /** Internal representation of the state. */ - private byte value; - - /** Internal representation of the CONNECT state. */ - private static final byte CONNECT_BYTE = 1; - - /** Internal representation of the GREET state. */ - private static final byte GREET_BYTE = 2; - - /** Internal representation of the MAIL state. */ - private static final byte MAIL_BYTE = 3; - - /** Internal representation of the RCPT state. */ - private static final byte RCPT_BYTE = 4; - - /** Internal representation of the DATA_HEADER state. */ - private static final byte DATA_HEADER_BYTE = 5; - - /** Internal representation of the DATA_BODY state. */ - private static final byte DATA_BODY_BYTE = 6; - - /** Internal representation of the QUIT state. */ - private static final byte QUIT_BYTE = 7; - - /** CONNECT state: waiting for a client connection. */ - public static final SmtpState CONNECT = new SmtpState(CONNECT_BYTE); - - /** GREET state: wating for a ELHO message. */ - public static final SmtpState GREET = new SmtpState(GREET_BYTE); - - /** MAIL state: waiting for the MAIL FROM: command. */ - public static final SmtpState MAIL = new SmtpState(MAIL_BYTE); - - /** RCPT state: waiting for a RCPT <email address> command. */ - public static final SmtpState RCPT = new SmtpState(RCPT_BYTE); - - /** Waiting for headers. */ - public static final SmtpState DATA_HDR = new SmtpState(DATA_HEADER_BYTE); - - /** Processing body text. */ - public static final SmtpState DATA_BODY = new SmtpState(DATA_BODY_BYTE); - - /** End of client transmission. */ - public static final SmtpState QUIT = new SmtpState(QUIT_BYTE); - - /** - * Create a new SmtpState object. Private to ensure that only valid states can be created. - * @param value one of the _BYTE values. - */ - private SmtpState(byte value) { - this.value = value; - } - - /** - * String representation of this SmtpState. - * @return a String - */ - public String toString() { - switch (value) { - case CONNECT_BYTE: - return "CONNECT"; - case GREET_BYTE: - return "GREET"; - case MAIL_BYTE: - return "MAIL"; - case RCPT_BYTE: - return "RCPT"; - case DATA_HEADER_BYTE: - return "DATA_HDR"; - case DATA_BODY_BYTE: - return "DATA_BODY"; - case QUIT_BYTE: - return "QUIT"; - default: - return "Unknown"; - } - } +/* + * Dumbster: a dummy SMTP server. + * Copyright (C) 2003, Jason Paul Kitchen + * lilnottsman@yahoo.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +package com.dumbster.smtp; + +/** + * SMTP server state. + */ +public class SmtpState { + + /** Internal representation of the state. */ + private byte value; + + /** Internal representation of the CONNECT state. */ + private static final byte CONNECT_BYTE = 1; + + /** Internal representation of the GREET state. */ + private static final byte GREET_BYTE = 2; + + /** Internal representation of the MAIL state. */ + private static final byte MAIL_BYTE = 3; + + /** Internal representation of the RCPT state. */ + private static final byte RCPT_BYTE = 4; + + /** Internal representation of the DATA_HEADER state. */ + private static final byte DATA_HEADER_BYTE = 5; + + /** Internal representation of the DATA_BODY state. */ + private static final byte DATA_BODY_BYTE = 6; + + /** Internal representation of the QUIT state. */ + private static final byte QUIT_BYTE = 7; + + /** CONNECT state: waiting for a client connection. */ + public static final SmtpState CONNECT = new SmtpState(CONNECT_BYTE); + + /** GREET state: wating for a ELHO message. */ + public static final SmtpState GREET = new SmtpState(GREET_BYTE); + + /** MAIL state: waiting for the MAIL FROM: command. */ + public static final SmtpState MAIL = new SmtpState(MAIL_BYTE); + + /** RCPT state: waiting for a RCPT <email address> command. */ + public static final SmtpState RCPT = new SmtpState(RCPT_BYTE); + + /** Waiting for headers. */ + public static final SmtpState DATA_HDR = new SmtpState(DATA_HEADER_BYTE); + + /** Processing body text. */ + public static final SmtpState DATA_BODY = new SmtpState(DATA_BODY_BYTE); + + /** End of client transmission. */ + public static final SmtpState QUIT = new SmtpState(QUIT_BYTE); + + /** + * Create a new SmtpState object. Private to ensure that only valid states can be created. + * @param value one of the _BYTE values. + */ + private SmtpState(byte value) { + this.value = value; + } + + /** + * String representation of this SmtpState. + * @return a String + */ + public String toString() { + switch (value) { + case CONNECT_BYTE: + return "CONNECT"; + case GREET_BYTE: + return "GREET"; + case MAIL_BYTE: + return "MAIL"; + case RCPT_BYTE: + return "RCPT"; + case DATA_HEADER_BYTE: + return "DATA_HDR"; + case DATA_BODY_BYTE: + return "DATA_BODY"; + case QUIT_BYTE: + return "QUIT"; + default: + return "Unknown"; + } + } } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/fetch/impl/FetchMailImplRealTest.java b/src/test/java/com/ozacc/mail/fetch/impl/FetchMailImplRealTest.java old mode 100755 new mode 100644 index 31182ee..4c6a418 --- a/src/test/java/com/ozacc/mail/fetch/impl/FetchMailImplRealTest.java +++ b/src/test/java/com/ozacc/mail/fetch/impl/FetchMailImplRealTest.java @@ -1,61 +1,61 @@ -package com.ozacc.mail.fetch.impl; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -/** - * FetchMailImplクラスのテストケース。実際にメールサーバから受信して確認するテストです。 - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: FetchMailImplRealTest.java,v 1.1.2.5 2005/01/23 06:52:04 otsuka Exp $ - */ -public class FetchMailImplRealTest extends TestCase { - - private String username = "username"; - - private String password = "password"; - - private String protocol = "pop3"; - - private String host = "localhost"; - - private FetchMailImpl fetchMail; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - BasicConfigurator.configure(); - - fetchMail = new FetchMailImpl(); - fetchMail.setHost(host); - fetchMail.setProtocol(protocol); - fetchMail.setUsername(username); - fetchMail.setPassword(password); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - BasicConfigurator.resetConfiguration(); - } - - /*public void testGetMails() throws Exception { - ReceivedMail[] mails = fetchMail.getMails(true); - for (int i = 0; i < mails.length; i++) { - ReceivedMail mail = mails[i]; - } - }*/ - - /** - * テストケースがひとつもないとビルド時にエラーになるので、ダミー。 - */ - public void testDummy() { - assertTrue(true); - } +package com.ozacc.mail.fetch.impl; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +/** + * FetchMailImplクラスのテストケース。実際にメールサーバから受信して確認するテストです。 + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: FetchMailImplRealTest.java,v 1.1.2.5 2005/01/23 06:52:04 otsuka Exp $ + */ +public class FetchMailImplRealTest extends TestCase { + + private String username = "username"; + + private String password = "password"; + + private String protocol = "pop3"; + + private String host = "localhost"; + + private FetchMailImpl fetchMail; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + BasicConfigurator.configure(); + + fetchMail = new FetchMailImpl(); + fetchMail.setHost(host); + fetchMail.setProtocol(protocol); + fetchMail.setUsername(username); + fetchMail.setPassword(password); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + BasicConfigurator.resetConfiguration(); + } + + /*public void testGetMails() throws Exception { + ReceivedMail[] mails = fetchMail.getMails(true); + for (int i = 0; i < mails.length; i++) { + ReceivedMail mail = mails[i]; + } + }*/ + + /** + * テストケースがひとつもないとビルド時にエラーになるので、ダミー。 + */ + public void testDummy() { + assertTrue(true); + } } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/fetch/impl/FetchMailProImplRealTest.java b/src/test/java/com/ozacc/mail/fetch/impl/FetchMailProImplRealTest.java old mode 100755 new mode 100644 index de9c23f..4166cb0 --- a/src/test/java/com/ozacc/mail/fetch/impl/FetchMailProImplRealTest.java +++ b/src/test/java/com/ozacc/mail/fetch/impl/FetchMailProImplRealTest.java @@ -1,59 +1,59 @@ -package com.ozacc.mail.fetch.impl; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -/** - * - * @since 1.2 - * @author Tomohiro Otsuka - * @version $Id: FetchMailProImplRealTest.java,v 1.1.2.3 2005/01/18 07:29:31 otsuka Exp $ - */ -public class FetchMailProImplRealTest extends TestCase { - - private String username = "username"; - - private String password = "password"; - - private String protocol = "pop3"; - - private String host = "localhost"; - - private FetchMailProImpl fetchMail; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - BasicConfigurator.configure(); - - fetchMail = new FetchMailProImpl(); - fetchMail.setHost(host); - fetchMail.setProtocol(protocol); - fetchMail.setUsername(username); - fetchMail.setPassword(password); - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - BasicConfigurator.resetConfiguration(); - } - - /*public void testGetMails() throws Exception { - fetchMail.connect(); - ReceivedMail[] mails = fetchMail.getMails(false); - fetchMail.disconnect(); - }*/ - - /** - * テストケースがひとつもないとビルド時にエラーになるので、ダミー。 - */ - public void testDummy() { - assertTrue(true); - } +package com.ozacc.mail.fetch.impl; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +/** + * + * @since 1.2 + * @author Tomohiro Otsuka + * @version $Id: FetchMailProImplRealTest.java,v 1.1.2.3 2005/01/18 07:29:31 otsuka Exp $ + */ +public class FetchMailProImplRealTest extends TestCase { + + private String username = "username"; + + private String password = "password"; + + private String protocol = "pop3"; + + private String host = "localhost"; + + private FetchMailProImpl fetchMail; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + BasicConfigurator.configure(); + + fetchMail = new FetchMailProImpl(); + fetchMail.setHost(host); + fetchMail.setProtocol(protocol); + fetchMail.setUsername(username); + fetchMail.setPassword(password); + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + BasicConfigurator.resetConfiguration(); + } + + /*public void testGetMails() throws Exception { + fetchMail.connect(); + ReceivedMail[] mails = fetchMail.getMails(false); + fetchMail.disconnect(); + }*/ + + /** + * テストケースがひとつもないとビルド時にエラーになるので、ダミー。 + */ + public void testDummy() { + assertTrue(true); + } } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/impl/JDomXMLMailBuilderTest.java b/src/test/java/com/ozacc/mail/impl/JDomXMLMailBuilderTest.java old mode 100755 new mode 100644 index f4d862c..c5ac44c --- a/src/test/java/com/ozacc/mail/impl/JDomXMLMailBuilderTest.java +++ b/src/test/java/com/ozacc/mail/impl/JDomXMLMailBuilderTest.java @@ -1,303 +1,303 @@ -package com.ozacc.mail.impl; - -import java.io.File; - -import javax.mail.internet.InternetAddress; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.apache.velocity.VelocityContext; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuildException; - -/** - * XMLMailBuilderのテストケース。 - * - * @author Tomohiro Otsuka - * @version $Id: JDomXMLMailBuilderTest.java,v 1.3.2.2 2005/02/01 20:38:14 otsuka Exp $ - */ -public class JDomXMLMailBuilderTest extends TestCase { - - private JDomXMLMailBuilder builder; - - protected void setUp() throws Exception { - super.setUp(); - BasicConfigurator.configure(); - - builder = new JDomXMLMailBuilder(); - } - - protected void tearDown() throws Exception { - super.tearDown(); - BasicConfigurator.resetConfiguration(); - } - - public final void testBuildMailCDATA() throws Exception { - String classPath = "/com/ozacc/mail/test-mail6-cdata.xml"; - - String expectedBody = "これはCDATAのテキストです。"; - - Mail result = builder.buildMail(classPath); - - assertEquals(expectedBody, result.getText()); - } - - /* - * Class under test for Mail buildMail(String) - * 存在しないファイルのパスを指定して失敗。 - */ - public final void testBuildMailFromClassPathNotExist() throws Exception { - String classPath = "/com/ozacc/mail/testtest-mail1.xml"; - try { - Mail result = builder.buildMail(classPath); - fail("This should never be called."); - } catch (MailBuildException expected) { - // success - } - } - - /* - * Class under test for Mail buildMail(File) - * 存在しないファイルを指定して失敗 - */ - public final void testBuildMailFromFileNotExist() throws Exception { - String path = "src/test/java/com/ozacc/mail/testtest-mail1.xml"; - File file = new File(path); - try { - Mail result = builder.buildMail(file); - fail("This should never be called."); - } catch (MailBuildException expected) { - // success - } - } - - /* - * Class under test for Mail buildMail(String) - * DTD違反のXMLのため失敗。 - */ - public final void testBuildMailFromClassPathInvalidXML() throws Exception { - String classPath = "/com/ozacc/mail/test-mail2-invalid.xml"; - try { - Mail result = builder.buildMail(classPath); - fail("This should never be called."); - } catch (MailBuildException expected) { - // success - } - } - - /* - * Class under test for Mail buildMail(String) - * XMLファイルのクラスパスからMailインスタンスを生成。 - */ - public final void testBuildMailFromClassPath() throws Exception { - String classPath = "/com/ozacc/mail/test-mail1.xml"; - - String subject = "XMLMailBuilderのテストケース"; - String text = "改行します。\n改行しました。\nテストは成功。"; - - InternetAddress from = new InternetAddress("from@example.com", "差出人"); - InternetAddress returnPath = new InternetAddress("return@example.com"); - InternetAddress replyTo = new InternetAddress("reply@example.com"); - - InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); - InternetAddress to2 = new InternetAddress("to2@example.com"); - - InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); - InternetAddress cc2 = new InternetAddress("cc2@example.com"); - - InternetAddress bcc = new InternetAddress("bcc@example.com"); - - Mail result = builder.buildMail(classPath); - - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - - assertEquals(from, result.getFrom()); - assertEquals(returnPath, result.getReturnPath()); - assertEquals(replyTo, result.getReplyTo()); - - InternetAddress[] tos = result.getTo(); - assertEquals(2, tos.length); - assertEquals(to1, tos[0]); - assertEquals(to2, tos[1]); - - InternetAddress[] ccs = result.getCc(); - assertEquals(2, ccs.length); - assertEquals(cc1, ccs[0]); - assertEquals(cc2, ccs[1]); - - InternetAddress[] bccs = result.getBcc(); - assertEquals(1, bccs.length); - assertEquals(bcc, bccs[0]); - } - - /* - * Class under test for Mail buildMail(File) - * XMLファイルのFileインスタンスからMailインスタンスを生成。 - */ - public final void testBuildMailFromFile() throws Exception { - String path = "src/test/java/com/ozacc/mail/test-mail1.xml"; - File file = new File(path); - - String subject = "XMLMailBuilderのテストケース"; - String text = "改行します。\n改行しました。\nテストは成功。"; - - InternetAddress from = new InternetAddress("from@example.com", "差出人"); - InternetAddress returnPath = new InternetAddress("return@example.com"); - InternetAddress replyTo = new InternetAddress("reply@example.com"); - - InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); - InternetAddress to2 = new InternetAddress("to2@example.com"); - - InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); - InternetAddress cc2 = new InternetAddress("cc2@example.com"); - - InternetAddress bcc = new InternetAddress("bcc@example.com"); - - Mail result = builder.buildMail(file); - - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - - assertEquals(from, result.getFrom()); - assertEquals(returnPath, result.getReturnPath()); - assertEquals(replyTo, result.getReplyTo()); - - InternetAddress[] tos = result.getTo(); - assertEquals(2, tos.length); - assertEquals(to1, tos[0]); - assertEquals(to2, tos[1]); - - InternetAddress[] ccs = result.getCc(); - assertEquals(2, ccs.length); - assertEquals(cc1, ccs[0]); - assertEquals(cc2, ccs[1]); - - InternetAddress[] bccs = result.getBcc(); - assertEquals(1, bccs.length); - assertEquals(bcc, bccs[0]); - } - - /* - * Class under test for Mail buildMail(String, VelocityContext) - */ - public final void testBuildMailStringVelocityContext() throws Exception { - String classPath = "/com/ozacc/mail/test-mail3-velocity.xml"; - - String name = "伊東美咲"; - String email = "misaki@example.com"; - Customer customer = new Customer(name, email); - String item = "GIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; - - InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); - InternetAddress to = new InternetAddress(email, name); - - String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; - String text = name - + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; - - VelocityContext context = new VelocityContext(); - context.put("customer", customer); - context.put("item", item); - - // メール生成実行 - Mail result = builder.buildMail(classPath, context); - - assertEquals(from, result.getFrom()); - assertEquals(to, result.getTo()[0]); - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - } - - /* - * Class under test for Mail buildMail(File, VelocityContext) - */ - public final void testBuildMailFileVelocityContext() throws Exception { - String path = "src/test/java/com/ozacc/mail/test-mail3-velocity.xml"; - File file = new File(path); - - String name = "伊東美咲"; - String email = "misaki@example.com"; - Customer customer = new Customer(name, email); - String item = "GIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; - - InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); - InternetAddress to = new InternetAddress(email, name); - - String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; - String text = name - + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; - - VelocityContext context = new VelocityContext(); - context.put("customer", customer); - context.put("item", item); - - // メール生成実行 - Mail result = builder.buildMail(file, context); - - assertEquals(from, result.getFrom()); - assertEquals(to, result.getTo()[0]); - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - } - - public void testBuildMailFromMultipleMailsTemplate() throws Exception { - String path = "src/test/java/com/ozacc/mail/test-mail7-multiple.xml"; - File file = new File(path); - - Mail result1 = builder.buildMail(file, "first"); - assertEquals("1通目", result1.getText()); - - Mail result2 = builder.buildMail(file, "second"); - assertEquals("2通目", result2.getText()); - - try { - Mail result3 = builder.buildMail(file, "サード"); - } catch (MailBuildException expected) { - - } - } - - public static class Customer { - - private String name; - - private String email; - - public Customer(String name, String email) { - this.name = name; - this.email = email; - } - - /** - * @return Returns the email. - */ - public String getEmail() { - return email; - } - - /** - * @param email The email to set. - */ - public void setEmail(String email) { - this.email = email; - } - - /** - * @return Returns the name. - */ - public String getName() { - return name; - } - - /** - * @param name The name to set. - */ - public void setName(String name) { - this.name = name; - } - } - +package com.ozacc.mail.impl; + +import java.io.File; + +import javax.mail.internet.InternetAddress; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; +import org.apache.velocity.VelocityContext; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuildException; + +/** + * XMLMailBuilderのテストケース。 + * + * @author Tomohiro Otsuka + * @version $Id: JDomXMLMailBuilderTest.java,v 1.3.2.2 2005/02/01 20:38:14 otsuka Exp $ + */ +public class JDomXMLMailBuilderTest extends TestCase { + + private JDomXMLMailBuilder builder; + + protected void setUp() throws Exception { + super.setUp(); + BasicConfigurator.configure(); + + builder = new JDomXMLMailBuilder(); + } + + protected void tearDown() throws Exception { + super.tearDown(); + BasicConfigurator.resetConfiguration(); + } + + public final void testBuildMailCDATA() throws Exception { + String classPath = "/com/ozacc/mail/test-mail6-cdata.xml"; + + String expectedBody = "これはCDATAのテキストです。"; + + Mail result = builder.buildMail(classPath); + + assertEquals(expectedBody, result.getText()); + } + + /* + * Class under test for Mail buildMail(String) + * 存在しないファイルのパスを指定して失敗。 + */ + public final void testBuildMailFromClassPathNotExist() throws Exception { + String classPath = "/com/ozacc/mail/testtest-mail1.xml"; + try { + Mail result = builder.buildMail(classPath); + fail("This should never be called."); + } catch (MailBuildException expected) { + // success + } + } + + /* + * Class under test for Mail buildMail(File) + * 存在しないファイルを指定して失敗 + */ + public final void testBuildMailFromFileNotExist() throws Exception { + String path = "src/test/java/com/ozacc/mail/testtest-mail1.xml"; + File file = new File(path); + try { + Mail result = builder.buildMail(file); + fail("This should never be called."); + } catch (MailBuildException expected) { + // success + } + } + + /* + * Class under test for Mail buildMail(String) + * DTD違反のXMLのため失敗。 + */ + public final void testBuildMailFromClassPathInvalidXML() throws Exception { + String classPath = "/com/ozacc/mail/test-mail2-invalid.xml"; + try { + Mail result = builder.buildMail(classPath); + fail("This should never be called."); + } catch (MailBuildException expected) { + // success + } + } + + /* + * Class under test for Mail buildMail(String) + * XMLファイルのクラスパスからMailインスタンスを生成。 + */ + public final void testBuildMailFromClassPath() throws Exception { + String classPath = "/com/ozacc/mail/test-mail1.xml"; + + String subject = "XMLMailBuilderのテストケース"; + String text = "改行します。\n改行しました。\nテストは成功。"; + + InternetAddress from = new InternetAddress("from@example.com", "差出人"); + InternetAddress returnPath = new InternetAddress("return@example.com"); + InternetAddress replyTo = new InternetAddress("reply@example.com"); + + InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); + InternetAddress to2 = new InternetAddress("to2@example.com"); + + InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); + InternetAddress cc2 = new InternetAddress("cc2@example.com"); + + InternetAddress bcc = new InternetAddress("bcc@example.com"); + + Mail result = builder.buildMail(classPath); + + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + + assertEquals(from, result.getFrom()); + assertEquals(returnPath, result.getReturnPath()); + assertEquals(replyTo, result.getReplyTo()); + + InternetAddress[] tos = result.getTo(); + assertEquals(2, tos.length); + assertEquals(to1, tos[0]); + assertEquals(to2, tos[1]); + + InternetAddress[] ccs = result.getCc(); + assertEquals(2, ccs.length); + assertEquals(cc1, ccs[0]); + assertEquals(cc2, ccs[1]); + + InternetAddress[] bccs = result.getBcc(); + assertEquals(1, bccs.length); + assertEquals(bcc, bccs[0]); + } + + /* + * Class under test for Mail buildMail(File) + * XMLファイルのFileインスタンスからMailインスタンスを生成。 + */ + public final void testBuildMailFromFile() throws Exception { + String path = "src/test/java/com/ozacc/mail/test-mail1.xml"; + File file = new File(path); + + String subject = "XMLMailBuilderのテストケース"; + String text = "改行します。\n改行しました。\nテストは成功。"; + + InternetAddress from = new InternetAddress("from@example.com", "差出人"); + InternetAddress returnPath = new InternetAddress("return@example.com"); + InternetAddress replyTo = new InternetAddress("reply@example.com"); + + InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); + InternetAddress to2 = new InternetAddress("to2@example.com"); + + InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); + InternetAddress cc2 = new InternetAddress("cc2@example.com"); + + InternetAddress bcc = new InternetAddress("bcc@example.com"); + + Mail result = builder.buildMail(file); + + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + + assertEquals(from, result.getFrom()); + assertEquals(returnPath, result.getReturnPath()); + assertEquals(replyTo, result.getReplyTo()); + + InternetAddress[] tos = result.getTo(); + assertEquals(2, tos.length); + assertEquals(to1, tos[0]); + assertEquals(to2, tos[1]); + + InternetAddress[] ccs = result.getCc(); + assertEquals(2, ccs.length); + assertEquals(cc1, ccs[0]); + assertEquals(cc2, ccs[1]); + + InternetAddress[] bccs = result.getBcc(); + assertEquals(1, bccs.length); + assertEquals(bcc, bccs[0]); + } + + /* + * Class under test for Mail buildMail(String, VelocityContext) + */ + public final void testBuildMailStringVelocityContext() throws Exception { + String classPath = "/com/ozacc/mail/test-mail3-velocity.xml"; + + String name = "伊東美咲"; + String email = "misaki@example.com"; + Customer customer = new Customer(name, email); + String item = "GIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; + + InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); + InternetAddress to = new InternetAddress(email, name); + + String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; + String text = name + + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; + + VelocityContext context = new VelocityContext(); + context.put("customer", customer); + context.put("item", item); + + // メール生成実行 + Mail result = builder.buildMail(classPath, context); + + assertEquals(from, result.getFrom()); + assertEquals(to, result.getTo()[0]); + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + } + + /* + * Class under test for Mail buildMail(File, VelocityContext) + */ + public final void testBuildMailFileVelocityContext() throws Exception { + String path = "src/test/java/com/ozacc/mail/test-mail3-velocity.xml"; + File file = new File(path); + + String name = "伊東美咲"; + String email = "misaki@example.com"; + Customer customer = new Customer(name, email); + String item = "GIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; + + InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); + InternetAddress to = new InternetAddress(email, name); + + String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; + String text = name + + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)\n\nDesigned by:Ronan & Erwan Boroullec, Size:W313*D84*H370, Color:グリーン, 本体:ABS樹脂"; + + VelocityContext context = new VelocityContext(); + context.put("customer", customer); + context.put("item", item); + + // メール生成実行 + Mail result = builder.buildMail(file, context); + + assertEquals(from, result.getFrom()); + assertEquals(to, result.getTo()[0]); + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + } + + public void testBuildMailFromMultipleMailsTemplate() throws Exception { + String path = "src/test/java/com/ozacc/mail/test-mail7-multiple.xml"; + File file = new File(path); + + Mail result1 = builder.buildMail(file, "first"); + assertEquals("1通目", result1.getText()); + + Mail result2 = builder.buildMail(file, "second"); + assertEquals("2通目", result2.getText()); + + try { + Mail result3 = builder.buildMail(file, "サード"); + } catch (MailBuildException expected) { + + } + } + + public static class Customer { + + private String name; + + private String email; + + public Customer(String name, String email) { + this.name = name; + this.email = email; + } + + /** + * @return Returns the email. + */ + public String getEmail() { + return email; + } + + /** + * @param email The email to set. + */ + public void setEmail(String email) { + this.email = email; + } + + /** + * @return Returns the name. + */ + public String getName() { + return name; + } + + /** + * @param name The name to set. + */ + public void setName(String name) { + this.name = name; + } + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/impl/OMLMimeMessageTest.java b/src/test/java/com/ozacc/mail/impl/OMLMimeMessageTest.java old mode 100755 new mode 100644 index 6aadfd1..f8cc665 --- a/src/test/java/com/ozacc/mail/impl/OMLMimeMessageTest.java +++ b/src/test/java/com/ozacc/mail/impl/OMLMimeMessageTest.java @@ -1,29 +1,29 @@ -package com.ozacc.mail.impl; - -import java.util.Properties; - -import javax.mail.Session; - -import junit.framework.TestCase; - -/** - * - * @author Tomohiro Otsuka - * @version $Id: OMLMimeMessageTest.java,v 1.1 2004/09/20 21:43:33 otsuka Exp $ - */ -public class OMLMimeMessageTest extends TestCase { - - public void testRandom() throws Exception { - Properties p = new Properties(); - OMLMimeMessage msg1 = new OMLMimeMessage(Session.getInstance(p), "JavaMail@ozacc.com"); - OMLMimeMessage msg2 = new OMLMimeMessage(Session.getInstance(p), ".JavaMail@ozacc.com"); - - String id1 = msg1.generateRandomMessageId(); - String id2 = msg2.generateRandomMessageId(); - - assertNotSame(id1, id2); - - System.out.println(id1); - System.out.println(id2); - } +package com.ozacc.mail.impl; + +import java.util.Properties; + +import javax.mail.Session; + +import junit.framework.TestCase; + +/** + * + * @author Tomohiro Otsuka + * @version $Id: OMLMimeMessageTest.java,v 1.1 2004/09/20 21:43:33 otsuka Exp $ + */ +public class OMLMimeMessageTest extends TestCase { + + public void testRandom() throws Exception { + Properties p = new Properties(); + OMLMimeMessage msg1 = new OMLMimeMessage(Session.getInstance(p), "JavaMail@ozacc.com"); + OMLMimeMessage msg2 = new OMLMimeMessage(Session.getInstance(p), ".JavaMail@ozacc.com"); + + String id1 = msg1.generateRandomMessageId(); + String id2 = msg2.generateRandomMessageId(); + + assertNotSame(id1, id2); + + System.out.println(id1); + System.out.println(id2); + } } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/impl/SendMailImplRealTest.java b/src/test/java/com/ozacc/mail/impl/SendMailImplRealTest.java old mode 100755 new mode 100644 index 3691aec..0ca4100 --- a/src/test/java/com/ozacc/mail/impl/SendMailImplRealTest.java +++ b/src/test/java/com/ozacc/mail/impl/SendMailImplRealTest.java @@ -1,138 +1,138 @@ -package com.ozacc.mail.impl; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuilder; - -/** - * SendMailImplクラスのテストケース。実際に送信し、メーラーで受信して確認するテストです。 - * - * @author Tomohiro Otsuka - * @version $Id: SendMailImplRealTest.java,v 1.6.2.1 2005/01/23 06:51:56 otsuka Exp $ - */ -public class SendMailImplRealTest extends TestCase { - - private MailBuilder builder; - - private String email; - - private String envelopeTo; - - private SendMailImpl sendMail; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - - BasicConfigurator.configure(); - - email = "to@example.com"; - envelopeTo = "to@example.com"; - - String host = "localhost"; - sendMail = new SendMailImpl(host); - sendMail.setMessageId("example.com"); - - builder = new XMLMailBuilderImpl(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - /* - public void testSendMailWithAttachmentInputStream() throws Exception { - String classPath = "/com/ozacc/mail/test-mail4.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - - File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); - FileInputStream fis = new FileInputStream(image1); - - mail.addFile(fis, "野菜画像.jpg"); - mail.setSubject("添付ファイルのInputStream送信テスト"); - - sendMail.send(mail); - } - - - public void testSendMailEnvelopeTo() throws Exception { - String classPath = "/com/ozacc/mail/test-mail4.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - mail.addEnvelopeTo(envelopeTo); - sendMail.send(mail); - } - - public void testSendMailSimpl() throws Exception { - String classPath = "/com/ozacc/mail/test-mail4.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - - sendMail.send(mail); - } - - public void testSendMailWithAttachmentFile() throws Exception { - String classPath = "/com/ozacc/mail/test-mail4.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - - File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); - File image2 = new File("src/test/java/com/ozacc/mail/image2.png"); - - mail.addFile(image1); - mail.addFile(image2, "野菜画像.png"); - mail.setSubject("添付ファイル送信テスト"); - - sendMail.send(mail); - } - - public void testSendMailHTML() throws Exception { - String classPath = "/com/ozacc/mail/test-mail5-html.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - mail.setHtmlText(mail.getText()); - mail.setText("プレーンテキスト"); - sendMail.send(mail); - } - - public void testSendMailHTMLOnly() throws Exception { - String classPath = "/com/ozacc/mail/test-mail5-html.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - mail.setHtmlText(mail.getText()); - mail.setText(null); - mail.setSubject("HTMLオンリー"); - sendMail.send(mail); - } - - public void testSendMailHTMLWithAttachmentFile() throws Exception { - String classPath = "/com/ozacc/mail/test-mail5-html.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - mail.setHtmlText(mail.getText()); - mail.setText("プレーンテキスト"); - - File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); - mail.addFile(image1); - - sendMail.send(mail); - } - */ - /** - * テストケースがひとつもないとエラーになるので、ダミー。 - */ - public void testSendMailSuccess() { - Mail mail; - assertTrue(true); - } - +package com.ozacc.mail.impl; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuilder; + +/** + * SendMailImplクラスのテストケース。実際に送信し、メーラーで受信して確認するテストです。 + * + * @author Tomohiro Otsuka + * @version $Id: SendMailImplRealTest.java,v 1.6.2.1 2005/01/23 06:51:56 otsuka Exp $ + */ +public class SendMailImplRealTest extends TestCase { + + private MailBuilder builder; + + private String email; + + private String envelopeTo; + + private SendMailImpl sendMail; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + + BasicConfigurator.configure(); + + email = "to@example.com"; + envelopeTo = "to@example.com"; + + String host = "localhost"; + sendMail = new SendMailImpl(host); + sendMail.setMessageId("example.com"); + + builder = new XMLMailBuilderImpl(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + /* + public void testSendMailWithAttachmentInputStream() throws Exception { + String classPath = "/com/ozacc/mail/test-mail4.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + + File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); + FileInputStream fis = new FileInputStream(image1); + + mail.addFile(fis, "野菜画像.jpg"); + mail.setSubject("添付ファイルのInputStream送信テスト"); + + sendMail.send(mail); + } + + + public void testSendMailEnvelopeTo() throws Exception { + String classPath = "/com/ozacc/mail/test-mail4.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + mail.addEnvelopeTo(envelopeTo); + sendMail.send(mail); + } + + public void testSendMailSimpl() throws Exception { + String classPath = "/com/ozacc/mail/test-mail4.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + + sendMail.send(mail); + } + + public void testSendMailWithAttachmentFile() throws Exception { + String classPath = "/com/ozacc/mail/test-mail4.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + + File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); + File image2 = new File("src/test/java/com/ozacc/mail/image2.png"); + + mail.addFile(image1); + mail.addFile(image2, "野菜画像.png"); + mail.setSubject("添付ファイル送信テスト"); + + sendMail.send(mail); + } + + public void testSendMailHTML() throws Exception { + String classPath = "/com/ozacc/mail/test-mail5-html.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + mail.setHtmlText(mail.getText()); + mail.setText("プレーンテキスト"); + sendMail.send(mail); + } + + public void testSendMailHTMLOnly() throws Exception { + String classPath = "/com/ozacc/mail/test-mail5-html.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + mail.setHtmlText(mail.getText()); + mail.setText(null); + mail.setSubject("HTMLオンリー"); + sendMail.send(mail); + } + + public void testSendMailHTMLWithAttachmentFile() throws Exception { + String classPath = "/com/ozacc/mail/test-mail5-html.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + mail.setHtmlText(mail.getText()); + mail.setText("プレーンテキスト"); + + File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); + mail.addFile(image1); + + sendMail.send(mail); + } + */ + /** + * テストケースがひとつもないとエラーになるので、ダミー。 + */ + public void testSendMailSuccess() { + Mail mail; + assertTrue(true); + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/impl/SendMailImplTest.java b/src/test/java/com/ozacc/mail/impl/SendMailImplTest.java old mode 100755 new mode 100644 index b74ab50..ad26413 --- a/src/test/java/com/ozacc/mail/impl/SendMailImplTest.java +++ b/src/test/java/com/ozacc/mail/impl/SendMailImplTest.java @@ -1,207 +1,207 @@ -package com.ozacc.mail.impl; - -import java.io.UnsupportedEncodingException; -import java.util.Iterator; - -import javax.mail.internet.MimeUtility; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -import com.dumbster.smtp.SimpleSmtpServer; -import com.dumbster.smtp.SmtpMessage; -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailException; - -/** - * SendMailImplクラスのテストケース。 - *

- * Dumbsterを使用してテストしているが、サポートされていない機能が多い。 - * - * @author Tomohiro Otsuka - * @version $Id: SendMailImplTest.java,v 1.3 2004/09/14 00:06:13 otsuka Exp $ - */ -public class SendMailImplTest extends TestCase { - - private SendMailImpl sendMail; - - private SimpleSmtpServer server; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - - BasicConfigurator.configure(); - - int port = 2525; - server = SimpleSmtpServer.start(port); - sendMail = new SendMailImpl(); - sendMail.setPort(port); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - private String convertJisValue(String str) throws UnsupportedEncodingException { - return new String(str.getBytes(), "JIS"); - } - - /** - * 単発メールのテスト。 - * - * @throws Exception - */ - public void testSendMail() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功"; - - Mail mail = new Mail(); - mail.setFrom(from, fromName); - mail.addTo(to); - mail.setSubject(subject); - mail.setText(text); - - sendMail.send(mail); - - server.stop(); - - assertEquals("1", 1, server.getReceievedEmailSize()); - Iterator inbox = server.getReceivedEmail(); - SmtpMessage email = (SmtpMessage)inbox.next(); - - assertEquals("2", mail.getTo()[0].toString(), email.getHeaderValue("To")); - assertEquals("3", mail.getFrom().toString(), email.getHeaderValue("From")); - - assertEquals("4", mail.getSubject(), MimeUtility - .decodeText(email.getHeaderValue("Subject"))); - assertEquals("5", mail.getText() + "\n", convertJisValue(email.getBody())); - } - - /** - * 複数メールの一括送信テスト。 - * 同一接続内の複数メッセージを送信するとDumbsterがエラーを吐くので、 - * とりあえず1つのMailインスタンスの配列でテスト。 - * 実際のSMTPサーバ(qmail)で正常に送信できることは確認済み。 - * - * @throws Exception - */ - public void testSendMailMultiple() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功"; - - Mail mail1 = new Mail(); - mail1.setFrom(from, fromName); - mail1.addTo(to); - mail1.setSubject(subject); - mail1.setText(text); - - Mail mail2 = new Mail(); - mail2.setFrom(from, fromName); - mail2.addTo(to); - mail2.setSubject(subject); - mail2.setText(text); - - Mail mail3 = new Mail(); - mail3.setFrom(from, fromName); - mail3.addTo(to); - mail3.setSubject(subject); - mail3.setText(text); - - // Dumbsterのバグが直ったら、mail1, mail2, mail3 を含めてテスト - sendMail.send(new Mail[] { mail1 }); - - server.stop(); - - // Dumbsterのバグが直ったら、3 に。 - assertEquals("1", 1, server.getReceievedEmailSize()); - - Iterator inbox = server.getReceivedEmail(); - SmtpMessage email = (SmtpMessage)inbox.next(); - - assertEquals("2", mail1.getTo()[0].toString(), email.getHeaderValue("To")); - assertEquals("3", mail1.getFrom().toString(), email.getHeaderValue("From")); - - assertEquals("4", mail1.getSubject(), MimeUtility.decodeText(email - .getHeaderValue("Subject"))); - assertEquals("5", mail1.getText() + "\n", convertJisValue(email.getBody())); - } - - public void testSendMailWithReturnPath() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功"; - String returnPath = "return-path@example.com"; - - Mail mail = new Mail(); - mail.setFrom(from, fromName); - mail.addTo(to); - mail.setSubject(subject); - mail.setText(text); - mail.setReturnPath(returnPath); - mail.setImportance(Mail.Importance.HIGH); - - sendMail.send(mail); - - server.stop(); - - assertEquals(1, server.getReceievedEmailSize()); - Iterator inbox = server.getReceivedEmail(); - SmtpMessage email = (SmtpMessage)inbox.next(); - - // ヘッダー出力 - /* - Iterator itr = email.getHeaderNames(); - while (itr.hasNext()) { - String name = (String)itr.next(); - System.out.println(name + "='" + email.getHeaderValue(name) + "'"); - } - */ - - // Dumbsterでは、Return-Pathヘッダを保持していない - //assertEquals(mail.getReturnPath().toString(), email.getHeaderValue("Return-Path")); - // 重要度を確認 - assertEquals(mail.getImportance(), email.getHeaderValue("Importance")); - assertEquals("1", email.getHeaderValue("X-Priority")); - } - - /** - * 宛先を一件も指定していないためsend()時に例外をスロー。 - * To、Cc、Bccを一件でも指定すれば、この例外は起こらない。 - * - * @throws Exception - */ - public void testSendMailNoRecpient() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String subject = "件名"; - String text = "テスト成功"; - - Mail mail = new Mail(); - mail.setFrom(from, fromName); - mail.setSubject(subject); - mail.setText(text); - - try { - sendMail.send(mail); - fail("This should never be called."); - } catch (MailException expected) { - assertEquals("MimeMessageの生成に失敗しました。", expected.getMessage()); - } - } - +package com.ozacc.mail.impl; + +import java.io.UnsupportedEncodingException; +import java.util.Iterator; + +import javax.mail.internet.MimeUtility; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +import com.dumbster.smtp.SimpleSmtpServer; +import com.dumbster.smtp.SmtpMessage; +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailException; + +/** + * SendMailImplクラスのテストケース。 + *

+ * Dumbsterを使用してテストしているが、サポートされていない機能が多い。 + * + * @author Tomohiro Otsuka + * @version $Id: SendMailImplTest.java,v 1.3 2004/09/14 00:06:13 otsuka Exp $ + */ +public class SendMailImplTest extends TestCase { + + private SendMailImpl sendMail; + + private SimpleSmtpServer server; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + + BasicConfigurator.configure(); + + int port = 2525; + server = SimpleSmtpServer.start(port); + sendMail = new SendMailImpl(); + sendMail.setPort(port); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + private String convertJisValue(String str) throws UnsupportedEncodingException { + return new String(str.getBytes(), "JIS"); + } + + /** + * 単発メールのテスト。 + * + * @throws Exception + */ + public void testSendMail() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功"; + + Mail mail = new Mail(); + mail.setFrom(from, fromName); + mail.addTo(to); + mail.setSubject(subject); + mail.setText(text); + + sendMail.send(mail); + + server.stop(); + + assertEquals("1", 1, server.getReceievedEmailSize()); + Iterator inbox = server.getReceivedEmail(); + SmtpMessage email = (SmtpMessage)inbox.next(); + + assertEquals("2", mail.getTo()[0].toString(), email.getHeaderValue("To")); + assertEquals("3", mail.getFrom().toString(), email.getHeaderValue("From")); + + assertEquals("4", mail.getSubject(), MimeUtility + .decodeText(email.getHeaderValue("Subject"))); + assertEquals("5", mail.getText() + "\n", convertJisValue(email.getBody())); + } + + /** + * 複数メールの一括送信テスト。 + * 同一接続内の複数メッセージを送信するとDumbsterがエラーを吐くので、 + * とりあえず1つのMailインスタンスの配列でテスト。 + * 実際のSMTPサーバ(qmail)で正常に送信できることは確認済み。 + * + * @throws Exception + */ + public void testSendMailMultiple() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功"; + + Mail mail1 = new Mail(); + mail1.setFrom(from, fromName); + mail1.addTo(to); + mail1.setSubject(subject); + mail1.setText(text); + + Mail mail2 = new Mail(); + mail2.setFrom(from, fromName); + mail2.addTo(to); + mail2.setSubject(subject); + mail2.setText(text); + + Mail mail3 = new Mail(); + mail3.setFrom(from, fromName); + mail3.addTo(to); + mail3.setSubject(subject); + mail3.setText(text); + + // Dumbsterのバグが直ったら、mail1, mail2, mail3 を含めてテスト + sendMail.send(new Mail[] { mail1 }); + + server.stop(); + + // Dumbsterのバグが直ったら、3 に。 + assertEquals("1", 1, server.getReceievedEmailSize()); + + Iterator inbox = server.getReceivedEmail(); + SmtpMessage email = (SmtpMessage)inbox.next(); + + assertEquals("2", mail1.getTo()[0].toString(), email.getHeaderValue("To")); + assertEquals("3", mail1.getFrom().toString(), email.getHeaderValue("From")); + + assertEquals("4", mail1.getSubject(), MimeUtility.decodeText(email + .getHeaderValue("Subject"))); + assertEquals("5", mail1.getText() + "\n", convertJisValue(email.getBody())); + } + + public void testSendMailWithReturnPath() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功"; + String returnPath = "return-path@example.com"; + + Mail mail = new Mail(); + mail.setFrom(from, fromName); + mail.addTo(to); + mail.setSubject(subject); + mail.setText(text); + mail.setReturnPath(returnPath); + mail.setImportance(Mail.Importance.HIGH); + + sendMail.send(mail); + + server.stop(); + + assertEquals(1, server.getReceievedEmailSize()); + Iterator inbox = server.getReceivedEmail(); + SmtpMessage email = (SmtpMessage)inbox.next(); + + // ヘッダー出力 + /* + Iterator itr = email.getHeaderNames(); + while (itr.hasNext()) { + String name = (String)itr.next(); + System.out.println(name + "='" + email.getHeaderValue(name) + "'"); + } + */ + + // Dumbsterでは、Return-Pathヘッダを保持していない + //assertEquals(mail.getReturnPath().toString(), email.getHeaderValue("Return-Path")); + // 重要度を確認 + assertEquals(mail.getImportance(), email.getHeaderValue("Importance")); + assertEquals("1", email.getHeaderValue("X-Priority")); + } + + /** + * 宛先を一件も指定していないためsend()時に例外をスロー。 + * To、Cc、Bccを一件でも指定すれば、この例外は起こらない。 + * + * @throws Exception + */ + public void testSendMailNoRecpient() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String subject = "件名"; + String text = "テスト成功"; + + Mail mail = new Mail(); + mail.setFrom(from, fromName); + mail.setSubject(subject); + mail.setText(text); + + try { + sendMail.send(mail); + fail("This should never be called."); + } catch (MailException expected) { + assertEquals("MimeMessageの生成に失敗しました。", expected.getMessage()); + } + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/impl/SendMailProImplRealTest.java b/src/test/java/com/ozacc/mail/impl/SendMailProImplRealTest.java old mode 100755 new mode 100644 index 74a1768..18f500c --- a/src/test/java/com/ozacc/mail/impl/SendMailProImplRealTest.java +++ b/src/test/java/com/ozacc/mail/impl/SendMailProImplRealTest.java @@ -1,86 +1,86 @@ -package com.ozacc.mail.impl; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuilder; - -/** - * SendMailProImplクラスのテストケース。実際に送信し、メーラーで受信して確認するテストです。 - * - * @author Tomohiro Otsuka - * @version $Id: SendMailProImplRealTest.java,v 1.1.2.1 2005/01/23 06:51:27 otsuka Exp $ - */ -public class SendMailProImplRealTest extends TestCase { - - private MailBuilder builder; - - private String email; - - private String envelopeTo; - - private SendMailProImpl sendMail; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - - BasicConfigurator.configure(); - - email = "to@example.com"; - envelopeTo = "to@example.com"; - - String host = "localhost"; - sendMail = new SendMailProImpl(host); - sendMail.setMessageId("example.com"); - - builder = new XMLMailBuilderImpl(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - /* public void testSendMailWithAttachmentInputStream() throws Exception { - String classPath = "/com/ozacc/mail/test-mail4.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - - File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); - FileInputStream fis = new FileInputStream(image1); - - mail.addFile(fis, "野菜画像.jpg"); - mail.setSubject("添付ファイルのInputStream送信テスト"); - - sendMail.connect(); - sendMail.send(mail); - sendMail.disconnect(); - } - - public void testSendMailEnvelopeTo() throws Exception { - String classPath = "/com/ozacc/mail/test-mail4.xml"; - Mail mail = builder.buildMail(classPath); - mail.addTo(email); - mail.addEnvelopeTo(envelopeTo); - - sendMail.connect(); - sendMail.send(mail); - sendMail.disconnect(); - }*/ - - /** - * テストケースがひとつもないとエラーになるので、ダミー。 - */ - public void testSendMailSuccess() { - Mail mail; - assertTrue(true); - } - +package com.ozacc.mail.impl; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuilder; + +/** + * SendMailProImplクラスのテストケース。実際に送信し、メーラーで受信して確認するテストです。 + * + * @author Tomohiro Otsuka + * @version $Id: SendMailProImplRealTest.java,v 1.1.2.1 2005/01/23 06:51:27 otsuka Exp $ + */ +public class SendMailProImplRealTest extends TestCase { + + private MailBuilder builder; + + private String email; + + private String envelopeTo; + + private SendMailProImpl sendMail; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + + BasicConfigurator.configure(); + + email = "to@example.com"; + envelopeTo = "to@example.com"; + + String host = "localhost"; + sendMail = new SendMailProImpl(host); + sendMail.setMessageId("example.com"); + + builder = new XMLMailBuilderImpl(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + /* public void testSendMailWithAttachmentInputStream() throws Exception { + String classPath = "/com/ozacc/mail/test-mail4.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + + File image1 = new File("src/test/java/com/ozacc/mail/image1.jpg"); + FileInputStream fis = new FileInputStream(image1); + + mail.addFile(fis, "野菜画像.jpg"); + mail.setSubject("添付ファイルのInputStream送信テスト"); + + sendMail.connect(); + sendMail.send(mail); + sendMail.disconnect(); + } + + public void testSendMailEnvelopeTo() throws Exception { + String classPath = "/com/ozacc/mail/test-mail4.xml"; + Mail mail = builder.buildMail(classPath); + mail.addTo(email); + mail.addEnvelopeTo(envelopeTo); + + sendMail.connect(); + sendMail.send(mail); + sendMail.disconnect(); + }*/ + + /** + * テストケースがひとつもないとエラーになるので、ダミー。 + */ + public void testSendMailSuccess() { + Mail mail; + assertTrue(true); + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/impl/XMLMailBuilderImplTest.java b/src/test/java/com/ozacc/mail/impl/XMLMailBuilderImplTest.java old mode 100755 new mode 100644 index cdd9e7d..f6cc5e1 --- a/src/test/java/com/ozacc/mail/impl/XMLMailBuilderImplTest.java +++ b/src/test/java/com/ozacc/mail/impl/XMLMailBuilderImplTest.java @@ -1,210 +1,210 @@ -package com.ozacc.mail.impl; - -import java.io.File; - -import javax.mail.internet.InternetAddress; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.MailBuildException; -import com.ozacc.mail.MultipleMailBuilder; - -/** - * - * @since 1.0.1 - * @author Tomohiro Otsuka - * @version $Id: XMLMailBuilderImplTest.java,v 1.6.2.1 2005/01/21 22:17:27 otsuka Exp $ - */ -public class XMLMailBuilderImplTest extends TestCase { - - private MultipleMailBuilder builder; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - BasicConfigurator.configure(); - - builder = new XMLMailBuilderImpl(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - BasicConfigurator.resetConfiguration(); - } - - public final void testBuildMailCDATA() throws Exception { - String classPath = "/com/ozacc/mail/test-mail6-cdata.xml"; - - String expectedBody = "これはCDATAのテキストです。"; - - Mail result = builder.buildMail(classPath); - - assertEquals(expectedBody, result.getText()); - } - - public final void testBuildMultipartMailFromFile() throws Exception { - String path = "src/test/java/com/ozacc/mail/test-mail1.xml"; - File file = new File(path); - - String subject = "XMLMailBuilderのテストケース"; - String text = "改行します。\n改行しました。\nテストは成功。"; - String htmlText = "これはHTMLテキスト"; - - InternetAddress from = new InternetAddress("from@example.com", "差出人"); - InternetAddress returnPath = new InternetAddress("return@example.com"); - InternetAddress replyTo = new InternetAddress("reply@example.com"); - - InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); - InternetAddress to2 = new InternetAddress("to2@example.com"); - - InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); - InternetAddress cc2 = new InternetAddress("cc2@example.com"); - - InternetAddress bcc = new InternetAddress("bcc@example.com"); - - Mail result = builder.buildMail(file); - - System.out.println(result); - - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - - assertTrue(result.isMultipartMail()); - assertTrue(result.isHtmlMail()); - assertEquals(htmlText, result.getHtmlText()); - - assertEquals(from, result.getFrom()); - assertEquals(returnPath, result.getReturnPath()); - assertEquals(replyTo, result.getReplyTo()); - - InternetAddress[] tos = result.getTo(); - assertEquals(2, tos.length); - assertEquals(to1, tos[0]); - assertEquals(to2, tos[1]); - - InternetAddress[] ccs = result.getCc(); - assertEquals(2, ccs.length); - assertEquals(cc1, ccs[0]); - assertEquals(cc2, ccs[1]); - - InternetAddress[] bccs = result.getBcc(); - assertEquals(1, bccs.length); - assertEquals(bcc, bccs[0]); - } - - /* - * Class under test for Mail buildMail(String) - */ - public final void testBuildMailFromClassPath() throws Exception { - String classPath = "/com/ozacc/mail/test-mail1.xml"; - - String subject = "XMLMailBuilderのテストケース"; - String text = "改行します。\n改行しました。\nテストは成功。"; - - InternetAddress from = new InternetAddress("from@example.com", "差出人"); - InternetAddress returnPath = new InternetAddress("return@example.com"); - InternetAddress replyTo = new InternetAddress("reply@example.com"); - - InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); - InternetAddress to2 = new InternetAddress("to2@example.com"); - - InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); - InternetAddress cc2 = new InternetAddress("cc2@example.com"); - - InternetAddress bcc = new InternetAddress("bcc@example.com"); - - Mail result = builder.buildMail(classPath); - - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - - assertEquals(from, result.getFrom()); - assertEquals(returnPath, result.getReturnPath()); - assertEquals(replyTo, result.getReplyTo()); - - InternetAddress[] tos = result.getTo(); - assertEquals(2, tos.length); - assertEquals(to1, tos[0]); - assertEquals(to2, tos[1]); - - InternetAddress[] ccs = result.getCc(); - assertEquals(2, ccs.length); - assertEquals(cc1, ccs[0]); - assertEquals(cc2, ccs[1]); - - InternetAddress[] bccs = result.getBcc(); - assertEquals(1, bccs.length); - assertEquals(bcc, bccs[0]); - } - - /* - * Class under test for Mail buildMail(File) - */ - public final void testBuildMailFile() throws Exception { - String path = "src/test/java/com/ozacc/mail/test-mail1.xml"; - File file = new File(path); - - String subject = "XMLMailBuilderのテストケース"; - String text = "改行します。\n改行しました。\nテストは成功。"; - - InternetAddress from = new InternetAddress("from@example.com", "差出人"); - InternetAddress returnPath = new InternetAddress("return@example.com"); - InternetAddress replyTo = new InternetAddress("reply@example.com"); - - InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); - InternetAddress to2 = new InternetAddress("to2@example.com"); - - InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); - InternetAddress cc2 = new InternetAddress("cc2@example.com"); - - InternetAddress bcc = new InternetAddress("bcc@example.com"); - - Mail result = builder.buildMail(file); - - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - - assertEquals(from, result.getFrom()); - assertEquals(returnPath, result.getReturnPath()); - assertEquals(replyTo, result.getReplyTo()); - - InternetAddress[] tos = result.getTo(); - assertEquals(2, tos.length); - assertEquals(to1, tos[0]); - assertEquals(to2, tos[1]); - - InternetAddress[] ccs = result.getCc(); - assertEquals(2, ccs.length); - assertEquals(cc1, ccs[0]); - assertEquals(cc2, ccs[1]); - - InternetAddress[] bccs = result.getBcc(); - assertEquals(1, bccs.length); - assertEquals(bcc, bccs[0]); - } - - public void testBuildMailFromMultipleMailsTemplate() throws Exception { - String path = "src/test/java/com/ozacc/mail/test-mail7-multiple.xml"; - File file = new File(path); - - Mail result1 = builder.buildMail(file, "first"); - assertEquals("1通目", result1.getText()); - - Mail result2 = builder.buildMail(file, "second"); - assertEquals("2通目", result2.getText()); - - try { - Mail result3 = builder.buildMail(file, "サード"); - } catch (MailBuildException expected) { - - } - } +package com.ozacc.mail.impl; + +import java.io.File; + +import javax.mail.internet.InternetAddress; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.MailBuildException; +import com.ozacc.mail.MultipleMailBuilder; + +/** + * + * @since 1.0.1 + * @author Tomohiro Otsuka + * @version $Id: XMLMailBuilderImplTest.java,v 1.6.2.1 2005/01/21 22:17:27 otsuka Exp $ + */ +public class XMLMailBuilderImplTest extends TestCase { + + private MultipleMailBuilder builder; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + BasicConfigurator.configure(); + + builder = new XMLMailBuilderImpl(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + BasicConfigurator.resetConfiguration(); + } + + public final void testBuildMailCDATA() throws Exception { + String classPath = "/com/ozacc/mail/test-mail6-cdata.xml"; + + String expectedBody = "これはCDATAのテキストです。"; + + Mail result = builder.buildMail(classPath); + + assertEquals(expectedBody, result.getText()); + } + + public final void testBuildMultipartMailFromFile() throws Exception { + String path = "src/test/java/com/ozacc/mail/test-mail1.xml"; + File file = new File(path); + + String subject = "XMLMailBuilderのテストケース"; + String text = "改行します。\n改行しました。\nテストは成功。"; + String htmlText = "これはHTMLテキスト"; + + InternetAddress from = new InternetAddress("from@example.com", "差出人"); + InternetAddress returnPath = new InternetAddress("return@example.com"); + InternetAddress replyTo = new InternetAddress("reply@example.com"); + + InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); + InternetAddress to2 = new InternetAddress("to2@example.com"); + + InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); + InternetAddress cc2 = new InternetAddress("cc2@example.com"); + + InternetAddress bcc = new InternetAddress("bcc@example.com"); + + Mail result = builder.buildMail(file); + + System.out.println(result); + + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + + assertTrue(result.isMultipartMail()); + assertTrue(result.isHtmlMail()); + assertEquals(htmlText, result.getHtmlText()); + + assertEquals(from, result.getFrom()); + assertEquals(returnPath, result.getReturnPath()); + assertEquals(replyTo, result.getReplyTo()); + + InternetAddress[] tos = result.getTo(); + assertEquals(2, tos.length); + assertEquals(to1, tos[0]); + assertEquals(to2, tos[1]); + + InternetAddress[] ccs = result.getCc(); + assertEquals(2, ccs.length); + assertEquals(cc1, ccs[0]); + assertEquals(cc2, ccs[1]); + + InternetAddress[] bccs = result.getBcc(); + assertEquals(1, bccs.length); + assertEquals(bcc, bccs[0]); + } + + /* + * Class under test for Mail buildMail(String) + */ + public final void testBuildMailFromClassPath() throws Exception { + String classPath = "/com/ozacc/mail/test-mail1.xml"; + + String subject = "XMLMailBuilderのテストケース"; + String text = "改行します。\n改行しました。\nテストは成功。"; + + InternetAddress from = new InternetAddress("from@example.com", "差出人"); + InternetAddress returnPath = new InternetAddress("return@example.com"); + InternetAddress replyTo = new InternetAddress("reply@example.com"); + + InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); + InternetAddress to2 = new InternetAddress("to2@example.com"); + + InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); + InternetAddress cc2 = new InternetAddress("cc2@example.com"); + + InternetAddress bcc = new InternetAddress("bcc@example.com"); + + Mail result = builder.buildMail(classPath); + + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + + assertEquals(from, result.getFrom()); + assertEquals(returnPath, result.getReturnPath()); + assertEquals(replyTo, result.getReplyTo()); + + InternetAddress[] tos = result.getTo(); + assertEquals(2, tos.length); + assertEquals(to1, tos[0]); + assertEquals(to2, tos[1]); + + InternetAddress[] ccs = result.getCc(); + assertEquals(2, ccs.length); + assertEquals(cc1, ccs[0]); + assertEquals(cc2, ccs[1]); + + InternetAddress[] bccs = result.getBcc(); + assertEquals(1, bccs.length); + assertEquals(bcc, bccs[0]); + } + + /* + * Class under test for Mail buildMail(File) + */ + public final void testBuildMailFile() throws Exception { + String path = "src/test/java/com/ozacc/mail/test-mail1.xml"; + File file = new File(path); + + String subject = "XMLMailBuilderのテストケース"; + String text = "改行します。\n改行しました。\nテストは成功。"; + + InternetAddress from = new InternetAddress("from@example.com", "差出人"); + InternetAddress returnPath = new InternetAddress("return@example.com"); + InternetAddress replyTo = new InternetAddress("reply@example.com"); + + InternetAddress to1 = new InternetAddress("to1@example.com", "宛先1"); + InternetAddress to2 = new InternetAddress("to2@example.com"); + + InternetAddress cc1 = new InternetAddress("cc1@example.com", "CC1"); + InternetAddress cc2 = new InternetAddress("cc2@example.com"); + + InternetAddress bcc = new InternetAddress("bcc@example.com"); + + Mail result = builder.buildMail(file); + + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + + assertEquals(from, result.getFrom()); + assertEquals(returnPath, result.getReturnPath()); + assertEquals(replyTo, result.getReplyTo()); + + InternetAddress[] tos = result.getTo(); + assertEquals(2, tos.length); + assertEquals(to1, tos[0]); + assertEquals(to2, tos[1]); + + InternetAddress[] ccs = result.getCc(); + assertEquals(2, ccs.length); + assertEquals(cc1, ccs[0]); + assertEquals(cc2, ccs[1]); + + InternetAddress[] bccs = result.getBcc(); + assertEquals(1, bccs.length); + assertEquals(bcc, bccs[0]); + } + + public void testBuildMailFromMultipleMailsTemplate() throws Exception { + String path = "src/test/java/com/ozacc/mail/test-mail7-multiple.xml"; + File file = new File(path); + + Mail result1 = builder.buildMail(file, "first"); + assertEquals("1通目", result1.getText()); + + Mail result2 = builder.buildMail(file, "second"); + assertEquals("2通目", result2.getText()); + + try { + Mail result3 = builder.buildMail(file, "サード"); + } catch (MailBuildException expected) { + + } + } } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImplTest.java b/src/test/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImplTest.java old mode 100755 new mode 100644 index 8a02330..413995d --- a/src/test/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImplTest.java +++ b/src/test/java/com/ozacc/mail/impl/XMLVelocityMailBuilderImplTest.java @@ -1,127 +1,127 @@ -package com.ozacc.mail.impl; - -import java.io.File; - -import javax.mail.internet.InternetAddress; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.apache.velocity.VelocityContext; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.VelocityMailBuilder; -import com.ozacc.mail.impl.JDomXMLMailBuilderTest.Customer; - -/** - * - * @since 1.0.1 - * @author Tomohiro Otsuka - * @version $Id: XMLVelocityMailBuilderImplTest.java,v 1.1.2.1 2004/10/24 10:28:09 otsuka Exp $ - */ -public class XMLVelocityMailBuilderImplTest extends TestCase { - - private VelocityMailBuilder builder; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - BasicConfigurator.configure(); - builder = new XMLVelocityMailBuilderImpl(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - public void testBuildMailFromFile() throws Exception { - String path = "src/test/java/com/ozacc/mail/test-mail3-velocity.xml"; - File file = new File(path); - - String name = "伊東美咲"; - String email = "misaki@example.com"; - Customer customer = new Customer(name, email); - String item = "GIVE&TAKE (Beige)"; - - InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); - InternetAddress to = new InternetAddress(email, name); - - String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; - String text = name + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)"; - - VelocityContext context = new VelocityContext(); - context.put("customer", customer); - context.put("item", item); - - // メール生成実行 - Mail result = builder.buildMail(file, context); - - assertEquals(from, result.getFrom()); - assertEquals(to, result.getTo()[0]); - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - } - - public final void testBuildMailStringVelocityContext() throws Exception { - String classPath = "/com/ozacc/mail/test-mail3-velocity.xml"; - - String name = "伊東美咲"; - String email = "misaki@example.com"; - Customer customer = new Customer(name, email); - String item = "GIVE&TAKE (Beige)"; - - InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); - InternetAddress to = new InternetAddress(email, name); - - String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; - String text = name + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)"; - - VelocityContext context = new VelocityContext(); - context.put("customer", customer); - context.put("item", item); - - // メール生成実行 - Mail result = builder.buildMail(classPath, context); - - assertEquals(from, result.getFrom()); - assertEquals(to, result.getTo()[0]); - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - } - - public final void testBuildMailStringVelocityContextWithCache() throws Exception { - builder.setCacheEnabled(true); - - String classPath = "/com/ozacc/mail/test-mail3-velocity.xml"; - - String name = "伊東美咲"; - String email = "misaki@example.com"; - Customer customer = new Customer(name, email); - String item = "GIVE&TAKE (Beige)"; - - InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); - InternetAddress to = new InternetAddress(email, name); - String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; - String text = name + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)"; - - VelocityContext context = new VelocityContext(); - context.put("customer", customer); - context.put("item", item); - - // メール生成実行 - Mail result = builder.buildMail(classPath, context); - Mail result2 = builder.buildMail(classPath, context); - builder.clearCache(); - Mail result3 = builder.buildMail(classPath, context); - - assertEquals(from, result.getFrom()); - assertEquals(to, result.getTo()[0]); - assertEquals(subject, result.getSubject()); - assertEquals(text, result.getText()); - } +package com.ozacc.mail.impl; + +import java.io.File; + +import javax.mail.internet.InternetAddress; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; +import org.apache.velocity.VelocityContext; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.VelocityMailBuilder; +import com.ozacc.mail.impl.JDomXMLMailBuilderTest.Customer; + +/** + * + * @since 1.0.1 + * @author Tomohiro Otsuka + * @version $Id: XMLVelocityMailBuilderImplTest.java,v 1.1.2.1 2004/10/24 10:28:09 otsuka Exp $ + */ +public class XMLVelocityMailBuilderImplTest extends TestCase { + + private VelocityMailBuilder builder; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + BasicConfigurator.configure(); + builder = new XMLVelocityMailBuilderImpl(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + public void testBuildMailFromFile() throws Exception { + String path = "src/test/java/com/ozacc/mail/test-mail3-velocity.xml"; + File file = new File(path); + + String name = "伊東美咲"; + String email = "misaki@example.com"; + Customer customer = new Customer(name, email); + String item = "GIVE&TAKE (Beige)"; + + InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); + InternetAddress to = new InternetAddress(email, name); + + String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; + String text = name + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)"; + + VelocityContext context = new VelocityContext(); + context.put("customer", customer); + context.put("item", item); + + // メール生成実行 + Mail result = builder.buildMail(file, context); + + assertEquals(from, result.getFrom()); + assertEquals(to, result.getTo()[0]); + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + } + + public final void testBuildMailStringVelocityContext() throws Exception { + String classPath = "/com/ozacc/mail/test-mail3-velocity.xml"; + + String name = "伊東美咲"; + String email = "misaki@example.com"; + Customer customer = new Customer(name, email); + String item = "GIVE&TAKE (Beige)"; + + InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); + InternetAddress to = new InternetAddress(email, name); + + String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; + String text = name + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)"; + + VelocityContext context = new VelocityContext(); + context.put("customer", customer); + context.put("item", item); + + // メール生成実行 + Mail result = builder.buildMail(classPath, context); + + assertEquals(from, result.getFrom()); + assertEquals(to, result.getTo()[0]); + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + } + + public final void testBuildMailStringVelocityContextWithCache() throws Exception { + builder.setCacheEnabled(true); + + String classPath = "/com/ozacc/mail/test-mail3-velocity.xml"; + + String name = "伊東美咲"; + String email = "misaki@example.com"; + Customer customer = new Customer(name, email); + String item = "GIVE&TAKE (Beige)"; + + InternetAddress from = new InternetAddress("shop@example.com", "XMLMailBuilderオンラインショップ"); + InternetAddress to = new InternetAddress(email, name); + String subject = "XMLMailBuilderオンラインショップ - ご注文の確認"; + String text = name + "様\n\nお買い上げありがとうございました。\n\nGIVE&TAKE (Beige)"; + + VelocityContext context = new VelocityContext(); + context.put("customer", customer); + context.put("item", item); + + // メール生成実行 + Mail result = builder.buildMail(classPath, context); + Mail result2 = builder.buildMail(classPath, context); + builder.clearCache(); + Mail result3 = builder.buildMail(classPath, context); + + assertEquals(from, result.getFrom()); + assertEquals(to, result.getTo()[0]); + assertEquals(subject, result.getSubject()); + assertEquals(text, result.getText()); + } } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/mailet/MailetRunnerTest.java b/src/test/java/com/ozacc/mail/mailet/MailetRunnerTest.java old mode 100755 new mode 100644 index 9086e05..1581e0d --- a/src/test/java/com/ozacc/mail/mailet/MailetRunnerTest.java +++ b/src/test/java/com/ozacc/mail/mailet/MailetRunnerTest.java @@ -1,114 +1,114 @@ -package com.ozacc.mail.mailet; - -import java.util.ArrayList; -import java.util.List; - -import javax.mail.internet.InternetAddress; - -import org.apache.log4j.BasicConfigurator; - -import junit.framework.TestCase; - -import com.ozacc.mail.fetch.ReceivedMail; -import com.ozacc.mail.mock.MockFetchMailPro; - -/** - * MailetRunnerのテストケース。 - * - * @author Tomohiro Otsuka - * @version $Id: MailetRunnerTest.java,v 1.1.2.1 2005/02/06 13:53:54 otsuka Exp $ - */ -public class MailetRunnerTest extends TestCase { - - private MailetRunner mailetRunner; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - BasicConfigurator.configure(); - - MockFetchMailPro fetchMailPro = new MockFetchMailPro(); - fetchMailPro.setupGetMails(getSampleMails()); - - Mailet mailet = getSubjectOutputMailet(); - Matcher matcher = getExampleComAddressMatcher(); - List matcherList = new ArrayList(); - matcherList.add(matcher); - MailetWrapper mw = new MailetWrapper(mailet, matcherList); - List mwList = new ArrayList(); - mwList.add(mw); - mwList.add(mw); - - mailetRunner = new MailetRunner(); - mailetRunner.setFetchMailPro(fetchMailPro); - mailetRunner.setMailetWrapperList(mwList); - } - - /** - * @return - */ - private ReceivedMail[] getSampleMails() { - List list = new ArrayList(); - ReceivedMail m1 = new ReceivedMail(); - m1.setSubject("m1 - 出力されます。"); - m1.addTo("to@example.com"); - list.add(m1); - ReceivedMail m2 = new ReceivedMail(); - m2.setSubject("m2 - 出力されません。"); - m2.addTo("to@example.net"); - list.add(m2); - ReceivedMail m3 = new ReceivedMail(); - m3.setSubject("m3 - 出力されます。"); - m3.addTo("to@example.net"); - m3.addTo("to@example.com"); - list.add(m3); - return (ReceivedMail[])list.toArray(new ReceivedMail[list.size()]); - } - - /** - * @return - */ - private Matcher getExampleComAddressMatcher() { - Matcher m = new Matcher() { - - public boolean match(ReceivedMail mail) { - InternetAddress[] toAddresses = mail.getTo(); - for (int i = 0; i < toAddresses.length; i++) { - InternetAddress address = toAddresses[i]; - if (address.getAddress().equalsIgnoreCase("to@example.com")) { - return true; - } - } - return false; - } - }; - return m; - } - - /** - * @return - */ - private Mailet getSubjectOutputMailet() { - return new Mailet() { - - public void service(ReceivedMail mail) { - System.out.println(mail.getSubject()); - } - }; - } - - /* - * @see TestCase#tearDown() - */ - protected void tearDown() throws Exception { - super.tearDown(); - BasicConfigurator.resetConfiguration(); - } - - public void testRun() { - mailetRunner.run(); - } - +package com.ozacc.mail.mailet; + +import java.util.ArrayList; +import java.util.List; + +import javax.mail.internet.InternetAddress; + +import org.apache.log4j.BasicConfigurator; + +import junit.framework.TestCase; + +import com.ozacc.mail.fetch.ReceivedMail; +import com.ozacc.mail.mock.MockFetchMailPro; + +/** + * MailetRunnerのテストケース。 + * + * @author Tomohiro Otsuka + * @version $Id: MailetRunnerTest.java,v 1.1.2.1 2005/02/06 13:53:54 otsuka Exp $ + */ +public class MailetRunnerTest extends TestCase { + + private MailetRunner mailetRunner; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + BasicConfigurator.configure(); + + MockFetchMailPro fetchMailPro = new MockFetchMailPro(); + fetchMailPro.setupGetMails(getSampleMails()); + + Mailet mailet = getSubjectOutputMailet(); + Matcher matcher = getExampleComAddressMatcher(); + List matcherList = new ArrayList(); + matcherList.add(matcher); + MailetWrapper mw = new MailetWrapper(mailet, matcherList); + List mwList = new ArrayList(); + mwList.add(mw); + mwList.add(mw); + + mailetRunner = new MailetRunner(); + mailetRunner.setFetchMailPro(fetchMailPro); + mailetRunner.setMailetWrapperList(mwList); + } + + /** + * @return + */ + private ReceivedMail[] getSampleMails() { + List list = new ArrayList(); + ReceivedMail m1 = new ReceivedMail(); + m1.setSubject("m1 - 出力されます。"); + m1.addTo("to@example.com"); + list.add(m1); + ReceivedMail m2 = new ReceivedMail(); + m2.setSubject("m2 - 出力されません。"); + m2.addTo("to@example.net"); + list.add(m2); + ReceivedMail m3 = new ReceivedMail(); + m3.setSubject("m3 - 出力されます。"); + m3.addTo("to@example.net"); + m3.addTo("to@example.com"); + list.add(m3); + return (ReceivedMail[])list.toArray(new ReceivedMail[list.size()]); + } + + /** + * @return + */ + private Matcher getExampleComAddressMatcher() { + Matcher m = new Matcher() { + + public boolean match(ReceivedMail mail) { + InternetAddress[] toAddresses = mail.getTo(); + for (int i = 0; i < toAddresses.length; i++) { + InternetAddress address = toAddresses[i]; + if (address.getAddress().equalsIgnoreCase("to@example.com")) { + return true; + } + } + return false; + } + }; + return m; + } + + /** + * @return + */ + private Mailet getSubjectOutputMailet() { + return new Mailet() { + + public void service(ReceivedMail mail) { + System.out.println(mail.getSubject()); + } + }; + } + + /* + * @see TestCase#tearDown() + */ + protected void tearDown() throws Exception { + super.tearDown(); + BasicConfigurator.resetConfiguration(); + } + + public void testRun() { + mailetRunner.run(); + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/mock/MockFetchMailTest.java b/src/test/java/com/ozacc/mail/mock/MockFetchMailTest.java old mode 100755 new mode 100644 index 3626ae8..4333749 --- a/src/test/java/com/ozacc/mail/mock/MockFetchMailTest.java +++ b/src/test/java/com/ozacc/mail/mock/MockFetchMailTest.java @@ -1,61 +1,61 @@ -package com.ozacc.mail.mock; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -import com.ozacc.mail.fetch.ReceivedMail; - -/** - * MockFetchMailのテストケース。 - * - * @author Tomohiro Otsuka - * @version $Id: MockFetchMailTest.java,v 1.1.2.2 2005/02/05 09:28:58 otsuka Exp $ - */ -public class MockFetchMailTest extends TestCase { - - MockFetchMail mockFetchMail; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - BasicConfigurator.configure(); - mockFetchMail = new MockFetchMail(); - } - - /* - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - public final void testGetMailsReturnZero() { - ReceivedMail[] mails = mockFetchMail.getMails(); - assertEquals(0, mails.length); - } - - public final void testGetMails() { - ReceivedMail expectedMail = new ReceivedMail(); - expectedMail.setFrom("from@example.net", "差出人"); - expectedMail.addTo("to@example.com", "宛名"); - expectedMail.setSubject("MockFetchMailTest"); - expectedMail.setText("本文"); - - mockFetchMail.setupGetMails(expectedMail); - - ReceivedMail[] mails = mockFetchMail.getMails(); - assertEquals("1通受信", 1, mails.length); - - ReceivedMail mail = mails[0]; - assertEquals("差出人", "差出人", mail.getFrom().getPersonal()); - assertEquals("差出人アドレス", "from@example.net", mail.getFrom().getAddress()); - assertEquals("宛先は1つ", 1, mail.getTo().length); - assertEquals("宛名", "to@example.com", (mail.getTo()[0]).getAddress()); - assertEquals("件名", "MockFetchMailTest", mail.getSubject()); - assertEquals("本文", "本文", mail.getText()); - } - +package com.ozacc.mail.mock; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +import com.ozacc.mail.fetch.ReceivedMail; + +/** + * MockFetchMailのテストケース。 + * + * @author Tomohiro Otsuka + * @version $Id: MockFetchMailTest.java,v 1.1.2.2 2005/02/05 09:28:58 otsuka Exp $ + */ +public class MockFetchMailTest extends TestCase { + + MockFetchMail mockFetchMail; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + BasicConfigurator.configure(); + mockFetchMail = new MockFetchMail(); + } + + /* + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + public final void testGetMailsReturnZero() { + ReceivedMail[] mails = mockFetchMail.getMails(); + assertEquals(0, mails.length); + } + + public final void testGetMails() { + ReceivedMail expectedMail = new ReceivedMail(); + expectedMail.setFrom("from@example.net", "差出人"); + expectedMail.addTo("to@example.com", "宛名"); + expectedMail.setSubject("MockFetchMailTest"); + expectedMail.setText("本文"); + + mockFetchMail.setupGetMails(expectedMail); + + ReceivedMail[] mails = mockFetchMail.getMails(); + assertEquals("1通受信", 1, mails.length); + + ReceivedMail mail = mails[0]; + assertEquals("差出人", "差出人", mail.getFrom().getPersonal()); + assertEquals("差出人アドレス", "from@example.net", mail.getFrom().getAddress()); + assertEquals("宛先は1つ", 1, mail.getTo().length); + assertEquals("宛名", "to@example.com", (mail.getTo()[0]).getAddress()); + assertEquals("件名", "MockFetchMailTest", mail.getSubject()); + assertEquals("本文", "本文", mail.getText()); + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/mock/MockSendMailTest.java b/src/test/java/com/ozacc/mail/mock/MockSendMailTest.java old mode 100755 new mode 100644 index 72cd3ec..9c3cea3 --- a/src/test/java/com/ozacc/mail/mock/MockSendMailTest.java +++ b/src/test/java/com/ozacc/mail/mock/MockSendMailTest.java @@ -1,272 +1,272 @@ -package com.ozacc.mail.mock; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; - -import com.dumbster.smtp.SimpleSmtpServer; -import com.ozacc.mail.Mail; - -/** - * SendMailImplクラスのテストケース。 - *

- * Dumbsterを使用してテストしているが、サポートされていない機能が多い。 - * - * @author Tomohiro Otsuka - * @version $Id: MockSendMailTest.java,v 1.6.2.1 2005/01/18 07:24:47 otsuka Exp $ - */ -public class MockSendMailTest extends TestCase { - - private MockSendMail mockSendMail; - - private SimpleSmtpServer server; - - /* - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - - BasicConfigurator.configure(); - - mockSendMail = new MockSendMail(); - mockSendMail.setDebug(true); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - public void testSendMailNotMatchMailNum() throws Exception { - Mail mail = new Mail(); - mail.addTo("to@example.com"); - mail.setFrom("from@example.com"); - - mockSendMail.addExpectedMail(mail); - mockSendMail.addExpectedMail(mail); - - mockSendMail.send(mail); - - try { - mockSendMail.verify(); - fail("This should never be called."); - } catch (AssertionFailedException expected) { - // success - } - } - - public void testSendMailSuccess() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功"; - - Mail mail = new Mail(); - mail.setFrom(from, fromName); - mail.addTo(to); - mail.setSubject(subject); - mail.setText(text); - - mockSendMail.addExpectedMail(mail); - - mockSendMail.send(mail); - - mockSendMail.verify(); - } - - public void testSendMailToAddressNotMatch() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功"; - - Mail mail1 = new Mail(); - mail1.setFrom(from, fromName); - mail1.addTo(to); - mail1.setSubject(subject); - mail1.setText(text); - - Mail mail2 = new Mail(); - mail2.setFrom(from, fromName); - mail2.addTo("contact@example.com"); - mail2.setSubject(subject); - mail2.setText(text); - - mockSendMail.addExpectedMail(mail1); - - mockSendMail.send(mail2); - - try { - mockSendMail.verify(); - fail("This should never be called."); - } catch (AssertionFailedException expected) { - // success - } - } - - public void testSendMailWithMockMail() throws Exception { - Mail sentMail = new Mail(); - sentMail.setFrom("from@example.com"); - sentMail.setSubject("件名"); - sentMail.addTo("to@example.com"); - sentMail.setText("動的生成される本文"); - - Mail expectedMail = new Mail(); - expectedMail.setFrom("from@example.com"); - expectedMail.setSubject("件名"); - - MockMail mockMail = new MockMail(); - mockMail.setFrom("from@example.com"); - mockMail.setSubject("件名"); - - MockSendMail sendMail = new MockSendMail(); - sendMail.setDebug(true); - - sendMail.addExpectedMail(mockMail); - sendMail.send(sentMail); - sendMail.verify(); // 成功 - - sendMail = new MockSendMail(); - sendMail.addExpectedMail(expectedMail); - sendMail.send(sentMail); - try { - sendMail.verify(); // エラー - fail("This should never be called."); - } catch (AssertionFailedException expected) { - // success - } - } - - public void testSendMailWithMockMulitpartMail() throws Exception { - Mail sentMail = new Mail(); - sentMail.setFrom("from@example.com"); - sentMail.setSubject("件名"); - sentMail.addTo("to@example.com"); - sentMail.setText("動的生成される本文"); - - Mail expectedMail = new Mail(); - expectedMail.setFrom("from@example.com"); - expectedMail.setSubject("件名"); - expectedMail.addTo("to@example.com"); - expectedMail.setText("動的生成される本文"); - expectedMail.setHtmlText("HTMLの本文"); - - MockSendMail sendMail = new MockSendMail(); - sendMail.setDebug(true); - - sendMail.addExpectedMail(expectedMail); - sendMail.send(sentMail); - - try { - sendMail.verify(); - fail("This should never be called."); - } catch (AssertionFailedException expected) { - // success - } - - sendMail.initialize(); - - sendMail.addExpectedMail(expectedMail); - sendMail.send(sentMail); - try { - sendMail.verify(); - fail("This should never be called."); - } catch (AssertionFailedException expected) { - // HTML本文が一致しない - } - - sendMail.initialize(); - - sentMail.setHtmlText("HTMLの本文"); - sendMail.addExpectedMail(expectedMail); - sendMail.send(sentMail); - sendMail.verify(); - - sendMail.initialize(); - - expectedMail.setHtmlText(null); - sendMail.addExpectedMail(expectedMail); - sendMail.send(sentMail); - // expectedはマルチパートではないからsentMailのHTMLとは比較されない - sendMail.verify(); - - sendMail.initialize(); - - MockMail expectedMockMail = new MockMail(expectedMail); - sendMail.addExpectedMail(expectedMockMail); - sendMail.send(sentMail); - try { - sendMail.verify(); - } catch (AssertionFailedException expected) { - fail("This should never be called."); - } - } - - public void testSendMailToNameNotMatch() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功"; - - Mail mail1 = new Mail(); - mail1.setFrom(from, fromName); - mail1.addTo(to, "宛先A"); - mail1.setSubject(subject); - mail1.setText(text); - - Mail mail2 = new Mail(); - mail2.setFrom(from, fromName); - mail2.addTo(to, "宛先B"); - mail2.setSubject(subject); - mail2.setText(text); - - mockSendMail.addExpectedMail(mail1); - - mockSendMail.send(mail2); - - try { - mockSendMail.verify(); - fail("This should never be called."); - } catch (AssertionFailedException expected) { - // success - } - } - - public void testSendMailFromNotMatch() throws Exception { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功"; - - Mail mail1 = new Mail(); - mail1.setFrom(from, fromName); - mail1.addTo(to); - mail1.setSubject(subject); - mail1.setText(text); - - Mail mail2 = new Mail(); - mail2.setFrom("from@foo.com", fromName); - mail2.addTo(to); - mail2.setSubject(subject); - mail2.setText(text); - - mockSendMail.addExpectedMail(mail1); - - mockSendMail.send(mail2); - - try { - mockSendMail.verify(); - fail("This should never be called."); - } catch (AssertionFailedException expected) { - // success - } - } - +package com.ozacc.mail.mock; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; + +import com.dumbster.smtp.SimpleSmtpServer; +import com.ozacc.mail.Mail; + +/** + * SendMailImplクラスのテストケース。 + *

+ * Dumbsterを使用してテストしているが、サポートされていない機能が多い。 + * + * @author Tomohiro Otsuka + * @version $Id: MockSendMailTest.java,v 1.6.2.1 2005/01/18 07:24:47 otsuka Exp $ + */ +public class MockSendMailTest extends TestCase { + + private MockSendMail mockSendMail; + + private SimpleSmtpServer server; + + /* + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + + BasicConfigurator.configure(); + + mockSendMail = new MockSendMail(); + mockSendMail.setDebug(true); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + public void testSendMailNotMatchMailNum() throws Exception { + Mail mail = new Mail(); + mail.addTo("to@example.com"); + mail.setFrom("from@example.com"); + + mockSendMail.addExpectedMail(mail); + mockSendMail.addExpectedMail(mail); + + mockSendMail.send(mail); + + try { + mockSendMail.verify(); + fail("This should never be called."); + } catch (AssertionFailedException expected) { + // success + } + } + + public void testSendMailSuccess() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功"; + + Mail mail = new Mail(); + mail.setFrom(from, fromName); + mail.addTo(to); + mail.setSubject(subject); + mail.setText(text); + + mockSendMail.addExpectedMail(mail); + + mockSendMail.send(mail); + + mockSendMail.verify(); + } + + public void testSendMailToAddressNotMatch() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功"; + + Mail mail1 = new Mail(); + mail1.setFrom(from, fromName); + mail1.addTo(to); + mail1.setSubject(subject); + mail1.setText(text); + + Mail mail2 = new Mail(); + mail2.setFrom(from, fromName); + mail2.addTo("contact@example.com"); + mail2.setSubject(subject); + mail2.setText(text); + + mockSendMail.addExpectedMail(mail1); + + mockSendMail.send(mail2); + + try { + mockSendMail.verify(); + fail("This should never be called."); + } catch (AssertionFailedException expected) { + // success + } + } + + public void testSendMailWithMockMail() throws Exception { + Mail sentMail = new Mail(); + sentMail.setFrom("from@example.com"); + sentMail.setSubject("件名"); + sentMail.addTo("to@example.com"); + sentMail.setText("動的生成される本文"); + + Mail expectedMail = new Mail(); + expectedMail.setFrom("from@example.com"); + expectedMail.setSubject("件名"); + + MockMail mockMail = new MockMail(); + mockMail.setFrom("from@example.com"); + mockMail.setSubject("件名"); + + MockSendMail sendMail = new MockSendMail(); + sendMail.setDebug(true); + + sendMail.addExpectedMail(mockMail); + sendMail.send(sentMail); + sendMail.verify(); // 成功 + + sendMail = new MockSendMail(); + sendMail.addExpectedMail(expectedMail); + sendMail.send(sentMail); + try { + sendMail.verify(); // エラー + fail("This should never be called."); + } catch (AssertionFailedException expected) { + // success + } + } + + public void testSendMailWithMockMulitpartMail() throws Exception { + Mail sentMail = new Mail(); + sentMail.setFrom("from@example.com"); + sentMail.setSubject("件名"); + sentMail.addTo("to@example.com"); + sentMail.setText("動的生成される本文"); + + Mail expectedMail = new Mail(); + expectedMail.setFrom("from@example.com"); + expectedMail.setSubject("件名"); + expectedMail.addTo("to@example.com"); + expectedMail.setText("動的生成される本文"); + expectedMail.setHtmlText("HTMLの本文"); + + MockSendMail sendMail = new MockSendMail(); + sendMail.setDebug(true); + + sendMail.addExpectedMail(expectedMail); + sendMail.send(sentMail); + + try { + sendMail.verify(); + fail("This should never be called."); + } catch (AssertionFailedException expected) { + // success + } + + sendMail.initialize(); + + sendMail.addExpectedMail(expectedMail); + sendMail.send(sentMail); + try { + sendMail.verify(); + fail("This should never be called."); + } catch (AssertionFailedException expected) { + // HTML本文が一致しない + } + + sendMail.initialize(); + + sentMail.setHtmlText("HTMLの本文"); + sendMail.addExpectedMail(expectedMail); + sendMail.send(sentMail); + sendMail.verify(); + + sendMail.initialize(); + + expectedMail.setHtmlText(null); + sendMail.addExpectedMail(expectedMail); + sendMail.send(sentMail); + // expectedはマルチパートではないからsentMailのHTMLとは比較されない + sendMail.verify(); + + sendMail.initialize(); + + MockMail expectedMockMail = new MockMail(expectedMail); + sendMail.addExpectedMail(expectedMockMail); + sendMail.send(sentMail); + try { + sendMail.verify(); + } catch (AssertionFailedException expected) { + fail("This should never be called."); + } + } + + public void testSendMailToNameNotMatch() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功"; + + Mail mail1 = new Mail(); + mail1.setFrom(from, fromName); + mail1.addTo(to, "宛先A"); + mail1.setSubject(subject); + mail1.setText(text); + + Mail mail2 = new Mail(); + mail2.setFrom(from, fromName); + mail2.addTo(to, "宛先B"); + mail2.setSubject(subject); + mail2.setText(text); + + mockSendMail.addExpectedMail(mail1); + + mockSendMail.send(mail2); + + try { + mockSendMail.verify(); + fail("This should never be called."); + } catch (AssertionFailedException expected) { + // success + } + } + + public void testSendMailFromNotMatch() throws Exception { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功"; + + Mail mail1 = new Mail(); + mail1.setFrom(from, fromName); + mail1.addTo(to); + mail1.setSubject(subject); + mail1.setText(text); + + Mail mail2 = new Mail(); + mail2.setFrom("from@foo.com", fromName); + mail2.addTo(to); + mail2.setSubject(subject); + mail2.setText(text); + + mockSendMail.addExpectedMail(mail1); + + mockSendMail.send(mail2); + + try { + mockSendMail.verify(); + fail("This should never be called."); + } catch (AssertionFailedException expected) { + // success + } + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/spring/XMLMailFactoryBeanTest.java b/src/test/java/com/ozacc/mail/spring/XMLMailFactoryBeanTest.java old mode 100755 new mode 100644 index 4d5031d..8c47581 --- a/src/test/java/com/ozacc/mail/spring/XMLMailFactoryBeanTest.java +++ b/src/test/java/com/ozacc/mail/spring/XMLMailFactoryBeanTest.java @@ -1,93 +1,93 @@ -package com.ozacc.mail.spring; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.FileSystemXmlApplicationContext; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.mock.EqualityCheck; - -/** - * XMLMailFactoryBeanのTestCase。 - * - * @author Tomohiro Otsuka - * @version $Id: XMLMailFactoryBeanTest.java,v 1.5 2004/09/17 20:34:31 otsuka Exp $ - */ -public class XMLMailFactoryBeanTest extends TestCase { - - Mail mail; - - /** - * @see junit.framework.TestCase#setUp() - */ - public void setUp() throws Exception { - super.setUp(); - - BasicConfigurator.configure(); - - mail = new Mail(); - mail.setSubject("XMLMailBuilderのテストケース"); - mail.setText("改行します。\n改行しました。\nテストは成功。"); - mail.setFrom("from@example.com", "差出人"); - mail.setReturnPath("return@example.com"); - mail.setReplyTo("reply@example.com"); - mail.addTo("to1@example.com", "宛先1"); - mail.addTo("to2@example.com"); - mail.addCc("cc1@example.com", "CC1"); - mail.addCc("cc2@example.com"); - mail.addBcc("bcc@example.com"); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - public void testMailFactoryBeanClassPathFail() throws Exception { - mail.addBcc("ccb@example.com"); - - ApplicationContext context = new FileSystemXmlApplicationContext( - "src/test/java/com/ozacc/mail/spring/testContext.xml"); - Mail result = (Mail)context.getBean("mail"); - - assertFalse(EqualityCheck.equals(mail, result)); - - } - - public void testMailFactoryBeanClassPath() throws Exception { - ApplicationContext context = new FileSystemXmlApplicationContext( - "src/test/java/com/ozacc/mail/spring/testContext.xml"); - Mail result = (Mail)context.getBean("mail"); - - assertTrue(EqualityCheck.equals(mail, result)); - } - - public void testMailFactoryBeanFilePath() throws Exception { - ApplicationContext context = new FileSystemXmlApplicationContext( - "src/test/java/com/ozacc/mail/spring/testContext.xml"); - Mail result = (Mail)context.getBean("mail2"); - - assertTrue(EqualityCheck.equals(mail, result)); - } - - public void testMailFactoryBeanLocation() throws Exception { - ApplicationContext context = new FileSystemXmlApplicationContext( - "src/test/java/com/ozacc/mail/spring/testContext.xml"); - Mail result = (Mail)context.getBean("mail3"); - - assertTrue(EqualityCheck.equals(mail, result)); - } - - public void testMailFactoryBeanLocationClasspath() throws Exception { - ApplicationContext context = new FileSystemXmlApplicationContext( - "src/test/java/com/ozacc/mail/spring/testContext.xml"); - Mail result = (Mail)context.getBean("mail4"); - - assertTrue(EqualityCheck.equals(mail, result)); - } - +package com.ozacc.mail.spring; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.FileSystemXmlApplicationContext; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.mock.EqualityCheck; + +/** + * XMLMailFactoryBeanのTestCase。 + * + * @author Tomohiro Otsuka + * @version $Id: XMLMailFactoryBeanTest.java,v 1.5 2004/09/17 20:34:31 otsuka Exp $ + */ +public class XMLMailFactoryBeanTest extends TestCase { + + Mail mail; + + /** + * @see junit.framework.TestCase#setUp() + */ + public void setUp() throws Exception { + super.setUp(); + + BasicConfigurator.configure(); + + mail = new Mail(); + mail.setSubject("XMLMailBuilderのテストケース"); + mail.setText("改行します。\n改行しました。\nテストは成功。"); + mail.setFrom("from@example.com", "差出人"); + mail.setReturnPath("return@example.com"); + mail.setReplyTo("reply@example.com"); + mail.addTo("to1@example.com", "宛先1"); + mail.addTo("to2@example.com"); + mail.addCc("cc1@example.com", "CC1"); + mail.addCc("cc2@example.com"); + mail.addBcc("bcc@example.com"); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + public void testMailFactoryBeanClassPathFail() throws Exception { + mail.addBcc("ccb@example.com"); + + ApplicationContext context = new FileSystemXmlApplicationContext( + "src/test/java/com/ozacc/mail/spring/testContext.xml"); + Mail result = (Mail)context.getBean("mail"); + + assertFalse(EqualityCheck.equals(mail, result)); + + } + + public void testMailFactoryBeanClassPath() throws Exception { + ApplicationContext context = new FileSystemXmlApplicationContext( + "src/test/java/com/ozacc/mail/spring/testContext.xml"); + Mail result = (Mail)context.getBean("mail"); + + assertTrue(EqualityCheck.equals(mail, result)); + } + + public void testMailFactoryBeanFilePath() throws Exception { + ApplicationContext context = new FileSystemXmlApplicationContext( + "src/test/java/com/ozacc/mail/spring/testContext.xml"); + Mail result = (Mail)context.getBean("mail2"); + + assertTrue(EqualityCheck.equals(mail, result)); + } + + public void testMailFactoryBeanLocation() throws Exception { + ApplicationContext context = new FileSystemXmlApplicationContext( + "src/test/java/com/ozacc/mail/spring/testContext.xml"); + Mail result = (Mail)context.getBean("mail3"); + + assertTrue(EqualityCheck.equals(mail, result)); + } + + public void testMailFactoryBeanLocationClasspath() throws Exception { + ApplicationContext context = new FileSystemXmlApplicationContext( + "src/test/java/com/ozacc/mail/spring/testContext.xml"); + Mail result = (Mail)context.getBean("mail4"); + + assertTrue(EqualityCheck.equals(mail, result)); + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/spring/testContext.xml b/src/test/java/com/ozacc/mail/spring/testContext.xml old mode 100755 new mode 100644 index e5b50c1..61ea45b --- a/src/test/java/com/ozacc/mail/spring/testContext.xml +++ b/src/test/java/com/ozacc/mail/spring/testContext.xml @@ -1,25 +1,25 @@ - - - - - - - /com/ozacc/mail/test-mail1.xml - - - - - src/test/java/com/ozacc/mail/test-mail1.xml - - - - - file:src/test/java/com/ozacc/mail/test-mail1.xml - - - - - classpath:/com/ozacc/mail/test-mail1.xml - - + + + + + + + /com/ozacc/mail/test-mail1.xml + + + + + src/test/java/com/ozacc/mail/test-mail1.xml + + + + + file:src/test/java/com/ozacc/mail/test-mail1.xml + + + + + classpath:/com/ozacc/mail/test-mail1.xml + + \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/test-mail1.xml b/src/test/java/com/ozacc/mail/test-mail1.xml old mode 100755 new mode 100644 index a8e1d3b..7fbc8b3 --- a/src/test/java/com/ozacc/mail/test-mail1.xml +++ b/src/test/java/com/ozacc/mail/test-mail1.xml @@ -1,37 +1,37 @@ - - - - - - - - - - - - - - - - - - - - - XMLMailBuilderのテストケース - - - - -改行します。 -改行しました。 -テストは成功。 - - - -これはHTMLテキスト -]]> - - + + + + + + + + + + + + + + + + + + + + + XMLMailBuilderのテストケース + + + + +改行します。 +改行しました。 +テストは成功。 + + + +これはHTMLテキスト +]]> + + \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/test-mail2-invalid.xml b/src/test/java/com/ozacc/mail/test-mail2-invalid.xml old mode 100755 new mode 100644 index b76c28c..1a2ac11 --- a/src/test/java/com/ozacc/mail/test-mail2-invalid.xml +++ b/src/test/java/com/ozacc/mail/test-mail2-invalid.xml @@ -1,27 +1,27 @@ - - - - - - - - - - - - - - - - - XMLMailBuilderのテストケース - - - - -改行します。 -改行しました。 -テストは成功。 - - + + + + + + + + + + + + + + + + + XMLMailBuilderのテストケース + + + + +改行します。 +改行しました。 +テストは成功。 + + \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/test-mail3-velocity.xml b/src/test/java/com/ozacc/mail/test-mail3-velocity.xml old mode 100755 new mode 100644 index b5c4045..466d745 --- a/src/test/java/com/ozacc/mail/test-mail3-velocity.xml +++ b/src/test/java/com/ozacc/mail/test-mail3-velocity.xml @@ -1,27 +1,27 @@ - - - - - - - - - - - - - XMLMailBuilderオンラインショップ - ご注文の確認 - - - - - + + + + + + + + + + + + + XMLMailBuilderオンラインショップ - ご注文の確認 + + + + + \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/test-mail4.xml b/src/test/java/com/ozacc/mail/test-mail4.xml old mode 100755 new mode 100644 index 9a1e9a5..0bc863a --- a/src/test/java/com/ozacc/mail/test-mail4.xml +++ b/src/test/java/com/ozacc/mail/test-mail4.xml @@ -1,37 +1,37 @@ - - - - - - - - - 文字化けテスト -~¢£∥¬ - - - - -文字化けテスト -~¢£∥¬ - -ソニーは、ソニースタイル専用モデルとして「VAIO type B」を10月2日より発売する。BTOに対応し、直販価格は149,800円~。OSはWindows XP Professional。 - -14.1型液晶を搭載する2スピンドルノート「バイオノートZ」の後継モデル。夏のVAIOシリーズモデルチェンジ時にはラインナップされておらず、今回新たに直販専用モデルとしてリニューアルされた。 - -デザインはほぼ従来モデルを踏襲しながら各所を強化。従来モデルと比較して、マグネシウム合金部分の肉厚が0.3mm増え、強度が上昇したほか、パワーオンパスワード、ハードディスクパスワードなどデータ漏洩防止機能が追加され、ビジネス用途も意識した仕様となった。 - -ボディカラーは若干変更され、従来モデルではシルバーだったパームレスト部分がブラックに変更されるなど、落ち着いた印象となった。 - -液晶パネルは、従来モデルでは1,400×1,050ドット(SXGA+)液晶を搭載していたが、今回のモデルでは1,024×768ドット(XGA)の液晶パネルを搭載したモデルも用意される。 - -また、CPUとしてPentium M 755(2GHz)/745(1.8GHz)/725(1.6GHz)などのほか、Celeron-M 350(1.3GHz)も選択できるなど、ハイエンドからエントリーまでがカバーされる。 - -そのほかの主な仕様は、メモリ256MB~1.5GB、HDD 40GB~80GB、Intel 855GME(ビデオ機能内蔵)チップセットなどを搭載。光学ドライブとしてDVD±RWドライブまたはDVD/CD-RWドライブを選択可能。 - -インターフェイスはEthernet、IEEE 802.11b/g無線LAN、Type2 PCカードスロット×1、USB 2.0×2、IEEE 1394(4ピン)×1、D-Sub15ピンなどを搭載する。なお、各種インターフェイスを備えるポートリプリケータが付属するが、従来モデルに搭載されていたDVI出力端子が省略されている。 - -バッテリはリチウムイオンバッテリで、駆動時間は約4時間(Sバッテリ)。本体サイズは321×255.3×29~43.2mm(幅×奥行き×高さ)、重量は約2.3kg。 - -なお、企業向けのビジネスパーソナル向けとして液晶パネルやCPUなどが異なる8モデルも用意される。付属のアプリケーションなどが最小限に抑えられるなど、より企業ユーザー向けのモデルとなる。 - - + + + + + + + + + 文字化けテスト -~¢£∥¬ + + + + +文字化けテスト -~¢£∥¬ + +ソニーは、ソニースタイル専用モデルとして「VAIO type B」を10月2日より発売する。BTOに対応し、直販価格は149,800円~。OSはWindows XP Professional。 + +14.1型液晶を搭載する2スピンドルノート「バイオノートZ」の後継モデル。夏のVAIOシリーズモデルチェンジ時にはラインナップされておらず、今回新たに直販専用モデルとしてリニューアルされた。 + +デザインはほぼ従来モデルを踏襲しながら各所を強化。従来モデルと比較して、マグネシウム合金部分の肉厚が0.3mm増え、強度が上昇したほか、パワーオンパスワード、ハードディスクパスワードなどデータ漏洩防止機能が追加され、ビジネス用途も意識した仕様となった。 + +ボディカラーは若干変更され、従来モデルではシルバーだったパームレスト部分がブラックに変更されるなど、落ち着いた印象となった。 + +液晶パネルは、従来モデルでは1,400×1,050ドット(SXGA+)液晶を搭載していたが、今回のモデルでは1,024×768ドット(XGA)の液晶パネルを搭載したモデルも用意される。 + +また、CPUとしてPentium M 755(2GHz)/745(1.8GHz)/725(1.6GHz)などのほか、Celeron-M 350(1.3GHz)も選択できるなど、ハイエンドからエントリーまでがカバーされる。 + +そのほかの主な仕様は、メモリ256MB~1.5GB、HDD 40GB~80GB、Intel 855GME(ビデオ機能内蔵)チップセットなどを搭載。光学ドライブとしてDVD±RWドライブまたはDVD/CD-RWドライブを選択可能。 + +インターフェイスはEthernet、IEEE 802.11b/g無線LAN、Type2 PCカードスロット×1、USB 2.0×2、IEEE 1394(4ピン)×1、D-Sub15ピンなどを搭載する。なお、各種インターフェイスを備えるポートリプリケータが付属するが、従来モデルに搭載されていたDVI出力端子が省略されている。 + +バッテリはリチウムイオンバッテリで、駆動時間は約4時間(Sバッテリ)。本体サイズは321×255.3×29~43.2mm(幅×奥行き×高さ)、重量は約2.3kg。 + +なお、企業向けのビジネスパーソナル向けとして液晶パネルやCPUなどが異なる8モデルも用意される。付属のアプリケーションなどが最小限に抑えられるなど、より企業ユーザー向けのモデルとなる。 + + \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/test-mail5-html.xml b/src/test/java/com/ozacc/mail/test-mail5-html.xml old mode 100755 new mode 100644 index 15d73ba..648e8b1 --- a/src/test/java/com/ozacc/mail/test-mail5-html.xml +++ b/src/test/java/com/ozacc/mail/test-mail5-html.xml @@ -1,123 +1,123 @@ - - - - - - - - - HTML送信テスト - - - - - - - -Power Mac G5、登場。 - - - - - - - - - - - - - - - - -
Power Mac G5、登場。
- - - - - - - - - -
- - - - - - -
- -アップルが再び、コンピュータの世界を変えます。
-世界初の64ビットプロセッサを搭載したパーソナルコンピュータ、Power Mac G5の登場です。未来はもう、あなたの手の届くところにあります。

- - -
- -すべてが新しいPower Mac G5。
- -Power Mac G5には、最新技術が詰まっています。まずはアップルとIBMの共同開発による非常にパワフルな64ビット
- -PowerPC G5プロセッサ。 -これに、業界最速のフロントエンド・バス、高バンド幅のシステムアーキテクチャ、最大8GBまで増設可能な高速メモリが加わり、デスクトップコンピュータの処理能力を飛躍的に進化させました。実際に、Power Mac G5のパフォーマンスは、最速のPentium 4を搭載したデスクトップコンピュータをも凌ぐのです*。

- -
- -このマシンをまだ「パーソナルコンピュータ」と呼んでいいのだろうか?
- -Power Mac G5には、高速PCI-Xスロット、最新鋭のストレージ、AGP 8X Proグラフィック、驚くほど静かなエンクロージャなど、いままでのPCでは実現不可能だった革新的な機能が満載で、高度なマシンスペックが要求されるグラフィック制作や映像編集でさえも楽々とこなすことができます。
-さらにMac OS X v10.2がPowerPC G5プロセッサに合わせて特別にチューンされているため、どんなアプリケーションを使っても、すぐに64ビットのパワーを実感できます。
-
-
- - - -Order Now -先行予約 -Power Mac G5 -もっと詳しく -SPEC CPU2000ベンチマーク - - - -
- -
- -コンピュータは永遠に進化する。
- -いったん64ビットを体験したら、もう後戻りはできません。あなたが前へ進むための、エキサイティングな3つの選択肢を用意しています。Power Mac G5には、1.6GHz、1.8GHz、そしてデュアル2GHzの3つのモデルがあります。 -価格は驚きの244,800円(Apple Storeプライス、税別)から。Power Mac G5のお見積、ご購入に関するご相談はこちらからどうぞ。どのモデルにもSuperDriveが搭載され、自分自身でCDやDVDを作成することができるなど、Power Mac G5の魅力はまだまだたくさんあります。

- -これは革命にほかなりません。未来は64ビットPower Mac G5の中に。
- -「世界最速」は、SPEC CPU2000ベンチマークと、プロ向けの最新アプリケーションでのパフォーマンステストの結果に基づきます。このテストの比較には、3GHz Pentium 4搭載のDell Dimension 8300と、デュアル3.06GHz Xeon搭載のDell Precision 650を使用しています。SPEC CPU 2000ベンチマークはGCC 3.3で実行し、個別にテストしています。 -詳細レポートはVeritest社より入手できます。プロ向けアプリケーションを使ったテストは、2003年6月にアップル社内で実施されました。

- -* SPEC CPU2000ベンチマークと、プロ向けの最新アプリケーションでのパフォーマンステストの結果に基づきます。このテストの比較には、3GHz Pentium 4搭載のDell Dimension 8300と、デュアル3.06GHz Xeon搭載のDell Precision 650を使用しています。SPEC CPU2000ベンチマークはGCC 3.3で実行し、個別にテストしています。プロ向けアプリケーションを使ったテストは、2003年6月にApple社内で実施されました。

- -Copyright (C) 2003 Apple Computer, Inc. All rights reserved. | 登録内容の変更 | プライバシーについて
- -メールフォーマットの変更
- - - -]]> - - - + + + + + + + + + HTML送信テスト + + + + + + + +Power Mac G5、登場。 + + + + + + + + + + + + + + + + +
Power Mac G5、登場。
+ + + + + + + + + +
+ + + + + + +
+ +アップルが再び、コンピュータの世界を変えます。
+世界初の64ビットプロセッサを搭載したパーソナルコンピュータ、Power Mac G5の登場です。未来はもう、あなたの手の届くところにあります。

+ + +
+ +すべてが新しいPower Mac G5。
+ +Power Mac G5には、最新技術が詰まっています。まずはアップルとIBMの共同開発による非常にパワフルな64ビット
+ +PowerPC G5プロセッサ。 +これに、業界最速のフロントエンド・バス、高バンド幅のシステムアーキテクチャ、最大8GBまで増設可能な高速メモリが加わり、デスクトップコンピュータの処理能力を飛躍的に進化させました。実際に、Power Mac G5のパフォーマンスは、最速のPentium 4を搭載したデスクトップコンピュータをも凌ぐのです*。

+ +
+ +このマシンをまだ「パーソナルコンピュータ」と呼んでいいのだろうか?
+ +Power Mac G5には、高速PCI-Xスロット、最新鋭のストレージ、AGP 8X Proグラフィック、驚くほど静かなエンクロージャなど、いままでのPCでは実現不可能だった革新的な機能が満載で、高度なマシンスペックが要求されるグラフィック制作や映像編集でさえも楽々とこなすことができます。
+さらにMac OS X v10.2がPowerPC G5プロセッサに合わせて特別にチューンされているため、どんなアプリケーションを使っても、すぐに64ビットのパワーを実感できます。
+
+
+ + + +Order Now +先行予約 +Power Mac G5 +もっと詳しく +SPEC CPU2000ベンチマーク + + + +
+ +
+ +コンピュータは永遠に進化する。
+ +いったん64ビットを体験したら、もう後戻りはできません。あなたが前へ進むための、エキサイティングな3つの選択肢を用意しています。Power Mac G5には、1.6GHz、1.8GHz、そしてデュアル2GHzの3つのモデルがあります。 +価格は驚きの244,800円(Apple Storeプライス、税別)から。Power Mac G5のお見積、ご購入に関するご相談はこちらからどうぞ。どのモデルにもSuperDriveが搭載され、自分自身でCDやDVDを作成することができるなど、Power Mac G5の魅力はまだまだたくさんあります。

+ +これは革命にほかなりません。未来は64ビットPower Mac G5の中に。
+ +「世界最速」は、SPEC CPU2000ベンチマークと、プロ向けの最新アプリケーションでのパフォーマンステストの結果に基づきます。このテストの比較には、3GHz Pentium 4搭載のDell Dimension 8300と、デュアル3.06GHz Xeon搭載のDell Precision 650を使用しています。SPEC CPU 2000ベンチマークはGCC 3.3で実行し、個別にテストしています。 +詳細レポートはVeritest社より入手できます。プロ向けアプリケーションを使ったテストは、2003年6月にアップル社内で実施されました。

+ +* SPEC CPU2000ベンチマークと、プロ向けの最新アプリケーションでのパフォーマンステストの結果に基づきます。このテストの比較には、3GHz Pentium 4搭載のDell Dimension 8300と、デュアル3.06GHz Xeon搭載のDell Precision 650を使用しています。SPEC CPU2000ベンチマークはGCC 3.3で実行し、個別にテストしています。プロ向けアプリケーションを使ったテストは、2003年6月にApple社内で実施されました。

+ +Copyright (C) 2003 Apple Computer, Inc. All rights reserved. | 登録内容の変更 | プライバシーについて
+ +メールフォーマットの変更
+ + + +]]> + + +
\ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/test-mail6-cdata.xml b/src/test/java/com/ozacc/mail/test-mail6-cdata.xml old mode 100755 new mode 100644 index 156d4aa..7b71b85 --- a/src/test/java/com/ozacc/mail/test-mail6-cdata.xml +++ b/src/test/java/com/ozacc/mail/test-mail6-cdata.xml @@ -1,16 +1,16 @@ - - - - - - - - CDATA取り扱いのテストケース - - - - - - - + + + + + + + + CDATA取り扱いのテストケース + + + + + + + \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/test-mail7-multiple.xml b/src/test/java/com/ozacc/mail/test-mail7-multiple.xml old mode 100755 new mode 100644 index da94ba2..7b6872d --- a/src/test/java/com/ozacc/mail/test-mail7-multiple.xml +++ b/src/test/java/com/ozacc/mail/test-mail7-multiple.xml @@ -1,42 +1,42 @@ - - - - - - - - - - - MultipleMailBuilder 1通目 - - - 1通目 - - - - - - - - - - MultipleMailBuilder 2通目 - - - 2通目 - - - - - - - - - - MultipleMailBuilder 3通目 - - - 3通目 - + + + + + + + + + + + MultipleMailBuilder 1通目 + + + 1通目 + + + + + + + + + + MultipleMailBuilder 2通目 + + + 2通目 + + + + + + + + + + MultipleMailBuilder 3通目 + + + 3通目 + \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/xml/impl/JDomXMLBuilderTest.java b/src/test/java/com/ozacc/mail/xml/impl/JDomXMLBuilderTest.java old mode 100755 new mode 100644 index 63ee2b4..3f8d86e --- a/src/test/java/com/ozacc/mail/xml/impl/JDomXMLBuilderTest.java +++ b/src/test/java/com/ozacc/mail/xml/impl/JDomXMLBuilderTest.java @@ -1,99 +1,99 @@ -package com.ozacc.mail.xml.impl; - -import java.io.File; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.jdom.Document; -import org.jdom.input.DOMBuilder; -import org.jdom.output.XMLOutputter; - -import com.ozacc.mail.Mail; - -/** - * - * @author Tomohiro Otsuka - * @version $Id: JDomXMLBuilderTest.java,v 1.2.2.1 2004/10/24 10:28:09 otsuka Exp $ - */ -public class JDomXMLBuilderTest extends TestCase { - - private JDomXMLBuilder builder; - - /** - * @see TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - - BasicConfigurator.configure(); - - builder = new JDomXMLBuilder(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - public final void testCreateDocument() throws Exception { - Mail mail = getMailForTest(); - - org.w3c.dom.Document doc = builder.buildDocument(mail); - - DOMBuilder builder = new DOMBuilder(); - Document jdomDoc = builder.build(doc); - - System.out.println(jdomDoc); - - XMLOutputter outputter = new XMLOutputter(); - String document = outputter.outputString(jdomDoc); - System.out.println(document); - - } - - /* - * Class under test for void saveDocument(Mail, File) - */ - public final void testSaveDocumentMailFile() throws Exception { - Mail mail = getMailForTest(); - - String filePath = "target/test/data/mail.xml"; - File file = new File(filePath); - file.getParentFile().mkdirs(); - - builder.saveDocument(mail, file); - } - - public final void testSaveDocumentHtml() throws Exception { - Mail mail = getMailForTest(); - mail.setHtmlText("テスト成功"); - - String filePath = "target/test/data/mail-jdk-html.xml"; - File file = new File(filePath); - file.getParentFile().mkdirs(); - - builder.saveDocument(mail, file); - } - - /** - * @return - */ - private Mail getMailForTest() { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功\n&<>"; - - Mail mail = new Mail(); - mail.setFrom(from, fromName); - mail.addTo(to); - mail.setSubject(subject); - mail.setText(text); - return mail; - } - +package com.ozacc.mail.xml.impl; + +import java.io.File; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; +import org.jdom.Document; +import org.jdom.input.DOMBuilder; +import org.jdom.output.XMLOutputter; + +import com.ozacc.mail.Mail; + +/** + * + * @author Tomohiro Otsuka + * @version $Id: JDomXMLBuilderTest.java,v 1.2.2.1 2004/10/24 10:28:09 otsuka Exp $ + */ +public class JDomXMLBuilderTest extends TestCase { + + private JDomXMLBuilder builder; + + /** + * @see TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + + BasicConfigurator.configure(); + + builder = new JDomXMLBuilder(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + public final void testCreateDocument() throws Exception { + Mail mail = getMailForTest(); + + org.w3c.dom.Document doc = builder.buildDocument(mail); + + DOMBuilder builder = new DOMBuilder(); + Document jdomDoc = builder.build(doc); + + System.out.println(jdomDoc); + + XMLOutputter outputter = new XMLOutputter(); + String document = outputter.outputString(jdomDoc); + System.out.println(document); + + } + + /* + * Class under test for void saveDocument(Mail, File) + */ + public final void testSaveDocumentMailFile() throws Exception { + Mail mail = getMailForTest(); + + String filePath = "target/test/data/mail.xml"; + File file = new File(filePath); + file.getParentFile().mkdirs(); + + builder.saveDocument(mail, file); + } + + public final void testSaveDocumentHtml() throws Exception { + Mail mail = getMailForTest(); + mail.setHtmlText("テスト成功"); + + String filePath = "target/test/data/mail-jdk-html.xml"; + File file = new File(filePath); + file.getParentFile().mkdirs(); + + builder.saveDocument(mail, file); + } + + /** + * @return + */ + private Mail getMailForTest() { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功\n&<>"; + + Mail mail = new Mail(); + mail.setFrom(from, fromName); + mail.addTo(to); + mail.setSubject(subject); + mail.setText(text); + return mail; + } + } \ No newline at end of file diff --git a/src/test/java/com/ozacc/mail/xml/impl/XMLBuilderImplTest.java b/src/test/java/com/ozacc/mail/xml/impl/XMLBuilderImplTest.java old mode 100755 new mode 100644 index 28f8446..0adbae0 --- a/src/test/java/com/ozacc/mail/xml/impl/XMLBuilderImplTest.java +++ b/src/test/java/com/ozacc/mail/xml/impl/XMLBuilderImplTest.java @@ -1,99 +1,99 @@ -package com.ozacc.mail.xml.impl; - -import java.io.File; - -import junit.framework.TestCase; - -import org.apache.log4j.BasicConfigurator; -import org.jdom.Document; -import org.jdom.input.DOMBuilder; -import org.jdom.output.XMLOutputter; - -import com.ozacc.mail.Mail; -import com.ozacc.mail.xml.XMLBuilder; - -/** - * - * @author Tomohiro Otsuka - * @version $Id: XMLBuilderImplTest.java,v 1.4.2.1 2004/10/24 10:28:09 otsuka Exp $ - */ -public class XMLBuilderImplTest extends TestCase { - - private XMLBuilder builder; - - /** - * @see junit.framework.TestCase#setUp() - */ - protected void setUp() throws Exception { - super.setUp(); - - BasicConfigurator.configure(); - - builder = new XMLBuilderImpl(); - } - - /** - * @see junit.framework.TestCase#tearDown() - */ - protected void tearDown() throws Exception { - BasicConfigurator.resetConfiguration(); - } - - public final void testCreateDocument() throws Exception { - Mail mail = getMailForTest(); - - org.w3c.dom.Document doc = builder.buildDocument(mail); - - DOMBuilder builder = new DOMBuilder(); - Document jdomDoc = builder.build(doc); - - System.out.println(jdomDoc); - - XMLOutputter outputter = new XMLOutputter(); - String document = outputter.outputString(jdomDoc); - System.out.println(document); - } - - /* - * Class under test for void saveDocument(Mail, File) - */ - public final void testSaveDocumentMailFile() throws Exception { - Mail mail = getMailForTest(); - - String filePath = "target/test/data/mail-jdk.xml"; - File file = new File(filePath); - file.getParentFile().mkdirs(); - - builder.saveDocument(mail, file); - } - - public final void testSaveDocumentHtml() throws Exception { - Mail mail = getMailForTest(); - mail.setHtmlText("テスト成功"); - - String filePath = "target/test/data/mail-jdk-html.xml"; - File file = new File(filePath); - file.getParentFile().mkdirs(); - - builder.saveDocument(mail, file); - } - - /** - * @return - */ - private Mail getMailForTest() { - String from = "from@example.com"; - String fromName = "差出人"; - String to = "info@example.com"; - String subject = "件名"; - String text = "テスト成功\n&<>"; - - Mail mail = new Mail(); - mail.setFrom(from, fromName); - mail.addTo(to); - mail.setSubject(subject); - mail.setText(text); - return mail; - } - +package com.ozacc.mail.xml.impl; + +import java.io.File; + +import junit.framework.TestCase; + +import org.apache.log4j.BasicConfigurator; +import org.jdom.Document; +import org.jdom.input.DOMBuilder; +import org.jdom.output.XMLOutputter; + +import com.ozacc.mail.Mail; +import com.ozacc.mail.xml.XMLBuilder; + +/** + * + * @author Tomohiro Otsuka + * @version $Id: XMLBuilderImplTest.java,v 1.4.2.1 2004/10/24 10:28:09 otsuka Exp $ + */ +public class XMLBuilderImplTest extends TestCase { + + private XMLBuilder builder; + + /** + * @see junit.framework.TestCase#setUp() + */ + protected void setUp() throws Exception { + super.setUp(); + + BasicConfigurator.configure(); + + builder = new XMLBuilderImpl(); + } + + /** + * @see junit.framework.TestCase#tearDown() + */ + protected void tearDown() throws Exception { + BasicConfigurator.resetConfiguration(); + } + + public final void testCreateDocument() throws Exception { + Mail mail = getMailForTest(); + + org.w3c.dom.Document doc = builder.buildDocument(mail); + + DOMBuilder builder = new DOMBuilder(); + Document jdomDoc = builder.build(doc); + + System.out.println(jdomDoc); + + XMLOutputter outputter = new XMLOutputter(); + String document = outputter.outputString(jdomDoc); + System.out.println(document); + } + + /* + * Class under test for void saveDocument(Mail, File) + */ + public final void testSaveDocumentMailFile() throws Exception { + Mail mail = getMailForTest(); + + String filePath = "target/test/data/mail-jdk.xml"; + File file = new File(filePath); + file.getParentFile().mkdirs(); + + builder.saveDocument(mail, file); + } + + public final void testSaveDocumentHtml() throws Exception { + Mail mail = getMailForTest(); + mail.setHtmlText("テスト成功"); + + String filePath = "target/test/data/mail-jdk-html.xml"; + File file = new File(filePath); + file.getParentFile().mkdirs(); + + builder.saveDocument(mail, file); + } + + /** + * @return + */ + private Mail getMailForTest() { + String from = "from@example.com"; + String fromName = "差出人"; + String to = "info@example.com"; + String subject = "件名"; + String text = "テスト成功\n&<>"; + + Mail mail = new Mail(); + mail.setFrom(from, fromName); + mail.addTo(to); + mail.setSubject(subject); + mail.setText(text); + return mail; + } + } \ No newline at end of file diff --git a/xdocs/index.xml b/xdocs/index.xml old mode 100755 new mode 100644 index fc6e1df..eec0a68 --- a/xdocs/index.xml +++ b/xdocs/index.xml @@ -1,290 +1,290 @@ - - - - - ozacc-mail library - Tomohiro Otsuka - - - - -

-

ozacc-mail libraryは、Spring FrameworkやSeasar2といったDIコンテナに組み込んで使用できるメール送信ライブラリです。DIコンテナ上での使用を想定していますが、DIコンテナ環境外での使用も可能です。

-
- -
-

JDK 1.4以上の環境でご使用ください。
また、次のJARファイルをクラスパスに含めてください。
- 各ライブラリは、ozacc-mail libraryの配布ファイルには含まれていませんので、Dependenciesページを参考に各自で取得してください。

- -
    -
  • JavaMail 1.3.1 (mail.jar) [必須]
  • -
  • JavaBeans Activation Framework(JAF) 1.0.2 (activation.jar) [必須]
  • -
  • Jakarta Commons Logging 1.0.4 [必須]

  • - -
  • JDOM 1.0 [com.ozacc.mail.impl.JDomXMLMailBuilderを使用する場合]
  • -
  • Jakarta Velocity 1.4 [com.ozacc.mail.impl.XMLVelocityMailBuilder、com.ozacc.mail.impl.JDomXMLMailBuilderを使用する場合]
  • -
  • Jakarta Commons Collection 1.4 [com.ozacc.mail.impl.XMLVelocityMailBuilder、com.ozacc.mail.impl.JDomXMLMailBuilderを使用する場合]
  • -
-
- -
-

次のページからozacc-mail libraryの最新リリースをダウンロードできます。
http://sourceforge.jp/projects/spring-ext/

-

またMaven用のリモートレポジトリも用意しています。URLは「http://spring-ext.sourceforge.jp/maven/」です。このURLをmaven.repo.remoteプロパティに設定してください。groupId、artifactIdは共に「ozacc-mail」です。

-
- -
-

GNU Library or "Lesser" Public License (LGPL).

-
- -
-

JavaDoc API

-
- -
-

SendMailは、JavaMail APIをラップし、メール送信のための至極シンプルなインターフェースを提供しています。提供しているメソッド名はたった一つ、send()です。メールデータを表すcom.ozacc.mail.Mailインスタンスか、JavaMailのMimeMessageインスタンスを引数に指定すると、それを送信します。(これらの配列も指定可能です。)

- -

SendMail(SendMailImpl).send()メソッドは、スレッドセーフな設計になっていますが、呼び出すスレッドの数だけSMTPサーバに接続します。通常の使用では問題にならないはずですが、メールサーバやその設定によっては注意が必要です。

- -

SendMailの使用方法を、Springと連携させる場合を例にとって説明します。

- -

▼applicationContext.xmlでのBean定義

- <beans> - <bean id="sendMail" class="com.ozacc.mail.impl.SendMailImpl"> - <!-- SMTPサーバ --> - <property name="host"><value>smtp.example.com</value></property> - </bean> -</beans> - -

▼Javaソース

- // Mailインスタンスの生成 -Mail mail = new Mail(); -mail.setFrom("shop@example.com", "XXXオンラインショップ"); -mail.addTo("misaki@foo.com", "伊東美咲さま"); -mail.addBcc("order@example.com"); -mail.setSubject("ご注文の確認"); -mail.setText("お買い上げありがとうございました。\n\nご注文明細・・・"); - -// SendMailインスタンスの取得 -SendMail sendMail = (SendMail)applicationContext.getBean("sendMail"); - -// メールの送信 -sendMail.send(mail); - -

sendMail.send(mail)で、何らかの原因で送信に失敗すると、com.ozacc.mail.MailExceptionがスローされます。MailExceptionは非チェック例外なので、プログラムの要求に応じてキャッチしてください。

- -
- -
- -

MailBuilderを使用すると、ファイルに記述されたメールデータからMailインスタンスを生成できます。
さらに、MailBuilderインターフェースを継承したVelocityMailBuilderを使用すると、Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成できます。

- -

現バージョンでは、XML形式のメールデータを扱うXMLMailBuilderImplクラスが提供されています。ここではその使用方法を、Springと連携させる場合を例にとって説明します。

- -

▼applicationContext.xmlでのBean定義

- <beans> - <bean id="sendMail" class="com.ozacc.mail.impl.SendMailImpl"> - <property name="host"><value>smtp.example.com</value></property> - </bean> - - <bean id="mailBuilder" class="com.ozacc.mail.impl.XMLMailBuilderImpl" /> -</beans> - -

▼Javaソース

- // MailBuilderインスタンスの取得 -MailBuilder mailBuilder = (MailBuilder)applicationContext.getBean("mailBuilder"); - -// メールデータXMLファイルのパス (クラスパス上) -String path = "/com/example/mail/mail-template.xml"; - -// Mailインスタンスを生成 -Mail mail = mailBuilder.buildMail(path); - -// SendMailインスタンスの取得 -SendMail sendMail = (SendMail)applicationContext.getBean("sendMail"); - -// メールの送信 -sendMail.send(mail); - -

▼mail-template.xml

- <?xml version="1.0" encoding="utf-8" ?> -<!DOCTYPE mail PUBLIC "-//OZACC//DTD MAIL//EN" "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"> - -<mail> - - <returnPath email="return@example.com" /> - - <from email="from@example.com" name="差出人" /> - - <recipients> - <to email="to1@example.com" name="宛先1" /> - <cc email="cc1@example.com" name="CC1" /> - <bcc email="bcc@example.com" /> - <cc email="cc2@example.com" /> - <to email="to2@example.com" /> - </recipients> - - <replyTo email="reply@example.com" /> - - <!-- subject(件名)の前後のホワイトスペース(半角スペース、タブ、改行)は削除されます。 --> - <subject> - 件名 - </subject> - - <!-- body(本文)の前後のホワイトスペース(半角スペース、タブ、改行)は削除されます。 --> - <body> - 本文 - </body> - -</mail> - -

DTDで定義されているように、ルート要素<mail>以外の全要素はオプションです。
- 例えば<from>要素だけ含んだXMLからは、fromプロパティだけセットされたMailインスタンスが生成されます。

- -

Velocityとの連携については、テストケース(src/test/com/ozacc/mail/impl/XMLVelocityMailBuilderImplTest)を参照してください。

- -
- -
- -

XMLMailFactoryBeanはSpringと連携している場合にのみ使用可能です。

- -

上述したMailBuilderを使ってXMLメールデータからMailインスタンスを生成する場合、XMLファイルのロケーションを示すパスがソース内にハードコーディングされています。一般的にはアプリケーション側で、MailBuilderのインスタンスとXMLファイルのロケーションパスをプロパティとして保持するクラスを作り、DIコンテナでプロパティを設定するようにします。
- Springを使用している場合、このようなクラスを作らずともXMLファイルのロケーションパスをソースから追い出し、コンテナ上でMailインスタンスを生成させることができます。

- -

▼applicationContext.xmlでのBean定義

- <beans> - <bean id="sendMail" class="com.ozacc.mail.impl.SendMailImpl"> - <property name="host"><value>smtp.example.com</value></property> - </bean> - - <bean id="mail" class="com.ozacc.mail.spring.XMLMailFactoryBean"> - <!-- メールデータXMLファイルのパス (クラスパス上) --> - <property name="classPath"><value>/com/example/mail/mail-template.xml</value></property> - </bean> -</beans> - -

▼Javaソース

- // Mailインスタンスの生成、取得 -Mail mail = (Mail)applicationContext.getBean("mail"); - -// SendMailインスタンスの取得 -SendMail sendMail = (SendMail)applicationContext.getBean("sendMail"); - -// メールの送信 -sendMail.send(mail); - -

XMLMailFactoryBeanから生成されるMailインスタンスは、prototypeです。つまりシングルトンではなく、呼び出すたびに新しいMailインスタンスが生成されます。何かの理由でMailインスタンスをシングルトンにしたい場合は、XMLMailFactoryBeanのsingltonプロパティにtrueをセットするだけです。

- -

XMLMailFactoryBeanでは、Velocityと連携させてMailインスタンスを生成することはできません。

-
- -
-

1.1.2 -

    -
  • VelocityMailBuilderがテンプレートメールデータのキャッシュをサポートしました。
  • -
-

-

1.1.1 -

    -
  • XMLVelocityMailBuilderImplがXMLメールデータを読み込む際に、<![CDATA[]]>タグを削除しないように修正。
  • -
-

-

1.1 rc2 -

    -
  • SendMailImplとSendMailProImplクラスにsetMessageId(String)メソッドを追加。com.ozacc.mail.impl.OMLMimeMessageクラスを追加。Message-IDヘッダのドメイン部分がカスタマイズ可能に。
  • -
  • com.ozacc.mail.impl.DTDEntityResolverクラスを追加。ネットワークアクセスなしでDTDを参照できるようになった。
  • -
  • 本文がHTMLテキストだけの場合に生成されるMimeMessageをマルチパートからシングルパートに修正。
  • -
-

-

1.1 rc1 -

    -
  • MultipartMailクラスをMailクラスに統合。
  • -
  • 添付ファイルとしてInputStreamとURLインスタンスを指定できるメソッドを追加。
  • -
  • com.ozacc.mail.mock.EqualityCheckクラスを追加。
  • -
-

-

1.1 beta1 -

    -
  • com.ozacc.mail.MultipartMailクラスを追加。
  • -
  • XMLMailBuilderImpl、XMLVelocityMailBuilderImplが読み込むXMLで<![CDATA[]]>が利用できるように修正。
  • -
  • MimeMessageBuilderがMultipartMailインスタンスを判別して、マルチパート対応のMimeMessageを生成できるように修正。
  • -
  • ozacc-mail.dtdに<html>要素定義を追加。
  • -
-

-

1.0.3 -

    -
  • com.ozacc.mail.impl.VelocityLogSystemクラスを追加。XMLVelocityMailBuilderImplとJDomXMLMailBuilderで使用されいてるVelocityのログメッセージをcommons-logging経由で出力します。
  • -
  • XMLVelocityMailBuilderImplクラスを修正。buildMail(File, VelocityContext)、buildMail(String, VelocityContext)メソッドで読み込まれるXMLファイルのコメントに、VTL(Velocity Template Language)を記述できるようになった。
  • -
-

-

1.0.2 -

    -
  • Cp932クラスを用いて、文字化け懸念のある記号(全角のハイフンやチルダ等)を予めJISエンコードするように修正。
  • -
  • MailクラスにclearTo(), clearCc(), clearBcc()メソッドを追加。
  • -
  • MailクラスとMockMailクラスにコピーコンストラクタを追加。
  • -
-

-

1.0.1 -

    -
  • com.ozacc.mail.impl.XMLMailBuilderImplクラスを追加。
  • -
  • com.ozacc.mail.impl.XMLVelocityMailBuilderImplクラスを追加。
  • -
-

-
- -
- <?xml version="1.0" encoding="utf-8" ?> -<!DOCTYPE mail PUBLIC "-//OZACC//DTD MAIL//EN" "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"> - -<mail> - - <!-- Return-Path (?) --> - <!-- [attribute] email メールアドレス (必須) --> - <returnPath email="return@example.com" /> - - <!-- 差出人 (?) --> - <!-- [attribute] email メールアドレス (必須) --> - <!-- [attribute] name 差出人名 (オプション) --> - <from email="from@example.com" name="差出人名" /> - - <!-- 送信先 (?) --> - <recipients> - <!-- Toアドレス (*) --> - <!-- [attribute] email メールアドレス (必須) --> - <!-- [attribute] name 宛名 (オプション) --> - <to email="to@example.com" name="宛名" /> - - <!-- Ccアドレス (*) --> - <!-- [attribute] email メールアドレス (必須) --> - <!-- [attribute] name 宛名 (オプション) --> - <cc email="cc@example.com" name="宛名" /> - - <!-- Bccアドレス (*) --> - <!-- [attribute] email メールアドレス (必須) --> - <bcc email="bcc@example.com" /> - </recipients> - - <!-- 返信先 (?) --> - <!-- [attribute] email メールアドレス (必須) --> - <replyTo email="reply@example.com" /> - - <!-- 件名 (?) --> - <subject><![CDATA[ - 件名 - ]]></subject> - - <!-- 本文 (?) --> - <body><![CDATA[ - 本文 - ]]></body> - - <!-- HTMLメールの本文 (?) --> - <html><![CDATA[ - HTML - ]]></html> - -</mail> -
- - + + + + + ozacc-mail library + Tomohiro Otsuka + + + + +
+

ozacc-mail libraryは、Spring FrameworkやSeasar2といったDIコンテナに組み込んで使用できるメール送信ライブラリです。DIコンテナ上での使用を想定していますが、DIコンテナ環境外での使用も可能です。

+
+ +
+

JDK 1.4以上の環境でご使用ください。
また、次のJARファイルをクラスパスに含めてください。
+ 各ライブラリは、ozacc-mail libraryの配布ファイルには含まれていませんので、Dependenciesページを参考に各自で取得してください。

+ +
    +
  • JavaMail 1.3.1 (mail.jar) [必須]
  • +
  • JavaBeans Activation Framework(JAF) 1.0.2 (activation.jar) [必須]
  • +
  • Jakarta Commons Logging 1.0.4 [必須]

  • + +
  • JDOM 1.0 [com.ozacc.mail.impl.JDomXMLMailBuilderを使用する場合]
  • +
  • Jakarta Velocity 1.4 [com.ozacc.mail.impl.XMLVelocityMailBuilder、com.ozacc.mail.impl.JDomXMLMailBuilderを使用する場合]
  • +
  • Jakarta Commons Collection 1.4 [com.ozacc.mail.impl.XMLVelocityMailBuilder、com.ozacc.mail.impl.JDomXMLMailBuilderを使用する場合]
  • +
+
+ +
+

次のページからozacc-mail libraryの最新リリースをダウンロードできます。
http://sourceforge.jp/projects/spring-ext/

+

またMaven用のリモートレポジトリも用意しています。URLは「http://spring-ext.sourceforge.jp/maven/」です。このURLをmaven.repo.remoteプロパティに設定してください。groupId、artifactIdは共に「ozacc-mail」です。

+
+ +
+

GNU Library or "Lesser" Public License (LGPL).

+
+ +
+

JavaDoc API

+
+ +
+

SendMailは、JavaMail APIをラップし、メール送信のための至極シンプルなインターフェースを提供しています。提供しているメソッド名はたった一つ、send()です。メールデータを表すcom.ozacc.mail.Mailインスタンスか、JavaMailのMimeMessageインスタンスを引数に指定すると、それを送信します。(これらの配列も指定可能です。)

+ +

SendMail(SendMailImpl).send()メソッドは、スレッドセーフな設計になっていますが、呼び出すスレッドの数だけSMTPサーバに接続します。通常の使用では問題にならないはずですが、メールサーバやその設定によっては注意が必要です。

+ +

SendMailの使用方法を、Springと連携させる場合を例にとって説明します。

+ +

▼applicationContext.xmlでのBean定義

+ <beans> + <bean id="sendMail" class="com.ozacc.mail.impl.SendMailImpl"> + <!-- SMTPサーバ --> + <property name="host"><value>smtp.example.com</value></property> + </bean> +</beans> + +

▼Javaソース

+ // Mailインスタンスの生成 +Mail mail = new Mail(); +mail.setFrom("shop@example.com", "XXXオンラインショップ"); +mail.addTo("misaki@foo.com", "伊東美咲さま"); +mail.addBcc("order@example.com"); +mail.setSubject("ご注文の確認"); +mail.setText("お買い上げありがとうございました。\n\nご注文明細・・・"); + +// SendMailインスタンスの取得 +SendMail sendMail = (SendMail)applicationContext.getBean("sendMail"); + +// メールの送信 +sendMail.send(mail); + +

sendMail.send(mail)で、何らかの原因で送信に失敗すると、com.ozacc.mail.MailExceptionがスローされます。MailExceptionは非チェック例外なので、プログラムの要求に応じてキャッチしてください。

+ +
+ +
+ +

MailBuilderを使用すると、ファイルに記述されたメールデータからMailインスタンスを生成できます。
さらに、MailBuilderインターフェースを継承したVelocityMailBuilderを使用すると、Velocityと連携して動的にメールデータを生成し、そのデータからMailインスタンスを生成できます。

+ +

現バージョンでは、XML形式のメールデータを扱うXMLMailBuilderImplクラスが提供されています。ここではその使用方法を、Springと連携させる場合を例にとって説明します。

+ +

▼applicationContext.xmlでのBean定義

+ <beans> + <bean id="sendMail" class="com.ozacc.mail.impl.SendMailImpl"> + <property name="host"><value>smtp.example.com</value></property> + </bean> + + <bean id="mailBuilder" class="com.ozacc.mail.impl.XMLMailBuilderImpl" /> +</beans> + +

▼Javaソース

+ // MailBuilderインスタンスの取得 +MailBuilder mailBuilder = (MailBuilder)applicationContext.getBean("mailBuilder"); + +// メールデータXMLファイルのパス (クラスパス上) +String path = "/com/example/mail/mail-template.xml"; + +// Mailインスタンスを生成 +Mail mail = mailBuilder.buildMail(path); + +// SendMailインスタンスの取得 +SendMail sendMail = (SendMail)applicationContext.getBean("sendMail"); + +// メールの送信 +sendMail.send(mail); + +

▼mail-template.xml

+ <?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE mail PUBLIC "-//OZACC//DTD MAIL//EN" "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"> + +<mail> + + <returnPath email="return@example.com" /> + + <from email="from@example.com" name="差出人" /> + + <recipients> + <to email="to1@example.com" name="宛先1" /> + <cc email="cc1@example.com" name="CC1" /> + <bcc email="bcc@example.com" /> + <cc email="cc2@example.com" /> + <to email="to2@example.com" /> + </recipients> + + <replyTo email="reply@example.com" /> + + <!-- subject(件名)の前後のホワイトスペース(半角スペース、タブ、改行)は削除されます。 --> + <subject> + 件名 + </subject> + + <!-- body(本文)の前後のホワイトスペース(半角スペース、タブ、改行)は削除されます。 --> + <body> + 本文 + </body> + +</mail> + +

DTDで定義されているように、ルート要素<mail>以外の全要素はオプションです。
+ 例えば<from>要素だけ含んだXMLからは、fromプロパティだけセットされたMailインスタンスが生成されます。

+ +

Velocityとの連携については、テストケース(src/test/com/ozacc/mail/impl/XMLVelocityMailBuilderImplTest)を参照してください。

+ +
+ +
+ +

XMLMailFactoryBeanはSpringと連携している場合にのみ使用可能です。

+ +

上述したMailBuilderを使ってXMLメールデータからMailインスタンスを生成する場合、XMLファイルのロケーションを示すパスがソース内にハードコーディングされています。一般的にはアプリケーション側で、MailBuilderのインスタンスとXMLファイルのロケーションパスをプロパティとして保持するクラスを作り、DIコンテナでプロパティを設定するようにします。
+ Springを使用している場合、このようなクラスを作らずともXMLファイルのロケーションパスをソースから追い出し、コンテナ上でMailインスタンスを生成させることができます。

+ +

▼applicationContext.xmlでのBean定義

+ <beans> + <bean id="sendMail" class="com.ozacc.mail.impl.SendMailImpl"> + <property name="host"><value>smtp.example.com</value></property> + </bean> + + <bean id="mail" class="com.ozacc.mail.spring.XMLMailFactoryBean"> + <!-- メールデータXMLファイルのパス (クラスパス上) --> + <property name="classPath"><value>/com/example/mail/mail-template.xml</value></property> + </bean> +</beans> + +

▼Javaソース

+ // Mailインスタンスの生成、取得 +Mail mail = (Mail)applicationContext.getBean("mail"); + +// SendMailインスタンスの取得 +SendMail sendMail = (SendMail)applicationContext.getBean("sendMail"); + +// メールの送信 +sendMail.send(mail); + +

XMLMailFactoryBeanから生成されるMailインスタンスは、prototypeです。つまりシングルトンではなく、呼び出すたびに新しいMailインスタンスが生成されます。何かの理由でMailインスタンスをシングルトンにしたい場合は、XMLMailFactoryBeanのsingltonプロパティにtrueをセットするだけです。

+ +

XMLMailFactoryBeanでは、Velocityと連携させてMailインスタンスを生成することはできません。

+
+ +
+

1.1.2 +

    +
  • VelocityMailBuilderがテンプレートメールデータのキャッシュをサポートしました。
  • +
+

+

1.1.1 +

    +
  • XMLVelocityMailBuilderImplがXMLメールデータを読み込む際に、<![CDATA[]]>タグを削除しないように修正。
  • +
+

+

1.1 rc2 +

    +
  • SendMailImplとSendMailProImplクラスにsetMessageId(String)メソッドを追加。com.ozacc.mail.impl.OMLMimeMessageクラスを追加。Message-IDヘッダのドメイン部分がカスタマイズ可能に。
  • +
  • com.ozacc.mail.impl.DTDEntityResolverクラスを追加。ネットワークアクセスなしでDTDを参照できるようになった。
  • +
  • 本文がHTMLテキストだけの場合に生成されるMimeMessageをマルチパートからシングルパートに修正。
  • +
+

+

1.1 rc1 +

    +
  • MultipartMailクラスをMailクラスに統合。
  • +
  • 添付ファイルとしてInputStreamとURLインスタンスを指定できるメソッドを追加。
  • +
  • com.ozacc.mail.mock.EqualityCheckクラスを追加。
  • +
+

+

1.1 beta1 +

    +
  • com.ozacc.mail.MultipartMailクラスを追加。
  • +
  • XMLMailBuilderImpl、XMLVelocityMailBuilderImplが読み込むXMLで<![CDATA[]]>が利用できるように修正。
  • +
  • MimeMessageBuilderがMultipartMailインスタンスを判別して、マルチパート対応のMimeMessageを生成できるように修正。
  • +
  • ozacc-mail.dtdに<html>要素定義を追加。
  • +
+

+

1.0.3 +

    +
  • com.ozacc.mail.impl.VelocityLogSystemクラスを追加。XMLVelocityMailBuilderImplとJDomXMLMailBuilderで使用されいてるVelocityのログメッセージをcommons-logging経由で出力します。
  • +
  • XMLVelocityMailBuilderImplクラスを修正。buildMail(File, VelocityContext)、buildMail(String, VelocityContext)メソッドで読み込まれるXMLファイルのコメントに、VTL(Velocity Template Language)を記述できるようになった。
  • +
+

+

1.0.2 +

    +
  • Cp932クラスを用いて、文字化け懸念のある記号(全角のハイフンやチルダ等)を予めJISエンコードするように修正。
  • +
  • MailクラスにclearTo(), clearCc(), clearBcc()メソッドを追加。
  • +
  • MailクラスとMockMailクラスにコピーコンストラクタを追加。
  • +
+

+

1.0.1 +

    +
  • com.ozacc.mail.impl.XMLMailBuilderImplクラスを追加。
  • +
  • com.ozacc.mail.impl.XMLVelocityMailBuilderImplクラスを追加。
  • +
+

+
+ +
+ <?xml version="1.0" encoding="utf-8" ?> +<!DOCTYPE mail PUBLIC "-//OZACC//DTD MAIL//EN" "http://www.ozacc.com/library/dtd/ozacc-mail.dtd"> + +<mail> + + <!-- Return-Path (?) --> + <!-- [attribute] email メールアドレス (必須) --> + <returnPath email="return@example.com" /> + + <!-- 差出人 (?) --> + <!-- [attribute] email メールアドレス (必須) --> + <!-- [attribute] name 差出人名 (オプション) --> + <from email="from@example.com" name="差出人名" /> + + <!-- 送信先 (?) --> + <recipients> + <!-- Toアドレス (*) --> + <!-- [attribute] email メールアドレス (必須) --> + <!-- [attribute] name 宛名 (オプション) --> + <to email="to@example.com" name="宛名" /> + + <!-- Ccアドレス (*) --> + <!-- [attribute] email メールアドレス (必須) --> + <!-- [attribute] name 宛名 (オプション) --> + <cc email="cc@example.com" name="宛名" /> + + <!-- Bccアドレス (*) --> + <!-- [attribute] email メールアドレス (必須) --> + <bcc email="bcc@example.com" /> + </recipients> + + <!-- 返信先 (?) --> + <!-- [attribute] email メールアドレス (必須) --> + <replyTo email="reply@example.com" /> + + <!-- 件名 (?) --> + <subject><![CDATA[ + 件名 + ]]></subject> + + <!-- 本文 (?) --> + <body><![CDATA[ + 本文 + ]]></body> + + <!-- HTMLメールの本文 (?) --> + <html><![CDATA[ + HTML + ]]></html> + +</mail> +
+ +
\ No newline at end of file -- 2.11.0