summaryrefslogtreecommitdiffstats
path: root/emailcommon
diff options
context:
space:
mode:
Diffstat (limited to 'emailcommon')
-rw-r--r--emailcommon/Android.mk34
-rw-r--r--emailcommon/src/com/android/emailcommon/AccountManagerTypes.java23
-rw-r--r--emailcommon/src/com/android/emailcommon/Api.java24
-rw-r--r--emailcommon/src/com/android/emailcommon/CalendarProviderStub.java25
-rw-r--r--emailcommon/src/com/android/emailcommon/Configuration.java23
-rw-r--r--emailcommon/src/com/android/emailcommon/Device.java109
-rw-r--r--emailcommon/src/com/android/emailcommon/Logging.java21
-rw-r--r--emailcommon/src/com/android/emailcommon/TempDirectory.java42
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/BinaryTempFileBody.java89
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/MimeBodyPart.java193
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/MimeHeader.java153
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/MimeMessage.java626
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/MimeMultipart.java111
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/MimeUtility.java452
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java357
-rw-r--r--emailcommon/src/com/android/emailcommon/internet/TextBody.java62
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Address.java519
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/AuthenticationFailedException.java34
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Body.java26
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/BodyPart.java25
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/CertificateValidationException.java30
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/FetchProfile.java85
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Fetchable.java24
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Flag.java79
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Folder.java257
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/MeetingInfo.java29
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Message.java159
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/MessageDateComparator.java34
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/MessagingException.java105
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Multipart.java63
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/PackedString.java176
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Part.java52
-rw-r--r--emailcommon/src/com/android/emailcommon/mail/Snippet.java487
-rw-r--r--emailcommon/src/com/android/emailcommon/provider/EmailContent.aidl21
-rw-r--r--emailcommon/src/com/android/emailcommon/provider/EmailContent.java2870
-rw-r--r--emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java139
-rw-r--r--emailcommon/src/com/android/emailcommon/service/EmailServiceConstants.java23
-rw-r--r--emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java273
-rw-r--r--emailcommon/src/com/android/emailcommon/service/EmailServiceStatus.java39
-rw-r--r--emailcommon/src/com/android/emailcommon/service/IAccountService.aidl34
-rw-r--r--emailcommon/src/com/android/emailcommon/service/IEmailService.aidl58
-rw-r--r--emailcommon/src/com/android/emailcommon/service/IEmailServiceCallback.aidl68
-rw-r--r--emailcommon/src/com/android/emailcommon/service/IPolicyService.aidl30
-rw-r--r--emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java227
-rw-r--r--emailcommon/src/com/android/emailcommon/service/PolicySet.aidl19
-rw-r--r--emailcommon/src/com/android/emailcommon/service/PolicySet.java356
-rw-r--r--emailcommon/src/com/android/emailcommon/service/ServiceProxy.java201
-rw-r--r--emailcommon/src/com/android/emailcommon/service/SyncWindow.java27
-rw-r--r--emailcommon/src/com/android/emailcommon/utility/AccountReconciler.java116
-rw-r--r--emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java335
-rw-r--r--emailcommon/src/com/android/emailcommon/utility/ConversionUtilities.java139
-rw-r--r--emailcommon/src/com/android/emailcommon/utility/LoggingInputStream.java109
-rw-r--r--emailcommon/src/com/android/emailcommon/utility/SSLUtils.java45
-rw-r--r--emailcommon/src/com/android/emailcommon/utility/Utility.java1131
-rw-r--r--emailcommon/src/org/apache/commons/io/CopyUtils.java332
-rw-r--r--emailcommon/src/org/apache/commons/io/DirectoryWalker.java620
-rw-r--r--emailcommon/src/org/apache/commons/io/EndianUtils.java489
-rw-r--r--emailcommon/src/org/apache/commons/io/FileCleaner.java154
-rw-r--r--emailcommon/src/org/apache/commons/io/FileCleaningTracker.java259
-rw-r--r--emailcommon/src/org/apache/commons/io/FileDeleteStrategy.java156
-rw-r--r--emailcommon/src/org/apache/commons/io/FileSystemUtils.java457
-rw-r--r--emailcommon/src/org/apache/commons/io/FileUtils.java1890
-rw-r--r--emailcommon/src/org/apache/commons/io/FilenameUtils.java1260
-rw-r--r--emailcommon/src/org/apache/commons/io/HexDump.java149
-rw-r--r--emailcommon/src/org/apache/commons/io/IOCase.java238
-rw-r--r--emailcommon/src/org/apache/commons/io/IOExceptionWithCause.java69
-rw-r--r--emailcommon/src/org/apache/commons/io/IOUtils.java1274
-rw-r--r--emailcommon/src/org/apache/commons/io/LineIterator.java181
-rw-r--r--emailcommon/src/org/apache/commons/io/ThirdPartyProject.prop9
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/DefaultFileComparator.java66
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/ExtensionFileComparator.java110
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/LastModifiedFileComparator.java77
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/NameFileComparator.java104
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/PathFileComparator.java105
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/ReverseComparator.java57
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/SizeFileComparator.java130
-rw-r--r--emailcommon/src/org/apache/commons/io/comparator/package.html25
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/AbstractFileFilter.java67
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/AgeFileFilter.java150
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/AndFileFilter.java171
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/CanReadFileFilter.java92
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/CanWriteFileFilter.java80
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/ConditionalFileFilter.java67
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/DelegateFileFilter.java104
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/DirectoryFileFilter.java73
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/EmptyFileFilter.java84
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/FalseFileFilter.java72
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/FileFileFilter.java60
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/FileFilterUtils.java361
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/HiddenFileFilter.java76
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/IOFileFilter.java55
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/NameFileFilter.java194
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/NotFileFilter.java78
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/OrFileFilter.java164
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/PrefixFileFilter.java200
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/RegexFileFilter.java122
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/SizeFileFilter.java103
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/SuffixFileFilter.java201
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/TrueFileFilter.java72
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/WildcardFileFilter.java199
-rw-r--r--emailcommon/src/org/apache/commons/io/filefilter/package.html143
-rw-r--r--emailcommon/src/org/apache/commons/io/input/AutoCloseInputStream.java129
-rw-r--r--emailcommon/src/org/apache/commons/io/input/CharSequenceReader.java155
-rw-r--r--emailcommon/src/org/apache/commons/io/input/ClassLoaderObjectInputStream.java77
-rw-r--r--emailcommon/src/org/apache/commons/io/input/CloseShieldInputStream.java52
-rw-r--r--emailcommon/src/org/apache/commons/io/input/ClosedInputStream.java48
-rw-r--r--emailcommon/src/org/apache/commons/io/input/CountingInputStream.java175
-rw-r--r--emailcommon/src/org/apache/commons/io/input/DemuxInputStream.java93
-rw-r--r--emailcommon/src/org/apache/commons/io/input/NullInputStream.java329
-rw-r--r--emailcommon/src/org/apache/commons/io/input/NullReader.java313
-rw-r--r--emailcommon/src/org/apache/commons/io/input/ProxyInputStream.java129
-rw-r--r--emailcommon/src/org/apache/commons/io/input/ProxyReader.java130
-rw-r--r--emailcommon/src/org/apache/commons/io/input/SwappedDataInputStream.java251
-rw-r--r--emailcommon/src/org/apache/commons/io/input/TeeInputStream.java147
-rw-r--r--emailcommon/src/org/apache/commons/io/input/package.html25
-rw-r--r--emailcommon/src/org/apache/commons/io/output/ByteArrayOutputStream.java312
-rw-r--r--emailcommon/src/org/apache/commons/io/output/CloseShieldOutputStream.java52
-rw-r--r--emailcommon/src/org/apache/commons/io/output/ClosedOutputStream.java50
-rw-r--r--emailcommon/src/org/apache/commons/io/output/CountingOutputStream.java154
-rw-r--r--emailcommon/src/org/apache/commons/io/output/DeferredFileOutputStream.java269
-rw-r--r--emailcommon/src/org/apache/commons/io/output/DemuxOutputStream.java105
-rw-r--r--emailcommon/src/org/apache/commons/io/output/FileWriterWithEncoding.java324
-rw-r--r--emailcommon/src/org/apache/commons/io/output/LockableFileWriter.java333
-rw-r--r--emailcommon/src/org/apache/commons/io/output/NullOutputStream.java65
-rw-r--r--emailcommon/src/org/apache/commons/io/output/NullWriter.java96
-rw-r--r--emailcommon/src/org/apache/commons/io/output/ProxyOutputStream.java89
-rw-r--r--emailcommon/src/org/apache/commons/io/output/ProxyWriter.java111
-rw-r--r--emailcommon/src/org/apache/commons/io/output/TeeOutputStream.java94
-rw-r--r--emailcommon/src/org/apache/commons/io/output/ThresholdingOutputStream.java257
-rw-r--r--emailcommon/src/org/apache/commons/io/output/package.html25
-rw-r--r--emailcommon/src/org/apache/commons/io/overview.html32
-rw-r--r--emailcommon/src/org/apache/commons/io/package.html47
-rw-r--r--emailcommon/src/org/apache/james/mime4j/AbstractContentHandler.java113
-rw-r--r--emailcommon/src/org/apache/james/mime4j/BodyDescriptor.java392
-rw-r--r--emailcommon/src/org/apache/james/mime4j/CloseShieldInputStream.java129
-rw-r--r--emailcommon/src/org/apache/james/mime4j/ContentHandler.java177
-rw-r--r--emailcommon/src/org/apache/james/mime4j/EOLConvertingInputStream.java108
-rw-r--r--emailcommon/src/org/apache/james/mime4j/Log.java114
-rw-r--r--emailcommon/src/org/apache/james/mime4j/LogFactory.java29
-rw-r--r--emailcommon/src/org/apache/james/mime4j/MimeBoundaryInputStream.java184
-rw-r--r--emailcommon/src/org/apache/james/mime4j/MimeStreamParser.java325
-rw-r--r--emailcommon/src/org/apache/james/mime4j/RootInputStream.java111
-rw-r--r--emailcommon/src/org/apache/james/mime4j/SimpleContentHandler.java100
-rw-r--r--emailcommon/src/org/apache/james/mime4j/ThirdPartyProject.prop10
-rw-r--r--emailcommon/src/org/apache/james/mime4j/codec/EncoderUtil.java630
-rw-r--r--emailcommon/src/org/apache/james/mime4j/decoder/Base64InputStream.java151
-rw-r--r--emailcommon/src/org/apache/james/mime4j/decoder/ByteQueue.java62
-rw-r--r--emailcommon/src/org/apache/james/mime4j/decoder/DecoderUtil.java279
-rw-r--r--emailcommon/src/org/apache/james/mime4j/decoder/QuotedPrintableInputStream.java229
-rw-r--r--emailcommon/src/org/apache/james/mime4j/decoder/UnboundedFifoByteBuffer.java272
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/AddressListField.java65
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/ContentTransferEncodingField.java88
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/ContentTypeField.java259
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/DateTimeField.java72
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/DefaultFieldParser.java45
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/DelegatingFieldParser.java47
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/Field.java192
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/FieldParser.java21
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/MailboxField.java70
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/MailboxListField.java67
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/UnstructuredField.java49
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/Address.java52
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/AddressList.java138
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/Builder.java243
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/DomainList.java76
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/Group.java75
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/Mailbox.java121
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/MailboxList.java71
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/NamedMailbox.java71
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddr_spec.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress_list.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTangle_addr.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTdomain.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTgroup_body.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTlocal_part.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTmailbox.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTname_addr.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTphrase.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTroute.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.java977
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.jj595
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserConstants.java76
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTokenManager.java1009
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTreeConstants.java35
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserVisitor.java19
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/BaseNode.java30
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/JJTAddressListParserState.java123
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/Node.java37
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/ParseException.java207
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleCharStream.java454
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleNode.java87
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/Token.java96
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/address/parser/TokenMgrError.java148
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParser.java268
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserConstants.java62
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserTokenManager.java877
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ParseException.java207
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/SimpleCharStream.java454
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/Token.java96
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/TokenMgrError.java148
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/DateTime.java127
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParser.java570
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserConstants.java86
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserTokenManager.java882
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/parser/ParseException.java207
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/parser/SimpleCharStream.java454
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/parser/Token.java96
-rw-r--r--emailcommon/src/org/apache/james/mime4j/field/datetime/parser/TokenMgrError.java148
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/AbstractBody.java47
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/BinaryBody.java42
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/Body.java54
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/BodyPart.java42
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/Entity.java170
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/Header.java158
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/MemoryBinaryBody.java92
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/MemoryTextBody.java118
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/Message.java257
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/Multipart.java203
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/TempFileBinaryBody.java91
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/TempFileTextBody.java117
-rw-r--r--emailcommon/src/org/apache/james/mime4j/message/TextBody.java42
-rw-r--r--emailcommon/src/org/apache/james/mime4j/util/CharsetUtil.java1246
-rw-r--r--emailcommon/src/org/apache/james/mime4j/util/PartialInputStream.java63
-rw-r--r--emailcommon/src/org/apache/james/mime4j/util/PositionInputStream.java87
-rw-r--r--emailcommon/src/org/apache/james/mime4j/util/SimpleTempStorage.java238
-rw-r--r--emailcommon/src/org/apache/james/mime4j/util/TempFile.java84
-rw-r--r--emailcommon/src/org/apache/james/mime4j/util/TempPath.java73
-rw-r--r--emailcommon/src/org/apache/james/mime4j/util/TempStorage.java72
229 files changed, 0 insertions, 43772 deletions
diff --git a/emailcommon/Android.mk b/emailcommon/Android.mk
deleted file mode 100644
index 5173b8d0e..000000000
--- a/emailcommon/Android.mk
+++ /dev/null
@@ -1,34 +0,0 @@
-# Copyright 2011, The Android Open Source Project
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-
-LOCAL_PATH := $(call my-dir)
-
-# Build the com.android.emailcommon static library. At the moment, this includes
-# the emailcommon files themselves plus everything under src/org (apache code). All of our
-# AIDL files are also compiled into the static library
-
-include $(CLEAR_VARS)
-
-LOCAL_MODULE := com.android.emailcommon
-LOCAL_SRC_FILES := $(call all-java-files-under, src/com/android/emailcommon)
-LOCAL_SRC_FILES += $(call all-java-files-under, src/org)
-LOCAL_SRC_FILES += \
- src/com/android/emailcommon/service/IEmailServiceCallback.aidl \
- src/com/android/emailcommon/service/IEmailService.aidl \
- src/com/android/emailcommon/service/IPolicyService.aidl \
- src/com/android/emailcommon/service/IAccountService.aidl
-
-LOCAL_SDK_VERSION := current
-
-include $(BUILD_STATIC_JAVA_LIBRARY)
diff --git a/emailcommon/src/com/android/emailcommon/AccountManagerTypes.java b/emailcommon/src/com/android/emailcommon/AccountManagerTypes.java
deleted file mode 100644
index 4ccd480a5..000000000
--- a/emailcommon/src/com/android/emailcommon/AccountManagerTypes.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- /*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon;
-
-public class AccountManagerTypes {
- public static final String TYPE_EXCHANGE = "com.android.exchange";
- public static final String TYPE_POP_IMAP = "com.android.email";
-}
diff --git a/emailcommon/src/com/android/emailcommon/Api.java b/emailcommon/src/com/android/emailcommon/Api.java
deleted file mode 100644
index ed284d7fb..000000000
--- a/emailcommon/src/com/android/emailcommon/Api.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon;
-
-/**
- * This class will be used for API-related definitions; for now, just the api "level"
- */
-public class Api {
- public static final int LEVEL = 1;
-}
diff --git a/emailcommon/src/com/android/emailcommon/CalendarProviderStub.java b/emailcommon/src/com/android/emailcommon/CalendarProviderStub.java
deleted file mode 100644
index eac371ada..000000000
--- a/emailcommon/src/com/android/emailcommon/CalendarProviderStub.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon;
-
-/**
- * This is the only non-SDK reference in the com.android.email project, referencing the once and
- * future CalendarProvider authority name.
- */
-public class CalendarProviderStub {
- public static final String AUTHORITY = "com.android.calendar";
-}
diff --git a/emailcommon/src/com/android/emailcommon/Configuration.java b/emailcommon/src/com/android/emailcommon/Configuration.java
deleted file mode 100644
index d9469d906..000000000
--- a/emailcommon/src/com/android/emailcommon/Configuration.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon;
-
-public class Configuration {
- // Bundle key for Exchange configuration (boolean value)
- public static final String EXCHANGE_CONFIGURATION_USE_ALTERNATE_STRINGS =
- "com.android.email.EXCHANGE_CONFIGURATION_USE_ALTERNATE_STRINGS";
-}
diff --git a/emailcommon/src/com/android/emailcommon/Device.java b/emailcommon/src/com/android/emailcommon/Device.java
deleted file mode 100644
index a93a17a2e..000000000
--- a/emailcommon/src/com/android/emailcommon/Device.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- /*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon;
-
-import com.android.emailcommon.utility.Utility;
-
-import android.content.Context;
-import android.telephony.TelephonyManager;
-import android.util.Log;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.File;
-import java.io.FileReader;
-import java.io.FileWriter;
-import java.io.IOException;
-
-public class Device {
- private static String sDeviceId = null;
-
- /**
- * EAS requires a unique device id, so that sync is possible from a variety of different
- * devices (e.g. the syncKey is specific to a device) If we're on an emulator or some other
- * device that doesn't provide one, we can create it as android<n> where <n> is system time.
- * This would work on a real device as well, but it would be better to use the "real" id if
- * it's available
- */
- static public synchronized String getDeviceId(Context context) throws IOException {
- if (sDeviceId == null) {
- sDeviceId = getDeviceIdInternal(context);
- }
- return sDeviceId;
- }
-
- static private String getDeviceIdInternal(Context context) throws IOException {
- if (context == null) {
- throw new IllegalStateException("getDeviceId requires a Context");
- }
- File f = context.getFileStreamPath("deviceName");
- BufferedReader rdr = null;
- String id;
- if (f.exists()) {
- if (f.canRead()) {
- rdr = new BufferedReader(new FileReader(f), 128);
- id = rdr.readLine();
- rdr.close();
- // STOPSHIP Remove logging
- Log.w(Logging.LOG_TAG, "deviceId read as: " + id);
- return id;
- } else {
- Log.w(Logging.LOG_TAG, f.getAbsolutePath() + ": File exists, but can't read?" +
- " Trying to remove.");
- if (!f.delete()) {
- Log.w(Logging.LOG_TAG, "Remove failed. Tring to overwrite.");
- }
- }
- }
- BufferedWriter w = new BufferedWriter(new FileWriter(f), 128);
- final String consistentDeviceId = getConsistentDeviceId(context);
- if (consistentDeviceId != null) {
- // Use different prefix from random IDs.
- id = "androidc" + consistentDeviceId;
- } else {
- id = "android" + System.currentTimeMillis();
- }
- w.write(id);
- w.close();
- // STOPSHIP Remove logging
- Log.w(Logging.LOG_TAG, "deviceId written as: " + id);
- return id;
- }
-
- /**
- * @return Device's unique ID if available. null if the device has no unique ID.
- */
- public static String getConsistentDeviceId(Context context) {
- final String deviceId;
- try {
- TelephonyManager tm =
- (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
- if (tm == null) {
- return null;
- }
- deviceId = tm.getDeviceId();
- if (deviceId == null) {
- return null;
- }
- } catch (Exception e) {
- Log.d(Logging.LOG_TAG, "Error in TelephonyManager.getDeviceId(): " + e.getMessage());
- return null;
- }
- return Utility.getSmallHash(deviceId);
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/Logging.java b/emailcommon/src/com/android/emailcommon/Logging.java
deleted file mode 100644
index f9bf7b755..000000000
--- a/emailcommon/src/com/android/emailcommon/Logging.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon;
-
-public class Logging {
- public static final String LOG_TAG = "Email";
-}
diff --git a/emailcommon/src/com/android/emailcommon/TempDirectory.java b/emailcommon/src/com/android/emailcommon/TempDirectory.java
deleted file mode 100644
index 252488c9f..000000000
--- a/emailcommon/src/com/android/emailcommon/TempDirectory.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon;
-
-import android.content.Context;
-
-import java.io.File;
-
-/**
- * TempDirectory caches the directory used for caching file. It is set up during application
- * initialization.
- */
-public class TempDirectory {
- private static File sTempDirectory = null;
-
- public static void setTempDirectory(Context context) {
- sTempDirectory = context.getCacheDir();
- }
-
- public static File getTempDirectory() {
- if (sTempDirectory == null) {
- throw new RuntimeException(
- "TempDirectory not set. " +
- "If in a unit test, call Email.setTempDirectory(context) in setUp().");
- }
- return sTempDirectory;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/BinaryTempFileBody.java b/emailcommon/src/com/android/emailcommon/internet/BinaryTempFileBody.java
deleted file mode 100644
index f0821edd4..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/BinaryTempFileBody.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.TempDirectory;
-import com.android.emailcommon.mail.Body;
-import com.android.emailcommon.mail.MessagingException;
-
-import org.apache.commons.io.IOUtils;
-
-import android.util.Base64;
-import android.util.Base64OutputStream;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * A Body that is backed by a temp file. The Body exposes a getOutputStream method that allows
- * the user to write to the temp file. After the write the body is available via getInputStream
- * and writeTo one time. After writeTo is called, or the InputStream returned from
- * getInputStream is closed the file is deleted and the Body should be considered disposed of.
- */
-public class BinaryTempFileBody implements Body {
- private File mFile;
-
- /**
- * An alternate way to put data into a BinaryTempFileBody is to simply supply an already-
- * created file. Note that this file will be deleted after it is read.
- * @param filePath The file containing the data to be stored on disk temporarily
- */
- public void setFile(String filePath) {
- mFile = new File(filePath);
- }
-
- public OutputStream getOutputStream() throws IOException {
- mFile = File.createTempFile("body", null, TempDirectory.getTempDirectory());
- mFile.deleteOnExit();
- return new FileOutputStream(mFile);
- }
-
- public InputStream getInputStream() throws MessagingException {
- try {
- return new BinaryTempFileBodyInputStream(new FileInputStream(mFile));
- }
- catch (IOException ioe) {
- throw new MessagingException("Unable to open body", ioe);
- }
- }
-
- public void writeTo(OutputStream out) throws IOException, MessagingException {
- InputStream in = getInputStream();
- Base64OutputStream base64Out = new Base64OutputStream(
- out, Base64.CRLF | Base64.NO_CLOSE);
- IOUtils.copy(in, base64Out);
- base64Out.close();
- mFile.delete();
- }
-
- class BinaryTempFileBodyInputStream extends FilterInputStream {
- public BinaryTempFileBodyInputStream(InputStream in) {
- super(in);
- }
-
- @Override
- public void close() throws IOException {
- super.close();
- mFile.delete();
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/MimeBodyPart.java b/emailcommon/src/com/android/emailcommon/internet/MimeBodyPart.java
deleted file mode 100644
index 01efd554f..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/MimeBodyPart.java
+++ /dev/null
@@ -1,193 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.mail.Body;
-import com.android.emailcommon.mail.BodyPart;
-import com.android.emailcommon.mail.MessagingException;
-
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.regex.Pattern;
-
-/**
- * TODO this is a close approximation of Message, need to update along with
- * Message.
- */
-public class MimeBodyPart extends BodyPart {
- protected MimeHeader mHeader = new MimeHeader();
- protected MimeHeader mExtendedHeader;
- protected Body mBody;
- protected int mSize;
-
- // regex that matches content id surrounded by "<>" optionally.
- private static final Pattern REMOVE_OPTIONAL_BRACKETS = Pattern.compile("^<?([^>]+)>?$");
- // regex that matches end of line.
- private static final Pattern END_OF_LINE = Pattern.compile("\r?\n");
-
- public MimeBodyPart() throws MessagingException {
- this(null);
- }
-
- public MimeBodyPart(Body body) throws MessagingException {
- this(body, null);
- }
-
- public MimeBodyPart(Body body, String mimeType) throws MessagingException {
- if (mimeType != null) {
- setHeader(MimeHeader.HEADER_CONTENT_TYPE, mimeType);
- }
- setBody(body);
- }
-
- protected String getFirstHeader(String name) throws MessagingException {
- return mHeader.getFirstHeader(name);
- }
-
- public void addHeader(String name, String value) throws MessagingException {
- mHeader.addHeader(name, value);
- }
-
- public void setHeader(String name, String value) throws MessagingException {
- mHeader.setHeader(name, value);
- }
-
- public String[] getHeader(String name) throws MessagingException {
- return mHeader.getHeader(name);
- }
-
- public void removeHeader(String name) throws MessagingException {
- mHeader.removeHeader(name);
- }
-
- public Body getBody() throws MessagingException {
- return mBody;
- }
-
- public void setBody(Body body) throws MessagingException {
- this.mBody = body;
- if (body instanceof com.android.emailcommon.mail.Multipart) {
- com.android.emailcommon.mail.Multipart multipart =
- ((com.android.emailcommon.mail.Multipart)body);
- multipart.setParent(this);
- setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType());
- }
- else if (body instanceof TextBody) {
- String contentType = String.format("%s;\n charset=utf-8", getMimeType());
- String name = MimeUtility.getHeaderParameter(getContentType(), "name");
- if (name != null) {
- contentType += String.format(";\n name=\"%s\"", name);
- }
- setHeader(MimeHeader.HEADER_CONTENT_TYPE, contentType);
- setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
- }
- }
-
- public String getContentType() throws MessagingException {
- String contentType = getFirstHeader(MimeHeader.HEADER_CONTENT_TYPE);
- if (contentType == null) {
- return "text/plain";
- } else {
- return contentType;
- }
- }
-
- public String getDisposition() throws MessagingException {
- String contentDisposition = getFirstHeader(MimeHeader.HEADER_CONTENT_DISPOSITION);
- if (contentDisposition == null) {
- return null;
- } else {
- return contentDisposition;
- }
- }
-
- public String getContentId() throws MessagingException {
- String contentId = getFirstHeader(MimeHeader.HEADER_CONTENT_ID);
- if (contentId == null) {
- return null;
- } else {
- // remove optionally surrounding brackets.
- return REMOVE_OPTIONAL_BRACKETS.matcher(contentId).replaceAll("$1");
- }
- }
-
- public String getMimeType() throws MessagingException {
- return MimeUtility.getHeaderParameter(getContentType(), null);
- }
-
- public boolean isMimeType(String mimeType) throws MessagingException {
- return getMimeType().equals(mimeType);
- }
-
- public void setSize(int size) {
- this.mSize = size;
- }
-
- public int getSize() throws MessagingException {
- return mSize;
- }
-
- /**
- * Set extended header
- *
- * @param name Extended header name
- * @param value header value - flattened by removing CR-NL if any
- * remove header if value is null
- * @throws MessagingException
- */
- public void setExtendedHeader(String name, String value) throws MessagingException {
- if (value == null) {
- if (mExtendedHeader != null) {
- mExtendedHeader.removeHeader(name);
- }
- return;
- }
- if (mExtendedHeader == null) {
- mExtendedHeader = new MimeHeader();
- }
- mExtendedHeader.setHeader(name, END_OF_LINE.matcher(value).replaceAll(""));
- }
-
- /**
- * Get extended header
- *
- * @param name Extended header name
- * @return header value - null if header does not exist
- * @throws MessagingException
- */
- public String getExtendedHeader(String name) throws MessagingException {
- if (mExtendedHeader == null) {
- return null;
- }
- return mExtendedHeader.getFirstHeader(name);
- }
-
- /**
- * Write the MimeMessage out in MIME format.
- */
- public void writeTo(OutputStream out) throws IOException, MessagingException {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024);
- mHeader.writeTo(out);
- writer.write("\r\n");
- writer.flush();
- if (mBody != null) {
- mBody.writeTo(out);
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/MimeHeader.java b/emailcommon/src/com/android/emailcommon/internet/MimeHeader.java
deleted file mode 100644
index b0ad7772e..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/MimeHeader.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.mail.MessagingException;
-import com.android.emailcommon.utility.Utility;
-
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.ArrayList;
-
-public class MimeHeader {
- /**
- * Application specific header that contains Store specific information about an attachment.
- * In IMAP this contains the IMAP BODYSTRUCTURE part id so that the ImapStore can later
- * retrieve the attachment at will from the server.
- * The info is recorded from this header on LocalStore.appendMessages and is put back
- * into the MIME data by LocalStore.fetch.
- */
- public static final String HEADER_ANDROID_ATTACHMENT_STORE_DATA = "X-Android-Attachment-StoreData";
- /**
- * Application specific header that is used to tag body parts for quoted/forwarded messages.
- */
- public static final String HEADER_ANDROID_BODY_QUOTED_PART = "X-Android-Body-Quoted-Part";
-
- public static final String HEADER_CONTENT_TYPE = "Content-Type";
- public static final String HEADER_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding";
- public static final String HEADER_CONTENT_DISPOSITION = "Content-Disposition";
- public static final String HEADER_CONTENT_ID = "Content-ID";
-
- /**
- * Fields that should be omitted when writing the header using writeTo()
- */
- private static final String[] WRITE_OMIT_FIELDS = {
-// HEADER_ANDROID_ATTACHMENT_DOWNLOADED,
-// HEADER_ANDROID_ATTACHMENT_ID,
- HEADER_ANDROID_ATTACHMENT_STORE_DATA
- };
-
- protected final ArrayList<Field> mFields = new ArrayList<Field>();
-
- public void clear() {
- mFields.clear();
- }
-
- public String getFirstHeader(String name) throws MessagingException {
- String[] header = getHeader(name);
- if (header == null) {
- return null;
- }
- return header[0];
- }
-
- public void addHeader(String name, String value) throws MessagingException {
- mFields.add(new Field(name, value));
- }
-
- public void setHeader(String name, String value) throws MessagingException {
- if (name == null || value == null) {
- return;
- }
- removeHeader(name);
- addHeader(name, value);
- }
-
- public String[] getHeader(String name) throws MessagingException {
- ArrayList<String> values = new ArrayList<String>();
- for (Field field : mFields) {
- if (field.name.equalsIgnoreCase(name)) {
- values.add(field.value);
- }
- }
- if (values.size() == 0) {
- return null;
- }
- return values.toArray(new String[] {});
- }
-
- public void removeHeader(String name) throws MessagingException {
- ArrayList<Field> removeFields = new ArrayList<Field>();
- for (Field field : mFields) {
- if (field.name.equalsIgnoreCase(name)) {
- removeFields.add(field);
- }
- }
- mFields.removeAll(removeFields);
- }
-
- /**
- * Write header into String
- *
- * @return CR-NL separated header string except the headers in writeOmitFields
- * null if header is empty
- */
- public String writeToString() {
- if (mFields.size() == 0) {
- return null;
- }
- StringBuilder builder = new StringBuilder();
- for (Field field : mFields) {
- if (!Utility.arrayContains(WRITE_OMIT_FIELDS, field.name)) {
- builder.append(field.name + ": " + field.value + "\r\n");
- }
- }
- return builder.toString();
- }
-
- public void writeTo(OutputStream out) throws IOException, MessagingException {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024);
- for (Field field : mFields) {
- if (!Utility.arrayContains(WRITE_OMIT_FIELDS, field.name)) {
- writer.write(field.name + ": " + field.value + "\r\n");
- }
- }
- writer.flush();
- }
-
- private static class Field {
- final String name;
- final String value;
-
- public Field(String name, String value) {
- this.name = name;
- this.value = value;
- }
-
- @Override
- public String toString() {
- return name + "=" + value;
- }
- }
-
- @Override
- public String toString() {
- return (mFields == null) ? null : mFields.toString();
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/MimeMessage.java b/emailcommon/src/com/android/emailcommon/internet/MimeMessage.java
deleted file mode 100644
index 412092da4..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/MimeMessage.java
+++ /dev/null
@@ -1,626 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.mail.Address;
-import com.android.emailcommon.mail.Body;
-import com.android.emailcommon.mail.BodyPart;
-import com.android.emailcommon.mail.Message;
-import com.android.emailcommon.mail.MessagingException;
-import com.android.emailcommon.mail.Multipart;
-import com.android.emailcommon.mail.Part;
-
-import org.apache.james.mime4j.BodyDescriptor;
-import org.apache.james.mime4j.ContentHandler;
-import org.apache.james.mime4j.EOLConvertingInputStream;
-import org.apache.james.mime4j.MimeStreamParser;
-import org.apache.james.mime4j.field.DateTimeField;
-import org.apache.james.mime4j.field.Field;
-
-import android.text.TextUtils;
-
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-import java.util.Stack;
-import java.util.regex.Pattern;
-
-/**
- * An implementation of Message that stores all of its metadata in RFC 822 and
- * RFC 2045 style headers.
- *
- * NOTE: Automatic generation of a local message-id is becoming unwieldy and should be removed.
- * It would be better to simply do it explicitly on local creation of new outgoing messages.
- */
-public class MimeMessage extends Message {
- private MimeHeader mHeader;
- private MimeHeader mExtendedHeader;
-
- // NOTE: The fields here are transcribed out of headers, and values stored here will supercede
- // the values found in the headers. Use caution to prevent any out-of-phase errors. In
- // particular, any adds/changes/deletes here must be echoed by changes in the parse() function.
- private Address[] mFrom;
- private Address[] mTo;
- private Address[] mCc;
- private Address[] mBcc;
- private Address[] mReplyTo;
- private Date mSentDate;
- private Body mBody;
- protected int mSize;
- private boolean mInhibitLocalMessageId = false;
-
- // Shared random source for generating local message-id values
- private static final java.util.Random sRandom = new java.util.Random();
-
- // In MIME, en_US-like date format should be used. In other words "MMM" should be encoded to
- // "Jan", not the other localized format like "Ene" (meaning January in locale es).
- // This conversion is used when generating outgoing MIME messages. Incoming MIME date
- // headers are parsed by org.apache.james.mime4j.field.DateTimeField which does not have any
- // localization code.
- private static final SimpleDateFormat DATE_FORMAT =
- new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
-
- // regex that matches content id surrounded by "<>" optionally.
- private static final Pattern REMOVE_OPTIONAL_BRACKETS = Pattern.compile("^<?([^>]+)>?$");
- // regex that matches end of line.
- private static final Pattern END_OF_LINE = Pattern.compile("\r?\n");
-
- public MimeMessage() {
- mHeader = null;
- }
-
- /**
- * Generate a local message id. This is only used when none has been assigned, and is
- * installed lazily. Any remote (typically server-assigned) message id takes precedence.
- * @return a long, locally-generated message-ID value
- */
- private String generateMessageId() {
- StringBuffer sb = new StringBuffer();
- sb.append("<");
- for (int i = 0; i < 24; i++) {
- // We'll use a 5-bit range (0..31)
- int value = sRandom.nextInt() & 31;
- char c = "0123456789abcdefghijklmnopqrstuv".charAt(value);
- sb.append(c);
- }
- sb.append(".");
- sb.append(Long.toString(System.currentTimeMillis()));
- sb.append("@email.android.com>");
- return sb.toString();
- }
-
- /**
- * Parse the given InputStream using Apache Mime4J to build a MimeMessage.
- *
- * @param in
- * @throws IOException
- * @throws MessagingException
- */
- public MimeMessage(InputStream in) throws IOException, MessagingException {
- parse(in);
- }
-
- protected void parse(InputStream in) throws IOException, MessagingException {
- // Before parsing the input stream, clear all local fields that may be superceded by
- // the new incoming message.
- getMimeHeaders().clear();
- mInhibitLocalMessageId = true;
- mFrom = null;
- mTo = null;
- mCc = null;
- mBcc = null;
- mReplyTo = null;
- mSentDate = null;
- mBody = null;
-
- MimeStreamParser parser = new MimeStreamParser();
- parser.setContentHandler(new MimeMessageBuilder());
- parser.parse(new EOLConvertingInputStream(in));
- }
-
- /**
- * Return the internal mHeader value, with very lazy initialization.
- * The goal is to save memory by not creating the headers until needed.
- */
- private MimeHeader getMimeHeaders() {
- if (mHeader == null) {
- mHeader = new MimeHeader();
- }
- return mHeader;
- }
-
- @Override
- public Date getReceivedDate() throws MessagingException {
- return null;
- }
-
- @Override
- public Date getSentDate() throws MessagingException {
- if (mSentDate == null) {
- try {
- DateTimeField field = (DateTimeField)Field.parse("Date: "
- + MimeUtility.unfoldAndDecode(getFirstHeader("Date")));
- mSentDate = field.getDate();
- } catch (Exception e) {
-
- }
- }
- return mSentDate;
- }
-
- @Override
- public void setSentDate(Date sentDate) throws MessagingException {
- setHeader("Date", DATE_FORMAT.format(sentDate));
- this.mSentDate = sentDate;
- }
-
- @Override
- public String getContentType() throws MessagingException {
- String contentType = getFirstHeader(MimeHeader.HEADER_CONTENT_TYPE);
- if (contentType == null) {
- return "text/plain";
- } else {
- return contentType;
- }
- }
-
- public String getDisposition() throws MessagingException {
- String contentDisposition = getFirstHeader(MimeHeader.HEADER_CONTENT_DISPOSITION);
- if (contentDisposition == null) {
- return null;
- } else {
- return contentDisposition;
- }
- }
-
- public String getContentId() throws MessagingException {
- String contentId = getFirstHeader(MimeHeader.HEADER_CONTENT_ID);
- if (contentId == null) {
- return null;
- } else {
- // remove optionally surrounding brackets.
- return REMOVE_OPTIONAL_BRACKETS.matcher(contentId).replaceAll("$1");
- }
- }
-
- public String getMimeType() throws MessagingException {
- return MimeUtility.getHeaderParameter(getContentType(), null);
- }
-
- public int getSize() throws MessagingException {
- return mSize;
- }
-
- /**
- * Returns a list of the given recipient type from this message. If no addresses are
- * found the method returns an empty array.
- */
- @Override
- public Address[] getRecipients(RecipientType type) throws MessagingException {
- if (type == RecipientType.TO) {
- if (mTo == null) {
- mTo = Address.parse(MimeUtility.unfold(getFirstHeader("To")));
- }
- return mTo;
- } else if (type == RecipientType.CC) {
- if (mCc == null) {
- mCc = Address.parse(MimeUtility.unfold(getFirstHeader("CC")));
- }
- return mCc;
- } else if (type == RecipientType.BCC) {
- if (mBcc == null) {
- mBcc = Address.parse(MimeUtility.unfold(getFirstHeader("BCC")));
- }
- return mBcc;
- } else {
- throw new MessagingException("Unrecognized recipient type.");
- }
- }
-
- @Override
- public void setRecipients(RecipientType type, Address[] addresses) throws MessagingException {
- final int TO_LENGTH = 4; // "To: "
- final int CC_LENGTH = 4; // "Cc: "
- final int BCC_LENGTH = 5; // "Bcc: "
- if (type == RecipientType.TO) {
- if (addresses == null || addresses.length == 0) {
- removeHeader("To");
- this.mTo = null;
- } else {
- setHeader("To", MimeUtility.fold(Address.toHeader(addresses), TO_LENGTH));
- this.mTo = addresses;
- }
- } else if (type == RecipientType.CC) {
- if (addresses == null || addresses.length == 0) {
- removeHeader("CC");
- this.mCc = null;
- } else {
- setHeader("CC", MimeUtility.fold(Address.toHeader(addresses), CC_LENGTH));
- this.mCc = addresses;
- }
- } else if (type == RecipientType.BCC) {
- if (addresses == null || addresses.length == 0) {
- removeHeader("BCC");
- this.mBcc = null;
- } else {
- setHeader("BCC", MimeUtility.fold(Address.toHeader(addresses), BCC_LENGTH));
- this.mBcc = addresses;
- }
- } else {
- throw new MessagingException("Unrecognized recipient type.");
- }
- }
-
- /**
- * Returns the unfolded, decoded value of the Subject header.
- */
- @Override
- public String getSubject() throws MessagingException {
- return MimeUtility.unfoldAndDecode(getFirstHeader("Subject"));
- }
-
- @Override
- public void setSubject(String subject) throws MessagingException {
- final int HEADER_NAME_LENGTH = 9; // "Subject: "
- setHeader("Subject", MimeUtility.foldAndEncode2(subject, HEADER_NAME_LENGTH));
- }
-
- @Override
- public Address[] getFrom() throws MessagingException {
- if (mFrom == null) {
- String list = MimeUtility.unfold(getFirstHeader("From"));
- if (list == null || list.length() == 0) {
- list = MimeUtility.unfold(getFirstHeader("Sender"));
- }
- mFrom = Address.parse(list);
- }
- return mFrom;
- }
-
- @Override
- public void setFrom(Address from) throws MessagingException {
- final int FROM_LENGTH = 6; // "From: "
- if (from != null) {
- setHeader("From", MimeUtility.fold(from.toHeader(), FROM_LENGTH));
- this.mFrom = new Address[] {
- from
- };
- } else {
- this.mFrom = null;
- }
- }
-
- @Override
- public Address[] getReplyTo() throws MessagingException {
- if (mReplyTo == null) {
- mReplyTo = Address.parse(MimeUtility.unfold(getFirstHeader("Reply-to")));
- }
- return mReplyTo;
- }
-
- @Override
- public void setReplyTo(Address[] replyTo) throws MessagingException {
- final int REPLY_TO_LENGTH = 10; // "Reply-to: "
- if (replyTo == null || replyTo.length == 0) {
- removeHeader("Reply-to");
- mReplyTo = null;
- } else {
- setHeader("Reply-to", MimeUtility.fold(Address.toHeader(replyTo), REPLY_TO_LENGTH));
- mReplyTo = replyTo;
- }
- }
-
- /**
- * Set the mime "Message-ID" header
- * @param messageId the new Message-ID value
- * @throws MessagingException
- */
- @Override
- public void setMessageId(String messageId) throws MessagingException {
- setHeader("Message-ID", messageId);
- }
-
- /**
- * Get the mime "Message-ID" header. This value will be preloaded with a locally-generated
- * random ID, if the value has not previously been set. Local generation can be inhibited/
- * overridden by explicitly clearing the headers, removing the message-id header, etc.
- * @return the Message-ID header string, or null if explicitly has been set to null
- */
- @Override
- public String getMessageId() throws MessagingException {
- String messageId = getFirstHeader("Message-ID");
- if (messageId == null && !mInhibitLocalMessageId) {
- messageId = generateMessageId();
- setMessageId(messageId);
- }
- return messageId;
- }
-
- @Override
- public void saveChanges() throws MessagingException {
- throw new MessagingException("saveChanges not yet implemented");
- }
-
- @Override
- public Body getBody() throws MessagingException {
- return mBody;
- }
-
- @Override
- public void setBody(Body body) throws MessagingException {
- this.mBody = body;
- if (body instanceof Multipart) {
- Multipart multipart = ((Multipart)body);
- multipart.setParent(this);
- setHeader(MimeHeader.HEADER_CONTENT_TYPE, multipart.getContentType());
- setHeader("MIME-Version", "1.0");
- }
- else if (body instanceof TextBody) {
- setHeader(MimeHeader.HEADER_CONTENT_TYPE, String.format("%s;\n charset=utf-8",
- getMimeType()));
- setHeader(MimeHeader.HEADER_CONTENT_TRANSFER_ENCODING, "base64");
- }
- }
-
- protected String getFirstHeader(String name) throws MessagingException {
- return getMimeHeaders().getFirstHeader(name);
- }
-
- @Override
- public void addHeader(String name, String value) throws MessagingException {
- getMimeHeaders().addHeader(name, value);
- }
-
- @Override
- public void setHeader(String name, String value) throws MessagingException {
- getMimeHeaders().setHeader(name, value);
- }
-
- @Override
- public String[] getHeader(String name) throws MessagingException {
- return getMimeHeaders().getHeader(name);
- }
-
- @Override
- public void removeHeader(String name) throws MessagingException {
- getMimeHeaders().removeHeader(name);
- if ("Message-ID".equalsIgnoreCase(name)) {
- mInhibitLocalMessageId = true;
- }
- }
-
- /**
- * Set extended header
- *
- * @param name Extended header name
- * @param value header value - flattened by removing CR-NL if any
- * remove header if value is null
- * @throws MessagingException
- */
- public void setExtendedHeader(String name, String value) throws MessagingException {
- if (value == null) {
- if (mExtendedHeader != null) {
- mExtendedHeader.removeHeader(name);
- }
- return;
- }
- if (mExtendedHeader == null) {
- mExtendedHeader = new MimeHeader();
- }
- mExtendedHeader.setHeader(name, END_OF_LINE.matcher(value).replaceAll(""));
- }
-
- /**
- * Get extended header
- *
- * @param name Extended header name
- * @return header value - null if header does not exist
- * @throws MessagingException
- */
- public String getExtendedHeader(String name) throws MessagingException {
- if (mExtendedHeader == null) {
- return null;
- }
- return mExtendedHeader.getFirstHeader(name);
- }
-
- /**
- * Set entire extended headers from String
- *
- * @param headers Extended header and its value - "CR-NL-separated pairs
- * if null or empty, remove entire extended headers
- * @throws MessagingException
- */
- public void setExtendedHeaders(String headers) throws MessagingException {
- if (TextUtils.isEmpty(headers)) {
- mExtendedHeader = null;
- } else {
- mExtendedHeader = new MimeHeader();
- for (String header : END_OF_LINE.split(headers)) {
- String[] tokens = header.split(":", 2);
- if (tokens.length != 2) {
- throw new MessagingException("Illegal extended headers: " + headers);
- }
- mExtendedHeader.setHeader(tokens[0].trim(), tokens[1].trim());
- }
- }
- }
-
- /**
- * Get entire extended headers as String
- *
- * @return "CR-NL-separated extended headers - null if extended header does not exist
- */
- public String getExtendedHeaders() {
- if (mExtendedHeader != null) {
- return mExtendedHeader.writeToString();
- }
- return null;
- }
-
- /**
- * Write message header and body to output stream
- *
- * @param out Output steam to write message header and body.
- */
- public void writeTo(OutputStream out) throws IOException, MessagingException {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024);
- // Force creation of local message-id
- getMessageId();
- getMimeHeaders().writeTo(out);
- // mExtendedHeader will not be write out to external output stream,
- // because it is intended to internal use.
- writer.write("\r\n");
- writer.flush();
- if (mBody != null) {
- mBody.writeTo(out);
- }
- }
-
- public InputStream getInputStream() throws MessagingException {
- return null;
- }
-
- class MimeMessageBuilder implements ContentHandler {
- private Stack<Object> stack = new Stack<Object>();
-
- public MimeMessageBuilder() {
- }
-
- private void expect(Class c) {
- if (!c.isInstance(stack.peek())) {
- throw new IllegalStateException("Internal stack error: " + "Expected '"
- + c.getName() + "' found '" + stack.peek().getClass().getName() + "'");
- }
- }
-
- public void startMessage() {
- if (stack.isEmpty()) {
- stack.push(MimeMessage.this);
- } else {
- expect(Part.class);
- try {
- MimeMessage m = new MimeMessage();
- ((Part)stack.peek()).setBody(m);
- stack.push(m);
- } catch (MessagingException me) {
- throw new Error(me);
- }
- }
- }
-
- public void endMessage() {
- expect(MimeMessage.class);
- stack.pop();
- }
-
- public void startHeader() {
- expect(Part.class);
- }
-
- public void field(String fieldData) {
- expect(Part.class);
- try {
- String[] tokens = fieldData.split(":", 2);
- ((Part)stack.peek()).addHeader(tokens[0], tokens[1].trim());
- } catch (MessagingException me) {
- throw new Error(me);
- }
- }
-
- public void endHeader() {
- expect(Part.class);
- }
-
- public void startMultipart(BodyDescriptor bd) {
- expect(Part.class);
-
- Part e = (Part)stack.peek();
- try {
- MimeMultipart multiPart = new MimeMultipart(e.getContentType());
- e.setBody(multiPart);
- stack.push(multiPart);
- } catch (MessagingException me) {
- throw new Error(me);
- }
- }
-
- public void body(BodyDescriptor bd, InputStream in) throws IOException {
- expect(Part.class);
- Body body = MimeUtility.decodeBody(in, bd.getTransferEncoding());
- try {
- ((Part)stack.peek()).setBody(body);
- } catch (MessagingException me) {
- throw new Error(me);
- }
- }
-
- public void endMultipart() {
- stack.pop();
- }
-
- public void startBodyPart() {
- expect(MimeMultipart.class);
-
- try {
- MimeBodyPart bodyPart = new MimeBodyPart();
- ((MimeMultipart)stack.peek()).addBodyPart(bodyPart);
- stack.push(bodyPart);
- } catch (MessagingException me) {
- throw new Error(me);
- }
- }
-
- public void endBodyPart() {
- expect(BodyPart.class);
- stack.pop();
- }
-
- public void epilogue(InputStream is) throws IOException {
- expect(MimeMultipart.class);
- StringBuffer sb = new StringBuffer();
- int b;
- while ((b = is.read()) != -1) {
- sb.append((char)b);
- }
- // ((Multipart) stack.peek()).setEpilogue(sb.toString());
- }
-
- public void preamble(InputStream is) throws IOException {
- expect(MimeMultipart.class);
- StringBuffer sb = new StringBuffer();
- int b;
- while ((b = is.read()) != -1) {
- sb.append((char)b);
- }
- try {
- ((MimeMultipart)stack.peek()).setPreamble(sb.toString());
- } catch (MessagingException me) {
- throw new Error(me);
- }
- }
-
- public void raw(InputStream is) throws IOException {
- throw new UnsupportedOperationException("Not supported");
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/MimeMultipart.java b/emailcommon/src/com/android/emailcommon/internet/MimeMultipart.java
deleted file mode 100644
index e6977ee4f..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/MimeMultipart.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.mail.BodyPart;
-import com.android.emailcommon.mail.MessagingException;
-import com.android.emailcommon.mail.Multipart;
-
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-
-public class MimeMultipart extends Multipart {
- protected String mPreamble;
-
- protected String mContentType;
-
- protected String mBoundary;
-
- protected String mSubType;
-
- public MimeMultipart() throws MessagingException {
- mBoundary = generateBoundary();
- setSubType("mixed");
- }
-
- public MimeMultipart(String contentType) throws MessagingException {
- this.mContentType = contentType;
- try {
- mSubType = MimeUtility.getHeaderParameter(contentType, null).split("/")[1];
- mBoundary = MimeUtility.getHeaderParameter(contentType, "boundary");
- if (mBoundary == null) {
- throw new MessagingException("MultiPart does not contain boundary: " + contentType);
- }
- } catch (Exception e) {
- throw new MessagingException(
- "Invalid MultiPart Content-Type; must contain subtype and boundary. ("
- + contentType + ")", e);
- }
- }
-
- public String generateBoundary() {
- StringBuffer sb = new StringBuffer();
- sb.append("----");
- for (int i = 0; i < 30; i++) {
- sb.append(Integer.toString((int)(Math.random() * 35), 36));
- }
- return sb.toString().toUpperCase();
- }
-
- public String getPreamble() throws MessagingException {
- return mPreamble;
- }
-
- public void setPreamble(String preamble) throws MessagingException {
- this.mPreamble = preamble;
- }
-
- @Override
- public String getContentType() throws MessagingException {
- return mContentType;
- }
-
- public void setSubType(String subType) throws MessagingException {
- this.mSubType = subType;
- mContentType = String.format("multipart/%s; boundary=\"%s\"", subType, mBoundary);
- }
-
- public void writeTo(OutputStream out) throws IOException, MessagingException {
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out), 1024);
-
- if (mPreamble != null) {
- writer.write(mPreamble + "\r\n");
- }
-
- for (int i = 0, count = mParts.size(); i < count; i++) {
- BodyPart bodyPart = mParts.get(i);
- writer.write("--" + mBoundary + "\r\n");
- writer.flush();
- bodyPart.writeTo(out);
- writer.write("\r\n");
- }
-
- writer.write("--" + mBoundary + "--\r\n");
- writer.flush();
- }
-
- public InputStream getInputStream() throws MessagingException {
- return null;
- }
-
- public String getSubTypeForTest() {
- return mSubType;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/MimeUtility.java b/emailcommon/src/com/android/emailcommon/internet/MimeUtility.java
deleted file mode 100644
index 69330d76b..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/MimeUtility.java
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.Logging;
-import com.android.emailcommon.mail.Body;
-import com.android.emailcommon.mail.BodyPart;
-import com.android.emailcommon.mail.Message;
-import com.android.emailcommon.mail.MessagingException;
-import com.android.emailcommon.mail.Multipart;
-import com.android.emailcommon.mail.Part;
-
-import org.apache.commons.io.IOUtils;
-import org.apache.james.mime4j.codec.EncoderUtil;
-import org.apache.james.mime4j.decoder.DecoderUtil;
-import org.apache.james.mime4j.decoder.QuotedPrintableInputStream;
-import org.apache.james.mime4j.util.CharsetUtil;
-
-import android.util.Base64;
-import android.util.Base64DataException;
-import android.util.Base64InputStream;
-import android.util.Log;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-public class MimeUtility {
-
- public static final String MIME_TYPE_RFC822 = "message/rfc822";
- private final static Pattern PATTERN_CR_OR_LF = Pattern.compile("\r|\n");
-
- /**
- * Replace sequences of CRLF+WSP with WSP. Tries to preserve original string
- * object whenever possible.
- */
- public static String unfold(String s) {
- if (s == null) {
- return null;
- }
- Matcher patternMatcher = PATTERN_CR_OR_LF.matcher(s);
- if (patternMatcher.find()) {
- patternMatcher.reset();
- s = patternMatcher.replaceAll("");
- }
- return s;
- }
-
- public static String decode(String s) {
- if (s == null) {
- return null;
- }
- return DecoderUtil.decodeEncodedWords(s);
- }
-
- public static String unfoldAndDecode(String s) {
- return decode(unfold(s));
- }
-
- // TODO implement proper foldAndEncode
- // NOTE: When this really works, we *must* remove all calls to foldAndEncode2() to prevent
- // duplication of encoding.
- public static String foldAndEncode(String s) {
- return s;
- }
-
- /**
- * INTERIM version of foldAndEncode that will be used only by Subject: headers.
- * This is safer than implementing foldAndEncode() (see above) and risking unknown damage
- * to other headers.
- *
- * TODO: Copy this code to foldAndEncode(), get rid of this function, confirm all working OK.
- *
- * @param s original string to encode and fold
- * @param usedCharacters number of characters already used up by header name
-
- * @return the String ready to be transmitted
- */
- public static String foldAndEncode2(String s, int usedCharacters) {
- // james.mime4j.codec.EncoderUtil.java
- // encode: encodeIfNecessary(text, usage, numUsedInHeaderName)
- // Usage.TEXT_TOKENlooks like the right thing for subjects
- // use WORD_ENTITY for address/names
-
- String encoded = EncoderUtil.encodeIfNecessary(s, EncoderUtil.Usage.TEXT_TOKEN,
- usedCharacters);
-
- return fold(encoded, usedCharacters);
- }
-
- /**
- * INTERIM: From newer version of org.apache.james (but we don't want to import
- * the entire MimeUtil class).
- *
- * Splits the specified string into a multiple-line representation with
- * lines no longer than 76 characters (because the line might contain
- * encoded words; see <a href='http://www.faqs.org/rfcs/rfc2047.html'>RFC
- * 2047</a> section 2). If the string contains non-whitespace sequences
- * longer than 76 characters a line break is inserted at the whitespace
- * character following the sequence resulting in a line longer than 76
- * characters.
- *
- * @param s
- * string to split.
- * @param usedCharacters
- * number of characters already used up. Usually the number of
- * characters for header field name plus colon and one space.
- * @return a multiple-line representation of the given string.
- */
- public static String fold(String s, int usedCharacters) {
- final int maxCharacters = 76;
-
- final int length = s.length();
- if (usedCharacters + length <= maxCharacters)
- return s;
-
- StringBuilder sb = new StringBuilder();
-
- int lastLineBreak = -usedCharacters;
- int wspIdx = indexOfWsp(s, 0);
- while (true) {
- if (wspIdx == length) {
- sb.append(s.substring(Math.max(0, lastLineBreak)));
- return sb.toString();
- }
-
- int nextWspIdx = indexOfWsp(s, wspIdx + 1);
-
- if (nextWspIdx - lastLineBreak > maxCharacters) {
- sb.append(s.substring(Math.max(0, lastLineBreak), wspIdx));
- sb.append("\r\n");
- lastLineBreak = wspIdx;
- }
-
- wspIdx = nextWspIdx;
- }
- }
-
- /**
- * INTERIM: From newer version of org.apache.james (but we don't want to import
- * the entire MimeUtil class).
- *
- * Search for whitespace.
- */
- private static int indexOfWsp(String s, int fromIndex) {
- final int len = s.length();
- for (int index = fromIndex; index < len; index++) {
- char c = s.charAt(index);
- if (c == ' ' || c == '\t')
- return index;
- }
- return len;
- }
-
- /**
- * Returns the named parameter of a header field. If name is null the first
- * parameter is returned, or if there are no additional parameters in the
- * field the entire field is returned. Otherwise the named parameter is
- * searched for in a case insensitive fashion and returned. If the parameter
- * cannot be found the method returns null.
- *
- * TODO: quite inefficient with the inner trimming & splitting.
- * TODO: Also has a latent bug: uses "startsWith" to match the name, which can false-positive.
- * TODO: The doc says that for a null name you get the first param, but you get the header.
- * Should probably just fix the doc, but if other code assumes that behavior, fix the code.
- * TODO: Need to decode %-escaped strings, as in: filename="ab%22d".
- * ('+' -> ' ' conversion too? check RFC)
- *
- * @param header
- * @param name
- * @return the entire header (if name=null), the found parameter, or null
- */
- public static String getHeaderParameter(String header, String name) {
- if (header == null) {
- return null;
- }
- String[] parts = unfold(header).split(";");
- if (name == null) {
- return parts[0].trim();
- }
- String lowerCaseName = name.toLowerCase();
- for (String part : parts) {
- if (part.trim().toLowerCase().startsWith(lowerCaseName)) {
- String[] parameterParts = part.split("=", 2);
- if (parameterParts.length < 2) {
- return null;
- }
- String parameter = parameterParts[1].trim();
- if (parameter.startsWith("\"") && parameter.endsWith("\"")) {
- return parameter.substring(1, parameter.length() - 1);
- } else {
- return parameter;
- }
- }
- }
- return null;
- }
-
- public static Part findFirstPartByMimeType(Part part, String mimeType)
- throws MessagingException {
- if (part.getBody() instanceof Multipart) {
- Multipart multipart = (Multipart)part.getBody();
- for (int i = 0, count = multipart.getCount(); i < count; i++) {
- BodyPart bodyPart = multipart.getBodyPart(i);
- Part ret = findFirstPartByMimeType(bodyPart, mimeType);
- if (ret != null) {
- return ret;
- }
- }
- }
- else if (part.getMimeType().equalsIgnoreCase(mimeType)) {
- return part;
- }
- return null;
- }
-
- public static Part findPartByContentId(Part part, String contentId) throws Exception {
- if (part.getBody() instanceof Multipart) {
- Multipart multipart = (Multipart)part.getBody();
- for (int i = 0, count = multipart.getCount(); i < count; i++) {
- BodyPart bodyPart = multipart.getBodyPart(i);
- Part ret = findPartByContentId(bodyPart, contentId);
- if (ret != null) {
- return ret;
- }
- }
- }
- String cid = part.getContentId();
- if (contentId.equals(cid)) {
- return part;
- }
- return null;
- }
-
- /**
- * Reads the Part's body and returns a String based on any charset conversion that needed
- * to be done.
- * @param part The part containing a body
- * @return a String containing the converted text in the body, or null if there was no text
- * or an error during conversion.
- */
- public static String getTextFromPart(Part part) {
- try {
- if (part != null && part.getBody() != null) {
- InputStream in = part.getBody().getInputStream();
- String mimeType = part.getMimeType();
- if (mimeType != null && MimeUtility.mimeTypeMatches(mimeType, "text/*")) {
- /*
- * Now we read the part into a buffer for further processing. Because
- * the stream is now wrapped we'll remove any transfer encoding at this point.
- */
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- IOUtils.copy(in, out);
- in.close();
- in = null; // we want all of our memory back, and close might not release
-
- /*
- * We've got a text part, so let's see if it needs to be processed further.
- */
- String charset = getHeaderParameter(part.getContentType(), "charset");
- if (charset != null) {
- /*
- * See if there is conversion from the MIME charset to the Java one.
- */
- charset = CharsetUtil.toJavaCharset(charset);
- }
- /*
- * No encoding, so use us-ascii, which is the standard.
- */
- if (charset == null) {
- charset = "ASCII";
- }
- /*
- * Convert and return as new String
- */
- String result = out.toString(charset);
- out.close();
- return result;
- }
- }
-
- }
- catch (OutOfMemoryError oom) {
- /*
- * If we are not able to process the body there's nothing we can do about it. Return
- * null and let the upper layers handle the missing content.
- */
- Log.e(Logging.LOG_TAG, "Unable to getTextFromPart " + oom.toString());
- }
- catch (Exception e) {
- /*
- * If we are not able to process the body there's nothing we can do about it. Return
- * null and let the upper layers handle the missing content.
- */
- Log.e(Logging.LOG_TAG, "Unable to getTextFromPart " + e.toString());
- }
- return null;
- }
-
- /**
- * Returns true if the given mimeType matches the matchAgainst specification. The comparison
- * ignores case and the matchAgainst string may include "*" for a wildcard (e.g. "image/*").
- *
- * @param mimeType A MIME type to check.
- * @param matchAgainst A MIME type to check against. May include wildcards.
- * @return true if the mimeType matches
- */
- public static boolean mimeTypeMatches(String mimeType, String matchAgainst) {
- Pattern p = Pattern.compile(matchAgainst.replaceAll("\\*", "\\.\\*"),
- Pattern.CASE_INSENSITIVE);
- return p.matcher(mimeType).matches();
- }
-
- /**
- * Returns true if the given mimeType matches any of the matchAgainst specifications. The
- * comparison ignores case and the matchAgainst strings may include "*" for a wildcard
- * (e.g. "image/*").
- *
- * @param mimeType A MIME type to check.
- * @param matchAgainst An array of MIME types to check against. May include wildcards.
- * @return true if the mimeType matches any of the matchAgainst strings
- */
- public static boolean mimeTypeMatches(String mimeType, String[] matchAgainst) {
- for (String matchType : matchAgainst) {
- if (mimeTypeMatches(mimeType, matchType)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Given an input stream and a transfer encoding, return a wrapped input stream for that
- * encoding (or the original if none is required)
- * @param in the input stream
- * @param contentTransferEncoding the content transfer encoding
- * @return a properly wrapped stream
- */
- public static InputStream getInputStreamForContentTransferEncoding(InputStream in,
- String contentTransferEncoding) {
- if (contentTransferEncoding != null) {
- contentTransferEncoding =
- MimeUtility.getHeaderParameter(contentTransferEncoding, null);
- if ("quoted-printable".equalsIgnoreCase(contentTransferEncoding)) {
- in = new QuotedPrintableInputStream(in);
- }
- else if ("base64".equalsIgnoreCase(contentTransferEncoding)) {
- in = new Base64InputStream(in, Base64.DEFAULT);
- }
- }
- return in;
- }
-
- /**
- * Removes any content transfer encoding from the stream and returns a Body.
- */
- public static Body decodeBody(InputStream in, String contentTransferEncoding)
- throws IOException {
- /*
- * We'll remove any transfer encoding by wrapping the stream.
- */
- in = getInputStreamForContentTransferEncoding(in, contentTransferEncoding);
- BinaryTempFileBody tempBody = new BinaryTempFileBody();
- OutputStream out = tempBody.getOutputStream();
- try {
- IOUtils.copy(in, out);
- } catch (Base64DataException bde) {
- // STOPSHIP Need to fix this somehow
- //String warning = "\n\n" + Email.getMessageDecodeErrorString();
- //out.write(warning.getBytes());
- } finally {
- out.close();
- }
- return tempBody;
- }
-
- /**
- * Recursively scan a Part (usually a Message) and sort out which of its children will be
- * "viewable" and which will be attachments.
- *
- * @param part The part to be broken down
- * @param viewables This arraylist will be populated with all parts that appear to be
- * the "message" (e.g. text/plain & text/html)
- * @param attachments This arraylist will be populated with all parts that appear to be
- * attachments (including inlines)
- * @throws MessagingException
- */
- public static void collectParts(Part part, ArrayList<Part> viewables,
- ArrayList<Part> attachments) throws MessagingException {
- String disposition = part.getDisposition();
- String dispositionType = null;
- String dispositionFilename = null;
- if (disposition != null) {
- dispositionType = MimeUtility.getHeaderParameter(disposition, null);
- dispositionFilename = MimeUtility.getHeaderParameter(disposition, "filename");
- }
- boolean attachmentDisposition = "attachment".equalsIgnoreCase(dispositionType);
- boolean inlineDisposition = "inline".equalsIgnoreCase(dispositionType);
-
- // A guess that this part is intended to be an attachment
- boolean attachment = attachmentDisposition
- || (dispositionFilename != null && !inlineDisposition);
-
- // A guess that this part is intended to be an inline.
- boolean inline = inlineDisposition && (dispositionFilename != null);
-
- // One or the other
- boolean attachmentOrInline = attachment || inline;
-
- if (part.getBody() instanceof Multipart) {
- // If the part is Multipart but not alternative it's either mixed or
- // something we don't know about, which means we treat it as mixed
- // per the spec. We just process its pieces recursively.
- Multipart mp = (Multipart)part.getBody();
- for (int i = 0; i < mp.getCount(); i++) {
- collectParts(mp.getBodyPart(i), viewables, attachments);
- }
- } else if (part.getBody() instanceof Message) {
- // If the part is an embedded message we just continue to process
- // it, pulling any viewables or attachments into the running list.
- Message message = (Message)part.getBody();
- collectParts(message, viewables, attachments);
- } else if ((!attachmentOrInline) && ("text/html".equalsIgnoreCase(part.getMimeType()))) {
- // If the part is HTML and we got this far, it's a viewable part of a mixed
- viewables.add(part);
- } else if ((!attachmentOrInline) && ("text/plain".equalsIgnoreCase(part.getMimeType()))) {
- // If the part is text and we got this far, it's a viewable part of a mixed
- viewables.add(part);
- } else if (attachmentOrInline) {
- // Finally, if it's an attachment or an inline we will include it as an attachment.
- attachments.add(part);
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java b/emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java
deleted file mode 100644
index 7382d30b2..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/Rfc822Output.java
+++ /dev/null
@@ -1,357 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.mail.Address;
-import com.android.emailcommon.mail.MessagingException;
-import com.android.emailcommon.provider.EmailContent.Attachment;
-import com.android.emailcommon.provider.EmailContent.Body;
-import com.android.emailcommon.provider.EmailContent.Message;
-
-import org.apache.commons.io.IOUtils;
-
-import android.content.ContentUris;
-import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-import android.util.Base64;
-import android.util.Base64OutputStream;
-
-import java.io.BufferedOutputStream;
-import java.io.ByteArrayInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Utility class to output RFC 822 messages from provider email messages
- */
-public class Rfc822Output {
-
- private static final Pattern PATTERN_START_OF_LINE = Pattern.compile("(?m)^");
- private static final Pattern PATTERN_ENDLINE_CRLF = Pattern.compile("\r\n");
-
- // In MIME, en_US-like date format should be used. In other words "MMM" should be encoded to
- // "Jan", not the other localized format like "Ene" (meaning January in locale es).
- private static final SimpleDateFormat DATE_FORMAT =
- new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US);
-
- private static final String WHERE_NOT_SMART_FORWARD = "(" + Attachment.FLAGS + "&" +
- Attachment.FLAG_SMART_FORWARD + ")=0";
-
- /*package*/ static String buildBodyText(Context context, Message message,
- boolean useSmartReply) {
- Body body = Body.restoreBodyWithMessageId(context, message.mId);
- if (body == null) {
- return null;
- }
-
- String text = body.mTextContent;
- int flags = message.mFlags;
- boolean isReply = (flags & Message.FLAG_TYPE_REPLY) != 0;
- boolean isForward = (flags & Message.FLAG_TYPE_FORWARD) != 0;
- // For all forwards/replies, we add the intro text
- if (isReply || isForward) {
- String intro = body.mIntroText == null ? "" : body.mIntroText;
- text += intro;
- }
- if (useSmartReply) {
- // useSmartReply is set to true for use by SmartReply/SmartForward in EAS.
- // SmartForward doesn't put a break between the original and new text, so we add an LF
- if (isForward) {
- text += "\n";
- }
- return text;
- }
-
- String quotedText = body.mTextReply;
- if (quotedText != null) {
- // fix CR-LF line endings to LF-only needed by EditText.
- Matcher matcher = PATTERN_ENDLINE_CRLF.matcher(quotedText);
- quotedText = matcher.replaceAll("\n");
- }
- if (isReply) {
- if (quotedText != null) {
- Matcher matcher = PATTERN_START_OF_LINE.matcher(quotedText);
- text += matcher.replaceAll(">");
- }
- } else if (isForward) {
- if (quotedText != null) {
- text += quotedText;
- }
- }
- return text;
- }
-
- /**
- * Write the entire message to an output stream. This method provides buffering, so it is
- * not necessary to pass in a buffered output stream here.
- *
- * @param context system context for accessing the provider
- * @param messageId the message to write out
- * @param out the output stream to write the message to
- * @param useSmartReply whether or not quoted text is appended to a reply/forward
- *
- * TODO alternative parts (e.g. text+html) are not supported here.
- */
- public static void writeTo(Context context, long messageId, OutputStream out,
- boolean useSmartReply, boolean sendBcc) throws IOException, MessagingException {
- Message message = Message.restoreMessageWithId(context, messageId);
- if (message == null) {
- // throw something?
- return;
- }
-
- OutputStream stream = new BufferedOutputStream(out, 1024);
- Writer writer = new OutputStreamWriter(stream);
-
- // Write the fixed headers. Ordering is arbitrary (the legacy code iterated through a
- // hashmap here).
-
- String date = DATE_FORMAT.format(new Date(message.mTimeStamp));
- writeHeader(writer, "Date", date);
-
- writeEncodedHeader(writer, "Subject", message.mSubject);
-
- writeHeader(writer, "Message-ID", message.mMessageId);
-
- writeAddressHeader(writer, "From", message.mFrom);
- writeAddressHeader(writer, "To", message.mTo);
- writeAddressHeader(writer, "Cc", message.mCc);
- // Address fields. Note that we skip bcc unless the sendBcc argument is true
- // SMTP should NOT send bcc headers, but EAS must send it!
- if (sendBcc) {
- writeAddressHeader(writer, "Bcc", message.mBcc);
- }
- writeAddressHeader(writer, "Reply-To", message.mReplyTo);
- writeHeader(writer, "MIME-Version", "1.0");
-
- // Analyze message and determine if we have multiparts
- String text = buildBodyText(context, message, useSmartReply);
-
- Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
- Cursor attachmentsCursor = context.getContentResolver().query(uri,
- Attachment.CONTENT_PROJECTION, WHERE_NOT_SMART_FORWARD, null, null);
-
- try {
- int attachmentCount = attachmentsCursor.getCount();
- boolean multipart = attachmentCount > 0;
- String multipartBoundary = null;
- String multipartType = "mixed";
-
- // Simplified case for no multipart - just emit text and be done.
- if (!multipart) {
- if (text != null) {
- writeTextWithHeaders(writer, stream, text);
- } else {
- writer.write("\r\n"); // a truly empty message
- }
- } else {
- // continue with multipart headers, then into multipart body
- multipartBoundary = "--_com.android.email_" + System.nanoTime();
-
- // Move to the first attachment; this must succeed because multipart is true
- attachmentsCursor.moveToFirst();
- if (attachmentCount == 1) {
- // If we've got one attachment and it's an ics "attachment", we want to send
- // this as multipart/alternative instead of multipart/mixed
- int flags = attachmentsCursor.getInt(Attachment.CONTENT_FLAGS_COLUMN);
- if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) {
- multipartType = "alternative";
- }
- }
-
- writeHeader(writer, "Content-Type",
- "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\"");
- // Finish headers and prepare for body section(s)
- writer.write("\r\n");
-
- // first multipart element is the body
- if (text != null) {
- writeBoundary(writer, multipartBoundary, false);
- writeTextWithHeaders(writer, stream, text);
- }
-
- // Write out the attachments until we run out
- do {
- writeBoundary(writer, multipartBoundary, false);
- Attachment attachment =
- Attachment.getContent(attachmentsCursor, Attachment.class);
- writeOneAttachment(context, writer, stream, attachment);
- writer.write("\r\n");
- } while (attachmentsCursor.moveToNext());
-
- // end of multipart section
- writeBoundary(writer, multipartBoundary, true);
- }
- } finally {
- attachmentsCursor.close();
- }
-
- writer.flush();
- out.flush();
- }
-
- /**
- * Write a single attachment and its payload
- */
- private static void writeOneAttachment(Context context, Writer writer, OutputStream out,
- Attachment attachment) throws IOException, MessagingException {
- writeHeader(writer, "Content-Type",
- attachment.mMimeType + ";\n name=\"" + attachment.mFileName + "\"");
- writeHeader(writer, "Content-Transfer-Encoding", "base64");
- // Most attachments (real files) will send Content-Disposition. The suppression option
- // is used when sending calendar invites.
- if ((attachment.mFlags & Attachment.FLAG_ICS_ALTERNATIVE_PART) == 0) {
- writeHeader(writer, "Content-Disposition",
- "attachment;"
- + "\n filename=\"" + attachment.mFileName + "\";"
- + "\n size=" + Long.toString(attachment.mSize));
- }
- writeHeader(writer, "Content-ID", attachment.mContentId);
- writer.append("\r\n");
-
- // Set up input stream and write it out via base64
- InputStream inStream = null;
- try {
- // Use content, if provided; otherwise, use the contentUri
- if (attachment.mContentBytes != null) {
- inStream = new ByteArrayInputStream(attachment.mContentBytes);
- } else {
- // try to open the file
- Uri fileUri = Uri.parse(attachment.mContentUri);
- inStream = context.getContentResolver().openInputStream(fileUri);
- }
- // switch to output stream for base64 text output
- writer.flush();
- Base64OutputStream base64Out = new Base64OutputStream(
- out, Base64.CRLF | Base64.NO_CLOSE);
- // copy base64 data and close up
- IOUtils.copy(inStream, base64Out);
- base64Out.close();
-
- // The old Base64OutputStream wrote an extra CRLF after
- // the output. It's not required by the base-64 spec; not
- // sure if it's required by RFC 822 or not.
- out.write('\r');
- out.write('\n');
- out.flush();
- }
- catch (FileNotFoundException fnfe) {
- // Ignore this - empty file is OK
- }
- catch (IOException ioe) {
- throw new MessagingException("Invalid attachment.", ioe);
- }
- }
-
- /**
- * Write a single header with no wrapping or encoding
- *
- * @param writer the output writer
- * @param name the header name
- * @param value the header value
- */
- private static void writeHeader(Writer writer, String name, String value) throws IOException {
- if (value != null && value.length() > 0) {
- writer.append(name);
- writer.append(": ");
- writer.append(value);
- writer.append("\r\n");
- }
- }
-
- /**
- * Write a single header using appropriate folding & encoding
- *
- * @param writer the output writer
- * @param name the header name
- * @param value the header value
- */
- private static void writeEncodedHeader(Writer writer, String name, String value)
- throws IOException {
- if (value != null && value.length() > 0) {
- writer.append(name);
- writer.append(": ");
- writer.append(MimeUtility.foldAndEncode2(value, name.length() + 2));
- writer.append("\r\n");
- }
- }
-
- /**
- * Unpack, encode, and fold address(es) into a header
- *
- * @param writer the output writer
- * @param name the header name
- * @param value the header value (a packed list of addresses)
- */
- private static void writeAddressHeader(Writer writer, String name, String value)
- throws IOException {
- if (value != null && value.length() > 0) {
- writer.append(name);
- writer.append(": ");
- writer.append(MimeUtility.fold(Address.packedToHeader(value), name.length() + 2));
- writer.append("\r\n");
- }
- }
-
- /**
- * Write a multipart boundary
- *
- * @param writer the output writer
- * @param boundary the boundary string
- * @param end false if inner boundary, true if final boundary
- */
- private static void writeBoundary(Writer writer, String boundary, boolean end)
- throws IOException {
- writer.append("--");
- writer.append(boundary);
- if (end) {
- writer.append("--");
- }
- writer.append("\r\n");
- }
-
- /**
- * Write text (either as main body or inside a multipart), preceded by appropriate headers.
- *
- * Note this always uses base64, even when not required. Slightly less efficient for
- * US-ASCII text, but handles all formats even when non-ascii chars are involved. A small
- * optimization might be to prescan the string for safety and send raw if possible.
- *
- * @param writer the output writer
- * @param out the output stream inside the writer (used for byte[] access)
- * @param text The original text of the message
- */
- private static void writeTextWithHeaders(Writer writer, OutputStream out, String text)
- throws IOException {
- writeHeader(writer, "Content-Type", "text/plain; charset=utf-8");
- writeHeader(writer, "Content-Transfer-Encoding", "base64");
- writer.write("\r\n");
- byte[] bytes = text.getBytes("UTF-8");
- writer.flush();
- out.write(Base64.encode(bytes, Base64.CRLF));
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/internet/TextBody.java b/emailcommon/src/com/android/emailcommon/internet/TextBody.java
deleted file mode 100644
index 09c265c8e..000000000
--- a/emailcommon/src/com/android/emailcommon/internet/TextBody.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.internet;
-
-import com.android.emailcommon.mail.Body;
-import com.android.emailcommon.mail.MessagingException;
-
-import android.util.Base64;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-
-public class TextBody implements Body {
- String mBody;
-
- public TextBody(String body) {
- this.mBody = body;
- }
-
- public void writeTo(OutputStream out) throws IOException, MessagingException {
- byte[] bytes = mBody.getBytes("UTF-8");
- out.write(Base64.encode(bytes, Base64.CRLF));
- }
-
- /**
- * Get the text of the body in it's unencoded format.
- * @return
- */
- public String getText() {
- return mBody;
- }
-
- /**
- * Returns an InputStream that reads this body's text in UTF-8 format.
- */
- public InputStream getInputStream() throws MessagingException {
- try {
- byte[] b = mBody.getBytes("UTF-8");
- return new ByteArrayInputStream(b);
- }
- catch (UnsupportedEncodingException usee) {
- return null;
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Address.java b/emailcommon/src/com/android/emailcommon/mail/Address.java
deleted file mode 100644
index 76a3b7c6f..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Address.java
+++ /dev/null
@@ -1,519 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import com.android.emailcommon.utility.Utility;
-
-import org.apache.james.mime4j.codec.EncoderUtil;
-import org.apache.james.mime4j.decoder.DecoderUtil;
-
-import android.text.TextUtils;
-import android.text.util.Rfc822Token;
-import android.text.util.Rfc822Tokenizer;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.util.ArrayList;
-import java.util.regex.Pattern;
-
-/**
- * This class represent email address.
- *
- * RFC822 email address may have following format.
- * "name" <address> (comment)
- * "name" <address>
- * name <address>
- * address
- * Name and comment part should be MIME/base64 encoded in header if necessary.
- *
- */
-public class Address {
- /**
- * Address part, in the form local_part@domain_part. No surrounding angle brackets.
- */
- private String mAddress;
-
- /**
- * Name part. No surrounding double quote, and no MIME/base64 encoding.
- * This must be null if Address has no name part.
- */
- private String mPersonal;
-
- // Regex that matches address surrounded by '<>' optionally. '^<?([^>]+)>?$'
- private static final Pattern REMOVE_OPTIONAL_BRACKET = Pattern.compile("^<?([^>]+)>?$");
- // Regex that matches personal name surrounded by '""' optionally. '^"?([^"]+)"?$'
- private static final Pattern REMOVE_OPTIONAL_DQUOTE = Pattern.compile("^\"?([^\"]*)\"?$");
- // Regex that matches escaped character '\\([\\"])'
- private static final Pattern UNQUOTE = Pattern.compile("\\\\([\\\\\"])");
-
- private static final Address[] EMPTY_ADDRESS_ARRAY = new Address[0];
-
- // delimiters are chars that do not appear in an email address, used by pack/unpack
- private static final char LIST_DELIMITER_EMAIL = '\1';
- private static final char LIST_DELIMITER_PERSONAL = '\2';
-
- public Address(String address, String personal) {
- setAddress(address);
- setPersonal(personal);
- }
-
- public Address(String address) {
- setAddress(address);
- }
-
- public String getAddress() {
- return mAddress;
- }
-
- public void setAddress(String address) {
- this.mAddress = REMOVE_OPTIONAL_BRACKET.matcher(address).replaceAll("$1");;
- }
-
- /**
- * Get name part as UTF-16 string. No surrounding double quote, and no MIME/base64 encoding.
- *
- * @return Name part of email address. Returns null if it is omitted.
- */
- public String getPersonal() {
- return mPersonal;
- }
-
- /**
- * Set name part from UTF-16 string. Optional surrounding double quote will be removed.
- * It will be also unquoted and MIME/base64 decoded.
- *
- * @param Personal name part of email address as UTF-16 string. Null is acceptable.
- */
- public void setPersonal(String personal) {
- if (personal != null) {
- personal = REMOVE_OPTIONAL_DQUOTE.matcher(personal).replaceAll("$1");
- personal = UNQUOTE.matcher(personal).replaceAll("$1");
- personal = DecoderUtil.decodeEncodedWords(personal);
- if (personal.length() == 0) {
- personal = null;
- }
- }
- this.mPersonal = personal;
- }
-
- /**
- * This method is used to check that all the addresses that the user
- * entered in a list (e.g. To:) are valid, so that none is dropped.
- */
- public static boolean isAllValid(String addressList) {
- // This code mimics the parse() method below.
- // I don't know how to better avoid the code-duplication.
- if (addressList != null && addressList.length() > 0) {
- Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressList);
- for (int i = 0, length = tokens.length; i < length; ++i) {
- Rfc822Token token = tokens[i];
- String address = token.getAddress();
- if (!TextUtils.isEmpty(address) && !isValidAddress(address)) {
- return false;
- }
- }
- }
- return true;
- }
-
- /**
- * Parse a comma-delimited list of addresses in RFC822 format and return an
- * array of Address objects.
- *
- * @param addressList Address list in comma-delimited string.
- * @return An array of 0 or more Addresses.
- */
- public static Address[] parse(String addressList) {
- if (addressList == null || addressList.length() == 0) {
- return EMPTY_ADDRESS_ARRAY;
- }
- Rfc822Token[] tokens = Rfc822Tokenizer.tokenize(addressList);
- ArrayList<Address> addresses = new ArrayList<Address>();
- for (int i = 0, length = tokens.length; i < length; ++i) {
- Rfc822Token token = tokens[i];
- String address = token.getAddress();
- if (!TextUtils.isEmpty(address)) {
- if (isValidAddress(address)) {
- String name = token.getName();
- if (TextUtils.isEmpty(name)) {
- name = null;
- }
- addresses.add(new Address(address, name));
- }
- }
- }
- return addresses.toArray(new Address[] {});
- }
-
- /**
- * Checks whether a string email address is valid.
- * E.g. name@domain.com is valid.
- */
- /* package */ static boolean isValidAddress(String address) {
- // Note: Some email provider may violate the standard, so here we only check that
- // address consists of two part that are separated by '@', and domain part contains
- // at least one '.'.
- int len = address.length();
- int firstAt = address.indexOf('@');
- int lastAt = address.lastIndexOf('@');
- int firstDot = address.indexOf('.', lastAt + 1);
- int lastDot = address.lastIndexOf('.');
- return firstAt > 0 && firstAt == lastAt && lastAt + 1 < firstDot
- && firstDot <= lastDot && lastDot < len - 1;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o instanceof Address) {
- // It seems that the spec says that the "user" part is case-sensitive,
- // while the domain part in case-insesitive.
- // So foo@yahoo.com and Foo@yahoo.com are different.
- // This may seem non-intuitive from the user POV, so we
- // may re-consider it if it creates UI trouble.
- // A problem case is "replyAll" sending to both
- // a@b.c and to A@b.c, which turn out to be the same on the server.
- // Leave unchanged for now (i.e. case-sensitive).
- return getAddress().equals(((Address) o).getAddress());
- }
- return super.equals(o);
- }
-
- /**
- * Get human readable address string.
- * Do not use this for email header.
- *
- * @return Human readable address string. Not quoted and not encoded.
- */
- @Override
- public String toString() {
- if (mPersonal != null && !mPersonal.equals(mAddress)) {
- if (mPersonal.matches(".*[\\(\\)<>@,;:\\\\\".\\[\\]].*")) {
- return Utility.quoteString(mPersonal) + " <" + mAddress + ">";
- } else {
- return mPersonal + " <" + mAddress + ">";
- }
- } else {
- return mAddress;
- }
- }
-
- /**
- * Get human readable comma-delimited address string.
- *
- * @param addresses Address array
- * @return Human readable comma-delimited address string.
- */
- public static String toString(Address[] addresses) {
- return toString(addresses, ",");
- }
-
- /**
- * Get human readable address strings joined with the specified separator.
- *
- * @param addresses Address array
- * @param separator Separator
- * @return Human readable comma-delimited address string.
- */
- public static String toString(Address[] addresses, String separator) {
- if (addresses == null || addresses.length == 0) {
- return null;
- }
- if (addresses.length == 1) {
- return addresses[0].toString();
- }
- StringBuffer sb = new StringBuffer(addresses[0].toString());
- for (int i = 1; i < addresses.length; i++) {
- sb.append(separator);
- sb.append(addresses[i].toString());
- }
- return sb.toString();
- }
-
- /**
- * Get RFC822/MIME compatible address string.
- *
- * @return RFC822/MIME compatible address string.
- * It may be surrounded by double quote or quoted and MIME/base64 encoded if necessary.
- */
- public String toHeader() {
- if (mPersonal != null) {
- return EncoderUtil.encodeAddressDisplayName(mPersonal) + " <" + mAddress + ">";
- } else {
- return mAddress;
- }
- }
-
- /**
- * Get RFC822/MIME compatible comma-delimited address string.
- *
- * @param addresses Address array
- * @return RFC822/MIME compatible comma-delimited address string.
- * it may be surrounded by double quoted or quoted and MIME/base64 encoded if necessary.
- */
- public static String toHeader(Address[] addresses) {
- if (addresses == null || addresses.length == 0) {
- return null;
- }
- if (addresses.length == 1) {
- return addresses[0].toHeader();
- }
- StringBuffer sb = new StringBuffer(addresses[0].toHeader());
- for (int i = 1; i < addresses.length; i++) {
- // We need space character to be able to fold line.
- sb.append(", ");
- sb.append(addresses[i].toHeader());
- }
- return sb.toString();
- }
-
- /**
- * Get Human friendly address string.
- *
- * @return the personal part of this Address, or the address part if the
- * personal part is not available
- */
- public String toFriendly() {
- if (mPersonal != null && mPersonal.length() > 0) {
- return mPersonal;
- } else {
- return mAddress;
- }
- }
-
- /**
- * Creates a comma-delimited list of addresses in the "friendly" format (see toFriendly() for
- * details on the per-address conversion).
- *
- * @param addresses Array of Address[] values
- * @return A comma-delimited string listing all of the addresses supplied. Null if source
- * was null or empty.
- */
- public static String toFriendly(Address[] addresses) {
- if (addresses == null || addresses.length == 0) {
- return null;
- }
- if (addresses.length == 1) {
- return addresses[0].toFriendly();
- }
- StringBuffer sb = new StringBuffer(addresses[0].toFriendly());
- for (int i = 1; i < addresses.length; i++) {
- sb.append(',');
- sb.append(addresses[i].toFriendly());
- }
- return sb.toString();
- }
-
- /**
- * Returns exactly the same result as Address.toString(Address.unpack(packedList)).
- */
- public static String unpackToString(String packedList) {
- return toString(unpack(packedList));
- }
-
- /**
- * Returns exactly the same result as Address.pack(Address.parse(textList)).
- */
- public static String parseAndPack(String textList) {
- return Address.pack(Address.parse(textList));
- }
-
- /**
- * Returns null if the packedList has 0 addresses, otherwise returns the first address.
- * The same as Address.unpack(packedList)[0] for non-empty list.
- * This is an utility method that offers some performance optimization opportunities.
- */
- public static Address unpackFirst(String packedList) {
- Address[] array = unpack(packedList);
- return array.length > 0 ? array[0] : null;
- }
-
- /**
- * Convert a packed list of addresses to a form suitable for use in an RFC822 header.
- * This implementation is brute-force, and could be replaced with a more efficient version
- * if desired.
- */
- public static String packedToHeader(String packedList) {
- return toHeader(unpack(packedList));
- }
-
- /**
- * Unpacks an address list previously packed with pack()
- * @param addressList String with packed addresses as returned by pack()
- * @return array of addresses resulting from unpack
- */
- public static Address[] unpack(String addressList) {
- if (addressList == null || addressList.length() == 0) {
- return EMPTY_ADDRESS_ARRAY;
- }
- ArrayList<Address> addresses = new ArrayList<Address>();
- int length = addressList.length();
- int pairStartIndex = 0;
- int pairEndIndex = 0;
-
- /* addressEndIndex is only re-scanned (indexOf()) when a LIST_DELIMITER_PERSONAL
- is used, not for every email address; i.e. not for every iteration of the while().
- This reduces the theoretical complexity from quadratic to linear,
- and provides some speed-up in practice by removing redundant scans of the string.
- */
- int addressEndIndex = addressList.indexOf(LIST_DELIMITER_PERSONAL);
-
- while (pairStartIndex < length) {
- pairEndIndex = addressList.indexOf(LIST_DELIMITER_EMAIL, pairStartIndex);
- if (pairEndIndex == -1) {
- pairEndIndex = length;
- }
- Address address;
- if (addressEndIndex == -1 || pairEndIndex <= addressEndIndex) {
- // in this case the DELIMITER_PERSONAL is in a future pair,
- // so don't use personal, and don't update addressEndIndex
- address = new Address(addressList.substring(pairStartIndex, pairEndIndex), null);
- } else {
- address = new Address(addressList.substring(pairStartIndex, addressEndIndex),
- addressList.substring(addressEndIndex + 1, pairEndIndex));
- // only update addressEndIndex when we use the LIST_DELIMITER_PERSONAL
- addressEndIndex = addressList.indexOf(LIST_DELIMITER_PERSONAL, pairEndIndex + 1);
- }
- addresses.add(address);
- pairStartIndex = pairEndIndex + 1;
- }
- return addresses.toArray(EMPTY_ADDRESS_ARRAY);
- }
-
- /**
- * Packs an address list into a String that is very quick to read
- * and parse. Packed lists can be unpacked with unpack().
- * The format is a series of packed addresses separated by LIST_DELIMITER_EMAIL.
- * Each address is packed as
- * a pair of address and personal separated by LIST_DELIMITER_PERSONAL,
- * where the personal and delimiter are optional.
- * E.g. "foo@x.com\1joe@x.com\2Joe Doe"
- * @param addresses Array of addresses
- * @return a string containing the packed addresses.
- */
- public static String pack(Address[] addresses) {
- // TODO: return same value for both null & empty list
- if (addresses == null) {
- return null;
- }
- final int nAddr = addresses.length;
- if (nAddr == 0) {
- return "";
- }
-
- // shortcut: one email with no displayName
- if (nAddr == 1 && addresses[0].getPersonal() == null) {
- return addresses[0].getAddress();
- }
-
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < nAddr; i++) {
- if (i != 0) {
- sb.append(LIST_DELIMITER_EMAIL);
- }
- final Address address = addresses[i];
- sb.append(address.getAddress());
- final String displayName = address.getPersonal();
- if (displayName != null) {
- sb.append(LIST_DELIMITER_PERSONAL);
- sb.append(displayName);
- }
- }
- return sb.toString();
- }
-
- /**
- * Produces the same result as pack(array), but only packs one (this) address.
- */
- public String pack() {
- final String address = getAddress();
- final String personal = getPersonal();
- if (personal == null) {
- return address;
- } else {
- return address + LIST_DELIMITER_PERSONAL + personal;
- }
- }
-
- /**
- * Legacy unpack() used for reading the old data (migration),
- * as found in LocalStore (Donut; db version up to 24).
- * @See unpack()
- */
- public static Address[] legacyUnpack(String addressList) {
- if (addressList == null || addressList.length() == 0) {
- return new Address[] { };
- }
- ArrayList<Address> addresses = new ArrayList<Address>();
- int length = addressList.length();
- int pairStartIndex = 0;
- int pairEndIndex = 0;
- int addressEndIndex = 0;
- while (pairStartIndex < length) {
- pairEndIndex = addressList.indexOf(',', pairStartIndex);
- if (pairEndIndex == -1) {
- pairEndIndex = length;
- }
- addressEndIndex = addressList.indexOf(';', pairStartIndex);
- String address = null;
- String personal = null;
- if (addressEndIndex == -1 || addressEndIndex > pairEndIndex) {
- address =
- Utility.fastUrlDecode(addressList.substring(pairStartIndex, pairEndIndex));
- }
- else {
- address =
- Utility.fastUrlDecode(addressList.substring(pairStartIndex, addressEndIndex));
- personal =
- Utility.fastUrlDecode(addressList.substring(addressEndIndex + 1, pairEndIndex));
- }
- addresses.add(new Address(address, personal));
- pairStartIndex = pairEndIndex + 1;
- }
- return addresses.toArray(new Address[] { });
- }
-
- /**
- * Legacy pack() used for writing to old data (migration),
- * as found in LocalStore (Donut; db version up to 24).
- * @See unpack()
- */
- public static String legacyPack(Address[] addresses) {
- if (addresses == null) {
- return null;
- } else if (addresses.length == 0) {
- return "";
- }
- StringBuffer sb = new StringBuffer();
- for (int i = 0, count = addresses.length; i < count; i++) {
- Address address = addresses[i];
- try {
- sb.append(URLEncoder.encode(address.getAddress(), "UTF-8"));
- if (address.getPersonal() != null) {
- sb.append(';');
- sb.append(URLEncoder.encode(address.getPersonal(), "UTF-8"));
- }
- if (i < count - 1) {
- sb.append(',');
- }
- }
- catch (UnsupportedEncodingException uee) {
- return null;
- }
- }
- return sb.toString();
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/AuthenticationFailedException.java b/emailcommon/src/com/android/emailcommon/mail/AuthenticationFailedException.java
deleted file mode 100644
index af8d96c09..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/AuthenticationFailedException.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-
-public class AuthenticationFailedException extends MessagingException {
- public static final long serialVersionUID = -1;
-
- public AuthenticationFailedException(String message) {
- super(MessagingException.AUTHENTICATION_FAILED, message);
- }
-
- public AuthenticationFailedException(int exceptionType, String message) {
- super(exceptionType, message);
- }
-
- public AuthenticationFailedException(String message, Throwable throwable) {
- super(MessagingException.AUTHENTICATION_FAILED, message, throwable);
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Body.java b/emailcommon/src/com/android/emailcommon/mail/Body.java
deleted file mode 100644
index 841ab42a7..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Body.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-public interface Body {
- public InputStream getInputStream() throws MessagingException;
- public void writeTo(OutputStream out) throws IOException, MessagingException;
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/BodyPart.java b/emailcommon/src/com/android/emailcommon/mail/BodyPart.java
deleted file mode 100644
index f698a139d..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/BodyPart.java
+++ /dev/null
@@ -1,25 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-public abstract class BodyPart implements Part {
- protected Multipart mParent;
-
- public Multipart getParent() {
- return mParent;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/CertificateValidationException.java b/emailcommon/src/com/android/emailcommon/mail/CertificateValidationException.java
deleted file mode 100644
index 83c6224df..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/CertificateValidationException.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-
-public class CertificateValidationException extends MessagingException {
- public static final long serialVersionUID = -1;
-
- public CertificateValidationException(String message) {
- super(MessagingException.CERTIFICATE_VALIDATION_ERROR, message);
- }
-
- public CertificateValidationException(String message, Throwable throwable) {
- super(MessagingException.CERTIFICATE_VALIDATION_ERROR, message, throwable);
- }
-} \ No newline at end of file
diff --git a/emailcommon/src/com/android/emailcommon/mail/FetchProfile.java b/emailcommon/src/com/android/emailcommon/mail/FetchProfile.java
deleted file mode 100644
index bfa48d30f..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/FetchProfile.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import java.util.ArrayList;
-
-/**
- * <pre>
- * A FetchProfile is a list of items that should be downloaded in bulk for a set of messages.
- * FetchProfile can contain the following objects:
- * FetchProfile.Item: Described below.
- * Message: Indicates that the body of the entire message should be fetched.
- * Synonymous with FetchProfile.Item.BODY.
- * Part: Indicates that the given Part should be fetched. The provider
- * is expected have previously created the given BodyPart and stored
- * any information it needs to download the content.
- * </pre>
- */
-public class FetchProfile extends ArrayList<Fetchable> {
- /**
- * Default items available for pre-fetching. It should be expected that any
- * item fetched by using these items could potentially include all of the
- * previous items.
- */
- public enum Item implements Fetchable {
- /**
- * Download the flags of the message.
- */
- FLAGS,
-
- /**
- * Download the envelope of the message. This should include at minimum
- * the size and the following headers: date, subject, from, content-type, to, cc
- */
- ENVELOPE,
-
- /**
- * Download the structure of the message. This maps directly to IMAP's BODYSTRUCTURE
- * and may map to other providers.
- * The provider should, if possible, fill in a properly formatted MIME structure in
- * the message without actually downloading any message data. If the provider is not
- * capable of this operation it should specifically set the body of the message to null
- * so that upper levels can detect that a full body download is needed.
- */
- STRUCTURE,
-
- /**
- * A sane portion of the entire message, cut off at a provider determined limit.
- * This should generaly be around 50kB.
- */
- BODY_SANE,
-
- /**
- * The entire message.
- */
- BODY,
- }
-
- /**
- * @return the first {@link Part} in this collection, or null if it doesn't contain
- * {@link Part}.
- */
- public Part getFirstPart() {
- for (Fetchable o : this) {
- if (o instanceof Part) {
- return (Part) o;
- }
- }
- return null;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Fetchable.java b/emailcommon/src/com/android/emailcommon/mail/Fetchable.java
deleted file mode 100644
index 4314f93f5..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Fetchable.java
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-/**
- * Interface for classes that can be added to {@link FetchProfile}.
- * i.e. {@link Part} and its subclasses, and {@link FetchProfile.Item}.
- */
-public interface Fetchable {
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Flag.java b/emailcommon/src/com/android/emailcommon/mail/Flag.java
deleted file mode 100644
index bcdcb8b7e..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Flag.java
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-/**
- * Flags that can be applied to Messages.
- */
-public enum Flag {
-
- // If adding new flags: ALL FLAGS MUST BE UPPER CASE.
-
- DELETED,
- SEEN,
- ANSWERED,
- FLAGGED,
- DRAFT,
- RECENT,
-
- /*
- * The following flags are for internal library use only.
- * TODO Eventually we should creates a Flags class that extends ArrayList that allows
- * these flags and Strings to represent user defined flags. At that point the below
- * flags should become user defined flags.
- */
- /**
- * Delete and remove from the LocalStore immediately.
- */
- X_DESTROYED,
-
- /**
- * Sending of an unsent message failed. It will be retried. Used to show status.
- */
- X_SEND_FAILED,
-
- /**
- * Sending of an unsent message is in progress.
- */
- X_SEND_IN_PROGRESS,
-
- /**
- * Indicates that a message is fully downloaded from the server and can be viewed normally.
- * This does not include attachments, which are never downloaded fully.
- */
- X_DOWNLOADED_FULL,
-
- /**
- * Indicates that a message is partially downloaded from the server and can be viewed but
- * more content is available on the server.
- * This does not include attachments, which are never downloaded fully.
- */
- X_DOWNLOADED_PARTIAL,
-
- /**
- * General purpose flag that can be used by any remote store. The flag will be
- * saved and restored by the LocalStore.
- */
- X_STORE_1,
-
- /**
- * General purpose flag that can be used by any remote store. The flag will be
- * saved and restored by the LocalStore.
- */
- X_STORE_2,
-
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Folder.java b/emailcommon/src/com/android/emailcommon/mail/Folder.java
deleted file mode 100644
index ea7fc5984..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Folder.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-
-public abstract class Folder {
- public enum OpenMode {
- READ_WRITE, READ_ONLY,
- }
-
- public enum FolderType {
- HOLDS_FOLDERS, HOLDS_MESSAGES,
- }
-
- /**
- * Identifiers of "special" folders.
- */
- public enum FolderRole {
- INBOX, // NOTE: The folder's name must be INBOX
- TRASH,
- SENT,
- DRAFTS,
-
- OUTBOX, // Local folders only - not used in remote Stores
- OTHER, // this folder has no specific role
- UNKNOWN // the role of this folder is unknown
- }
-
- /**
- * Callback for each message retrieval.
- *
- * Not all {@link Folder} implementation won't call it.
- * (Currently {@link com.android.email.mail.store.LocalStore.LocalFolder} won't.)
- */
- public interface MessageRetrievalListener {
- public void messageRetrieved(Message message);
- public void loadAttachmentProgress(int progress);
- }
-
- /**
- * Forces an open of the MailProvider. If the provider is already open this
- * function returns without doing anything.
- *
- * @param mode READ_ONLY or READ_WRITE
- * @param callbacks Pointer to callbacks class. This may be used by the folder between this
- * time and when close() is called. This is only used for remote stores - should be null
- * for LocalStore.LocalFolder.
- */
- public abstract void open(OpenMode mode, PersistentDataCallbacks callbacks)
- throws MessagingException;
-
- /**
- * Forces a close of the MailProvider. Any further access will attempt to
- * reopen the MailProvider.
- *
- * @param expunge If true all deleted messages will be expunged.
- */
- public abstract void close(boolean expunge) throws MessagingException;
-
- /**
- * @return True if further commands are not expected to have to open the
- * connection.
- */
- // TODO not used, get rid of this - it's a transport function
- public abstract boolean isOpen();
-
- /**
- * Get the mode the folder was opened with. This may be different than the mode the open
- * was requested with.
- * @return
- */
- public abstract OpenMode getMode() throws MessagingException;
-
- /**
- * Reports if the Store is able to create folders of the given type.
- * Does not actually attempt to create a folder.
- * @param type
- * @return true if can create, false if cannot create
- */
- public abstract boolean canCreate(FolderType type);
-
- /**
- * Attempt to create the given folder remotely using the given type.
- * @param type
- * @return true if created, false if cannot create (e.g. server side)
- */
- public abstract boolean create(FolderType type) throws MessagingException;
-
- public abstract boolean exists() throws MessagingException;
-
- /**
- * @return A count of the messages in the selected folder.
- */
- public abstract int getMessageCount() throws MessagingException;
-
- public abstract int getUnreadMessageCount() throws MessagingException;
-
- public abstract Message getMessage(String uid) throws MessagingException;
-
- public abstract Message[] getMessages(int start, int end, MessageRetrievalListener listener)
- throws MessagingException;
-
- /**
- * Fetches the given list of messages. The specified listener is notified as
- * each fetch completes. Messages are downloaded as (as) lightweight (as
- * possible) objects to be filled in with later requests. In most cases this
- * means that only the UID is downloaded.
- *
- * @param uids
- * @param listener
- */
- public abstract Message[] getMessages(MessageRetrievalListener listener)
- throws MessagingException;
-
- public abstract Message[] getMessages(String[] uids, MessageRetrievalListener listener)
- throws MessagingException;
-
- /**
- * Return a set of messages based on the state of the flags.
- * Note: Not typically implemented in remote stores, so not abstract.
- *
- * @param setFlags The flags that should be set for a message to be selected (can be null)
- * @param clearFlags The flags that should be clear for a message to be selected (can be null)
- * @param listener
- * @return A list of messages matching the desired flag states.
- * @throws MessagingException
- */
- public Message[] getMessages(Flag[] setFlags, Flag[] clearFlags,
- MessageRetrievalListener listener) throws MessagingException {
- throw new MessagingException("Not implemented");
- }
-
- public abstract void appendMessages(Message[] messages) throws MessagingException;
-
- public abstract void copyMessages(Message[] msgs, Folder folder,
- MessageUpdateCallbacks callbacks) throws MessagingException;
-
- public abstract void setFlags(Message[] messages, Flag[] flags, boolean value)
- throws MessagingException;
-
- public abstract Message[] expunge() throws MessagingException;
-
- public abstract void fetch(Message[] messages, FetchProfile fp,
- MessageRetrievalListener listener) throws MessagingException;
-
- public abstract void delete(boolean recurse) throws MessagingException;
-
- public abstract String getName();
-
- public abstract Flag[] getPermanentFlags() throws MessagingException;
-
- /**
- * This method returns a string identifying the name of a "role" folder
- * (such as inbox, draft, sent, or trash). Stores that do not implement this
- * feature can be used - the account UI will provide default strings. To
- * let the server identify specific folder roles, simply override this method.
- *
- * @return The server- or protocol- specific role for this folder. If some roles are known
- * but this is not one of them, return FolderRole.OTHER. If roles are unsupported here,
- * return FolderRole.UNKNOWN.
- */
- public FolderRole getRole() {
- return FolderRole.UNKNOWN;
- }
-
- /**
- * This function will be called after the messaging controller has called
- * getPersonalNamespaces() and has created a matching LocalFolder object. This can
- * be used as a trigger for the folder to write back any folder-specific persistent data using
- * callbacks.
- *
- * This is not abstract because most folders do not require this functionality and do not
- * need to implement it.
- */
- @SuppressWarnings("unused")
- public void localFolderSetupComplete(Folder localFolder) throws MessagingException {
- // Do nothing - return immediately
- }
-
- /**
- * Create an empty message of the appropriate type for the Folder.
- */
- public abstract Message createMessage(String uid) throws MessagingException;
-
- /**
- * Callback interface by which a Folder can read and write persistent data.
- * TODO This needs to be made more generic & flexible
- */
- public interface PersistentDataCallbacks {
-
- /**
- * Provides keyed storage of strings. Should be used for per-folder data. Do not use for
- * per-message data.
- * @param key identifier for the data (e.g. "sync.key" or "folder.id")
- * @param value Data to persist. All data must be encoded into a string,
- * so use base64 or some other encoding if necessary.
- */
- public void setPersistentString(String key, String value);
-
- /**
- * @param key identifier for the data of interest
- * @return the data saved by the Folder, or defaultValue if never set.
- */
- public String getPersistentString(String key, String defaultValue);
-
- /**
- * In a single transaction: Set a key/value pair for the folder, and bulk set or clear
- * message flags. Typically used at the beginning or conclusion of a bulk sync operation.
- *
- * @param key if non-null, the transaction will set this folder persistent value
- * @param value the value that will be stored for the key
- * @param setFlags if non-null, flag(s) will be set for all messages in the folder
- * @param clearFlags if non-null, flag(s) will be cleared for all messages in the folder
- */
- public void setPersistentStringAndMessageFlags(String key, String value,
- Flag[] setFlags, Flag[] clearFlags) throws MessagingException;
- }
-
- /**
- * Callback interface by which a folder can report UID changes caused by certain operations.
- */
- public interface MessageUpdateCallbacks {
- /**
- * The operation caused the message's UID to change
- * @param message The message for which the UID changed
- * @param newUid The new UID for the message
- */
- public void onMessageUidChange(Message message, String newUid) throws MessagingException;
-
- /**
- * The operation could not be completed because the message doesn't exist
- * (for example, it was already deleted from the server side.)
- * @param message The message that does not exist
- * @throws MessagingException
- */
- public void onMessageNotFound(Message message) throws MessagingException;
- }
-
- @Override
- public String toString() {
- return getName();
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/MeetingInfo.java b/emailcommon/src/com/android/emailcommon/mail/MeetingInfo.java
deleted file mode 100644
index 1489a5597..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/MeetingInfo.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-public class MeetingInfo {
- // Predefined tags; others can be added
- public static final String MEETING_DTSTAMP = "DTSTAMP";
- public static final String MEETING_UID = "UID";
- public static final String MEETING_ORGANIZER_EMAIL = "ORGMAIL";
- public static final String MEETING_DTSTART = "DTSTART";
- public static final String MEETING_DTEND = "DTEND";
- public static final String MEETING_TITLE = "TITLE";
- public static final String MEETING_LOCATION = "LOC";
- public static final String MEETING_RESPONSE_REQUESTED = "RESPONSE";
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Message.java b/emailcommon/src/com/android/emailcommon/mail/Message.java
deleted file mode 100644
index 09aef87d1..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Message.java
+++ /dev/null
@@ -1,159 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import java.util.Date;
-import java.util.HashSet;
-
-public abstract class Message implements Part, Body {
- public static final Message[] EMPTY_ARRAY = new Message[0];
-
- public enum RecipientType {
- TO, CC, BCC,
- }
-
- protected String mUid;
-
- private HashSet<Flag> mFlags = null;
-
- protected Date mInternalDate;
-
- protected Folder mFolder;
-
- public String getUid() {
- return mUid;
- }
-
- public void setUid(String uid) {
- this.mUid = uid;
- }
-
- public Folder getFolder() {
- return mFolder;
- }
-
- public abstract String getSubject() throws MessagingException;
-
- public abstract void setSubject(String subject) throws MessagingException;
-
- public Date getInternalDate() {
- return mInternalDate;
- }
-
- public void setInternalDate(Date internalDate) {
- this.mInternalDate = internalDate;
- }
-
- public abstract Date getReceivedDate() throws MessagingException;
-
- public abstract Date getSentDate() throws MessagingException;
-
- public abstract void setSentDate(Date sentDate) throws MessagingException;
-
- public abstract Address[] getRecipients(RecipientType type) throws MessagingException;
-
- public abstract void setRecipients(RecipientType type, Address[] addresses)
- throws MessagingException;
-
- public void setRecipient(RecipientType type, Address address) throws MessagingException {
- setRecipients(type, new Address[] {
- address
- });
- }
-
- public abstract Address[] getFrom() throws MessagingException;
-
- public abstract void setFrom(Address from) throws MessagingException;
-
- public abstract Address[] getReplyTo() throws MessagingException;
-
- public abstract void setReplyTo(Address[] from) throws MessagingException;
-
- public abstract Body getBody() throws MessagingException;
-
- public abstract String getContentType() throws MessagingException;
-
- public abstract void addHeader(String name, String value) throws MessagingException;
-
- public abstract void setHeader(String name, String value) throws MessagingException;
-
- public abstract String[] getHeader(String name) throws MessagingException;
-
- public abstract void removeHeader(String name) throws MessagingException;
-
- // Always use these instead of getHeader("Message-ID") or setHeader("Message-ID");
- public abstract void setMessageId(String messageId) throws MessagingException;
- public abstract String getMessageId() throws MessagingException;
-
- public abstract void setBody(Body body) throws MessagingException;
-
- public boolean isMimeType(String mimeType) throws MessagingException {
- return getContentType().startsWith(mimeType);
- }
-
- private HashSet<Flag> getFlagSet() {
- if (mFlags == null) {
- mFlags = new HashSet<Flag>();
- }
- return mFlags;
- }
-
- /*
- * TODO Refactor Flags at some point to be able to store user defined flags.
- */
- public Flag[] getFlags() {
- return getFlagSet().toArray(new Flag[] {});
- }
-
- /**
- * Set/clear a flag directly, without involving overrides of {@link #setFlag} in subclasses.
- * Only used for testing.
- */
- public final void setFlagDirectlyForTest(Flag flag, boolean set) throws MessagingException {
- if (set) {
- getFlagSet().add(flag);
- } else {
- getFlagSet().remove(flag);
- }
- }
-
- public void setFlag(Flag flag, boolean set) throws MessagingException {
- setFlagDirectlyForTest(flag, set);
- }
-
- /**
- * This method calls setFlag(Flag, boolean)
- * @param flags
- * @param set
- */
- public void setFlags(Flag[] flags, boolean set) throws MessagingException {
- for (Flag flag : flags) {
- setFlag(flag, set);
- }
- }
-
- public boolean isSet(Flag flag) {
- return getFlagSet().contains(flag);
- }
-
- public abstract void saveChanges() throws MessagingException;
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + ':' + mUid;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/MessageDateComparator.java b/emailcommon/src/com/android/emailcommon/mail/MessageDateComparator.java
deleted file mode 100644
index 0b1a55115..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/MessageDateComparator.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import java.util.Comparator;
-
-public class MessageDateComparator implements Comparator<Message> {
- public int compare(Message o1, Message o2) {
- try {
- if (o1.getSentDate() == null) {
- return 1;
- } else if (o2.getSentDate() == null) {
- return -1;
- } else
- return o2.getSentDate().compareTo(o1.getSentDate());
- } catch (Exception e) {
- return 0;
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/MessagingException.java b/emailcommon/src/com/android/emailcommon/mail/MessagingException.java
deleted file mode 100644
index ba3cf2383..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/MessagingException.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-
-/**
- * This exception is used for most types of failures that occur during server interactions.
- *
- * Data passed through this exception should be considered non-localized. Any strings should
- * either be internal-only (for debugging) or server-generated.
- *
- * TO DO: Does it make sense to further collapse AuthenticationFailedException and
- * CertificateValidationException and any others into this?
- */
-public class MessagingException extends Exception {
- public static final long serialVersionUID = -1;
-
- public static final int NO_ERROR = -1;
- /** Any exception that does not specify a specific issue */
- public static final int UNSPECIFIED_EXCEPTION = 0;
- /** Connection or IO errors */
- public static final int IOERROR = 1;
- /** The configuration requested TLS but the server did not support it. */
- public static final int TLS_REQUIRED = 2;
- /** Authentication is required but the server did not support it. */
- public static final int AUTH_REQUIRED = 3;
- /** General security failures */
- public static final int GENERAL_SECURITY = 4;
- /** Authentication failed */
- public static final int AUTHENTICATION_FAILED = 5;
- /** Attempt to create duplicate account */
- public static final int DUPLICATE_ACCOUNT = 6;
- /** Required security policies reported - advisory only */
- public static final int SECURITY_POLICIES_REQUIRED = 7;
- /** Required security policies not supported */
- public static final int SECURITY_POLICIES_UNSUPPORTED = 8;
- /** The protocol (or protocol version) isn't supported */
- public static final int PROTOCOL_VERSION_UNSUPPORTED = 9;
- /** An SSL certificate couldn't be validated */
- public static final int CERTIFICATE_VALIDATION_ERROR = 10;
- /** Authentication failed during autodiscover */
- public static final int AUTODISCOVER_AUTHENTICATION_FAILED = 11;
- /** Autodiscover completed with a result (non-error) */
- public static final int AUTODISCOVER_AUTHENTICATION_RESULT = 12;
- /** Ambiguous failure; server error or bad credentials */
- public static final int AUTHENTICATION_FAILED_OR_SERVER_ERROR = 13;
-
- protected int mExceptionType;
-
- public MessagingException(String message) {
- super(message);
- mExceptionType = UNSPECIFIED_EXCEPTION;
- }
-
- public MessagingException(String message, Throwable throwable) {
- super(message, throwable);
- mExceptionType = UNSPECIFIED_EXCEPTION;
- }
-
- public MessagingException(int exceptionType, String message, Throwable throwable) {
- super(message, throwable);
- mExceptionType = exceptionType;
- }
-
- /**
- * Constructs a MessagingException with an exceptionType and a null message.
- * @param exceptionType The exception type to set for this exception.
- */
- public MessagingException(int exceptionType) {
- super();
- mExceptionType = exceptionType;
- }
-
- /**
- * Constructs a MessagingException with an exceptionType and a message.
- * @param exceptionType The exception type to set for this exception.
- */
- public MessagingException(int exceptionType, String message) {
- super(message);
- mExceptionType = exceptionType;
- }
-
- /**
- * Return the exception type. Will be OTHER_EXCEPTION if not explicitly set.
- *
- * @return Returns the exception type.
- */
- public int getExceptionType() {
- return mExceptionType;
- }
-} \ No newline at end of file
diff --git a/emailcommon/src/com/android/emailcommon/mail/Multipart.java b/emailcommon/src/com/android/emailcommon/mail/Multipart.java
deleted file mode 100644
index 4a1a06714..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Multipart.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import java.util.ArrayList;
-
-public abstract class Multipart implements Body {
- protected Part mParent;
-
- protected ArrayList<BodyPart> mParts = new ArrayList<BodyPart>();
-
- protected String mContentType;
-
- public void addBodyPart(BodyPart part) throws MessagingException {
- mParts.add(part);
- }
-
- public void addBodyPart(BodyPart part, int index) throws MessagingException {
- mParts.add(index, part);
- }
-
- public BodyPart getBodyPart(int index) throws MessagingException {
- return mParts.get(index);
- }
-
- public String getContentType() throws MessagingException {
- return mContentType;
- }
-
- public int getCount() throws MessagingException {
- return mParts.size();
- }
-
- public boolean removeBodyPart(BodyPart part) throws MessagingException {
- return mParts.remove(part);
- }
-
- public void removeBodyPart(int index) throws MessagingException {
- mParts.remove(index);
- }
-
- public Part getParent() throws MessagingException {
- return mParent;
- }
-
- public void setParent(Part parent) throws MessagingException {
- this.mParent = parent;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/PackedString.java b/emailcommon/src/com/android/emailcommon/mail/PackedString.java
deleted file mode 100644
index de5fe4692..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/PackedString.java
+++ /dev/null
@@ -1,176 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * A utility class for creating and modifying Strings that are tagged and packed together.
- *
- * Uses non-printable (control chars) for internal delimiters; Intended for regular displayable
- * strings only, so please use base64 or other encoding if you need to hide any binary data here.
- *
- * Binary compatible with Address.pack() format, which should migrate to use this code.
- */
-public class PackedString {
-
- /**
- * Packing format is:
- * element : [ value ] or [ value TAG-DELIMITER tag ]
- * packed-string : [ element ] [ ELEMENT-DELIMITER [ element ] ]*
- */
- private static final char DELIMITER_ELEMENT = '\1';
- private static final char DELIMITER_TAG = '\2';
-
- private String mString;
- private HashMap<String, String> mExploded;
- private static final HashMap<String, String> EMPTY_MAP = new HashMap<String, String>();
-
- /**
- * Create a packed string using an already-packed string (e.g. from database)
- * @param string packed string
- */
- public PackedString(String string) {
- mString = string;
- mExploded = null;
- }
-
- /**
- * Get the value referred to by a given tag. If the tag does not exist, return null.
- * @param tag identifier of string of interest
- * @return returns value, or null if no string is found
- */
- public String get(String tag) {
- if (mExploded == null) {
- mExploded = explode(mString);
- }
- return mExploded.get(tag);
- }
-
- /**
- * Return a map of all of the values referred to by a given tag. This is a shallow
- * copy, don't edit the values.
- * @return a map of the values in the packed string
- */
- public Map<String, String> unpack() {
- if (mExploded == null) {
- mExploded = explode(mString);
- }
- return new HashMap<String,String>(mExploded);
- }
-
- /**
- * Read out all values into a map.
- */
- private static HashMap<String, String> explode(String packed) {
- if (packed == null || packed.length() == 0) {
- return EMPTY_MAP;
- }
- HashMap<String, String> map = new HashMap<String, String>();
-
- int length = packed.length();
- int elementStartIndex = 0;
- int elementEndIndex = 0;
- int tagEndIndex = packed.indexOf(DELIMITER_TAG);
-
- while (elementStartIndex < length) {
- elementEndIndex = packed.indexOf(DELIMITER_ELEMENT, elementStartIndex);
- if (elementEndIndex == -1) {
- elementEndIndex = length;
- }
- String tag;
- String value;
- if (tagEndIndex == -1 || elementEndIndex <= tagEndIndex) {
- // in this case the DELIMITER_PERSONAL is in a future pair (or not found)
- // so synthesize a positional tag for the value, and don't update tagEndIndex
- value = packed.substring(elementStartIndex, elementEndIndex);
- tag = Integer.toString(map.size());
- } else {
- value = packed.substring(elementStartIndex, tagEndIndex);
- tag = packed.substring(tagEndIndex + 1, elementEndIndex);
- // scan forward for next tag, if any
- tagEndIndex = packed.indexOf(DELIMITER_TAG, elementEndIndex + 1);
- }
- map.put(tag, value);
- elementStartIndex = elementEndIndex + 1;
- }
-
- return map;
- }
-
- /**
- * Builder class for creating PackedString values. Can also be used for editing existing
- * PackedString representations.
- */
- static public class Builder {
- HashMap<String, String> mMap;
-
- /**
- * Create a builder that's empty (for filling)
- */
- public Builder() {
- mMap = new HashMap<String, String>();
- }
-
- /**
- * Create a builder using the values of an existing PackedString (for editing).
- */
- public Builder(String packed) {
- mMap = explode(packed);
- }
-
- /**
- * Add a tagged value
- * @param tag identifier of string of interest
- * @param value the value to record in this position. null to delete entry.
- */
- public void put(String tag, String value) {
- if (value == null) {
- mMap.remove(tag);
- } else {
- mMap.put(tag, value);
- }
- }
-
- /**
- * Get the value referred to by a given tag. If the tag does not exist, return null.
- * @param tag identifier of string of interest
- * @return returns value, or null if no string is found
- */
- public String get(String tag) {
- return mMap.get(tag);
- }
-
- /**
- * Pack the values and return a single, encoded string
- */
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- for (Map.Entry<String,String> entry : mMap.entrySet()) {
- if (sb.length() > 0) {
- sb.append(DELIMITER_ELEMENT);
- }
- sb.append(entry.getValue());
- sb.append(DELIMITER_TAG);
- sb.append(entry.getKey());
- }
- return sb.toString();
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Part.java b/emailcommon/src/com/android/emailcommon/mail/Part.java
deleted file mode 100644
index eeb233ca9..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Part.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-public interface Part extends Fetchable {
- public void addHeader(String name, String value) throws MessagingException;
-
- public void removeHeader(String name) throws MessagingException;
-
- public void setHeader(String name, String value) throws MessagingException;
-
- public Body getBody() throws MessagingException;
-
- public String getContentType() throws MessagingException;
-
- public String getDisposition() throws MessagingException;
-
- public String getContentId() throws MessagingException;
-
- public String[] getHeader(String name) throws MessagingException;
-
- public void setExtendedHeader(String name, String value) throws MessagingException;
-
- public String getExtendedHeader(String name) throws MessagingException;
-
- public int getSize() throws MessagingException;
-
- public boolean isMimeType(String mimeType) throws MessagingException;
-
- public String getMimeType() throws MessagingException;
-
- public void setBody(Body body) throws MessagingException;
-
- public void writeTo(OutputStream out) throws IOException, MessagingException;
-}
diff --git a/emailcommon/src/com/android/emailcommon/mail/Snippet.java b/emailcommon/src/com/android/emailcommon/mail/Snippet.java
deleted file mode 100644
index 38f982e5d..000000000
--- a/emailcommon/src/com/android/emailcommon/mail/Snippet.java
+++ /dev/null
@@ -1,487 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.mail;
-
-import android.text.TextUtils;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Class to generate a short 'snippet' from either plain text or html text
- *
- * If the sync protocol can get plain text, that's great, but we'll still strip out extraneous
- * whitespace. If it's HTML, we'll 1) strip out tags, 2) turn entities into the appropriate
- * characters, and 3) strip out extraneous whitespace, all in one pass
- *
- * Why not use an existing class? The best answer is performance; yet another answer is
- * correctness (e.g. Html.textFromHtml simply doesn't generate well-stripped text). But performance
- * is key; we frequently sync text that is 10K or (much) longer, yet we really only care about a
- * small amount of text for the snippet. So it's critically important that we just stop when we've
- * gotten enough; existing methods that exist will go through the entire incoming string, at great
- * (and useless) expense.
- */
-public class Snippet {
- // This is how many chars we'll allow in a snippet
- private static final int MAX_PLAIN_TEXT_SCAN_LENGTH = 200;
- // For some reason, isWhitespace() returns false with the following...
- /*package*/ static final char NON_BREAKING_SPACE_CHARACTER = (char)160;
-
- // Tags whose content must be stripped as well
- static final String[] STRIP_TAGS =
- new String[] {"title", "script", "style", "applet", "head"};
- // The number of characters we peel off for testing against STRIP_TAGS
- static final int STRIP_TAG_LENGTH = 6;
-
- static final Map<String, Character> ESCAPE_STRINGS;
- static {
- // HTML character entity references as defined in HTML 4
- // see http://www.w3.org/TR/REC-html40/sgml/entities.html
- ESCAPE_STRINGS = new HashMap<String, Character>(252);
-
- ESCAPE_STRINGS.put("&nbsp", '\u00A0');
- ESCAPE_STRINGS.put("&iexcl", '\u00A1');
- ESCAPE_STRINGS.put("&cent", '\u00A2');
- ESCAPE_STRINGS.put("&pound", '\u00A3');
- ESCAPE_STRINGS.put("&curren", '\u00A4');
- ESCAPE_STRINGS.put("&yen", '\u00A5');
- ESCAPE_STRINGS.put("&brvbar", '\u00A6');
- ESCAPE_STRINGS.put("&sect", '\u00A7');
- ESCAPE_STRINGS.put("&uml", '\u00A8');
- ESCAPE_STRINGS.put("&copy", '\u00A9');
- ESCAPE_STRINGS.put("&ordf", '\u00AA');
- ESCAPE_STRINGS.put("&laquo", '\u00AB');
- ESCAPE_STRINGS.put("&not", '\u00AC');
- ESCAPE_STRINGS.put("&shy", '\u00AD');
- ESCAPE_STRINGS.put("&reg", '\u00AE');
- ESCAPE_STRINGS.put("&macr", '\u00AF');
- ESCAPE_STRINGS.put("&deg", '\u00B0');
- ESCAPE_STRINGS.put("&plusmn", '\u00B1');
- ESCAPE_STRINGS.put("&sup2", '\u00B2');
- ESCAPE_STRINGS.put("&sup3", '\u00B3');
- ESCAPE_STRINGS.put("&acute", '\u00B4');
- ESCAPE_STRINGS.put("&micro", '\u00B5');
- ESCAPE_STRINGS.put("&para", '\u00B6');
- ESCAPE_STRINGS.put("&middot", '\u00B7');
- ESCAPE_STRINGS.put("&cedil", '\u00B8');
- ESCAPE_STRINGS.put("&sup1", '\u00B9');
- ESCAPE_STRINGS.put("&ordm", '\u00BA');
- ESCAPE_STRINGS.put("&raquo", '\u00BB');
- ESCAPE_STRINGS.put("&frac14", '\u00BC');
- ESCAPE_STRINGS.put("&frac12", '\u00BD');
- ESCAPE_STRINGS.put("&frac34", '\u00BE');
- ESCAPE_STRINGS.put("&iquest", '\u00BF');
- ESCAPE_STRINGS.put("&Agrave", '\u00C0');
- ESCAPE_STRINGS.put("&Aacute", '\u00C1');
- ESCAPE_STRINGS.put("&Acirc", '\u00C2');
- ESCAPE_STRINGS.put("&Atilde", '\u00C3');
- ESCAPE_STRINGS.put("&Auml", '\u00C4');
- ESCAPE_STRINGS.put("&Aring", '\u00C5');
- ESCAPE_STRINGS.put("&AElig", '\u00C6');
- ESCAPE_STRINGS.put("&Ccedil", '\u00C7');
- ESCAPE_STRINGS.put("&Egrave", '\u00C8');
- ESCAPE_STRINGS.put("&Eacute", '\u00C9');
- ESCAPE_STRINGS.put("&Ecirc", '\u00CA');
- ESCAPE_STRINGS.put("&Euml", '\u00CB');
- ESCAPE_STRINGS.put("&Igrave", '\u00CC');
- ESCAPE_STRINGS.put("&Iacute", '\u00CD');
- ESCAPE_STRINGS.put("&Icirc", '\u00CE');
- ESCAPE_STRINGS.put("&Iuml", '\u00CF');
- ESCAPE_STRINGS.put("&ETH", '\u00D0');
- ESCAPE_STRINGS.put("&Ntilde", '\u00D1');
- ESCAPE_STRINGS.put("&Ograve", '\u00D2');
- ESCAPE_STRINGS.put("&Oacute", '\u00D3');
- ESCAPE_STRINGS.put("&Ocirc", '\u00D4');
- ESCAPE_STRINGS.put("&Otilde", '\u00D5');
- ESCAPE_STRINGS.put("&Ouml", '\u00D6');
- ESCAPE_STRINGS.put("&times", '\u00D7');
- ESCAPE_STRINGS.put("&Oslash", '\u00D8');
- ESCAPE_STRINGS.put("&Ugrave", '\u00D9');
- ESCAPE_STRINGS.put("&Uacute", '\u00DA');
- ESCAPE_STRINGS.put("&Ucirc", '\u00DB');
- ESCAPE_STRINGS.put("&Uuml", '\u00DC');
- ESCAPE_STRINGS.put("&Yacute", '\u00DD');
- ESCAPE_STRINGS.put("&THORN", '\u00DE');
- ESCAPE_STRINGS.put("&szlig", '\u00DF');
- ESCAPE_STRINGS.put("&agrave", '\u00E0');
- ESCAPE_STRINGS.put("&aacute", '\u00E1');
- ESCAPE_STRINGS.put("&acirc", '\u00E2');
- ESCAPE_STRINGS.put("&atilde", '\u00E3');
- ESCAPE_STRINGS.put("&auml", '\u00E4');
- ESCAPE_STRINGS.put("&aring", '\u00E5');
- ESCAPE_STRINGS.put("&aelig", '\u00E6');
- ESCAPE_STRINGS.put("&ccedil", '\u00E7');
- ESCAPE_STRINGS.put("&egrave", '\u00E8');
- ESCAPE_STRINGS.put("&eacute", '\u00E9');
- ESCAPE_STRINGS.put("&ecirc", '\u00EA');
- ESCAPE_STRINGS.put("&euml", '\u00EB');
- ESCAPE_STRINGS.put("&igrave", '\u00EC');
- ESCAPE_STRINGS.put("&iacute", '\u00ED');
- ESCAPE_STRINGS.put("&icirc", '\u00EE');
- ESCAPE_STRINGS.put("&iuml", '\u00EF');
- ESCAPE_STRINGS.put("&eth", '\u00F0');
- ESCAPE_STRINGS.put("&ntilde", '\u00F1');
- ESCAPE_STRINGS.put("&ograve", '\u00F2');
- ESCAPE_STRINGS.put("&oacute", '\u00F3');
- ESCAPE_STRINGS.put("&ocirc", '\u00F4');
- ESCAPE_STRINGS.put("&otilde", '\u00F5');
- ESCAPE_STRINGS.put("&ouml", '\u00F6');
- ESCAPE_STRINGS.put("&divide", '\u00F7');
- ESCAPE_STRINGS.put("&oslash", '\u00F8');
- ESCAPE_STRINGS.put("&ugrave", '\u00F9');
- ESCAPE_STRINGS.put("&uacute", '\u00FA');
- ESCAPE_STRINGS.put("&ucirc", '\u00FB');
- ESCAPE_STRINGS.put("&uuml", '\u00FC');
- ESCAPE_STRINGS.put("&yacute", '\u00FD');
- ESCAPE_STRINGS.put("&thorn", '\u00FE');
- ESCAPE_STRINGS.put("&yuml", '\u00FF');
- ESCAPE_STRINGS.put("&fnof", '\u0192');
- ESCAPE_STRINGS.put("&Alpha", '\u0391');
- ESCAPE_STRINGS.put("&Beta", '\u0392');
- ESCAPE_STRINGS.put("&Gamma", '\u0393');
- ESCAPE_STRINGS.put("&Delta", '\u0394');
- ESCAPE_STRINGS.put("&Epsilon", '\u0395');
- ESCAPE_STRINGS.put("&Zeta", '\u0396');
- ESCAPE_STRINGS.put("&Eta", '\u0397');
- ESCAPE_STRINGS.put("&Theta", '\u0398');
- ESCAPE_STRINGS.put("&Iota", '\u0399');
- ESCAPE_STRINGS.put("&Kappa", '\u039A');
- ESCAPE_STRINGS.put("&Lambda", '\u039B');
- ESCAPE_STRINGS.put("&Mu", '\u039C');
- ESCAPE_STRINGS.put("&Nu", '\u039D');
- ESCAPE_STRINGS.put("&Xi", '\u039E');
- ESCAPE_STRINGS.put("&Omicron", '\u039F');
- ESCAPE_STRINGS.put("&Pi", '\u03A0');
- ESCAPE_STRINGS.put("&Rho", '\u03A1');
- ESCAPE_STRINGS.put("&Sigma", '\u03A3');
- ESCAPE_STRINGS.put("&Tau", '\u03A4');
- ESCAPE_STRINGS.put("&Upsilon", '\u03A5');
- ESCAPE_STRINGS.put("&Phi", '\u03A6');
- ESCAPE_STRINGS.put("&Chi", '\u03A7');
- ESCAPE_STRINGS.put("&Psi", '\u03A8');
- ESCAPE_STRINGS.put("&Omega", '\u03A9');
- ESCAPE_STRINGS.put("&alpha", '\u03B1');
- ESCAPE_STRINGS.put("&beta", '\u03B2');
- ESCAPE_STRINGS.put("&gamma", '\u03B3');
- ESCAPE_STRINGS.put("&delta", '\u03B4');
- ESCAPE_STRINGS.put("&epsilon", '\u03B5');
- ESCAPE_STRINGS.put("&zeta", '\u03B6');
- ESCAPE_STRINGS.put("&eta", '\u03B7');
- ESCAPE_STRINGS.put("&theta", '\u03B8');
- ESCAPE_STRINGS.put("&iota", '\u03B9');
- ESCAPE_STRINGS.put("&kappa", '\u03BA');
- ESCAPE_STRINGS.put("&lambda", '\u03BB');
- ESCAPE_STRINGS.put("&mu", '\u03BC');
- ESCAPE_STRINGS.put("&nu", '\u03BD');
- ESCAPE_STRINGS.put("&xi", '\u03BE');
- ESCAPE_STRINGS.put("&omicron", '\u03BF');
- ESCAPE_STRINGS.put("&pi", '\u03C0');
- ESCAPE_STRINGS.put("&rho", '\u03C1');
- ESCAPE_STRINGS.put("&sigmaf", '\u03C2');
- ESCAPE_STRINGS.put("&sigma", '\u03C3');
- ESCAPE_STRINGS.put("&tau", '\u03C4');
- ESCAPE_STRINGS.put("&upsilon", '\u03C5');
- ESCAPE_STRINGS.put("&phi", '\u03C6');
- ESCAPE_STRINGS.put("&chi", '\u03C7');
- ESCAPE_STRINGS.put("&psi", '\u03C8');
- ESCAPE_STRINGS.put("&omega", '\u03C9');
- ESCAPE_STRINGS.put("&thetasym", '\u03D1');
- ESCAPE_STRINGS.put("&upsih", '\u03D2');
- ESCAPE_STRINGS.put("&piv", '\u03D6');
- ESCAPE_STRINGS.put("&bull", '\u2022');
- ESCAPE_STRINGS.put("&hellip", '\u2026');
- ESCAPE_STRINGS.put("&prime", '\u2032');
- ESCAPE_STRINGS.put("&Prime", '\u2033');
- ESCAPE_STRINGS.put("&oline", '\u203E');
- ESCAPE_STRINGS.put("&frasl", '\u2044');
- ESCAPE_STRINGS.put("&weierp", '\u2118');
- ESCAPE_STRINGS.put("&image", '\u2111');
- ESCAPE_STRINGS.put("&real", '\u211C');
- ESCAPE_STRINGS.put("&trade", '\u2122');
- ESCAPE_STRINGS.put("&alefsym", '\u2135');
- ESCAPE_STRINGS.put("&larr", '\u2190');
- ESCAPE_STRINGS.put("&uarr", '\u2191');
- ESCAPE_STRINGS.put("&rarr", '\u2192');
- ESCAPE_STRINGS.put("&darr", '\u2193');
- ESCAPE_STRINGS.put("&harr", '\u2194');
- ESCAPE_STRINGS.put("&crarr", '\u21B5');
- ESCAPE_STRINGS.put("&lArr", '\u21D0');
- ESCAPE_STRINGS.put("&uArr", '\u21D1');
- ESCAPE_STRINGS.put("&rArr", '\u21D2');
- ESCAPE_STRINGS.put("&dArr", '\u21D3');
- ESCAPE_STRINGS.put("&hArr", '\u21D4');
- ESCAPE_STRINGS.put("&forall", '\u2200');
- ESCAPE_STRINGS.put("&part", '\u2202');
- ESCAPE_STRINGS.put("&exist", '\u2203');
- ESCAPE_STRINGS.put("&empty", '\u2205');
- ESCAPE_STRINGS.put("&nabla", '\u2207');
- ESCAPE_STRINGS.put("&isin", '\u2208');
- ESCAPE_STRINGS.put("&notin", '\u2209');
- ESCAPE_STRINGS.put("&ni", '\u220B');
- ESCAPE_STRINGS.put("&prod", '\u220F');
- ESCAPE_STRINGS.put("&sum", '\u2211');
- ESCAPE_STRINGS.put("&minus", '\u2212');
- ESCAPE_STRINGS.put("&lowast", '\u2217');
- ESCAPE_STRINGS.put("&radic", '\u221A');
- ESCAPE_STRINGS.put("&prop", '\u221D');
- ESCAPE_STRINGS.put("&infin", '\u221E');
- ESCAPE_STRINGS.put("&ang", '\u2220');
- ESCAPE_STRINGS.put("&and", '\u2227');
- ESCAPE_STRINGS.put("&or", '\u2228');
- ESCAPE_STRINGS.put("&cap", '\u2229');
- ESCAPE_STRINGS.put("&cup", '\u222A');
- ESCAPE_STRINGS.put("&int", '\u222B');
- ESCAPE_STRINGS.put("&there4", '\u2234');
- ESCAPE_STRINGS.put("&sim", '\u223C');
- ESCAPE_STRINGS.put("&cong", '\u2245');
- ESCAPE_STRINGS.put("&asymp", '\u2248');
- ESCAPE_STRINGS.put("&ne", '\u2260');
- ESCAPE_STRINGS.put("&equiv", '\u2261');
- ESCAPE_STRINGS.put("&le", '\u2264');
- ESCAPE_STRINGS.put("&ge", '\u2265');
- ESCAPE_STRINGS.put("&sub", '\u2282');
- ESCAPE_STRINGS.put("&sup", '\u2283');
- ESCAPE_STRINGS.put("&nsub", '\u2284');
- ESCAPE_STRINGS.put("&sube", '\u2286');
- ESCAPE_STRINGS.put("&supe", '\u2287');
- ESCAPE_STRINGS.put("&oplus", '\u2295');
- ESCAPE_STRINGS.put("&otimes", '\u2297');
- ESCAPE_STRINGS.put("&perp", '\u22A5');
- ESCAPE_STRINGS.put("&sdot", '\u22C5');
- ESCAPE_STRINGS.put("&lceil", '\u2308');
- ESCAPE_STRINGS.put("&rceil", '\u2309');
- ESCAPE_STRINGS.put("&lfloor", '\u230A');
- ESCAPE_STRINGS.put("&rfloor", '\u230B');
- ESCAPE_STRINGS.put("&lang", '\u2329');
- ESCAPE_STRINGS.put("&rang", '\u232A');
- ESCAPE_STRINGS.put("&loz", '\u25CA');
- ESCAPE_STRINGS.put("&spades", '\u2660');
- ESCAPE_STRINGS.put("&clubs", '\u2663');
- ESCAPE_STRINGS.put("&hearts", '\u2665');
- ESCAPE_STRINGS.put("&diams", '\u2666');
- ESCAPE_STRINGS.put("&quot", '\u0022');
- ESCAPE_STRINGS.put("&amp", '\u0026');
- ESCAPE_STRINGS.put("&lt", '\u003C');
- ESCAPE_STRINGS.put("&gt", '\u003E');
- ESCAPE_STRINGS.put("&OElig", '\u0152');
- ESCAPE_STRINGS.put("&oelig", '\u0153');
- ESCAPE_STRINGS.put("&Scaron", '\u0160');
- ESCAPE_STRINGS.put("&scaron", '\u0161');
- ESCAPE_STRINGS.put("&Yuml", '\u0178');
- ESCAPE_STRINGS.put("&circ", '\u02C6');
- ESCAPE_STRINGS.put("&tilde", '\u02DC');
- ESCAPE_STRINGS.put("&ensp", '\u2002');
- ESCAPE_STRINGS.put("&emsp", '\u2003');
- ESCAPE_STRINGS.put("&thinsp", '\u2009');
- ESCAPE_STRINGS.put("&zwnj", '\u200C');
- ESCAPE_STRINGS.put("&zwj", '\u200D');
- ESCAPE_STRINGS.put("&lrm", '\u200E');
- ESCAPE_STRINGS.put("&rlm", '\u200F');
- ESCAPE_STRINGS.put("&ndash", '\u2013');
- ESCAPE_STRINGS.put("&mdash", '\u2014');
- ESCAPE_STRINGS.put("&lsquo", '\u2018');
- ESCAPE_STRINGS.put("&rsquo", '\u2019');
- ESCAPE_STRINGS.put("&sbquo", '\u201A');
- ESCAPE_STRINGS.put("&ldquo", '\u201C');
- ESCAPE_STRINGS.put("&rdquo", '\u201D');
- ESCAPE_STRINGS.put("&bdquo", '\u201E');
- ESCAPE_STRINGS.put("&dagger", '\u2020');
- ESCAPE_STRINGS.put("&Dagger", '\u2021');
- ESCAPE_STRINGS.put("&permil", '\u2030');
- ESCAPE_STRINGS.put("&lsaquo", '\u2039');
- ESCAPE_STRINGS.put("&rsaquo", '\u203A');
- ESCAPE_STRINGS.put("&euro", '\u20AC');
- }
-
- public static String fromHtmlText(String text) {
- return fromText(text, true);
- }
-
- public static String fromPlainText(String text) {
- return fromText(text, false);
- }
-
- /**
- * Find the end of this tag; there are two alternatives: <tag .../> or <tag ...> ... </tag>
- * @param htmlText some HTML text
- * @param tag the HTML tag
- * @param startPos the start position in the HTML text where the tag starts
- * @return the position just before the end of the tag or -1 if not found
- */
- /*package*/ static int findTagEnd(String htmlText, String tag, int startPos) {
- if (tag.endsWith(" ")) {
- tag = tag.substring(0, tag.length() - 1);
- }
- int length = htmlText.length();
- char prevChar = 0;
- for (int i = startPos; i < length; i++) {
- char c = htmlText.charAt(i);
- if (c == '>') {
- if (prevChar == '/') {
- return i - 1;
- }
- break;
- }
- prevChar = c;
- }
- // We didn't find /> at the end of the tag so find </tag>
- return htmlText.indexOf("/" + tag, startPos);
- }
-
- public static String fromText(String text, boolean stripHtml) {
- // Handle null and empty string
- if (TextUtils.isEmpty(text)) return "";
-
- final int length = text.length();
- // Use char[] instead of StringBuilder purely for performance; fewer method calls, etc.
- char[] buffer = new char[MAX_PLAIN_TEXT_SCAN_LENGTH];
- // skipCount is an array of a single int; that int is set inside stripHtmlEntity and is
- // used to determine how many characters can be "skipped" due to the transformation of the
- // entity to a single character. When Java allows multiple return values, we can make this
- // much cleaner :-)
- int[] skipCount = new int[1];
- int bufferCount = 0;
- // Start with space as last character to avoid leading whitespace
- char last = ' ';
- // Indicates whether we're in the middle of an HTML tag
- boolean inTag = false;
-
- // Walk through the text until we're done with the input OR we've got a large enough snippet
- for (int i = 0; i < length && bufferCount < MAX_PLAIN_TEXT_SCAN_LENGTH; i++) {
- char c = text.charAt(i);
- if (stripHtml && !inTag && (c == '<')) {
- // Find tags to strip; they will begin with <! or !- or </ or <letter
- if (i < (length - 1)) {
- char peek = text.charAt(i + 1);
- if (peek == '!' || peek == '-' || peek == '/' || Character.isLetter(peek)) {
- inTag = true;
- // Strip content of title, script, style and applet tags
- if (i < (length - (STRIP_TAG_LENGTH + 2))) {
- String tag = text.substring(i + 1, i + STRIP_TAG_LENGTH + 1);
- String tagLowerCase = tag.toLowerCase();
- boolean stripContent = false;
- for (String stripTag: STRIP_TAGS) {
- if (tagLowerCase.startsWith(stripTag)) {
- stripContent = true;
- tag = tag.substring(0, stripTag.length());
- break;
- }
- }
- if (stripContent) {
- // Look for the end of this tag
- int endTagPosition = findTagEnd(text, tag, i);
- if (endTagPosition < 0) {
- break;
- } else {
- i = endTagPosition;
- }
- }
- }
- }
- }
- } else if (stripHtml && inTag && (c == '>')) {
- // Terminate stripping here
- inTag = false;
- continue;
- }
-
- if (inTag) {
- // We just skip by everything while we're in a tag
- continue;
- } else if (stripHtml && (c == '&')) {
- // Handle a possible HTML entity here
- // We always get back a character to use; we also get back a "skip count",
- // indicating how many characters were eaten from the entity
- c = stripHtmlEntity(text, i, skipCount);
- i += skipCount[0];
- }
-
- if (Character.isWhitespace(c) || (c == NON_BREAKING_SPACE_CHARACTER)) {
- // The idea is to find the content in the message, not the whitespace, so we'll
- // turn any combination of contiguous whitespace into a single space
- if (last == ' ') {
- continue;
- } else {
- // Make every whitespace character a simple space
- c = ' ';
- }
- } else if ((c == '-' || c == '=') && (last == c)) {
- // Lots of messages (especially digests) have whole lines of --- or ===
- // We'll get rid of those duplicates here
- continue;
- }
-
- // After all that, maybe we've got a character for our snippet
- buffer[bufferCount++] = c;
- last = c;
- }
-
- // Lose trailing space and return our snippet
- if ((bufferCount > 0) && (last == ' ')) {
- bufferCount--;
- }
- return new String(buffer, 0, bufferCount);
- }
-
- static /*package*/ char stripHtmlEntity(String text, int pos, int[] skipCount) {
- int length = text.length();
- // Ugly, but we store our skip count in this array; we can't use a static here, because
- // multiple threads might be calling in
- skipCount[0] = 0;
- // All entities are <= 8 characters long, so that's how far we'll look for one (+ & and ;)
- int end = pos + 10;
- String entity = null;
- // Isolate the entity
- for (int i = pos; (i < length) && (i < end); i++) {
- if (text.charAt(i) == ';') {
- entity = text.substring(pos, i);
- break;
- }
- }
- if (entity == null) {
- // This wasn't really an HTML entity
- return '&';
- } else {
- // Skip count is the length of the entity
- Character mapping = ESCAPE_STRINGS.get(entity);
- int entityLength = entity.length();
- if (mapping != null) {
- skipCount[0] = entityLength;
- return mapping;
- } else if ((entityLength > 2) && (entity.charAt(1) == '#')) {
- // &#nn; means ascii nn (decimal) and &#xnn means ascii nn (hex)
- char c = '?';
- try {
- int i;
- if ((entity.charAt(2) == 'x') && (entityLength > 3)) {
- i = Integer.parseInt(entity.substring(3), 16);
- } else {
- i = Integer.parseInt(entity.substring(2));
- }
- c = (char)i;
- } catch (NumberFormatException e) {
- // We'll just return the ? in this case
- }
- skipCount[0] = entityLength;
- return c;
- }
- }
- // Worst case, we return the original start character, ampersand
- return '&';
- }
-
-}
diff --git a/emailcommon/src/com/android/emailcommon/provider/EmailContent.aidl b/emailcommon/src/com/android/emailcommon/provider/EmailContent.aidl
deleted file mode 100644
index 7505fa6f9..000000000
--- a/emailcommon/src/com/android/emailcommon/provider/EmailContent.aidl
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright (C) 2008-2009 Marc Blank
- * Licensed to The Android Open Source Project.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.provider;
-
-parcelable EmailContent.HostAuth;
-
diff --git a/emailcommon/src/com/android/emailcommon/provider/EmailContent.java b/emailcommon/src/com/android/emailcommon/provider/EmailContent.java
deleted file mode 100644
index f17390e56..000000000
--- a/emailcommon/src/com/android/emailcommon/provider/EmailContent.java
+++ /dev/null
@@ -1,2870 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.provider;
-
-import com.android.emailcommon.mail.Snippet;
-import com.android.emailcommon.utility.Utility;
-
-import android.content.ContentProviderOperation;
-import android.content.ContentProviderResult;
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.OperationApplicationException;
-import android.database.Cursor;
-import android.net.Uri;
-import android.os.Environment;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.os.RemoteException;
-import android.text.TextUtils;
-
-import java.io.File;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.security.InvalidParameterException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-
-
-/**
- * EmailContent is the superclass of the various classes of content stored by EmailProvider.
- *
- * It is intended to include 1) column definitions for use with the Provider, and 2) convenience
- * methods for saving and retrieving content from the Provider.
- *
- * This class will be used by 1) the Email process (which includes the application and
- * EmaiLProvider) as well as 2) the Exchange process (which runs independently). It will
- * necessarily be cloned for use in these two cases.
- *
- * Conventions used in naming columns:
- * RECORD_ID is the primary key for all Email records
- * The SyncColumns interface is used by all classes that are synced to the server directly
- * (Mailbox and Email)
- *
- * <name>_KEY always refers to a foreign key
- * <name>_ID always refers to a unique identifier (whether on client, server, etc.)
- *
- */
-public abstract class EmailContent {
-
- public static final String AUTHORITY = "com.android.email.provider";
- // The notifier authority is used to send notifications regarding changes to messages (insert,
- // delete, or update) and is intended as an optimization for use by clients of message list
- // cursors (initially, the email AppWidget).
- public static final String NOTIFIER_AUTHORITY = "com.android.email.notifier";
-
- public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
- public static final String PARAMETER_LIMIT = "limit";
-
- public static final Uri CONTENT_NOTIFIER_URI = Uri.parse("content://" + NOTIFIER_AUTHORITY);
-
- public static final String PROVIDER_PERMISSION = "com.android.email.permission.ACCESS_PROVIDER";
-
- // All classes share this
- public static final String RECORD_ID = "_id";
-
- public static final String[] COUNT_COLUMNS = new String[]{"count(*)"};
-
- /**
- * This projection can be used with any of the EmailContent classes, when all you need
- * is a list of id's. Use ID_PROJECTION_COLUMN to access the row data.
- */
- public static final String[] ID_PROJECTION = new String[] {
- RECORD_ID
- };
- public static final int ID_PROJECTION_COLUMN = 0;
-
- public static final String ID_SELECTION = RECORD_ID + " =?";
-
- public static final String FIELD_COLUMN_NAME = "field";
- public static final String ADD_COLUMN_NAME = "add";
-
- // Newly created objects get this id
- public static final int NOT_SAVED = -1;
- // The base Uri that this piece of content came from
- public Uri mBaseUri;
- // Lazily initialized uri for this Content
- private Uri mUri = null;
- // The id of the Content
- public long mId = NOT_SAVED;
-
- // Write the Content into a ContentValues container
- public abstract ContentValues toContentValues();
- // Read the Content from a ContentCursor
- public abstract void restore (Cursor cursor);
-
- // The Uri is lazily initialized
- public Uri getUri() {
- if (mUri == null) {
- mUri = ContentUris.withAppendedId(mBaseUri, mId);
- }
- return mUri;
- }
-
- public boolean isSaved() {
- return mId != NOT_SAVED;
- }
-
- // The Content sub class must have a no-arg constructor
- static public <T extends EmailContent> T getContent(Cursor cursor, Class<T> klass) {
- try {
- T content = klass.newInstance();
- content.mId = cursor.getLong(0);
- content.restore(cursor);
- return content;
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- public Uri save(Context context) {
- if (isSaved()) {
- throw new UnsupportedOperationException();
- }
- Uri res = context.getContentResolver().insert(mBaseUri, toContentValues());
- mId = Long.parseLong(res.getPathSegments().get(1));
- return res;
- }
-
- public int update(Context context, ContentValues contentValues) {
- if (!isSaved()) {
- throw new UnsupportedOperationException();
- }
- return context.getContentResolver().update(getUri(), contentValues, null, null);
- }
-
- static public int update(Context context, Uri baseUri, long id, ContentValues contentValues) {
- return context.getContentResolver()
- .update(ContentUris.withAppendedId(baseUri, id), contentValues, null, null);
- }
-
- static public int delete(Context context, Uri baseUri, long id) {
- return context.getContentResolver()
- .delete(ContentUris.withAppendedId(baseUri, id), null, null);
- }
-
- /**
- * Generic count method that can be used for any ContentProvider
- *
- * @param context the calling Context
- * @param uri the Uri for the provider query
- * @param selection as with a query call
- * @param selectionArgs as with a query call
- * @return the number of items matching the query (or zero)
- */
- static public int count(Context context, Uri uri, String selection, String[] selectionArgs) {
- return Utility.getFirstRowLong(context,
- uri, COUNT_COLUMNS, selection, selectionArgs, null, 0, Long.valueOf(0)).intValue();
- }
-
- /**
- * Same as {@link #count(Context, Uri, String, String[])} without selection.
- */
- static public int count(Context context, Uri uri) {
- return count(context, uri, null, null);
- }
-
- static public Uri uriWithLimit(Uri uri, int limit) {
- return uri.buildUpon().appendQueryParameter(EmailContent.PARAMETER_LIMIT,
- Integer.toString(limit)).build();
- }
-
- /**
- * no public constructor since this is a utility class
- */
- private EmailContent() {
- }
-
- public interface SyncColumns {
- public static final String ID = "_id";
- // source id (string) : the source's name of this item
- public static final String SERVER_ID = "syncServerId";
- // source's timestamp (long) for this item
- public static final String SERVER_TIMESTAMP = "syncServerTimeStamp";
- }
-
- public interface BodyColumns {
- public static final String ID = "_id";
- // Foreign key to the message corresponding to this body
- public static final String MESSAGE_KEY = "messageKey";
- // The html content itself
- public static final String HTML_CONTENT = "htmlContent";
- // The plain text content itself
- public static final String TEXT_CONTENT = "textContent";
- // Replied-to or forwarded body (in html form)
- public static final String HTML_REPLY = "htmlReply";
- // Replied-to or forwarded body (in text form)
- public static final String TEXT_REPLY = "textReply";
- // A reference to a message's unique id used in reply/forward.
- // Protocol code can be expected to use this column in determining whether a message can be
- // deleted safely (i.e. isn't referenced by other messages)
- public static final String SOURCE_MESSAGE_KEY = "sourceMessageKey";
- // The text to be placed between a reply/forward response and the original message
- public static final String INTRO_TEXT = "introText";
- }
-
- public static final class Body extends EmailContent implements BodyColumns {
- public static final String TABLE_NAME = "Body";
-
- @SuppressWarnings("hiding")
- public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/body");
-
- public static final int CONTENT_ID_COLUMN = 0;
- public static final int CONTENT_MESSAGE_KEY_COLUMN = 1;
- public static final int CONTENT_HTML_CONTENT_COLUMN = 2;
- public static final int CONTENT_TEXT_CONTENT_COLUMN = 3;
- public static final int CONTENT_HTML_REPLY_COLUMN = 4;
- public static final int CONTENT_TEXT_REPLY_COLUMN = 5;
- public static final int CONTENT_SOURCE_KEY_COLUMN = 6;
- public static final int CONTENT_INTRO_TEXT_COLUMN = 7;
- public static final String[] CONTENT_PROJECTION = new String[] {
- RECORD_ID, BodyColumns.MESSAGE_KEY, BodyColumns.HTML_CONTENT, BodyColumns.TEXT_CONTENT,
- BodyColumns.HTML_REPLY, BodyColumns.TEXT_REPLY, BodyColumns.SOURCE_MESSAGE_KEY,
- BodyColumns.INTRO_TEXT
- };
-
- public static final String[] COMMON_PROJECTION_TEXT = new String[] {
- RECORD_ID, BodyColumns.TEXT_CONTENT
- };
- public static final String[] COMMON_PROJECTION_HTML = new String[] {
- RECORD_ID, BodyColumns.HTML_CONTENT
- };
- public static final String[] COMMON_PROJECTION_REPLY_TEXT = new String[] {
- RECORD_ID, BodyColumns.TEXT_REPLY
- };
- public static final String[] COMMON_PROJECTION_REPLY_HTML = new String[] {
- RECORD_ID, BodyColumns.HTML_REPLY
- };
- public static final String[] COMMON_PROJECTION_INTRO = new String[] {
- RECORD_ID, BodyColumns.INTRO_TEXT
- };
- public static final String[] COMMON_PROJECTION_SOURCE = new String[] {
- RECORD_ID, BodyColumns.SOURCE_MESSAGE_KEY
- };
- public static final int COMMON_PROJECTION_COLUMN_TEXT = 1;
-
- private static final String[] PROJECTION_SOURCE_KEY =
- new String[] { BodyColumns.SOURCE_MESSAGE_KEY };
-
- public long mMessageKey;
- public String mHtmlContent;
- public String mTextContent;
- public String mHtmlReply;
- public String mTextReply;
- public long mSourceKey;
- public String mIntroText;
-
- public Body() {
- mBaseUri = CONTENT_URI;
- }
-
- @Override
- public ContentValues toContentValues() {
- ContentValues values = new ContentValues();
-
- // Assign values for each row.
- values.put(BodyColumns.MESSAGE_KEY, mMessageKey);
- values.put(BodyColumns.HTML_CONTENT, mHtmlContent);
- values.put(BodyColumns.TEXT_CONTENT, mTextContent);
- values.put(BodyColumns.HTML_REPLY, mHtmlReply);
- values.put(BodyColumns.TEXT_REPLY, mTextReply);
- values.put(BodyColumns.SOURCE_MESSAGE_KEY, mSourceKey);
- values.put(BodyColumns.INTRO_TEXT, mIntroText);
- return values;
- }
-
- private static Body restoreBodyWithCursor(Cursor cursor) {
- try {
- if (cursor.moveToFirst()) {
- return getContent(cursor, Body.class);
- } else {
- return null;
- }
- } finally {
- cursor.close();
- }
- }
-
- public static Body restoreBodyWithId(Context context, long id) {
- Uri u = ContentUris.withAppendedId(Body.CONTENT_URI, id);
- Cursor c = context.getContentResolver().query(u, Body.CONTENT_PROJECTION,
- null, null, null);
- return restoreBodyWithCursor(c);
- }
-
- public static Body restoreBodyWithMessageId(Context context, long messageId) {
- Cursor c = context.getContentResolver().query(Body.CONTENT_URI,
- Body.CONTENT_PROJECTION, Body.MESSAGE_KEY + "=?",
- new String[] {Long.toString(messageId)}, null);
- return restoreBodyWithCursor(c);
- }
-
- /**
- * Returns the bodyId for the given messageId, or -1 if no body is found.
- */
- public static long lookupBodyIdWithMessageId(Context context, long messageId) {
- return Utility.getFirstRowLong(context, Body.CONTENT_URI,
- ID_PROJECTION, Body.MESSAGE_KEY + "=?",
- new String[] {Long.toString(messageId)}, null, ID_PROJECTION_COLUMN,
- Long.valueOf(-1));
- }
-
- /**
- * Updates the Body for a messageId with the given ContentValues.
- * If the message has no body, a new body is inserted for the message.
- * Warning: the argument "values" is modified by this method, setting MESSAGE_KEY.
- */
- public static void updateBodyWithMessageId(Context context, long messageId,
- ContentValues values) {
- ContentResolver resolver = context.getContentResolver();
- long bodyId = lookupBodyIdWithMessageId(context, messageId);
- values.put(BodyColumns.MESSAGE_KEY, messageId);
- if (bodyId == -1) {
- resolver.insert(CONTENT_URI, values);
- } else {
- final Uri uri = ContentUris.withAppendedId(CONTENT_URI, bodyId);
- resolver.update(uri, values, null, null);
- }
- }
-
- public static long restoreBodySourceKey(Context context, long messageId) {
- return Utility.getFirstRowLong(context, Body.CONTENT_URI,
- Body.PROJECTION_SOURCE_KEY,
- Body.MESSAGE_KEY + "=?", new String[] {Long.toString(messageId)}, null, 0,
- Long.valueOf(0));
- }
-
- private static String restoreTextWithMessageId(Context context, long messageId,
- String[] projection) {
- Cursor c = context.getContentResolver().query(Body.CONTENT_URI, projection,
- Body.MESSAGE_KEY + "=?", new String[] {Long.toString(messageId)}, null);
- try {
- if (c.moveToFirst()) {
- return c.getString(COMMON_PROJECTION_COLUMN_TEXT);
- } else {
- return null;
- }
- } finally {
- c.close();
- }
- }
-
- public static String restoreBodyTextWithMessageId(Context context, long messageId) {
- return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_TEXT);
- }
-
- public static String restoreBodyHtmlWithMessageId(Context context, long messageId) {
- return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_HTML);
- }
-
- public static String restoreReplyTextWithMessageId(Context context, long messageId) {
- return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_REPLY_TEXT);
- }
-
- public static String restoreReplyHtmlWithMessageId(Context context, long messageId) {
- return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_REPLY_HTML);
- }
-
- public static String restoreIntroTextWithMessageId(Context context, long messageId) {
- return restoreTextWithMessageId(context, messageId, Body.COMMON_PROJECTION_INTRO);
- }
-
- @Override
- public void restore(Cursor cursor) {
- mBaseUri = EmailContent.Body.CONTENT_URI;
- mMessageKey = cursor.getLong(CONTENT_MESSAGE_KEY_COLUMN);
- mHtmlContent = cursor.getString(CONTENT_HTML_CONTENT_COLUMN);
- mTextContent = cursor.getString(CONTENT_TEXT_CONTENT_COLUMN);
- mHtmlReply = cursor.getString(CONTENT_HTML_REPLY_COLUMN);
- mTextReply = cursor.getString(CONTENT_TEXT_REPLY_COLUMN);
- mSourceKey = cursor.getLong(CONTENT_SOURCE_KEY_COLUMN);
- mIntroText = cursor.getString(CONTENT_INTRO_TEXT_COLUMN);
- }
-
- public boolean update() {
- // TODO Auto-generated method stub
- return false;
- }
- }
-
- public interface MessageColumns {
- public static final String ID = "_id";
- // Basic columns used in message list presentation
- // The name as shown to the user in a message list
- public static final String DISPLAY_NAME = "displayName";
- // The time (millis) as shown to the user in a message list [INDEX]
- public static final String TIMESTAMP = "timeStamp";
- // Message subject
- public static final String SUBJECT = "subject";
- // Boolean, unread = 0, read = 1 [INDEX]
- public static final String FLAG_READ = "flagRead";
- // Load state, see constants below (unloaded, partial, complete, deleted)
- public static final String FLAG_LOADED = "flagLoaded";
- // Boolean, unflagged = 0, flagged (favorite) = 1
- public static final String FLAG_FAVORITE = "flagFavorite";
- // Boolean, no attachment = 0, attachment = 1
- public static final String FLAG_ATTACHMENT = "flagAttachment";
- // Bit field for flags which we'll not be selecting on
- public static final String FLAGS = "flags";
-
- // Sync related identifiers
- // Any client-required identifier
- public static final String CLIENT_ID = "clientId";
- // The message-id in the message's header
- public static final String MESSAGE_ID = "messageId";
-
- // References to other Email objects in the database
- // Foreign key to the Mailbox holding this message [INDEX]
- public static final String MAILBOX_KEY = "mailboxKey";
- // Foreign key to the Account holding this message
- public static final String ACCOUNT_KEY = "accountKey";
-
- // Address lists, packed with Address.pack()
- public static final String FROM_LIST = "fromList";
- public static final String TO_LIST = "toList";
- public static final String CC_LIST = "ccList";
- public static final String BCC_LIST = "bccList";
- public static final String REPLY_TO_LIST = "replyToList";
- // Meeting invitation related information (for now, start time in ms)
- public static final String MEETING_INFO = "meetingInfo";
- // A text "snippet" derived from the body of the message
- public static final String SNIPPET = "snippet";
- }
-
- public static final class Message extends EmailContent implements SyncColumns, MessageColumns {
- public static final String TABLE_NAME = "Message";
- public static final String UPDATED_TABLE_NAME = "Message_Updates";
- public static final String DELETED_TABLE_NAME = "Message_Deletes";
-
- // To refer to a specific message, use ContentUris.withAppendedId(CONTENT_URI, id)
- @SuppressWarnings("hiding")
- public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/message");
- public static final Uri CONTENT_URI_LIMIT_1 = uriWithLimit(CONTENT_URI, 1);
- public static final Uri SYNCED_CONTENT_URI =
- Uri.parse(EmailContent.CONTENT_URI + "/syncedMessage");
- public static final Uri DELETED_CONTENT_URI =
- Uri.parse(EmailContent.CONTENT_URI + "/deletedMessage");
- public static final Uri UPDATED_CONTENT_URI =
- Uri.parse(EmailContent.CONTENT_URI + "/updatedMessage");
- public static final Uri NOTIFIER_URI =
- Uri.parse(EmailContent.CONTENT_NOTIFIER_URI + "/message");
-
- public static final String KEY_TIMESTAMP_DESC = MessageColumns.TIMESTAMP + " desc";
-
- public static final int CONTENT_ID_COLUMN = 0;
- public static final int CONTENT_DISPLAY_NAME_COLUMN = 1;
- public static final int CONTENT_TIMESTAMP_COLUMN = 2;
- public static final int CONTENT_SUBJECT_COLUMN = 3;
- public static final int CONTENT_FLAG_READ_COLUMN = 4;
- public static final int CONTENT_FLAG_LOADED_COLUMN = 5;
- public static final int CONTENT_FLAG_FAVORITE_COLUMN = 6;
- public static final int CONTENT_FLAG_ATTACHMENT_COLUMN = 7;
- public static final int CONTENT_FLAGS_COLUMN = 8;
- public static final int CONTENT_SERVER_ID_COLUMN = 9;
- public static final int CONTENT_CLIENT_ID_COLUMN = 10;
- public static final int CONTENT_MESSAGE_ID_COLUMN = 11;
- public static final int CONTENT_MAILBOX_KEY_COLUMN = 12;
- public static final int CONTENT_ACCOUNT_KEY_COLUMN = 13;
- public static final int CONTENT_FROM_LIST_COLUMN = 14;
- public static final int CONTENT_TO_LIST_COLUMN = 15;
- public static final int CONTENT_CC_LIST_COLUMN = 16;
- public static final int CONTENT_BCC_LIST_COLUMN = 17;
- public static final int CONTENT_REPLY_TO_COLUMN = 18;
- public static final int CONTENT_SERVER_TIMESTAMP_COLUMN = 19;
- public static final int CONTENT_MEETING_INFO_COLUMN = 20;
- public static final int CONTENT_SNIPPET_COLUMN = 21;
-
- public static final String[] CONTENT_PROJECTION = new String[] {
- RECORD_ID,
- MessageColumns.DISPLAY_NAME, MessageColumns.TIMESTAMP,
- MessageColumns.SUBJECT, MessageColumns.FLAG_READ,
- MessageColumns.FLAG_LOADED, MessageColumns.FLAG_FAVORITE,
- MessageColumns.FLAG_ATTACHMENT, MessageColumns.FLAGS,
- SyncColumns.SERVER_ID, MessageColumns.CLIENT_ID,
- MessageColumns.MESSAGE_ID, MessageColumns.MAILBOX_KEY,
- MessageColumns.ACCOUNT_KEY, MessageColumns.FROM_LIST,
- MessageColumns.TO_LIST, MessageColumns.CC_LIST,
- MessageColumns.BCC_LIST, MessageColumns.REPLY_TO_LIST,
- SyncColumns.SERVER_TIMESTAMP, MessageColumns.MEETING_INFO,
- MessageColumns.SNIPPET
- };
-
- public static final int LIST_ID_COLUMN = 0;
- public static final int LIST_DISPLAY_NAME_COLUMN = 1;
- public static final int LIST_TIMESTAMP_COLUMN = 2;
- public static final int LIST_SUBJECT_COLUMN = 3;
- public static final int LIST_READ_COLUMN = 4;
- public static final int LIST_LOADED_COLUMN = 5;
- public static final int LIST_FAVORITE_COLUMN = 6;
- public static final int LIST_ATTACHMENT_COLUMN = 7;
- public static final int LIST_FLAGS_COLUMN = 8;
- public static final int LIST_MAILBOX_KEY_COLUMN = 9;
- public static final int LIST_ACCOUNT_KEY_COLUMN = 10;
- public static final int LIST_SERVER_ID_COLUMN = 11;
- public static final int LIST_SNIPPET_COLUMN = 12;
-
- // Public projection for common list columns
- public static final String[] LIST_PROJECTION = new String[] {
- RECORD_ID,
- MessageColumns.DISPLAY_NAME, MessageColumns.TIMESTAMP,
- MessageColumns.SUBJECT, MessageColumns.FLAG_READ,
- MessageColumns.FLAG_LOADED, MessageColumns.FLAG_FAVORITE,
- MessageColumns.FLAG_ATTACHMENT, MessageColumns.FLAGS,
- MessageColumns.MAILBOX_KEY, MessageColumns.ACCOUNT_KEY,
- SyncColumns.SERVER_ID, MessageColumns.SNIPPET
- };
-
- public static final int ID_COLUMNS_ID_COLUMN = 0;
- public static final int ID_COLUMNS_SYNC_SERVER_ID = 1;
- public static final String[] ID_COLUMNS_PROJECTION = new String[] {
- RECORD_ID, SyncColumns.SERVER_ID
- };
-
- public static final int ID_MAILBOX_COLUMN_ID = 0;
- public static final int ID_MAILBOX_COLUMN_MAILBOX_KEY = 1;
- public static final String[] ID_MAILBOX_PROJECTION = new String[] {
- RECORD_ID, MessageColumns.MAILBOX_KEY
- };
-
- public static final String[] ID_COLUMN_PROJECTION = new String[] { RECORD_ID };
-
- private static final String ACCOUNT_KEY_SELECTION =
- MessageColumns.ACCOUNT_KEY + "=?";
-
- /** Selection for messages that are loaded */
- public static final String FLAG_LOADED_SELECTION =
- MessageColumns.FLAG_LOADED + " IN ("
- + Message.FLAG_LOADED_PARTIAL + "," + Message.FLAG_LOADED_COMPLETE
- + ")";
-
- public static final String ALL_FAVORITE_SELECTION =
- MessageColumns.FLAG_FAVORITE + "=1 AND "
- + MessageColumns.MAILBOX_KEY + " NOT IN ("
- + "SELECT " + MailboxColumns.ID + " FROM " + Mailbox.TABLE_NAME + ""
- + " WHERE " + MailboxColumns.TYPE + " = " + Mailbox.TYPE_TRASH
- + ")"
- + " AND " + FLAG_LOADED_SELECTION;
- /** Selection to retrieve all messages in "inbox" for any account */
- public static final String INBOX_SELECTION =
- MessageColumns.MAILBOX_KEY + " IN ("
- + "SELECT " + MailboxColumns.ID + " FROM " + Mailbox.TABLE_NAME
- + " WHERE " + MailboxColumns.TYPE + " = " + Mailbox.TYPE_INBOX
- + ")"
- + " AND " + FLAG_LOADED_SELECTION;
- /** Selection to retrieve unread messages in "inbox" for any account */
- public static final String UNREAD_SELECTION =
- MessageColumns.FLAG_READ + "=0 AND " + INBOX_SELECTION;
- /** Selection to retrieve all messages in "inbox" for one account */
- public static final String PER_ACCOUNT_INBOX_SELECTION =
- ACCOUNT_KEY_SELECTION + " AND " + INBOX_SELECTION;
-
- private static final String ACCOUNT_FAVORITE_SELECTION =
- ACCOUNT_KEY_SELECTION + " AND " + ALL_FAVORITE_SELECTION;
-
- /**
- * Selection for latest incoming messages. In order to tell whether incoming or not,
- * we need the mailbox type, which is in the mailbox table, not the message table, so
- * use a subquery.
- */
- private static final String LATEST_INCOMING_MESSAGE_SELECTION =
- MessageColumns.MAILBOX_KEY + " IN (SELECT " + RECORD_ID + " FROM " + Mailbox.TABLE_NAME
- + " WHERE " + MailboxColumns.ACCOUNT_KEY + "=? AND "
- + Mailbox.USER_VISIBLE_MAILBOX_SELECTION + " AND "
- + MailboxColumns.TYPE + " NOT IN ("
- + Mailbox.TYPE_DRAFTS + ","
- + Mailbox.TYPE_OUTBOX + ","
- + Mailbox.TYPE_SENT
- + "))";
-
- // _id field is in AbstractContent
- public String mDisplayName;
- public long mTimeStamp;
- public String mSubject;
- public boolean mFlagRead = false;
- public int mFlagLoaded = FLAG_LOADED_UNLOADED;
- public boolean mFlagFavorite = false;
- public boolean mFlagAttachment = false;
- public int mFlags = 0;
-
- public String mServerId;
- public long mServerTimeStamp;
- public String mClientId;
- public String mMessageId;
-
- public long mMailboxKey;
- public long mAccountKey;
-
- public String mFrom;
- public String mTo;
- public String mCc;
- public String mBcc;
- public String mReplyTo;
-
- // For now, just the start time of a meeting invite, in ms
- public String mMeetingInfo;
-
- public String mSnippet;
-
- // The following transient members may be used while building and manipulating messages,
- // but they are NOT persisted directly by EmailProvider
- transient public String mText;
- transient public String mHtml;
- transient public String mTextReply;
- transient public String mHtmlReply;
- transient public long mSourceKey;
- transient public ArrayList<Attachment> mAttachments = null;
- transient public String mIntroText;
-
- // Values used in mFlagRead
- public static final int UNREAD = 0;
- public static final int READ = 1;
-
- // Values used in mFlagLoaded
- public static final int FLAG_LOADED_UNLOADED = 0;
- public static final int FLAG_LOADED_COMPLETE = 1;
- public static final int FLAG_LOADED_PARTIAL = 2;
- public static final int FLAG_LOADED_DELETED = 3;
-
- // Bits used in mFlags
- // The following three states are mutually exclusive, and indicate whether the message is an
- // original, a reply, or a forward
- public static final int FLAG_TYPE_ORIGINAL = 0;
- public static final int FLAG_TYPE_REPLY = 1<<0;
- public static final int FLAG_TYPE_FORWARD = 1<<1;
- public static final int FLAG_TYPE_MASK = FLAG_TYPE_REPLY | FLAG_TYPE_FORWARD;
- // The following flags indicate messages that are determined to be incoming meeting related
- // (e.g. invites from others)
- public static final int FLAG_INCOMING_MEETING_INVITE = 1<<2;
- public static final int FLAG_INCOMING_MEETING_CANCEL = 1<<3;
- public static final int FLAG_INCOMING_MEETING_MASK =
- FLAG_INCOMING_MEETING_INVITE | FLAG_INCOMING_MEETING_CANCEL;
- // The following flags indicate messages that are outgoing and meeting related
- // (e.g. invites TO others)
- public static final int FLAG_OUTGOING_MEETING_INVITE = 1<<4;
- public static final int FLAG_OUTGOING_MEETING_CANCEL = 1<<5;
- public static final int FLAG_OUTGOING_MEETING_ACCEPT = 1<<6;
- public static final int FLAG_OUTGOING_MEETING_DECLINE = 1<<7;
- public static final int FLAG_OUTGOING_MEETING_TENTATIVE = 1<<8;
- public static final int FLAG_OUTGOING_MEETING_MASK =
- FLAG_OUTGOING_MEETING_INVITE | FLAG_OUTGOING_MEETING_CANCEL |
- FLAG_OUTGOING_MEETING_ACCEPT | FLAG_OUTGOING_MEETING_DECLINE |
- FLAG_OUTGOING_MEETING_TENTATIVE;
- public static final int FLAG_OUTGOING_MEETING_REQUEST_MASK =
- FLAG_OUTGOING_MEETING_INVITE | FLAG_OUTGOING_MEETING_CANCEL;
- // 8 general purpose flags (bits) that may be used at the discretion of the sync adapter
- public static final int FLAG_SYNC_ADAPTER_SHIFT = 9;
- public static final int FLAG_SYNC_ADAPTER_MASK = 255 << FLAG_SYNC_ADAPTER_SHIFT;
- /**
- * Bit used in mFlags indicating that the outgoing message should *not* include quoted
- * original message. ("Not", in order to keep compatibility with old databases)
- */
- public static final int FLAG_NOT_INCLUDE_QUOTED_TEXT_SHIFT = 17;
- public static final int FLAG_NOT_INCLUDE_QUOTED_TEXT
- = 1 << FLAG_NOT_INCLUDE_QUOTED_TEXT_SHIFT;
-
- public Message() {
- mBaseUri = CONTENT_URI;
- }
-
- @Override
- public ContentValues toContentValues() {
- ContentValues values = new ContentValues();
-
- // Assign values for each row.
- values.put(MessageColumns.DISPLAY_NAME, mDisplayName);
- values.put(MessageColumns.TIMESTAMP, mTimeStamp);
- values.put(MessageColumns.SUBJECT, mSubject);
- values.put(MessageColumns.FLAG_READ, mFlagRead);
- values.put(MessageColumns.FLAG_LOADED, mFlagLoaded);
- values.put(MessageColumns.FLAG_FAVORITE, mFlagFavorite);
- values.put(MessageColumns.FLAG_ATTACHMENT, mFlagAttachment);
- values.put(MessageColumns.FLAGS, mFlags);
-
- values.put(SyncColumns.SERVER_ID, mServerId);
- values.put(SyncColumns.SERVER_TIMESTAMP, mServerTimeStamp);
- values.put(MessageColumns.CLIENT_ID, mClientId);
- values.put(MessageColumns.MESSAGE_ID, mMessageId);
-
- values.put(MessageColumns.MAILBOX_KEY, mMailboxKey);
- values.put(MessageColumns.ACCOUNT_KEY, mAccountKey);
-
- values.put(MessageColumns.FROM_LIST, mFrom);
- values.put(MessageColumns.TO_LIST, mTo);
- values.put(MessageColumns.CC_LIST, mCc);
- values.put(MessageColumns.BCC_LIST, mBcc);
- values.put(MessageColumns.REPLY_TO_LIST, mReplyTo);
-
- values.put(MessageColumns.MEETING_INFO, mMeetingInfo);
-
- values.put(MessageColumns.SNIPPET, mSnippet);
-
- return values;
- }
-
- public static Message restoreMessageWithId(Context context, long id) {
- Uri u = ContentUris.withAppendedId(Message.CONTENT_URI, id);
- if (context == null) {
- throw new NullPointerException("context");
- }
- ContentResolver resolver = context.getContentResolver();
- if (resolver == null) {
- throw new NullPointerException("resolver");
- }
- Cursor c = resolver.query(u, Message.CONTENT_PROJECTION, null, null, null);
-
- try {
- if (c.moveToFirst()) {
- return getContent(c, Message.class);
- } else {
- return null;
- }
- } finally {
- c.close();
- }
- }
-
- @Override
- public void restore(Cursor cursor) {
- mBaseUri = CONTENT_URI;
- mId = cursor.getLong(CONTENT_ID_COLUMN);
- mDisplayName = cursor.getString(CONTENT_DISPLAY_NAME_COLUMN);
- mTimeStamp = cursor.getLong(CONTENT_TIMESTAMP_COLUMN);
- mSubject = cursor.getString(CONTENT_SUBJECT_COLUMN);
- mFlagRead = cursor.getInt(CONTENT_FLAG_READ_COLUMN) == 1;
- mFlagLoaded = cursor.getInt(CONTENT_FLAG_LOADED_COLUMN);
- mFlagFavorite = cursor.getInt(CONTENT_FLAG_FAVORITE_COLUMN) == 1;
- mFlagAttachment = cursor.getInt(CONTENT_FLAG_ATTACHMENT_COLUMN) == 1;
- mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN);
- mServerId = cursor.getString(CONTENT_SERVER_ID_COLUMN);
- mServerTimeStamp = cursor.getLong(CONTENT_SERVER_TIMESTAMP_COLUMN);
- mClientId = cursor.getString(CONTENT_CLIENT_ID_COLUMN);
- mMessageId = cursor.getString(CONTENT_MESSAGE_ID_COLUMN);
- mMailboxKey = cursor.getLong(CONTENT_MAILBOX_KEY_COLUMN);
- mAccountKey = cursor.getLong(CONTENT_ACCOUNT_KEY_COLUMN);
- mFrom = cursor.getString(CONTENT_FROM_LIST_COLUMN);
- mTo = cursor.getString(CONTENT_TO_LIST_COLUMN);
- mCc = cursor.getString(CONTENT_CC_LIST_COLUMN);
- mBcc = cursor.getString(CONTENT_BCC_LIST_COLUMN);
- mReplyTo = cursor.getString(CONTENT_REPLY_TO_COLUMN);
- mMeetingInfo = cursor.getString(CONTENT_MEETING_INFO_COLUMN);
- mSnippet = cursor.getString(CONTENT_SNIPPET_COLUMN);
- }
-
- public boolean update() {
- // TODO Auto-generated method stub
- return false;
- }
-
- /*
- * Override this so that we can store the Body first and link it to the Message
- * Also, attachments when we get there...
- * (non-Javadoc)
- * @see com.android.email.provider.EmailContent#save(android.content.Context)
- */
- @Override
- public Uri save(Context context) {
-
- boolean doSave = !isSaved();
-
- // This logic is in place so I can (a) short circuit the expensive stuff when
- // possible, and (b) override (and throw) if anyone tries to call save() or update()
- // directly for Message, which are unsupported.
- if (mText == null && mHtml == null && mTextReply == null && mHtmlReply == null &&
- (mAttachments == null || mAttachments.isEmpty())) {
- if (doSave) {
- return super.save(context);
- } else {
- // Call update, rather than super.update in case we ever override it
- if (update(context, toContentValues()) == 1) {
- return getUri();
- }
- return null;
- }
- }
-
- ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
- addSaveOps(ops);
- try {
- ContentProviderResult[] results =
- context.getContentResolver().applyBatch(AUTHORITY, ops);
- // If saving, set the mId's of the various saved objects
- if (doSave) {
- Uri u = results[0].uri;
- mId = Long.parseLong(u.getPathSegments().get(1));
- if (mAttachments != null) {
- int resultOffset = 2;
- for (Attachment a : mAttachments) {
- // Save the id of the attachment record
- u = results[resultOffset++].uri;
- if (u != null) {
- a.mId = Long.parseLong(u.getPathSegments().get(1));
- }
- a.mMessageKey = mId;
- }
- }
- return u;
- } else {
- return null;
- }
- } catch (RemoteException e) {
- // There is nothing to be done here; fail by returning null
- } catch (OperationApplicationException e) {
- // There is nothing to be done here; fail by returning null
- }
- return null;
- }
-
- public void addSaveOps(ArrayList<ContentProviderOperation> ops) {
- // First, save the message
- ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(mBaseUri);
- // Generate the snippet here, before we create the CPO for Message
- if (mText != null) {
- mSnippet = Snippet.fromPlainText(mText);
- } else if (mHtml != null) {
- mSnippet = Snippet.fromHtmlText(mHtml);
- }
- ops.add(b.withValues(toContentValues()).build());
-
- // Create and save the body
- ContentValues cv = new ContentValues();
- if (mText != null) {
- cv.put(Body.TEXT_CONTENT, mText);
- }
- if (mHtml != null) {
- cv.put(Body.HTML_CONTENT, mHtml);
- }
- if (mTextReply != null) {
- cv.put(Body.TEXT_REPLY, mTextReply);
- }
- if (mHtmlReply != null) {
- cv.put(Body.HTML_REPLY, mHtmlReply);
- }
- if (mSourceKey != 0) {
- cv.put(Body.SOURCE_MESSAGE_KEY, mSourceKey);
- }
- if (mIntroText != null) {
- cv.put(Body.INTRO_TEXT, mIntroText);
- }
- b = ContentProviderOperation.newInsert(Body.CONTENT_URI);
- b.withValues(cv);
- ContentValues backValues = new ContentValues();
- int messageBackValue = ops.size() - 1;
- backValues.put(Body.MESSAGE_KEY, messageBackValue);
- ops.add(b.withValueBackReferences(backValues).build());
-
- // Create the attaachments, if any
- if (mAttachments != null) {
- for (Attachment att: mAttachments) {
- ops.add(ContentProviderOperation.newInsert(Attachment.CONTENT_URI)
- .withValues(att.toContentValues())
- .withValueBackReference(Attachment.MESSAGE_KEY, messageBackValue)
- .build());
- }
- }
- }
-
- /**
- * @return number of favorite (starred) messages throughout all accounts.
- */
- public static int getFavoriteMessageCount(Context context) {
- return count(context, Message.CONTENT_URI, ALL_FAVORITE_SELECTION, null);
- }
-
- /**
- * @return number of favorite (starred) messages for an account
- */
- public static int getFavoriteMessageCount(Context context, long accountId) {
- return count(context, Message.CONTENT_URI, ACCOUNT_FAVORITE_SELECTION,
- new String[]{Long.toString(accountId)});
- }
-
- public static long getKeyColumnLong(Context context, long messageId, String column) {
- String[] columns =
- Utility.getRowColumns(context, Message.CONTENT_URI, messageId, column);
- if (columns != null && columns[0] != null) {
- return Long.parseLong(columns[0]);
- }
- return -1;
- }
-
- /**
- * @return the latest messages on an account.
- */
- public static Message getLatestIncomingMessage(Context context, Long accountId) {
- Cursor c = context.getContentResolver().query(Message.CONTENT_URI_LIMIT_1,
- Message.CONTENT_PROJECTION,
- LATEST_INCOMING_MESSAGE_SELECTION, new String[] {Long.toString(accountId)},
- EmailContent.MessageColumns.TIMESTAMP + " DESC");
- try {
- if (c.moveToFirst()) {
- Message m = new Message();
- m.restore(c);
- return m;
- }
- } finally {
- c.close();
- }
- return null; // not found;
- }
- }
-
- public interface AccountColumns {
- public static final String ID = "_id";
- // The display name of the account (user-settable)
- public static final String DISPLAY_NAME = "displayName";
- // The email address corresponding to this account
- public static final String EMAIL_ADDRESS = "emailAddress";
- // A server-based sync key on an account-wide basis (EAS needs this)
- public static final String SYNC_KEY = "syncKey";
- // The default sync lookback period for this account
- public static final String SYNC_LOOKBACK = "syncLookback";
- // The default sync frequency for this account, in minutes
- public static final String SYNC_INTERVAL = "syncInterval";
- // A foreign key into the account manager, having host, login, password, port, and ssl flags
- public static final String HOST_AUTH_KEY_RECV = "hostAuthKeyRecv";
- // (optional) A foreign key into the account manager, having host, login, password, port,
- // and ssl flags
- public static final String HOST_AUTH_KEY_SEND = "hostAuthKeySend";
- // Flags
- public static final String FLAGS = "flags";
- // Default account
- public static final String IS_DEFAULT = "isDefault";
- // Old-Style UUID for compatibility with previous versions
- public static final String COMPATIBILITY_UUID = "compatibilityUuid";
- // User name (for outgoing messages)
- public static final String SENDER_NAME = "senderName";
- // Ringtone
- public static final String RINGTONE_URI = "ringtoneUri";
- // Protocol version (arbitrary string, used by EAS currently)
- public static final String PROTOCOL_VERSION = "protocolVersion";
- // The number of new messages (reported by the sync/download engines
- public static final String NEW_MESSAGE_COUNT = "newMessageCount";
- // Flags defining security (provisioning) requirements of this account
- public static final String SECURITY_FLAGS = "securityFlags";
- // Server-based sync key for the security policies currently enforced
- public static final String SECURITY_SYNC_KEY = "securitySyncKey";
- // Signature to use with this account
- public static final String SIGNATURE = "signature";
- }
-
- public static final class Account extends EmailContent implements AccountColumns, Parcelable {
- public static final String TABLE_NAME = "Account";
- @SuppressWarnings("hiding")
- public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/account");
- public static final Uri ADD_TO_FIELD_URI =
- Uri.parse(EmailContent.CONTENT_URI + "/accountIdAddToField");
- public static final Uri RESET_NEW_MESSAGE_COUNT_URI =
- Uri.parse(EmailContent.CONTENT_URI + "/resetNewMessageCount");
-
- /**
- * Value used by UI to represent "combined view".
- *
- * NOTE: This must be used only by UI, and mustn't be stored in the database.
- *
- * This is defined here to avoid conflict with other pseudo account IDs, if any.
- */
- public static final long ACCOUNT_ID_COMBINED_VIEW = 0x1000000000000000L;
-
- public final static int FLAGS_NOTIFY_NEW_MAIL = 1;
- public final static int FLAGS_VIBRATE_ALWAYS = 2;
- public static final int FLAGS_DELETE_POLICY_MASK = 4+8;
- public static final int FLAGS_DELETE_POLICY_SHIFT = 2;
- public static final int FLAGS_INCOMPLETE = 16;
- public static final int FLAGS_SECURITY_HOLD = 32;
- public static final int FLAGS_VIBRATE_WHEN_SILENT = 64;
- public static final int FLAGS_SUPPORTS_SMART_FORWARD = 128;
- public static final int FLAGS_BACKGROUND_ATTACHMENTS = 256;
-
- public static final int DELETE_POLICY_NEVER = 0;
- public static final int DELETE_POLICY_7DAYS = 1; // not supported
- public static final int DELETE_POLICY_ON_DELETE = 2;
-
- // Sentinel values for the mSyncInterval field of both Account records
- public static final int CHECK_INTERVAL_NEVER = -1;
- public static final int CHECK_INTERVAL_PUSH = -2;
-
- public String mDisplayName;
- public String mEmailAddress;
- public String mSyncKey;
- public int mSyncLookback;
- public int mSyncInterval;
- public long mHostAuthKeyRecv;
- public long mHostAuthKeySend;
- public int mFlags;
- public boolean mIsDefault; // note: callers should use getDefaultAccountId()
- public String mCompatibilityUuid;
- public String mSenderName;
- public String mRingtoneUri;
- public String mProtocolVersion;
- public int mNewMessageCount;
- public long mSecurityFlags;
- public String mSecuritySyncKey;
- public String mSignature;
-
- // Convenience for creating an account
- public transient HostAuth mHostAuthRecv;
- public transient HostAuth mHostAuthSend;
-
- public static final int CONTENT_ID_COLUMN = 0;
- public static final int CONTENT_DISPLAY_NAME_COLUMN = 1;
- public static final int CONTENT_EMAIL_ADDRESS_COLUMN = 2;
- public static final int CONTENT_SYNC_KEY_COLUMN = 3;
- public static final int CONTENT_SYNC_LOOKBACK_COLUMN = 4;
- public static final int CONTENT_SYNC_INTERVAL_COLUMN = 5;
- public static final int CONTENT_HOST_AUTH_KEY_RECV_COLUMN = 6;
- public static final int CONTENT_HOST_AUTH_KEY_SEND_COLUMN = 7;
- public static final int CONTENT_FLAGS_COLUMN = 8;
- public static final int CONTENT_IS_DEFAULT_COLUMN = 9;
- public static final int CONTENT_COMPATIBILITY_UUID_COLUMN = 10;
- public static final int CONTENT_SENDER_NAME_COLUMN = 11;
- public static final int CONTENT_RINGTONE_URI_COLUMN = 12;
- public static final int CONTENT_PROTOCOL_VERSION_COLUMN = 13;
- public static final int CONTENT_NEW_MESSAGE_COUNT_COLUMN = 14;
- public static final int CONTENT_SECURITY_FLAGS_COLUMN = 15;
- public static final int CONTENT_SECURITY_SYNC_KEY_COLUMN = 16;
- public static final int CONTENT_SIGNATURE_COLUMN = 17;
-
- public static final String[] CONTENT_PROJECTION = new String[] {
- RECORD_ID, AccountColumns.DISPLAY_NAME,
- AccountColumns.EMAIL_ADDRESS, AccountColumns.SYNC_KEY, AccountColumns.SYNC_LOOKBACK,
- AccountColumns.SYNC_INTERVAL, AccountColumns.HOST_AUTH_KEY_RECV,
- AccountColumns.HOST_AUTH_KEY_SEND, AccountColumns.FLAGS, AccountColumns.IS_DEFAULT,
- AccountColumns.COMPATIBILITY_UUID, AccountColumns.SENDER_NAME,
- AccountColumns.RINGTONE_URI, AccountColumns.PROTOCOL_VERSION,
- AccountColumns.NEW_MESSAGE_COUNT, AccountColumns.SECURITY_FLAGS,
- AccountColumns.SECURITY_SYNC_KEY, AccountColumns.SIGNATURE
- };
-
- public static final int CONTENT_MAILBOX_TYPE_COLUMN = 1;
-
- /**
- * This projection is for listing account id's only
- */
- public static final String[] ID_TYPE_PROJECTION = new String[] {
- RECORD_ID, MailboxColumns.TYPE
- };
-
- public static final int ACCOUNT_FLAGS_COLUMN_ID = 0;
- public static final int ACCOUNT_FLAGS_COLUMN_FLAGS = 1;
- public static final String[] ACCOUNT_FLAGS_PROJECTION = new String[] {
- AccountColumns.ID, AccountColumns.FLAGS};
-
- public static final String MAILBOX_SELECTION =
- MessageColumns.MAILBOX_KEY + " =?";
-
- public static final String UNREAD_COUNT_SELECTION =
- MessageColumns.MAILBOX_KEY + " =? and " + MessageColumns.FLAG_READ + "= 0";
-
- public static final String UUID_SELECTION = AccountColumns.COMPATIBILITY_UUID + " =?";
-
- public static final String SECURITY_NONZERO_SELECTION =
- Account.SECURITY_FLAGS + " IS NOT NULL AND " + Account.SECURITY_FLAGS + "!=0";
-
- private static final String FIND_INBOX_SELECTION =
- MailboxColumns.TYPE + " = " + Mailbox.TYPE_INBOX +
- " AND " + MailboxColumns.ACCOUNT_KEY + " =?";
-
- /**
- * This projection is for searching for the default account
- */
- private static final String[] DEFAULT_ID_PROJECTION = new String[] {
- RECORD_ID, IS_DEFAULT
- };
-
- /**
- * no public constructor since this is a utility class
- */
- public Account() {
- mBaseUri = CONTENT_URI;
-
- // other defaults (policy)
- mRingtoneUri = "content://settings/system/notification_sound";
- mSyncInterval = -1;
- mSyncLookback = -1;
- mFlags = FLAGS_NOTIFY_NEW_MAIL;
- mCompatibilityUuid = UUID.randomUUID().toString();
- }
-
- public static Account restoreAccountWithId(Context context, long id) {
- Uri u = ContentUris.withAppendedId(Account.CONTENT_URI, id);
- Cursor c = context.getContentResolver().query(u, Account.CONTENT_PROJECTION,
- null, null, null);
-
- try {
- if (c.moveToFirst()) {
- return getContent(c, Account.class);
- } else {
- return null;
- }
- } finally {
- c.close();
- }
- }
-
- /**
- * Refresh an account that has already been loaded. This is slightly less expensive
- * that generating a brand-new account object.
- */
- public void refresh(Context context) {
- Cursor c = context.getContentResolver().query(this.getUri(), Account.CONTENT_PROJECTION,
- null, null, null);
- try {
- c.moveToFirst();
- restore(c);
- } finally {
- if (c != null) {
- c.close();
- }
- }
- }
-
- @Override
- public void restore(Cursor cursor) {
- mId = cursor.getLong(CONTENT_ID_COLUMN);
- mBaseUri = CONTENT_URI;
- mDisplayName = cursor.getString(CONTENT_DISPLAY_NAME_COLUMN);
- mEmailAddress = cursor.getString(CONTENT_EMAIL_ADDRESS_COLUMN);
- mSyncKey = cursor.getString(CONTENT_SYNC_KEY_COLUMN);
- mSyncLookback = cursor.getInt(CONTENT_SYNC_LOOKBACK_COLUMN);
- mSyncInterval = cursor.getInt(CONTENT_SYNC_INTERVAL_COLUMN);
- mHostAuthKeyRecv = cursor.getLong(CONTENT_HOST_AUTH_KEY_RECV_COLUMN);
- mHostAuthKeySend = cursor.getLong(CONTENT_HOST_AUTH_KEY_SEND_COLUMN);
- mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN);
- mIsDefault = cursor.getInt(CONTENT_IS_DEFAULT_COLUMN) == 1;
- mCompatibilityUuid = cursor.getString(CONTENT_COMPATIBILITY_UUID_COLUMN);
- mSenderName = cursor.getString(CONTENT_SENDER_NAME_COLUMN);
- mRingtoneUri = cursor.getString(CONTENT_RINGTONE_URI_COLUMN);
- mProtocolVersion = cursor.getString(CONTENT_PROTOCOL_VERSION_COLUMN);
- mNewMessageCount = cursor.getInt(CONTENT_NEW_MESSAGE_COUNT_COLUMN);
- mSecurityFlags = cursor.getLong(CONTENT_SECURITY_FLAGS_COLUMN);
- mSecuritySyncKey = cursor.getString(CONTENT_SECURITY_SYNC_KEY_COLUMN);
- mSignature = cursor.getString(CONTENT_SIGNATURE_COLUMN);
- }
-
- private long getId(Uri u) {
- return Long.parseLong(u.getPathSegments().get(1));
- }
-
- /**
- * @return the user-visible name for the account
- */
- public String getDisplayName() {
- return mDisplayName;
- }
-
- /**
- * Set the description. Be sure to call save() to commit to database.
- * @param description the new description
- */
- public void setDisplayName(String description) {
- mDisplayName = description;
- }
-
- /**
- * @return the email address for this account
- */
- public String getEmailAddress() {
- return mEmailAddress;
- }
-
- /**
- * Set the Email address for this account. Be sure to call save() to commit to database.
- * @param emailAddress the new email address for this account
- */
- public void setEmailAddress(String emailAddress) {
- mEmailAddress = emailAddress;
- }
-
- /**
- * @return the sender's name for this account
- */
- public String getSenderName() {
- return mSenderName;
- }
-
- /**
- * Set the sender's name. Be sure to call save() to commit to database.
- * @param name the new sender name
- */
- public void setSenderName(String name) {
- mSenderName = name;
- }
-
- public String getSignature() {
- return mSignature;
- }
-
- public void setSignature(String signature) {
- mSignature = signature;
- }
-
-
- /**
- * @return the minutes per check (for polling)
- * TODO define sentinel values for "never", "push", etc. See Account.java
- */
- public int getSyncInterval()
- {
- return mSyncInterval;
- }
-
- /**
- * Set the minutes per check (for polling). Be sure to call save() to commit to database.
- * TODO define sentinel values for "never", "push", etc. See Account.java
- * @param minutes the number of minutes between polling checks
- */
- public void setSyncInterval(int minutes)
- {
- mSyncInterval = minutes;
- }
-
- /**
- * @return One of the {@code Account.SYNC_WINDOW_*} constants that represents the sync
- * lookback window.
- * TODO define sentinel values for "all", "1 month", etc. See Account.java
- */
- public int getSyncLookback() {
- return mSyncLookback;
- }
-
- /**
- * Set the sync lookback window. Be sure to call save() to commit to database.
- * TODO define sentinel values for "all", "1 month", etc. See Account.java
- * @param value One of the {@code Account.SYNC_WINDOW_*} constants
- */
- public void setSyncLookback(int value) {
- mSyncLookback = value;
- }
-
- /**
- * @return the flags for this account
- * @see #FLAGS_NOTIFY_NEW_MAIL
- * @see #FLAGS_VIBRATE_ALWAYS
- * @see #FLAGS_VIBRATE_WHEN_SILENT
- */
- public int getFlags() {
- return mFlags;
- }
-
- /**
- * Set the flags for this account
- * @see #FLAGS_NOTIFY_NEW_MAIL
- * @see #FLAGS_VIBRATE_ALWAYS
- * @see #FLAGS_VIBRATE_WHEN_SILENT
- * @param newFlags the new value for the flags
- */
- public void setFlags(int newFlags) {
- mFlags = newFlags;
- }
-
- /**
- * @return the ringtone Uri for this account
- */
- public String getRingtone() {
- return mRingtoneUri;
- }
-
- /**
- * Set the ringtone Uri for this account
- * @param newUri the new URI string for the ringtone for this account
- */
- public void setRingtone(String newUri) {
- mRingtoneUri = newUri;
- }
-
- /**
- * Set the "delete policy" as a simple 0,1,2 value set.
- * @param newPolicy the new delete policy
- */
- public void setDeletePolicy(int newPolicy) {
- mFlags &= ~FLAGS_DELETE_POLICY_MASK;
- mFlags |= (newPolicy << FLAGS_DELETE_POLICY_SHIFT) & FLAGS_DELETE_POLICY_MASK;
- }
-
- /**
- * Return the "delete policy" as a simple 0,1,2 value set.
- * @return the current delete policy
- */
- public int getDeletePolicy() {
- return (mFlags & FLAGS_DELETE_POLICY_MASK) >> FLAGS_DELETE_POLICY_SHIFT;
- }
-
- /**
- * Return the Uuid associated with this account. This is primarily for compatibility
- * with accounts set up by previous versions, because there are externals references
- * to the Uuid (e.g. desktop shortcuts).
- */
- public String getUuid() {
- return mCompatibilityUuid;
- }
-
- /**
- * For compatibility while converting to provider model, generate a "store URI"
- *
- * @return a string in the form of a Uri, as used by the other parts of the email app
- */
- public String getStoreUri(Context context) {
- // reconstitute if necessary
- if (mHostAuthRecv == null) {
- mHostAuthRecv = HostAuth.restoreHostAuthWithId(context, mHostAuthKeyRecv);
- }
- // convert if available
- if (mHostAuthRecv != null) {
- String storeUri = mHostAuthRecv.getStoreUri();
- if (storeUri != null) {
- return storeUri;
- }
- }
- return "";
- }
-
- /**
- * For compatibility while converting to provider model, generate a "sender URI"
- *
- * @return a string in the form of a Uri, as used by the other parts of the email app
- */
- public String getSenderUri(Context context) {
- // reconstitute if necessary
- if (mHostAuthSend == null) {
- mHostAuthSend = HostAuth.restoreHostAuthWithId(context, mHostAuthKeySend);
- }
- // convert if available
- if (mHostAuthSend != null) {
- String senderUri = mHostAuthSend.getStoreUri();
- if (senderUri != null) {
- return senderUri;
- }
- }
- return "";
- }
-
- public HostAuth getOrCreateHostAuthSend(Context context) {
- if (mHostAuthSend == null) {
- if (mHostAuthKeySend != 0) {
- mHostAuthSend = HostAuth.restoreHostAuthWithId(context, mHostAuthKeySend);
- } else {
- mHostAuthSend = new EmailContent.HostAuth();
- }
- }
- return mHostAuthSend;
- }
-
- public HostAuth getOrCreateHostAuthRecv(Context context) {
- if (mHostAuthRecv == null) {
- if (mHostAuthKeyRecv != 0) {
- mHostAuthRecv = HostAuth.restoreHostAuthWithId(context, mHostAuthKeyRecv);
- } else {
- mHostAuthRecv = new EmailContent.HostAuth();
- }
- }
- return mHostAuthRecv;
- }
-
- /**
- * For compatibility while converting to provider model, generate a "local store URI"
- *
- * @return a string in the form of a Uri, as used by the other parts of the email app
- */
- public String getLocalStoreUri(Context context) {
- return "local://localhost/" + context.getDatabasePath(getUuid() + ".db");
- }
-
- /**
- * @return true if the instance is of an EAS account.
- *
- * NOTE This method accesses the DB if {@link #mHostAuthRecv} hasn't been restored yet.
- * Use caution when you use this on the main thread.
- */
- public boolean isEasAccount(Context context) {
- return "eas".equals(getProtocol(context));
- }
-
- /**
- * @return true if the account supports "move messages".
- */
- public static boolean supportsMoveMessages(Context context, long accountId) {
- String protocol = getProtocol(context, accountId);
- return "eas".equals(protocol) || "imap".equals(protocol);
- }
-
- /**
- * Set the account to be the default account. If this is set to "true", when the account
- * is saved, all other accounts will have the same value set to "false".
- * @param newDefaultState the new default state - if true, others will be cleared.
- */
- public void setDefaultAccount(boolean newDefaultState) {
- mIsDefault = newDefaultState;
- }
-
- /**
- * Helper method for finding the default account.
- */
- static private long getDefaultAccountWhere(Context context, String where) {
- return Utility.getFirstRowLong(context, CONTENT_URI,
- DEFAULT_ID_PROJECTION,
- where, null, null, 0, Long.valueOf(-1));
- }
-
- /**
- * @return {@link Uri} to this {@link Account} in the
- * {@code content://com.android.email.provider/account/UUID} format, which is safe to use
- * for desktop shortcuts.
- *
- * <p>We don't want to store _id in shortcuts, because
- * {@link com.android.email.AccountBackupRestore} won't preserve it.
- */
- public Uri getShortcutSafeUri() {
- return getShortcutSafeUriFromUuid(mCompatibilityUuid);
- }
-
- /**
- * @return {@link Uri} to an {@link Account} with a {@code uuid}.
- */
- public static Uri getShortcutSafeUriFromUuid(String uuid) {
- return CONTENT_URI.buildUpon().appendEncodedPath(uuid).build();
- }
-
- /**
- * Parse {@link Uri} in the {@code content://com.android.email.provider/account/ID} format
- * where ID = account id (used on Eclair, Android 2.0-2.1) or UUID, and return _id of
- * the {@link Account} associated with it.
- *
- * @param context context to access DB
- * @param uri URI of interest
- * @return _id of the {@link Account} associated with ID, or -1 if none found.
- */
- public static long getAccountIdFromShortcutSafeUri(Context context, Uri uri) {
- // Make sure the URI is in the correct format.
- if (!"content".equals(uri.getScheme())
- || !AUTHORITY.equals(uri.getAuthority())) {
- return -1;
- }
-
- final List<String> ps = uri.getPathSegments();
- if (ps.size() != 2 || !"account".equals(ps.get(0))) {
- return -1;
- }
-
- // Now get the ID part.
- final String id = ps.get(1);
-
- // First, see if ID can be parsed as long. (Eclair-style)
- // (UUIDs have '-' in them, so they are always non-parsable.)
- try {
- return Long.parseLong(id);
- } catch (NumberFormatException ok) {
- // OK, it's not a long. Continue...
- }
-
- // Now id is a UUId.
- return Utility.getFirstRowLong(context,
- CONTENT_URI, ID_PROJECTION,
- UUID_SELECTION, new String[] {id}, null, 0, Long.valueOf(-1));
- }
-
- /**
- * Return the id of the default account. If one hasn't been explicitly specified, return
- * the first one in the database. For any account saved in the DB, this must be used
- * to check for the default account - the mIsDefault field is set lazily and may be
- * incorrect.
- * @param context the caller's context
- * @return the id of the default account, or -1 if there are no accounts
- */
- static public long getDefaultAccountId(Context context) {
- long id = getDefaultAccountWhere(context, AccountColumns.IS_DEFAULT + "=1");
- if (id == -1) {
- id = getDefaultAccountWhere(context, null);
- }
- return id;
- }
-
- /**
- * Given an account id, return the account's protocol
- * @param context the caller's context
- * @param accountId the id of the account to be examined
- * @return the account's protocol (or null if the Account or HostAuth do not exist)
- */
- public static String getProtocol(Context context, long accountId) {
- Account account = Account.restoreAccountWithId(context, accountId);
- if (account != null) {
- return account.getProtocol(context);
- }
- return null;
- }
-
- /**
- * Return the account's protocol
- * @param context the caller's context
- * @return the account's protocol (or null if the HostAuth doesn't not exist)
- */
- public String getProtocol(Context context) {
- HostAuth hostAuth = HostAuth.restoreHostAuthWithId(context, mHostAuthKeyRecv);
- if (hostAuth != null) {
- return hostAuth.mProtocol;
- }
- return null;
- }
-
- /**
- * Return the account ID for a message with a given id
- *
- * @param context the caller's context
- * @param messageId the id of the message
- * @return the account ID, or -1 if the account doesn't exist
- */
- public static long getAccountIdForMessageId(Context context, long messageId) {
- return Message.getKeyColumnLong(context, messageId, MessageColumns.ACCOUNT_KEY);
- }
-
- /**
- * Return the account for a message with a given id
- * @param context the caller's context
- * @param messageId the id of the message
- * @return the account, or null if the account doesn't exist
- */
- public static Account getAccountForMessageId(Context context, long messageId) {
- long accountId = getAccountIdForMessageId(context, messageId);
- if (accountId != -1) {
- return Account.restoreAccountWithId(context, accountId);
- }
- return null;
- }
-
- /**
- * @return true if an {@code accountId} is assigned to any existing account.
- */
- public static boolean isValidId(Context context, long accountId) {
- return null != Utility.getFirstRowLong(context, CONTENT_URI, ID_PROJECTION,
- ID_SELECTION, new String[] {Long.toString(accountId)}, null,
- ID_PROJECTION_COLUMN);
- }
-
- /**
- * Check a single account for security hold status.
- */
- public static boolean isSecurityHold(Context context, long accountId) {
- return (Utility.getFirstRowLong(context,
- ContentUris.withAppendedId(Account.CONTENT_URI, accountId),
- ACCOUNT_FLAGS_PROJECTION, null, null, null, ACCOUNT_FLAGS_COLUMN_FLAGS, 0L)
- & Account.FLAGS_SECURITY_HOLD) != 0;
- }
-
- /**
- * @return id of the "inbox" mailbox, or -1 if not found.
- */
- public static long getInboxId(Context context, long accountId) {
- return Utility.getFirstRowLong(context, Mailbox.CONTENT_URI, ID_PROJECTION,
- FIND_INBOX_SELECTION, new String[] {Long.toString(accountId)}, null,
- ID_PROJECTION_COLUMN, -1L);
- }
-
- /**
- * Clear all account hold flags that are set.
- *
- * (This will trigger watchers, and in particular will cause EAS to try and resync the
- * account(s).)
- */
- public static void clearSecurityHoldOnAllAccounts(Context context) {
- ContentResolver resolver = context.getContentResolver();
- Cursor c = resolver.query(Account.CONTENT_URI, ACCOUNT_FLAGS_PROJECTION,
- SECURITY_NONZERO_SELECTION, null, null);
- try {
- while (c.moveToNext()) {
- int flags = c.getInt(ACCOUNT_FLAGS_COLUMN_FLAGS);
-
- if (0 != (flags & FLAGS_SECURITY_HOLD)) {
- ContentValues cv = new ContentValues();
- cv.put(AccountColumns.FLAGS, flags & ~FLAGS_SECURITY_HOLD);
- long accountId = c.getLong(ACCOUNT_FLAGS_COLUMN_ID);
- Uri uri = ContentUris.withAppendedId(Account.CONTENT_URI, accountId);
- resolver.update(uri, cv, null, null);
- }
- }
- } finally {
- c.close();
- }
- }
-
- /**
- * Override update to enforce a single default account, and do it atomically
- */
- @Override
- public int update(Context context, ContentValues cv) {
- if (cv.containsKey(AccountColumns.IS_DEFAULT) &&
- cv.getAsBoolean(AccountColumns.IS_DEFAULT)) {
- ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
- ContentValues cv1 = new ContentValues();
- cv1.put(AccountColumns.IS_DEFAULT, false);
- // Clear the default flag in all accounts
- ops.add(ContentProviderOperation.newUpdate(CONTENT_URI).withValues(cv1).build());
- // Update this account
- ops.add(ContentProviderOperation
- .newUpdate(ContentUris.withAppendedId(CONTENT_URI, mId))
- .withValues(cv).build());
- try {
- context.getContentResolver().applyBatch(AUTHORITY, ops);
- return 1;
- } catch (RemoteException e) {
- // There is nothing to be done here; fail by returning 0
- } catch (OperationApplicationException e) {
- // There is nothing to be done here; fail by returning 0
- }
- return 0;
- }
- return super.update(context, cv);
- }
-
- /*
- * Override this so that we can store the HostAuth's first and link them to the Account
- * (non-Javadoc)
- * @see com.android.email.provider.EmailContent#save(android.content.Context)
- */
- @Override
- public Uri save(Context context) {
- if (isSaved()) {
- throw new UnsupportedOperationException();
- }
- // This logic is in place so I can (a) short circuit the expensive stuff when
- // possible, and (b) override (and throw) if anyone tries to call save() or update()
- // directly for Account, which are unsupported.
- if (mHostAuthRecv == null && mHostAuthSend == null && mIsDefault == false) {
- return super.save(context);
- }
-
- int index = 0;
- int recvIndex = -1;
- int sendIndex = -1;
-
- // Create operations for saving the send and recv hostAuths
- // Also, remember which operation in the array they represent
- ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
- if (mHostAuthRecv != null) {
- recvIndex = index++;
- ops.add(ContentProviderOperation.newInsert(mHostAuthRecv.mBaseUri)
- .withValues(mHostAuthRecv.toContentValues())
- .build());
- }
- if (mHostAuthSend != null) {
- sendIndex = index++;
- ops.add(ContentProviderOperation.newInsert(mHostAuthSend.mBaseUri)
- .withValues(mHostAuthSend.toContentValues())
- .build());
- }
-
- // Create operations for making this the only default account
- // Note, these are always updates because they change existing accounts
- if (mIsDefault) {
- index++;
- ContentValues cv1 = new ContentValues();
- cv1.put(AccountColumns.IS_DEFAULT, 0);
- ops.add(ContentProviderOperation.newUpdate(CONTENT_URI).withValues(cv1).build());
- }
-
- // Now do the Account
- ContentValues cv = null;
- if (recvIndex >= 0 || sendIndex >= 0) {
- cv = new ContentValues();
- if (recvIndex >= 0) {
- cv.put(Account.HOST_AUTH_KEY_RECV, recvIndex);
- }
- if (sendIndex >= 0) {
- cv.put(Account.HOST_AUTH_KEY_SEND, sendIndex);
- }
- }
-
- ContentProviderOperation.Builder b = ContentProviderOperation.newInsert(mBaseUri);
- b.withValues(toContentValues());
- if (cv != null) {
- b.withValueBackReferences(cv);
- }
- ops.add(b.build());
-
- try {
- ContentProviderResult[] results =
- context.getContentResolver().applyBatch(AUTHORITY, ops);
- // If saving, set the mId's of the various saved objects
- if (recvIndex >= 0) {
- long newId = getId(results[recvIndex].uri);
- mHostAuthKeyRecv = newId;
- mHostAuthRecv.mId = newId;
- }
- if (sendIndex >= 0) {
- long newId = getId(results[sendIndex].uri);
- mHostAuthKeySend = newId;
- mHostAuthSend.mId = newId;
- }
- Uri u = results[index].uri;
- mId = getId(u);
- return u;
- } catch (RemoteException e) {
- // There is nothing to be done here; fail by returning null
- } catch (OperationApplicationException e) {
- // There is nothing to be done here; fail by returning null
- }
- return null;
- }
-
- @Override
- public ContentValues toContentValues() {
- ContentValues values = new ContentValues();
- values.put(AccountColumns.DISPLAY_NAME, mDisplayName);
- values.put(AccountColumns.EMAIL_ADDRESS, mEmailAddress);
- values.put(AccountColumns.SYNC_KEY, mSyncKey);
- values.put(AccountColumns.SYNC_LOOKBACK, mSyncLookback);
- values.put(AccountColumns.SYNC_INTERVAL, mSyncInterval);
- values.put(AccountColumns.HOST_AUTH_KEY_RECV, mHostAuthKeyRecv);
- values.put(AccountColumns.HOST_AUTH_KEY_SEND, mHostAuthKeySend);
- values.put(AccountColumns.FLAGS, mFlags);
- values.put(AccountColumns.IS_DEFAULT, mIsDefault);
- values.put(AccountColumns.COMPATIBILITY_UUID, mCompatibilityUuid);
- values.put(AccountColumns.SENDER_NAME, mSenderName);
- values.put(AccountColumns.RINGTONE_URI, mRingtoneUri);
- values.put(AccountColumns.PROTOCOL_VERSION, mProtocolVersion);
- values.put(AccountColumns.NEW_MESSAGE_COUNT, mNewMessageCount);
- values.put(AccountColumns.SECURITY_FLAGS, mSecurityFlags);
- values.put(AccountColumns.SECURITY_SYNC_KEY, mSecuritySyncKey);
- values.put(AccountColumns.SIGNATURE, mSignature);
- return values;
- }
-
- /**
- * Supports Parcelable
- */
- public int describeContents() {
- return 0;
- }
-
- /**
- * Supports Parcelable
- */
- public static final Parcelable.Creator<EmailContent.Account> CREATOR
- = new Parcelable.Creator<EmailContent.Account>() {
- public EmailContent.Account createFromParcel(Parcel in) {
- return new EmailContent.Account(in);
- }
-
- public EmailContent.Account[] newArray(int size) {
- return new EmailContent.Account[size];
- }
- };
-
- /**
- * Supports Parcelable
- */
- public void writeToParcel(Parcel dest, int flags) {
- // mBaseUri is not parceled
- dest.writeLong(mId);
- dest.writeString(mDisplayName);
- dest.writeString(mEmailAddress);
- dest.writeString(mSyncKey);
- dest.writeInt(mSyncLookback);
- dest.writeInt(mSyncInterval);
- dest.writeLong(mHostAuthKeyRecv);
- dest.writeLong(mHostAuthKeySend);
- dest.writeInt(mFlags);
- dest.writeByte(mIsDefault ? (byte)1 : (byte)0);
- dest.writeString(mCompatibilityUuid);
- dest.writeString(mSenderName);
- dest.writeString(mRingtoneUri);
- dest.writeString(mProtocolVersion);
- dest.writeInt(mNewMessageCount);
- dest.writeLong(mSecurityFlags);
- dest.writeString(mSecuritySyncKey);
- dest.writeString(mSignature);
-
- if (mHostAuthRecv != null) {
- dest.writeByte((byte)1);
- mHostAuthRecv.writeToParcel(dest, flags);
- } else {
- dest.writeByte((byte)0);
- }
-
- if (mHostAuthSend != null) {
- dest.writeByte((byte)1);
- mHostAuthSend.writeToParcel(dest, flags);
- } else {
- dest.writeByte((byte)0);
- }
- }
-
- /**
- * Supports Parcelable
- */
- public Account(Parcel in) {
- mBaseUri = EmailContent.Account.CONTENT_URI;
- mId = in.readLong();
- mDisplayName = in.readString();
- mEmailAddress = in.readString();
- mSyncKey = in.readString();
- mSyncLookback = in.readInt();
- mSyncInterval = in.readInt();
- mHostAuthKeyRecv = in.readLong();
- mHostAuthKeySend = in.readLong();
- mFlags = in.readInt();
- mIsDefault = in.readByte() == 1;
- mCompatibilityUuid = in.readString();
- mSenderName = in.readString();
- mRingtoneUri = in.readString();
- mProtocolVersion = in.readString();
- mNewMessageCount = in.readInt();
- mSecurityFlags = in.readLong();
- mSecuritySyncKey = in.readString();
- mSignature = in.readString();
-
- mHostAuthRecv = null;
- if (in.readByte() == 1) {
- mHostAuthRecv = new EmailContent.HostAuth(in);
- }
-
- mHostAuthSend = null;
- if (in.readByte() == 1) {
- mHostAuthSend = new EmailContent.HostAuth(in);
- }
- }
-
- /**
- * For debugger support only - DO NOT use for code.
- */
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder('[');
- if (mHostAuthRecv != null && mHostAuthRecv.mProtocol != null) {
- sb.append(mHostAuthRecv.mProtocol);
- sb.append(':');
- }
- if (mDisplayName != null) sb.append(mDisplayName);
- sb.append(':');
- if (mEmailAddress != null) sb.append(mEmailAddress);
- sb.append(':');
- if (mSenderName != null) sb.append(mSenderName);
- sb.append(']');
- return sb.toString();
- }
-
- }
-
- public interface AttachmentColumns {
- public static final String ID = "_id";
- // The display name of the attachment
- public static final String FILENAME = "fileName";
- // The mime type of the attachment
- public static final String MIME_TYPE = "mimeType";
- // The size of the attachment in bytes
- public static final String SIZE = "size";
- // The (internal) contentId of the attachment (inline attachments will have these)
- public static final String CONTENT_ID = "contentId";
- // The location of the loaded attachment (probably a file)
- @SuppressWarnings("hiding")
- public static final String CONTENT_URI = "contentUri";
- // A foreign key into the Message table (the message owning this attachment)
- public static final String MESSAGE_KEY = "messageKey";
- // The location of the attachment on the server side
- // For IMAP, this is a part number (e.g. 2.1); for EAS, it's the internal file name
- public static final String LOCATION = "location";
- // The transfer encoding of the attachment
- public static final String ENCODING = "encoding";
- // Not currently used
- public static final String CONTENT = "content";
- // Flags
- public static final String FLAGS = "flags";
- // Content that is actually contained in the Attachment row
- public static final String CONTENT_BYTES = "content_bytes";
- // A foreign key into the Account table (for the message owning this attachment)
- public static final String ACCOUNT_KEY = "accountKey";
- }
-
- public static final class Attachment extends EmailContent implements AttachmentColumns {
- public static final String TABLE_NAME = "Attachment";
- @SuppressWarnings("hiding")
- public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/attachment");
- // This must be used with an appended id: ContentUris.withAppendedId(MESSAGE_ID_URI, id)
- public static final Uri MESSAGE_ID_URI = Uri.parse(
- EmailContent.CONTENT_URI + "/attachment/message");
-
- public String mFileName;
- public String mMimeType;
- public long mSize;
- public String mContentId;
- public String mContentUri;
- public long mMessageKey;
- public String mLocation;
- public String mEncoding;
- public String mContent; // Not currently used
- public int mFlags;
- public byte[] mContentBytes;
- public long mAccountKey;
-
- public static final int CONTENT_ID_COLUMN = 0;
- public static final int CONTENT_FILENAME_COLUMN = 1;
- public static final int CONTENT_MIME_TYPE_COLUMN = 2;
- public static final int CONTENT_SIZE_COLUMN = 3;
- public static final int CONTENT_CONTENT_ID_COLUMN = 4;
- public static final int CONTENT_CONTENT_URI_COLUMN = 5;
- public static final int CONTENT_MESSAGE_ID_COLUMN = 6;
- public static final int CONTENT_LOCATION_COLUMN = 7;
- public static final int CONTENT_ENCODING_COLUMN = 8;
- public static final int CONTENT_CONTENT_COLUMN = 9; // Not currently used
- public static final int CONTENT_FLAGS_COLUMN = 10;
- public static final int CONTENT_CONTENT_BYTES_COLUMN = 11;
- public static final int CONTENT_ACCOUNT_KEY_COLUMN = 12;
- public static final String[] CONTENT_PROJECTION = new String[] {
- RECORD_ID, AttachmentColumns.FILENAME, AttachmentColumns.MIME_TYPE,
- AttachmentColumns.SIZE, AttachmentColumns.CONTENT_ID, AttachmentColumns.CONTENT_URI,
- AttachmentColumns.MESSAGE_KEY, AttachmentColumns.LOCATION, AttachmentColumns.ENCODING,
- AttachmentColumns.CONTENT, AttachmentColumns.FLAGS, AttachmentColumns.CONTENT_BYTES,
- AttachmentColumns.ACCOUNT_KEY
- };
-
- // All attachments with an empty URI, regardless of mailbox
- public static final String EMPTY_URI_SELECTION =
- AttachmentColumns.CONTENT_URI + " isnull AND " + Attachment.FLAGS + "=0";
- // Attachments with an empty URI that are in an inbox
- public static final String EMPTY_URI_INBOX_SELECTION =
- EMPTY_URI_SELECTION + " AND " + AttachmentColumns.MESSAGE_KEY + " IN ("
- + "SELECT " + MessageColumns.ID + " FROM " + Message.TABLE_NAME
- + " WHERE " + Message.INBOX_SELECTION
- + ")";
-
- // Bits used in mFlags
- // Instruct Rfc822Output to 1) not use Content-Disposition and 2) use multipart/alternative
- // with this attachment. This is only valid if there is one and only one attachment and
- // that attachment has this flag set
- public static final int FLAG_ICS_ALTERNATIVE_PART = 1<<0;
- // Indicate that this attachment has been requested for downloading by the user; this is
- // the highest priority for attachment downloading
- public static final int FLAG_DOWNLOAD_USER_REQUEST = 1<<1;
- // Indicate that this attachment needs to be downloaded as part of an outgoing forwarded
- // message
- public static final int FLAG_DOWNLOAD_FORWARD = 1<<2;
- // Indicates that the attachment download failed in a non-recoverable manner
- public static final int FLAG_DOWNLOAD_FAILED = 1<<3;
- // Allow "room" for some additional download-related flags here
- // Indicates that the attachment will be smart-forwarded
- public static final int FLAG_SMART_FORWARD = 1<<8;
- /**
- * no public constructor since this is a utility class
- */
- public Attachment() {
- mBaseUri = CONTENT_URI;
- }
-
- /**
- * Restore an Attachment from the database, given its unique id
- * @param context
- * @param id
- * @return the instantiated Attachment
- */
- public static Attachment restoreAttachmentWithId (Context context, long id) {
- Uri u = ContentUris.withAppendedId(Attachment.CONTENT_URI, id);
- Cursor c = context.getContentResolver().query(u, Attachment.CONTENT_PROJECTION,
- null, null, null);
-
- try {
- if (c.moveToFirst()) {
- return getContent(c, Attachment.class);
- } else {
- return null;
- }
- } finally {
- c.close();
- }
- }
-
- /**
- * Restore all the Attachments of a message given its messageId
- */
- public static Attachment[] restoreAttachmentsWithMessageId(Context context,
- long messageId) {
- Uri uri = ContentUris.withAppendedId(MESSAGE_ID_URI, messageId);
- Cursor c = context.getContentResolver().query(uri, CONTENT_PROJECTION,
- null, null, null);
- try {
- int count = c.getCount();
- Attachment[] attachments = new Attachment[count];
- for (int i = 0; i < count; ++i) {
- c.moveToNext();
- Attachment attach = new Attachment();
- attach.restore(c);
- attachments[i] = attach;
- }
- return attachments;
- } finally {
- c.close();
- }
- }
-
- /**
- * Creates a unique file in the external store by appending a hyphen
- * and a number to the given filename.
- * @param filename
- * @return a new File object, or null if one could not be created
- */
- public static File createUniqueFile(String filename) {
- // TODO Handle internal storage, as required
- if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
- File directory = Environment.getExternalStorageDirectory();
- File file = new File(directory, filename);
- if (!file.exists()) {
- return file;
- }
- // Get the extension of the file, if any.
- int index = filename.lastIndexOf('.');
- String name = filename;
- String extension = "";
- if (index != -1) {
- name = filename.substring(0, index);
- extension = filename.substring(index);
- }
- for (int i = 2; i < Integer.MAX_VALUE; i++) {
- file = new File(directory, name + '-' + i + extension);
- if (!file.exists()) {
- return file;
- }
- }
- return null;
- }
- return null;
- }
-
- @Override
- public void restore(Cursor cursor) {
- mBaseUri = CONTENT_URI;
- mId = cursor.getLong(CONTENT_ID_COLUMN);
- mFileName= cursor.getString(CONTENT_FILENAME_COLUMN);
- mMimeType = cursor.getString(CONTENT_MIME_TYPE_COLUMN);
- mSize = cursor.getLong(CONTENT_SIZE_COLUMN);
- mContentId = cursor.getString(CONTENT_CONTENT_ID_COLUMN);
- mContentUri = cursor.getString(CONTENT_CONTENT_URI_COLUMN);
- mMessageKey = cursor.getLong(CONTENT_MESSAGE_ID_COLUMN);
- mLocation = cursor.getString(CONTENT_LOCATION_COLUMN);
- mEncoding = cursor.getString(CONTENT_ENCODING_COLUMN);
- mContent = cursor.getString(CONTENT_CONTENT_COLUMN);
- mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN);
- mContentBytes = cursor.getBlob(CONTENT_CONTENT_BYTES_COLUMN);
- mAccountKey = cursor.getLong(CONTENT_ACCOUNT_KEY_COLUMN);
- }
-
- @Override
- public ContentValues toContentValues() {
- ContentValues values = new ContentValues();
- values.put(AttachmentColumns.FILENAME, mFileName);
- values.put(AttachmentColumns.MIME_TYPE, mMimeType);
- values.put(AttachmentColumns.SIZE, mSize);
- values.put(AttachmentColumns.CONTENT_ID, mContentId);
- values.put(AttachmentColumns.CONTENT_URI, mContentUri);
- values.put(AttachmentColumns.MESSAGE_KEY, mMessageKey);
- values.put(AttachmentColumns.LOCATION, mLocation);
- values.put(AttachmentColumns.ENCODING, mEncoding);
- values.put(AttachmentColumns.CONTENT, mContent);
- values.put(AttachmentColumns.FLAGS, mFlags);
- values.put(AttachmentColumns.CONTENT_BYTES, mContentBytes);
- values.put(AttachmentColumns.ACCOUNT_KEY, mAccountKey);
- return values;
- }
-
- public int describeContents() {
- return 0;
- }
-
- public void writeToParcel(Parcel dest, int flags) {
- // mBaseUri is not parceled
- dest.writeLong(mId);
- dest.writeString(mFileName);
- dest.writeString(mMimeType);
- dest.writeLong(mSize);
- dest.writeString(mContentId);
- dest.writeString(mContentUri);
- dest.writeLong(mMessageKey);
- dest.writeString(mLocation);
- dest.writeString(mEncoding);
- dest.writeString(mContent);
- dest.writeInt(mFlags);
- dest.writeLong(mAccountKey);
- if (mContentBytes == null) {
- dest.writeInt(-1);
- } else {
- dest.writeInt(mContentBytes.length);
- dest.writeByteArray(mContentBytes);
- }
- }
-
- public Attachment(Parcel in) {
- mBaseUri = EmailContent.Attachment.CONTENT_URI;
- mId = in.readLong();
- mFileName = in.readString();
- mMimeType = in.readString();
- mSize = in.readLong();
- mContentId = in.readString();
- mContentUri = in.readString();
- mMessageKey = in.readLong();
- mLocation = in.readString();
- mEncoding = in.readString();
- mContent = in.readString();
- mFlags = in.readInt();
- mAccountKey = in.readLong();
- final int contentBytesLen = in.readInt();
- if (contentBytesLen == -1) {
- mContentBytes = null;
- } else {
- mContentBytes = new byte[contentBytesLen];
- in.readByteArray(mContentBytes);
- }
- }
-
- public static final Parcelable.Creator<EmailContent.Attachment> CREATOR
- = new Parcelable.Creator<EmailContent.Attachment>() {
- public EmailContent.Attachment createFromParcel(Parcel in) {
- return new EmailContent.Attachment(in);
- }
-
- public EmailContent.Attachment[] newArray(int size) {
- return new EmailContent.Attachment[size];
- }
- };
-
- @Override
- public String toString() {
- return "[" + mFileName + ", " + mMimeType + ", " + mSize + ", " + mContentId + ", "
- + mContentUri + ", " + mMessageKey + ", " + mLocation + ", " + mEncoding + ", "
- + mFlags + ", " + mContentBytes + ", " + mAccountKey + "]";
- }
- }
-
- public interface MailboxColumns {
- public static final String ID = "_id";
- // The display name of this mailbox [INDEX]
- static final String DISPLAY_NAME = "displayName";
- // The server's identifier for this mailbox
- public static final String SERVER_ID = "serverId";
- // The server's identifier for the parent of this mailbox (null = top-level)
- public static final String PARENT_SERVER_ID = "parentServerId";
- // A foreign key to the Account that owns this mailbox
- public static final String ACCOUNT_KEY = "accountKey";
- // The type (role) of this mailbox
- public static final String TYPE = "type";
- // The hierarchy separator character
- public static final String DELIMITER = "delimiter";
- // Server-based sync key or validity marker (e.g. "SyncKey" for EAS, "uidvalidity" for IMAP)
- public static final String SYNC_KEY = "syncKey";
- // The sync lookback period for this mailbox (or null if using the account default)
- public static final String SYNC_LOOKBACK = "syncLookback";
- // The sync frequency for this mailbox (or null if using the account default)
- public static final String SYNC_INTERVAL = "syncInterval";
- // The time of last successful sync completion (millis)
- public static final String SYNC_TIME = "syncTime";
- // Cached unread count
- public static final String UNREAD_COUNT = "unreadCount";
- // Visibility of this folder in a list of folders [INDEX]
- public static final String FLAG_VISIBLE = "flagVisible";
- // Other states, as a bit field, e.g. CHILDREN_VISIBLE, HAS_CHILDREN
- public static final String FLAGS = "flags";
- // Backward compatible
- public static final String VISIBLE_LIMIT = "visibleLimit";
- // Sync status (can be used as desired by sync services)
- public static final String SYNC_STATUS = "syncStatus";
- // Number of messages in the mailbox.
- public static final String MESSAGE_COUNT = "messageCount";
- }
-
- public static final class Mailbox extends EmailContent implements SyncColumns, MailboxColumns {
- public static final String TABLE_NAME = "Mailbox";
- @SuppressWarnings("hiding")
- public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/mailbox");
- public static final Uri ADD_TO_FIELD_URI =
- Uri.parse(EmailContent.CONTENT_URI + "/mailboxIdAddToField");
-
- public String mDisplayName;
- public String mServerId;
- public String mParentServerId;
- public long mAccountKey;
- public int mType;
- public int mDelimiter;
- public String mSyncKey;
- public int mSyncLookback;
- public int mSyncInterval;
- public long mSyncTime;
- public boolean mFlagVisible = true;
- public int mFlags;
- public int mVisibleLimit;
- public String mSyncStatus;
-
- public static final int CONTENT_ID_COLUMN = 0;
- public static final int CONTENT_DISPLAY_NAME_COLUMN = 1;
- public static final int CONTENT_SERVER_ID_COLUMN = 2;
- public static final int CONTENT_PARENT_SERVER_ID_COLUMN = 3;
- public static final int CONTENT_ACCOUNT_KEY_COLUMN = 4;
- public static final int CONTENT_TYPE_COLUMN = 5;
- public static final int CONTENT_DELIMITER_COLUMN = 6;
- public static final int CONTENT_SYNC_KEY_COLUMN = 7;
- public static final int CONTENT_SYNC_LOOKBACK_COLUMN = 8;
- public static final int CONTENT_SYNC_INTERVAL_COLUMN = 9;
- public static final int CONTENT_SYNC_TIME_COLUMN = 10;
- public static final int CONTENT_FLAG_VISIBLE_COLUMN = 11;
- public static final int CONTENT_FLAGS_COLUMN = 12;
- public static final int CONTENT_VISIBLE_LIMIT_COLUMN = 13;
- public static final int CONTENT_SYNC_STATUS_COLUMN = 14;
- public static final String[] CONTENT_PROJECTION = new String[] {
- RECORD_ID, MailboxColumns.DISPLAY_NAME, MailboxColumns.SERVER_ID,
- MailboxColumns.PARENT_SERVER_ID, MailboxColumns.ACCOUNT_KEY, MailboxColumns.TYPE,
- MailboxColumns.DELIMITER, MailboxColumns.SYNC_KEY, MailboxColumns.SYNC_LOOKBACK,
- MailboxColumns.SYNC_INTERVAL, MailboxColumns.SYNC_TIME,
- MailboxColumns.FLAG_VISIBLE, MailboxColumns.FLAGS, MailboxColumns.VISIBLE_LIMIT,
- MailboxColumns.SYNC_STATUS
- };
-
- private static final String ACCOUNT_AND_MAILBOX_TYPE_SELECTION =
- MailboxColumns.ACCOUNT_KEY + " =? AND " +
- MailboxColumns.TYPE + " =?";
- private static final String MAILBOX_TYPE_SELECTION =
- MailboxColumns.TYPE + " =?";
- private static final String[] MAILBOX_SUM_OF_UNREAD_COUNT_PROJECTION = new String [] {
- "sum(" + MailboxColumns.UNREAD_COUNT + ")"
- };
- private static final int UNREAD_COUNT_COUNT_COLUMN = 0;
- private static final String[] MAILBOX_SUM_OF_MESSAGE_COUNT_PROJECTION = new String [] {
- "sum(" + MailboxColumns.MESSAGE_COUNT + ")"
- };
- private static final int MESSAGE_COUNT_COUNT_COLUMN = 0;
-
- private static final String[] MAILBOX_TYPE_PROJECTION = new String [] {
- MailboxColumns.TYPE
- };
- private static final int MAILBOX_TYPE_TYPE_COLUMN = 0;
-
- private static final String[] MAILBOX_DISPLAY_NAME_PROJECTION = new String [] {
- MailboxColumns.DISPLAY_NAME
- };
- private static final int MAILBOX_DISPLAY_NAME_COLUMN = 0;
-
- public static final long NO_MAILBOX = -1;
-
- // Sentinel values for the mSyncInterval field of both Mailbox records
- public static final int CHECK_INTERVAL_NEVER = -1;
- public static final int CHECK_INTERVAL_PUSH = -2;
- // The following two sentinel values are used by EAS
- // Ping indicates that the EAS mailbox is synced based on a "ping" from the server
- public static final int CHECK_INTERVAL_PING = -3;
- // Push-Hold indicates an EAS push or ping Mailbox shouldn't sync just yet
- public static final int CHECK_INTERVAL_PUSH_HOLD = -4;
-
- private static final String WHERE_TYPE_AND_ACCOUNT_KEY =
- MailboxColumns.TYPE + "=? and " + MailboxColumns.ACCOUNT_KEY + "=?";
-
- public static final String MOVE_TO_TARGET_MAILBOX_SELECTION =
- MailboxColumns.TYPE + " NOT IN (" + Mailbox.TYPE_DRAFTS + "," +
- Mailbox.TYPE_OUTBOX + "," + Mailbox.TYPE_SENT + "," + Mailbox.TYPE_TRASH + ")";
- public static final Integer[] INVALID_DROP_TARGETS = new Integer[] {Mailbox.TYPE_DRAFTS,
- Mailbox.TYPE_OUTBOX, Mailbox.TYPE_SENT};
-
- public static final String USER_VISIBLE_MAILBOX_SELECTION =
- MailboxColumns.TYPE + "<" + Mailbox.TYPE_NOT_EMAIL +
- " AND " + MailboxColumns.FLAG_VISIBLE + "=1";
-
- // Types of mailboxes. The list is ordered to match a typical UI presentation, e.g.
- // placing the inbox at the top.
- // The "main" mailbox for the account, almost always referred to as "Inbox"
- // Arrays of "special_mailbox_display_names" and "special_mailbox_icons" are depends on
- // types Id of mailboxes.
- public static final int TYPE_INBOX = 0;
- // Types of mailboxes
- // Holds mail (generic)
- public static final int TYPE_MAIL = 1;
- // Parent-only mailbox; holds no mail
- public static final int TYPE_PARENT = 2;
- // Holds drafts
- public static final int TYPE_DRAFTS = 3;
- // The local outbox associated with the Account
- public static final int TYPE_OUTBOX = 4;
- // Holds sent mail
- public static final int TYPE_SENT = 5;
- // Holds deleted mail
- public static final int TYPE_TRASH = 6;
- // Holds junk mail
- public static final int TYPE_JUNK = 7;
-
- // Types after this are used for non-mail mailboxes (as in EAS)
- public static final int TYPE_NOT_EMAIL = 0x40;
- public static final int TYPE_CALENDAR = 0x41;
- public static final int TYPE_CONTACTS = 0x42;
- public static final int TYPE_TASKS = 0x43;
- public static final int TYPE_EAS_ACCOUNT_MAILBOX = 0x44;
- public static final int TYPE_UNKNOWN = 0x45;
-
- public static final int TYPE_NOT_SYNCABLE = 0x100;
- // A mailbox that holds Messages that are attachments
- public static final int TYPE_ATTACHMENT = 0x101;
-
- // Bit field flags
- public static final int FLAG_HAS_CHILDREN = 1<<0;
- public static final int FLAG_CHILDREN_VISIBLE = 1<<1;
- public static final int FLAG_CANT_PUSH = 1<<2;
-
- // Magic mailbox ID's
- // NOTE: This is a quick solution for merged mailboxes. I would rather implement this
- // with a more generic way of packaging and sharing queries between activities
- public static final long QUERY_ALL_INBOXES = -2;
- public static final long QUERY_ALL_UNREAD = -3;
- public static final long QUERY_ALL_FAVORITES = -4;
- public static final long QUERY_ALL_DRAFTS = -5;
- public static final long QUERY_ALL_OUTBOX = -6;
-
- public Mailbox() {
- mBaseUri = CONTENT_URI;
- }
-
- /**
- * Restore a Mailbox from the database, given its unique id
- * @param context
- * @param id
- * @return the instantiated Mailbox
- */
- public static Mailbox restoreMailboxWithId(Context context, long id) {
- Uri u = ContentUris.withAppendedId(Mailbox.CONTENT_URI, id);
- Cursor c = context.getContentResolver().query(u, Mailbox.CONTENT_PROJECTION,
- null, null, null);
-
- try {
- if (c.moveToFirst()) {
- return getContent(c, Mailbox.class);
- } else {
- return null;
- }
- } finally {
- c.close();
- }
- }
-
- @Override
- public void restore(Cursor cursor) {
- mBaseUri = CONTENT_URI;
- mId = cursor.getLong(CONTENT_ID_COLUMN);
- mDisplayName = cursor.getString(CONTENT_DISPLAY_NAME_COLUMN);
- mServerId = cursor.getString(CONTENT_SERVER_ID_COLUMN);
- mParentServerId = cursor.getString(CONTENT_PARENT_SERVER_ID_COLUMN);
- mAccountKey = cursor.getLong(CONTENT_ACCOUNT_KEY_COLUMN);
- mType = cursor.getInt(CONTENT_TYPE_COLUMN);
- mDelimiter = cursor.getInt(CONTENT_DELIMITER_COLUMN);
- mSyncKey = cursor.getString(CONTENT_SYNC_KEY_COLUMN);
- mSyncLookback = cursor.getInt(CONTENT_SYNC_LOOKBACK_COLUMN);
- mSyncInterval = cursor.getInt(CONTENT_SYNC_INTERVAL_COLUMN);
- mSyncTime = cursor.getLong(CONTENT_SYNC_TIME_COLUMN);
- mFlagVisible = cursor.getInt(CONTENT_FLAG_VISIBLE_COLUMN) == 1;
- mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN);
- mVisibleLimit = cursor.getInt(CONTENT_VISIBLE_LIMIT_COLUMN);
- mSyncStatus = cursor.getString(CONTENT_SYNC_STATUS_COLUMN);
- }
-
- @Override
- public ContentValues toContentValues() {
- ContentValues values = new ContentValues();
- values.put(MailboxColumns.DISPLAY_NAME, mDisplayName);
- values.put(MailboxColumns.SERVER_ID, mServerId);
- values.put(MailboxColumns.PARENT_SERVER_ID, mParentServerId);
- values.put(MailboxColumns.ACCOUNT_KEY, mAccountKey);
- values.put(MailboxColumns.TYPE, mType);
- values.put(MailboxColumns.DELIMITER, mDelimiter);
- values.put(MailboxColumns.SYNC_KEY, mSyncKey);
- values.put(MailboxColumns.SYNC_LOOKBACK, mSyncLookback);
- values.put(MailboxColumns.SYNC_INTERVAL, mSyncInterval);
- values.put(MailboxColumns.SYNC_TIME, mSyncTime);
- values.put(MailboxColumns.FLAG_VISIBLE, mFlagVisible);
- values.put(MailboxColumns.FLAGS, mFlags);
- values.put(MailboxColumns.VISIBLE_LIMIT, mVisibleLimit);
- values.put(MailboxColumns.SYNC_STATUS, mSyncStatus);
- return values;
- }
-
- /**
- * Convenience method to return the id of a given type of Mailbox for a given Account
- * @param context the caller's context, used to get a ContentResolver
- * @param accountId the id of the account to be queried
- * @param type the mailbox type, as defined above
- * @return the id of the mailbox, or -1 if not found
- */
- public static long findMailboxOfType(Context context, long accountId, int type) {
- String[] bindArguments = new String[] {Long.toString(type), Long.toString(accountId)};
- return Utility.getFirstRowLong(context, Mailbox.CONTENT_URI,
- ID_PROJECTION, WHERE_TYPE_AND_ACCOUNT_KEY, bindArguments, null,
- ID_PROJECTION_COLUMN, NO_MAILBOX);
- }
-
- /**
- * Convenience method that returns the mailbox found using the method above
- */
- public static Mailbox restoreMailboxOfType(Context context, long accountId, int type) {
- long mailboxId = findMailboxOfType(context, accountId, type);
- if (mailboxId != Mailbox.NO_MAILBOX) {
- return Mailbox.restoreMailboxWithId(context, mailboxId);
- }
- return null;
- }
-
- public static int getUnreadCountByAccountAndMailboxType(Context context, long accountId,
- int type) {
- return Utility.getFirstRowInt(context, Mailbox.CONTENT_URI,
- MAILBOX_SUM_OF_UNREAD_COUNT_PROJECTION,
- ACCOUNT_AND_MAILBOX_TYPE_SELECTION,
- new String[] { String.valueOf(accountId), String.valueOf(type) },
- null, UNREAD_COUNT_COUNT_COLUMN, 0);
- }
-
- public static int getUnreadCountByMailboxType(Context context, int type) {
- return Utility.getFirstRowInt(context, Mailbox.CONTENT_URI,
- MAILBOX_SUM_OF_UNREAD_COUNT_PROJECTION,
- MAILBOX_TYPE_SELECTION,
- new String[] { String.valueOf(type) }, null, UNREAD_COUNT_COUNT_COLUMN, 0);
- }
-
- public static int getMessageCountByMailboxType(Context context, int type) {
- return Utility.getFirstRowInt(context, Mailbox.CONTENT_URI,
- MAILBOX_SUM_OF_MESSAGE_COUNT_PROJECTION,
- MAILBOX_TYPE_SELECTION,
- new String[] { String.valueOf(type) }, null, MESSAGE_COUNT_COUNT_COLUMN, 0);
- }
-
- /**
- * Return the mailbox for a message with a given id
- * @param context the caller's context
- * @param messageId the id of the message
- * @return the mailbox, or null if the mailbox doesn't exist
- */
- public static Mailbox getMailboxForMessageId(Context context, long messageId) {
- long mailboxId = Message.getKeyColumnLong(context, messageId,
- MessageColumns.MAILBOX_KEY);
- if (mailboxId != -1) {
- return Mailbox.restoreMailboxWithId(context, mailboxId);
- }
- return null;
- }
-
- /**
- * @return mailbox type, or -1 if mailbox not found.
- */
- public static int getMailboxType(Context context, long mailboxId) {
- Uri url = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId);
- return Utility.getFirstRowInt(context, url, MAILBOX_TYPE_PROJECTION,
- null, null, null, MAILBOX_TYPE_TYPE_COLUMN, -1);
- }
-
- /**
- * @return mailbox display name, or null if mailbox not found.
- */
- public static String getDisplayName(Context context, long mailboxId) {
- Uri url = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId);
- return Utility.getFirstRowString(context, url, MAILBOX_DISPLAY_NAME_PROJECTION,
- null, null, null, MAILBOX_DISPLAY_NAME_COLUMN);
- }
-
- /**
- * @param mailboxId ID of a mailbox. This method accepts magic mailbox IDs, such as
- * {@link #QUERY_ALL_INBOXES}. (They're all non-refreshable.)
- * @return true if a mailbox is refreshable.
- */
- public static boolean isRefreshable(Context context, long mailboxId) {
- if (mailboxId < 0) {
- return false; // magic mailboxes
- }
- switch (getMailboxType(context, mailboxId)) {
- case -1: // not found
- case TYPE_DRAFTS:
- case TYPE_OUTBOX:
- return false;
- }
- return true;
- }
-
- /**
- * @param mailboxId ID of a mailbox. This method DOES NOT accept magic mailbox IDs, such as
- * {@link #QUERY_ALL_INBOXES} (because only the actual mailbox ID matters here. e.g.
- * {@link #QUERY_ALL_FAVORITES} can contain ANY kind of messages), so don't pass a negative
- * value.
- * @return true if messages in a mailbox can be moved to another mailbox.
- * This method only checks the mailbox information. It doesn't check its account/protocol,
- * so it may return true even for POP3 mailbox.
- */
- public static boolean canMoveFrom(Context context, long mailboxId) {
- if (mailboxId < 0) {
- throw new InvalidParameterException();
- }
- Uri url = ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId);
- int type = Utility.getFirstRowInt(context, url, MAILBOX_TYPE_PROJECTION,
- null, null, null, MAILBOX_TYPE_TYPE_COLUMN);
- switch (type) {
- case TYPE_INBOX:
- case TYPE_MAIL:
- case TYPE_TRASH:
- case TYPE_JUNK:
- return true;
- }
- return false; // TYPE_DRAFTS, TYPE_OUTBOX, TYPE_SENT, etc
- }
-
- /**
- * @return true if messages in a mailbox of a type can be replied/forwarded.
- */
- public static boolean isMailboxTypeReplyAndForwardable(int type) {
- return (type != TYPE_TRASH) && (type != TYPE_DRAFTS);
- }
- }
-
- public interface HostAuthColumns {
- public static final String ID = "_id";
- // The protocol (e.g. "imap", "pop3", "eas", "smtp"
- static final String PROTOCOL = "protocol";
- // The host address
- static final String ADDRESS = "address";
- // The port to use for the connection
- static final String PORT = "port";
- // General purpose flags
- static final String FLAGS = "flags";
- // The login (user name)
- static final String LOGIN = "login";
- // Password
- static final String PASSWORD = "password";
- // A domain or path, if required (used in IMAP and EAS)
- static final String DOMAIN = "domain";
- // DEPRECATED - Will not be set or stored
- static final String ACCOUNT_KEY = "accountKey";
- }
-
- public static final class HostAuth extends EmailContent implements HostAuthColumns, Parcelable {
- public static final String TABLE_NAME = "HostAuth";
- @SuppressWarnings("hiding")
- public static final Uri CONTENT_URI = Uri.parse(EmailContent.CONTENT_URI + "/hostauth");
-
- public static final int PORT_UNKNOWN = -1;
-
- public static final int FLAG_NONE = 0x00; // No flags
- public static final int FLAG_SSL = 0x01; // Use SSL
- public static final int FLAG_TLS = 0x02; // Use TLS
- public static final int FLAG_AUTHENTICATE = 0x04; // Use name/password for authentication
- public static final int FLAG_TRUST_ALL = 0x08; // Trust all certificates
- // Mask of settings directly configurable by the user
- public static final int USER_CONFIG_MASK = 0x0b;
-
- public String mProtocol;
- public String mAddress;
- public int mPort;
- public int mFlags;
- public String mLogin;
- public String mPassword;
- public String mDomain;
-
- public static final int CONTENT_ID_COLUMN = 0;
- public static final int CONTENT_PROTOCOL_COLUMN = 1;
- public static final int CONTENT_ADDRESS_COLUMN = 2;
- public static final int CONTENT_PORT_COLUMN = 3;
- public static final int CONTENT_FLAGS_COLUMN = 4;
- public static final int CONTENT_LOGIN_COLUMN = 5;
- public static final int CONTENT_PASSWORD_COLUMN = 6;
- public static final int CONTENT_DOMAIN_COLUMN = 7;
-
- public static final String[] CONTENT_PROJECTION = new String[] {
- RECORD_ID, HostAuthColumns.PROTOCOL, HostAuthColumns.ADDRESS, HostAuthColumns.PORT,
- HostAuthColumns.FLAGS, HostAuthColumns.LOGIN,
- HostAuthColumns.PASSWORD, HostAuthColumns.DOMAIN
- };
-
- /**
- * no public constructor since this is a utility class
- */
- public HostAuth() {
- mBaseUri = CONTENT_URI;
-
- // other defaults policy)
- mPort = PORT_UNKNOWN;
- }
-
- /**
- * Restore a HostAuth from the database, given its unique id
- * @param context
- * @param id
- * @return the instantiated HostAuth
- */
- public static HostAuth restoreHostAuthWithId(Context context, long id) {
- Uri u = ContentUris.withAppendedId(EmailContent.HostAuth.CONTENT_URI, id);
- Cursor c = context.getContentResolver().query(u, HostAuth.CONTENT_PROJECTION,
- null, null, null);
-
- try {
- if (c.moveToFirst()) {
- return getContent(c, HostAuth.class);
- } else {
- return null;
- }
- } finally {
- c.close();
- }
- }
-
-
- /**
- * Returns the scheme for the specified flags.
- */
- public static String getSchemeString(String protocol, int flags) {
- String security = "";
- switch (flags & USER_CONFIG_MASK) {
- case FLAG_SSL:
- security = "+ssl+";
- break;
- case FLAG_SSL | FLAG_TRUST_ALL:
- security = "+ssl+trustallcerts";
- break;
- case FLAG_TLS:
- security = "+tls+";
- break;
- case FLAG_TLS | FLAG_TRUST_ALL:
- security = "+tls+trustallcerts";
- break;
- }
- return protocol + security;
- }
-
- /**
- * Returns the flags for the specified scheme.
- */
- public static int getSchemeFlags(String scheme) {
- String[] schemeParts = scheme.split("\\+");
- int flags = HostAuth.FLAG_NONE;
- if (schemeParts.length >= 2) {
- String part1 = schemeParts[1];
- if ("ssl".equals(part1)) {
- flags |= HostAuth.FLAG_SSL;
- } else if ("tls".equals(part1)) {
- flags |= HostAuth.FLAG_TLS;
- }
- if (schemeParts.length >= 3) {
- String part2 = schemeParts[2];
- if ("trustallcerts".equals(part2)) {
- flags |= HostAuth.FLAG_TRUST_ALL;
- }
- }
- }
- return flags;
- }
-
- @Override
- public void restore(Cursor cursor) {
- mBaseUri = CONTENT_URI;
- mId = cursor.getLong(CONTENT_ID_COLUMN);
- mProtocol = cursor.getString(CONTENT_PROTOCOL_COLUMN);
- mAddress = cursor.getString(CONTENT_ADDRESS_COLUMN);
- mPort = cursor.getInt(CONTENT_PORT_COLUMN);
- mFlags = cursor.getInt(CONTENT_FLAGS_COLUMN);
- mLogin = cursor.getString(CONTENT_LOGIN_COLUMN);
- mPassword = cursor.getString(CONTENT_PASSWORD_COLUMN);
- mDomain = cursor.getString(CONTENT_DOMAIN_COLUMN);
- }
-
- @Override
- public ContentValues toContentValues() {
- ContentValues values = new ContentValues();
- values.put(HostAuthColumns.PROTOCOL, mProtocol);
- values.put(HostAuthColumns.ADDRESS, mAddress);
- values.put(HostAuthColumns.PORT, mPort);
- values.put(HostAuthColumns.FLAGS, mFlags);
- values.put(HostAuthColumns.LOGIN, mLogin);
- values.put(HostAuthColumns.PASSWORD, mPassword);
- values.put(HostAuthColumns.DOMAIN, mDomain);
- values.put(HostAuthColumns.ACCOUNT_KEY, 0); // Need something to satisfy the DB
- return values;
- }
-
- /**
- * For compatibility while converting to provider model, generate a "store URI"
- * TODO cache this so we don't rebuild every time
- *
- * @return a string in the form of a Uri, as used by the other parts of the email app
- */
- public String getStoreUri() {
- String userInfo = null;
- if ((mFlags & FLAG_AUTHENTICATE) != 0) {
- String trimUser = (mLogin != null) ? mLogin.trim() : "";
- String password = (mPassword != null) ? mPassword : "";
- userInfo = trimUser + ":" + password;
- }
- String scheme = getSchemeString(mProtocol, mFlags);
- String address = (mAddress != null) ? mAddress.trim() : null;
- String path = (mDomain != null) ? "/" + mDomain : null;
-
- URI uri;
- try {
- uri = new URI(
- scheme,
- userInfo,
- address,
- mPort,
- path,
- null,
- null);
- return uri.toString();
- } catch (URISyntaxException e) {
- return null;
- }
- }
-
- /**
- * Sets the user name and password from URI user info string
- */
- public void setLogin(String userInfo) {
- String userName = null;
- String userPassword = null;
- if (!TextUtils.isEmpty(userInfo)) {
- String[] userInfoParts = userInfo.split(":", 2);
- userName = userInfoParts[0];
- if (userInfoParts.length > 1) {
- userPassword = userInfoParts[1];
- }
- }
- setLogin(userName, userPassword);
- }
-
- /**
- * Sets the user name and password
- */
- public void setLogin(String userName, String userPassword) {
- mLogin = userName;
- mPassword = userPassword;
-
- if (mLogin == null) {
- mFlags &= ~FLAG_AUTHENTICATE;
- } else {
- mFlags |= FLAG_AUTHENTICATE;
- }
- }
-
- /**
- * Sets the connection values of the auth structure per the given scheme, host and port.
- */
- public void setConnection(String scheme, String host, int port) {
- String[] schemeParts = scheme.split("\\+");
- String protocol = schemeParts[0];
- int flags = getSchemeFlags(scheme);
-
- setConnection(protocol, host, port, flags);
- }
-
- public void setConnection(String protocol, String address, int port, int flags) {
- // Set protocol, security, and additional flags based on uri scheme
- mProtocol = protocol;
-
- mFlags &= ~(FLAG_SSL | FLAG_TLS | FLAG_TRUST_ALL);
- mFlags |= (flags & USER_CONFIG_MASK);
-
- mAddress = address;
- mPort = port;
- if (mPort == PORT_UNKNOWN) {
- boolean useSSL = ((mFlags & FLAG_SSL) != 0);
- // infer port# from protocol + security
- // SSL implies a different port - TLS runs in the "regular" port
- // NOTE: Although the port should be setup in the various setup screens, this
- // block cannot easily be moved because we get process URIs from other sources
- // (e.g. for tests, provider templates and account restore) that may or may not
- // have a port specified.
- if ("pop3".equals(mProtocol)) {
- mPort = useSSL ? 995 : 110;
- } else if ("imap".equals(mProtocol)) {
- mPort = useSSL ? 993 : 143;
- } else if ("eas".equals(mProtocol)) {
- mPort = useSSL ? 443 : 80;
- } else if ("smtp".equals(mProtocol)) {
- mPort = useSSL ? 465 : 587;
- }
- }
- }
-
- /**
- * Supports Parcelable
- */
- public int describeContents() {
- return 0;
- }
-
- /**
- * Supports Parcelable
- */
- public static final Parcelable.Creator<EmailContent.HostAuth> CREATOR
- = new Parcelable.Creator<EmailContent.HostAuth>() {
- public EmailContent.HostAuth createFromParcel(Parcel in) {
- return new EmailContent.HostAuth(in);
- }
-
- public EmailContent.HostAuth[] newArray(int size) {
- return new EmailContent.HostAuth[size];
- }
- };
-
- /**
- * Supports Parcelable
- */
- public void writeToParcel(Parcel dest, int flags) {
- // mBaseUri is not parceled
- dest.writeLong(mId);
- dest.writeString(mProtocol);
- dest.writeString(mAddress);
- dest.writeInt(mPort);
- dest.writeInt(mFlags);
- dest.writeString(mLogin);
- dest.writeString(mPassword);
- dest.writeString(mDomain);
- }
-
- /**
- * Supports Parcelable
- */
- public HostAuth(Parcel in) {
- mBaseUri = CONTENT_URI;
- mId = in.readLong();
- mProtocol = in.readString();
- mAddress = in.readString();
- mPort = in.readInt();
- mFlags = in.readInt();
- mLogin = in.readString();
- mPassword = in.readString();
- mDomain = in.readString();
- }
-
- /**
- * For debugger support only - DO NOT use for code.
- */
- @Override
- public String toString() {
- return getStoreUri();
- }
-
- @Override
- public boolean equals(Object o) {
- if (!(o instanceof HostAuth)) {
- return false;
- }
- HostAuth that = (HostAuth)o;
- return mPort == that.mPort
- && mFlags == that.mFlags
- && Utility.areStringsEqual(mProtocol, that.mProtocol)
- && Utility.areStringsEqual(mAddress, that.mAddress)
- && Utility.areStringsEqual(mLogin, that.mLogin)
- && Utility.areStringsEqual(mPassword, that.mPassword)
- && Utility.areStringsEqual(mDomain, that.mDomain);
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java
deleted file mode 100644
index 55e381908..000000000
--- a/emailcommon/src/com/android/emailcommon/service/AccountServiceProxy.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.os.RemoteException;
-
-public class AccountServiceProxy extends ServiceProxy implements IAccountService {
-
- public static final String ACCOUNT_INTENT = "com.android.email.ACCOUNT_INTENT";
- public static final int DEFAULT_ACCOUNT_COLOR = 0xFF0000FF;
-
- private IAccountService mService = null;
- private Object mReturn;
-
- public AccountServiceProxy(Context _context) {
- super(_context, new Intent(ACCOUNT_INTENT));
- }
-
- @Override
- public void onConnected(IBinder binder) {
- mService = IAccountService.Stub.asInterface(binder);
- }
-
- public IBinder asBinder() {
- return null;
- }
-
- @Override
- public void notifyLoginFailed(final long accountId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.notifyLoginFailed(accountId);
- }
- }, "notifyLoginFailed");
- }
-
- @Override
- public void notifyLoginSucceeded(final long accountId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.notifyLoginSucceeded(accountId);
- }
- }, "notifyLoginSucceeded");
- }
-
- @Override
- public void notifyNewMessages(final long accountId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.notifyNewMessages(accountId);
- }
- }, "notifyNewMessages");
- }
-
- @Override
- public void accountDeleted() throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.accountDeleted();
- }
- }, "accountDeleted");
- }
-
- // The following call is synchronous, and should not be made from the UI thread
- @Override
- public void restoreAccountsIfNeeded() throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.restoreAccountsIfNeeded();
- }
- }, "restoreAccountsIfNeeded");
- waitForCompletion();
- }
-
- // The following call is synchronous, and should not be made from the UI thread
- @Override
- public int getAccountColor(final long accountId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException{
- mReturn = mService.getAccountColor(accountId);
- }
- }, "getAccountColor");
- waitForCompletion();
- if (mReturn == null) {
- return DEFAULT_ACCOUNT_COLOR;
- } else {
- return (Integer)mReturn;
- }
- }
-
- // The following call is synchronous, and should not be made from the UI thread
- public Bundle getConfigurationData(final String accountType) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException{
- mReturn = mService.getConfigurationData(accountType);
- }
- }, "getConfigurationData");
- waitForCompletion();
- if (mReturn == null) {
- return null;
- } else {
- return (Bundle)mReturn;
- }
- }
-
- // The following call is synchronous, and should not be made from the UI thread
- public String getDeviceId() throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException{
- mReturn = mService.getDeviceId();
- }
- }, "getDeviceId");
- waitForCompletion();
- if (mReturn == null) {
- return null;
- } else {
- return (String)mReturn;
- }
- }
-}
-
diff --git a/emailcommon/src/com/android/emailcommon/service/EmailServiceConstants.java b/emailcommon/src/com/android/emailcommon/service/EmailServiceConstants.java
deleted file mode 100644
index b229ffc64..000000000
--- a/emailcommon/src/com/android/emailcommon/service/EmailServiceConstants.java
+++ /dev/null
@@ -1,23 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-public class EmailServiceConstants {
- public static final int MEETING_REQUEST_ACCEPTED = 1;
- public static final int MEETING_REQUEST_TENTATIVE = 2;
- public static final int MEETING_REQUEST_DECLINED = 3;
-}
diff --git a/emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java
deleted file mode 100644
index ebe3b68a4..000000000
--- a/emailcommon/src/com/android/emailcommon/service/EmailServiceProxy.java
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-import com.android.emailcommon.Api;
-import com.android.emailcommon.Device;
-import com.android.emailcommon.mail.MessagingException;
-import com.android.emailcommon.provider.EmailContent.HostAuth;
-
-import android.content.Context;
-import android.content.Intent;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.Log;
-
-import java.io.IOException;
-
-/**
- * The EmailServiceProxy class provides a simple interface for the UI to call into the various
- * EmailService classes (e.g. ExchangeService for EAS). It wraps the service connect/disconnect
- * process so that the caller need not be concerned with it.
- *
- * Use the class like this:
- * new EmailServiceClass(context, class).loadAttachment(attachmentId, callback)
- *
- * Methods without a return value return immediately (i.e. are asynchronous); methods with a
- * return value wait for a result from the Service (i.e. they should not be called from the UI
- * thread) with a default timeout of 30 seconds (settable)
- *
- * An EmailServiceProxy object cannot be reused (trying to do so generates a RemoteException)
- */
-
-public class EmailServiceProxy extends ServiceProxy implements IEmailService {
- private static final String TAG = "EmailServiceProxy";
-
- // Private intent that will be used to connect to an independent Exchange service
- public static final String EXCHANGE_INTENT = "com.android.email.EXCHANGE_INTENT";
-
- public static final String AUTO_DISCOVER_BUNDLE_ERROR_CODE = "autodiscover_error_code";
- public static final String AUTO_DISCOVER_BUNDLE_HOST_AUTH = "autodiscover_host_auth";
-
- public static final String VALIDATE_BUNDLE_RESULT_CODE = "validate_result_code";
- public static final String VALIDATE_BUNDLE_POLICY_SET = "validate_policy_set";
- public static final String VALIDATE_BUNDLE_ERROR_MESSAGE = "validate_error_message";
-
- private final IEmailServiceCallback mCallback;
- private Object mReturn = null;
- private IEmailService mService;
-
- // Standard debugging
- public static final int DEBUG_BIT = 1;
- // Verbose (parser) logging
- public static final int DEBUG_VERBOSE_BIT = 2;
- // File (SD card) logging
- public static final int DEBUG_FILE_BIT = 4;
-
- // The first two constructors are used with local services that can be referenced by class
- public EmailServiceProxy(Context _context, Class<?> _class) {
- this(_context, _class, null);
- }
-
- public EmailServiceProxy(Context _context, Class<?> _class, IEmailServiceCallback _callback) {
- super(_context, new Intent(_context, _class));
- mCallback = _callback;
- }
-
- // The following two constructors are used with remote services that must be referenced by
- // a known action or by a prebuilt intent
- public EmailServiceProxy(Context _context, Intent _intent, IEmailServiceCallback _callback) {
- super(_context, _intent);
- try {
- Device.getDeviceId(_context);
- } catch (IOException e) {
- }
- mCallback = _callback;
- }
-
- public EmailServiceProxy(Context _context, String _action, IEmailServiceCallback _callback) {
- super(_context, new Intent(_action));
- try {
- Device.getDeviceId(_context);
- } catch (IOException e) {
- }
- mCallback = _callback;
- }
-
- @Override
- public void onConnected(IBinder binder) {
- mService = IEmailService.Stub.asInterface(binder);
- }
-
- @Override
- public int getApiLevel() {
- return Api.LEVEL;
- }
-
- public void loadAttachment(final long attachmentId, final boolean background)
- throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- try {
- if (mCallback != null) mService.setCallback(mCallback);
- mService.loadAttachment(attachmentId, background);
- } catch (RemoteException e) {
- try {
- // Try to send a callback (if set)
- if (mCallback != null) {
- mCallback.loadAttachmentStatus(-1, attachmentId,
- EmailServiceStatus.REMOTE_EXCEPTION, 0);
- }
- } catch (RemoteException e1) {
- }
- }
- }
- }, "loadAttachment");
- }
-
- public void startSync(final long mailboxId, final boolean userRequest) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- if (mCallback != null) mService.setCallback(mCallback);
- mService.startSync(mailboxId, userRequest);
- }
- }, "startSync");
- }
-
- public void stopSync(final long mailboxId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- if (mCallback != null) mService.setCallback(mCallback);
- mService.stopSync(mailboxId);
- }
- }, "stopSync");
- }
-
- public Bundle validate(final String protocol, final String host, final String userName,
- final String password, final int port, final boolean ssl,
- final boolean trustCertificates) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException{
- if (mCallback != null) mService.setCallback(mCallback);
- mReturn = mService.validate(protocol, host, userName, password, port, ssl,
- trustCertificates);
- }
- }, "validate");
- waitForCompletion();
- if (mReturn == null) {
- Bundle bundle = new Bundle();
- bundle.putInt(VALIDATE_BUNDLE_RESULT_CODE, MessagingException.UNSPECIFIED_EXCEPTION);
- return bundle;
- } else {
- Bundle bundle = (Bundle) mReturn;
- bundle.setClassLoader(PolicySet.class.getClassLoader());
- Log.v(TAG, "validate returns " + bundle.getInt(VALIDATE_BUNDLE_RESULT_CODE));
- return bundle;
- }
- }
-
- public Bundle autoDiscover(final String userName, final String password)
- throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException{
- if (mCallback != null) mService.setCallback(mCallback);
- mReturn = mService.autoDiscover(userName, password);
- }
- }, "autoDiscover");
- waitForCompletion();
- if (mReturn == null) {
- return null;
- } else {
- Bundle bundle = (Bundle) mReturn;
- bundle.setClassLoader(HostAuth.class.getClassLoader());
- Log.v(TAG, "autoDiscover returns " + bundle.getInt(AUTO_DISCOVER_BUNDLE_ERROR_CODE));
- return bundle;
- }
- }
-
- public void updateFolderList(final long accountId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- if (mCallback != null) mService.setCallback(mCallback);
- mService.updateFolderList(accountId);
- }
- }, "updateFolderList");
- }
-
- public void setLogging(final int on) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- if (mCallback != null) mService.setCallback(mCallback);
- mService.setLogging(on);
- }
- }, "setLogging");
- }
-
- public void setCallback(final IEmailServiceCallback cb) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.setCallback(cb);
- }
- }, "setCallback");
- }
-
- public void hostChanged(final long accountId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.hostChanged(accountId);
- }
- }, "hostChanged");
- }
-
- public void sendMeetingResponse(final long messageId, final int response)
- throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- if (mCallback != null) mService.setCallback(mCallback);
- mService.sendMeetingResponse(messageId, response);
- }
- }, "sendMeetingResponse");
- }
-
- public void loadMore(long messageId) throws RemoteException {
- // TODO Auto-generated method stub
- }
-
- public boolean createFolder(long accountId, String name) throws RemoteException {
- return false;
- }
-
- public boolean deleteFolder(long accountId, String name) throws RemoteException {
- return false;
- }
-
- public boolean renameFolder(long accountId, String oldName, String newName)
- throws RemoteException {
- return false;
- }
-
- public void moveMessage(final long messageId, final long mailboxId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.moveMessage(messageId, mailboxId);
- }
- }, "moveMessage");
- }
-
- public void deleteAccountPIMData(final long accountId) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.deleteAccountPIMData(accountId);
- }
- }, "deleteAccountPIMData");
- }
-
- public IBinder asBinder() {
- return null;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/service/EmailServiceStatus.java b/emailcommon/src/com/android/emailcommon/service/EmailServiceStatus.java
deleted file mode 100644
index 055f79a33..000000000
--- a/emailcommon/src/com/android/emailcommon/service/EmailServiceStatus.java
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- * Copyright (C) 2008-2009 Marc Blank
- * Licensed to The Android Open Source Project.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-/**
- * Definitions of service status codes returned to IEmailServiceCallback's status method
- */
-public interface EmailServiceStatus {
- public static final int SUCCESS = 0;
- public static final int IN_PROGRESS = 1;
-
- public static final int MESSAGE_NOT_FOUND = 0x10;
- public static final int ATTACHMENT_NOT_FOUND = 0x11;
- public static final int FOLDER_NOT_DELETED = 0x12;
- public static final int FOLDER_NOT_RENAMED = 0x13;
- public static final int FOLDER_NOT_CREATED = 0x14;
- public static final int REMOTE_EXCEPTION = 0x15;
- public static final int LOGIN_FAILED = 0x16;
- public static final int SECURITY_FAILURE = 0x17;
- public static final int ACCOUNT_UNINITIALIZED = 0x18;
-
- // Maybe we should automatically retry these?
- public static final int CONNECTION_ERROR = 0x20;
-}
diff --git a/emailcommon/src/com/android/emailcommon/service/IAccountService.aidl b/emailcommon/src/com/android/emailcommon/service/IAccountService.aidl
deleted file mode 100644
index ea945c04e..000000000
--- a/emailcommon/src/com/android/emailcommon/service/IAccountService.aidl
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-import android.os.Bundle;
-
-interface IAccountService {
- oneway void notifyLoginFailed(long accountId);
- oneway void notifyLoginSucceeded(long accountId);
- oneway void notifyNewMessages(long accountId);
-
- void accountDeleted();
- void restoreAccountsIfNeeded();
-
- int getAccountColor(long accountId);
-
- Bundle getConfigurationData(String accountType);
-
- String getDeviceId();
-} \ No newline at end of file
diff --git a/emailcommon/src/com/android/emailcommon/service/IEmailService.aidl b/emailcommon/src/com/android/emailcommon/service/IEmailService.aidl
deleted file mode 100644
index 75f10cf6b..000000000
--- a/emailcommon/src/com/android/emailcommon/service/IEmailService.aidl
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2008-2010 Marc Blank
- * Licensed to The Android Open Source Project.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-import com.android.emailcommon.service.IEmailServiceCallback;
-import android.os.Bundle;
-
-interface IEmailService {
- Bundle validate(in String protocol, in String host, in String userName, in String password,
- int port, boolean ssl, boolean trustCertificates) ;
-
- oneway void startSync(long mailboxId, boolean userRequest);
- oneway void stopSync(long mailboxId);
-
- oneway void loadMore(long messageId);
- oneway void loadAttachment(long attachmentId, boolean background);
-
- oneway void updateFolderList(long accountId);
-
- boolean createFolder(long accountId, String name);
- boolean deleteFolder(long accountId, String name);
- boolean renameFolder(long accountId, String oldName, String newName);
-
- // Must not be oneway; unless an exception is thrown, the caller is guaranteed that the callback
- // has been registered
- void setCallback(IEmailServiceCallback cb);
-
- oneway void setLogging(int on);
-
- oneway void hostChanged(long accountId);
-
- Bundle autoDiscover(String userName, String password);
-
- oneway void sendMeetingResponse(long messageId, int response);
-
- oneway void moveMessage(long messageId, long mailboxId);
-
- // Must not be oneway; unless an exception is thrown, the caller is guaranteed that the action
- // has been completed
- void deleteAccountPIMData(long accountId);
-
- int getApiLevel();
-} \ No newline at end of file
diff --git a/emailcommon/src/com/android/emailcommon/service/IEmailServiceCallback.aidl b/emailcommon/src/com/android/emailcommon/service/IEmailServiceCallback.aidl
deleted file mode 100644
index e4c6093fc..000000000
--- a/emailcommon/src/com/android/emailcommon/service/IEmailServiceCallback.aidl
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * Copyright (C) 2008-2009 Marc Blank
- * Licensed to The Android Open Source Project.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-oneway interface IEmailServiceCallback {
- /*
- * Ordinary results:
- * statuscode = 1, progress = 0: "starting"
- * statuscode = 0, progress = n/a: "finished"
- *
- * If there is an error, it must be reported as follows:
- * statuscode = err, progress = n/a: "stopping due to error"
- *
- * *Optionally* a callback can also include intermediate values from 1..99 e.g.
- * statuscode = 1, progress = 0: "starting"
- * statuscode = 1, progress = 30: "working"
- * statuscode = 1, progress = 60: "working"
- * statuscode = 0, progress = n/a: "finished"
- */
-
- /**
- * Callback to indicate that an account is being synced (updating folder list)
- * accountId = the account being synced
- * statusCode = 0 for OK, 1 for progress, other codes for error
- * progress = 0 for "start", 1..100 for optional progress reports
- */
- void syncMailboxListStatus(long accountId, int statusCode, int progress);
-
- /**
- * Callback to indicate that a mailbox is being synced
- * mailboxId = the mailbox being synced
- * statusCode = 0 for OK, 1 for progress, other codes for error
- * progress = 0 for "start", 1..100 for optional progress reports
- */
- void syncMailboxStatus(long mailboxId, int statusCode, int progress);
-
- /**
- * Callback to indicate that a particular attachment is being synced
- * messageId = the message that owns the attachment
- * attachmentId = the attachment being synced
- * statusCode = 0 for OK, 1 for progress, other codes for error
- * progress = 0 for "start", 1..100 for optional progress reports
- */
- void loadAttachmentStatus(long messageId, long attachmentId, int statusCode, int progress);
-
- /**
- * Callback to indicate that a particular message is being sent
- * messageId = the message being sent
- * statusCode = 0 for OK, 1 for progress, other codes for error
- * progress = 0 for "start", 1..100 for optional progress reports
- */
- void sendMessageStatus(long messageId, String subject, int statusCode, int progress);
-}
diff --git a/emailcommon/src/com/android/emailcommon/service/IPolicyService.aidl b/emailcommon/src/com/android/emailcommon/service/IPolicyService.aidl
deleted file mode 100644
index 646abf353..000000000
--- a/emailcommon/src/com/android/emailcommon/service/IPolicyService.aidl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package com.android.emailcommon.service;
-
-import com.android.emailcommon.service.PolicySet;
-
-interface IPolicyService {
- boolean isActive(in PolicySet policies);
- void policiesRequired(long accountId);
- void updatePolicies(long accountId);
- void setAccountHoldFlag(long accountId, boolean newState);
- boolean isActiveAdmin();
- // This is about as oneway as you can get
- oneway void remoteWipe();
- boolean isSupported(in PolicySet policies);
- PolicySet clearUnsupportedPolicies(in PolicySet policies);
-} \ No newline at end of file
diff --git a/emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java
deleted file mode 100644
index 0be702a31..000000000
--- a/emailcommon/src/com/android/emailcommon/service/PolicyServiceProxy.java
+++ /dev/null
@@ -1,227 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-import com.android.emailcommon.provider.EmailContent.Account;
-
-import android.content.Context;
-import android.content.Intent;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.Log;
-
-public class PolicyServiceProxy extends ServiceProxy implements IPolicyService {
- private static final boolean DEBUG_PROXY = true; // STOPSHIP DO NOT CHECK THIS IN SET TO TRUE
- private static final String TAG = "PolicyServiceProxy";
-
- // The intent used by sync adapter services to connect to the PolicyService
- public static final String POLICY_INTENT = "com.android.email.POLICY_INTENT";
-
- private IPolicyService mService = null;
- private Object mReturn = null;
-
- public PolicyServiceProxy(Context _context) {
- super(_context, new Intent(POLICY_INTENT));
- }
-
- @Override
- public void onConnected(IBinder binder) {
- mService = IPolicyService.Stub.asInterface(binder);
- }
-
- public IBinder asBinder() {
- return null;
- }
-
- @Override
- public PolicySet clearUnsupportedPolicies(final PolicySet arg0) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mReturn = mService.clearUnsupportedPolicies(arg0);
- }
- }, "clearUnsupportedPolicies");
- waitForCompletion();
- if (DEBUG_PROXY) {
- Log.v(TAG, "clearUnsupportedPolicies: " + ((mReturn == null) ? "null" : mReturn));
- }
- if (mReturn == null) {
- // Can this happen?
- return null;
- } else {
- return (PolicySet)mReturn;
- }
- }
-
- @Override
- public boolean isActive(final PolicySet arg0) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mReturn = mService.isActive(arg0);
- }
- }, "isActive");
- waitForCompletion();
- if (DEBUG_PROXY) {
- Log.v(TAG, "isActive: " + ((mReturn == null) ? "null" : mReturn));
- }
- if (mReturn == null) {
- // Can this happen?
- return false;
- } else {
- return (Boolean)mReturn;
- }
- }
-
- @Override
- public boolean isActiveAdmin() throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mReturn = mService.isActiveAdmin();
- }
- }, "isActiveAdmin");
- waitForCompletion();
- if (DEBUG_PROXY) {
- Log.v(TAG, "isActiveAdmin: " + ((mReturn == null) ? "null" : mReturn));
- }
- if (mReturn == null) {
- // Can this happen?
- return false;
- } else {
- return (Boolean)mReturn;
- }
- }
-
- @Override
- public boolean isSupported(final PolicySet arg0) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mReturn = mService.isSupported(arg0);
- }
- }, "isSupported");
- waitForCompletion();
- if (DEBUG_PROXY) {
- Log.v(TAG, "isSupported: " + ((mReturn == null) ? "null" : mReturn));
- }
- if (mReturn == null) {
- // Can this happen?
- return false;
- } else {
- return (Boolean)mReturn;
- }
- }
-
- @Override
- public void policiesRequired(final long arg0) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.policiesRequired(arg0);
- }
- }, "policiesRequired");
- }
-
- @Override
- public void remoteWipe() throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.remoteWipe();
- }
- }, "remoteWipe");
- }
-
- @Override
- public void setAccountHoldFlag(final long arg0, final boolean arg1) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.setAccountHoldFlag(arg0, arg1);
- }
- }, "setAccountHoldFlag");
- }
-
- @Override
- public void updatePolicies(final long arg0) throws RemoteException {
- setTask(new ProxyTask() {
- public void run() throws RemoteException {
- mService.updatePolicies(arg0);
- }
- }, "updatePolicies");
- }
-
- // Static methods that encapsulate the proxy calls above
- public static boolean isActive(Context context, PolicySet policies) {
- try {
- return new PolicyServiceProxy(context).isActive(policies);
- } catch (RemoteException e) {
- }
- return false;
- }
-
- public static void policiesRequired(Context context, long accountId) {
- try {
- new PolicyServiceProxy(context).policiesRequired(accountId);
- } catch (RemoteException e) {
- throw new IllegalStateException("PolicyService transaction failed");
- }
- }
-
- public static void updatePolicies(Context context, long accountId) {
- try {
- new PolicyServiceProxy(context).updatePolicies(accountId);
- } catch (RemoteException e) {
- throw new IllegalStateException("PolicyService transaction failed");
- }
- }
-
- public static void setAccountHoldFlag(Context context, Account account, boolean newState) {
- try {
- new PolicyServiceProxy(context).setAccountHoldFlag(account.mId, newState);
- } catch (RemoteException e) {
- throw new IllegalStateException("PolicyService transaction failed");
- }
- }
-
- public static boolean isActiveAdmin(Context context) {
- try {
- return new PolicyServiceProxy(context).isActiveAdmin();
- } catch (RemoteException e) {
- }
- return false;
- }
-
- public static void remoteWipe(Context context) {
- try {
- new PolicyServiceProxy(context).remoteWipe();
- } catch (RemoteException e) {
- throw new IllegalStateException("PolicyService transaction failed");
- }
- }
-
- public static boolean isSupported(Context context, PolicySet policies) {
- try {
- return new PolicyServiceProxy(context).isSupported(policies);
- } catch (RemoteException e) {
- }
- return false;
- }
-
- public static PolicySet clearUnsupportedPolicies(Context context, PolicySet policies) {
- try {
- return new PolicyServiceProxy(context).clearUnsupportedPolicies(policies);
- } catch (RemoteException e) {
- }
- throw new IllegalStateException("PolicyService transaction failed");
- }
-}
-
diff --git a/emailcommon/src/com/android/emailcommon/service/PolicySet.aidl b/emailcommon/src/com/android/emailcommon/service/PolicySet.aidl
deleted file mode 100644
index e825c62c3..000000000
--- a/emailcommon/src/com/android/emailcommon/service/PolicySet.aidl
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-parcelable PolicySet;
-
diff --git a/emailcommon/src/com/android/emailcommon/service/PolicySet.java b/emailcommon/src/com/android/emailcommon/service/PolicySet.java
deleted file mode 100644
index 8b983e94e..000000000
--- a/emailcommon/src/com/android/emailcommon/service/PolicySet.java
+++ /dev/null
@@ -1,356 +0,0 @@
-/* Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-import com.android.emailcommon.provider.EmailContent.Account;
-import com.android.emailcommon.provider.EmailContent.AccountColumns;
-
-import android.app.admin.DevicePolicyManager;
-import android.content.ContentValues;
-import android.content.Context;
-import android.os.Parcel;
-import android.os.Parcelable;
-
-
-/**
- * Class for tracking policies and reading/writing into accounts
- */
-public class PolicySet implements Parcelable {
-
- // Security (provisioning) flags
- // bits 0..4: password length (0=no password required)
- private static final int PASSWORD_LENGTH_MASK = 31;
- private static final int PASSWORD_LENGTH_SHIFT = 0;
- public static final int PASSWORD_LENGTH_MAX = 30;
- // bits 5..8: password mode
- private static final int PASSWORD_MODE_SHIFT = 5;
- private static final int PASSWORD_MODE_MASK = 15 << PASSWORD_MODE_SHIFT;
- public static final int PASSWORD_MODE_NONE = 0 << PASSWORD_MODE_SHIFT;
- public static final int PASSWORD_MODE_SIMPLE = 1 << PASSWORD_MODE_SHIFT;
- public static final int PASSWORD_MODE_STRONG = 2 << PASSWORD_MODE_SHIFT;
- // bits 9..13: password failures -> wipe device (0=disabled)
- private static final int PASSWORD_MAX_FAILS_SHIFT = 9;
- private static final int PASSWORD_MAX_FAILS_MASK = 31 << PASSWORD_MAX_FAILS_SHIFT;
- public static final int PASSWORD_MAX_FAILS_MAX = 31;
- // bits 14..24: seconds to screen lock (0=not required)
- private static final int SCREEN_LOCK_TIME_SHIFT = 14;
- private static final int SCREEN_LOCK_TIME_MASK = 2047 << SCREEN_LOCK_TIME_SHIFT;
- public static final int SCREEN_LOCK_TIME_MAX = 2047;
- // bit 25: remote wipe capability required
- private static final int REQUIRE_REMOTE_WIPE = 1 << 25;
- // bit 26..35: password expiration (days; 0=not required)
- private static final int PASSWORD_EXPIRATION_SHIFT = 26;
- private static final long PASSWORD_EXPIRATION_MASK = 1023L << PASSWORD_EXPIRATION_SHIFT;
- public static final int PASSWORD_EXPIRATION_MAX = 1023;
- // bit 36..43: password history (length; 0=not required)
- private static final int PASSWORD_HISTORY_SHIFT = 36;
- private static final long PASSWORD_HISTORY_MASK = 255L << PASSWORD_HISTORY_SHIFT;
- public static final int PASSWORD_HISTORY_MAX = 255;
- // bit 44..48: min complex characters (0=not required)
- private static final int PASSWORD_COMPLEX_CHARS_SHIFT = 44;
- private static final long PASSWORD_COMPLEX_CHARS_MASK = 31L << PASSWORD_COMPLEX_CHARS_SHIFT;
- public static final int PASSWORD_COMPLEX_CHARS_MAX = 31;
- // bit 49: requires device encryption
- private static final long REQUIRE_ENCRYPTION = 1L << 49;
-
- /* Convert days to mSec (used for password expiration) */
- private static final long DAYS_TO_MSEC = 24 * 60 * 60 * 1000;
- /* Small offset (2 minutes) added to policy expiration to make user testing easier. */
- private static final long EXPIRATION_OFFSET_MSEC = 2 * 60 * 1000;
-
- public final int mMinPasswordLength;
- public final int mPasswordMode;
- public final int mMaxPasswordFails;
- public final int mMaxScreenLockTime;
- public final boolean mRequireRemoteWipe;
- public final int mPasswordExpirationDays;
- public final int mPasswordHistory;
- public final int mPasswordComplexChars;
- public final boolean mRequireEncryption;
-
- public int getMinPasswordLengthForTest() {
- return mMinPasswordLength;
- }
-
- public int getPasswordModeForTest() {
- return mPasswordMode;
- }
-
- public int getMaxPasswordFailsForTest() {
- return mMaxPasswordFails;
- }
-
- public int getMaxScreenLockTimeForTest() {
- return mMaxScreenLockTime;
- }
-
- public boolean isRequireRemoteWipeForTest() {
- return mRequireRemoteWipe;
- }
-
- public boolean isRequireEncryptionForTest() {
- return mRequireEncryption;
- }
-
- /**
- * Create from raw values.
- * @param minPasswordLength (0=not enforced)
- * @param passwordMode
- * @param maxPasswordFails (0=not enforced)
- * @param maxScreenLockTime in seconds (0=not enforced)
- * @param requireRemoteWipe
- * @param passwordExpirationDays in days (0=not enforced)
- * @param passwordHistory (0=not enforced)
- * @param passwordComplexChars (0=not enforced)
- * @throws IllegalArgumentException for illegal arguments.
- */
- public PolicySet(int minPasswordLength, int passwordMode, int maxPasswordFails,
- int maxScreenLockTime, boolean requireRemoteWipe, int passwordExpirationDays,
- int passwordHistory, int passwordComplexChars, boolean requireEncryption)
- throws IllegalArgumentException {
- // If we're not enforcing passwords, make sure we clean up related values, since EAS
- // can send non-zero values for any or all of these
- if (passwordMode == PASSWORD_MODE_NONE) {
- maxPasswordFails = 0;
- maxScreenLockTime = 0;
- minPasswordLength = 0;
- passwordComplexChars = 0;
- passwordHistory = 0;
- passwordExpirationDays = 0;
- } else {
- if ((passwordMode != PASSWORD_MODE_SIMPLE) &&
- (passwordMode != PASSWORD_MODE_STRONG)) {
- throw new IllegalArgumentException("password mode");
- }
- // If we're only requiring a simple password, set complex chars to zero; note
- // that EAS can erroneously send non-zero values in this case
- if (passwordMode == PASSWORD_MODE_SIMPLE) {
- passwordComplexChars = 0;
- }
- // The next four values have hard limits which cannot be supported if exceeded.
- if (minPasswordLength > PASSWORD_LENGTH_MAX) {
- throw new IllegalArgumentException("password length");
- }
- if (passwordExpirationDays > PASSWORD_EXPIRATION_MAX) {
- throw new IllegalArgumentException("password expiration");
- }
- if (passwordHistory > PASSWORD_HISTORY_MAX) {
- throw new IllegalArgumentException("password history");
- }
- if (passwordComplexChars > PASSWORD_COMPLEX_CHARS_MAX) {
- throw new IllegalArgumentException("complex chars");
- }
- // This value can be reduced (which actually increases security) if necessary
- if (maxPasswordFails > PASSWORD_MAX_FAILS_MAX) {
- maxPasswordFails = PASSWORD_MAX_FAILS_MAX;
- }
- // This value can be reduced (which actually increases security) if necessary
- if (maxScreenLockTime > SCREEN_LOCK_TIME_MAX) {
- maxScreenLockTime = SCREEN_LOCK_TIME_MAX;
- }
- }
- mMinPasswordLength = minPasswordLength;
- mPasswordMode = passwordMode;
- mMaxPasswordFails = maxPasswordFails;
- mMaxScreenLockTime = maxScreenLockTime;
- mRequireRemoteWipe = requireRemoteWipe;
- mPasswordExpirationDays = passwordExpirationDays;
- mPasswordHistory = passwordHistory;
- mPasswordComplexChars = passwordComplexChars;
- mRequireEncryption = requireEncryption;
- }
-
- /**
- * Create from values encoded in an account
- * @param account
- */
- public PolicySet(Account account) {
- this(account.mSecurityFlags);
- }
-
- /**
- * Create from values encoded in an account flags int
- */
- public PolicySet(long flags) {
- mMinPasswordLength =
- (int) ((flags & PASSWORD_LENGTH_MASK) >> PASSWORD_LENGTH_SHIFT);
- mPasswordMode =
- (int) (flags & PASSWORD_MODE_MASK);
- mMaxPasswordFails =
- (int) ((flags & PASSWORD_MAX_FAILS_MASK) >> PASSWORD_MAX_FAILS_SHIFT);
- mMaxScreenLockTime =
- (int) ((flags & SCREEN_LOCK_TIME_MASK) >> SCREEN_LOCK_TIME_SHIFT);
- mRequireRemoteWipe = 0 != (flags & REQUIRE_REMOTE_WIPE);
- mPasswordExpirationDays =
- (int) ((flags & PASSWORD_EXPIRATION_MASK) >> PASSWORD_EXPIRATION_SHIFT);
- mPasswordHistory =
- (int) ((flags & PASSWORD_HISTORY_MASK) >> PASSWORD_HISTORY_SHIFT);
- mPasswordComplexChars =
- (int) ((flags & PASSWORD_COMPLEX_CHARS_MASK) >> PASSWORD_COMPLEX_CHARS_SHIFT);
- mRequireEncryption = 0 != (flags & REQUIRE_ENCRYPTION);
- }
-
- /**
- * Helper to map our internal encoding to DevicePolicyManager password modes.
- */
- public int getDPManagerPasswordQuality() {
- switch (mPasswordMode) {
- case PASSWORD_MODE_SIMPLE:
- return DevicePolicyManager.PASSWORD_QUALITY_NUMERIC;
- case PASSWORD_MODE_STRONG:
- return DevicePolicyManager.PASSWORD_QUALITY_ALPHANUMERIC;
- default:
- return DevicePolicyManager .PASSWORD_QUALITY_UNSPECIFIED;
- }
- }
-
- /**
- * Helper to map expiration times to the millisecond values used by DevicePolicyManager.
- */
- public long getDPManagerPasswordExpirationTimeout() {
- long result = mPasswordExpirationDays * DAYS_TO_MSEC;
- // Add a small offset to the password expiration. This makes it easier to test
- // by changing (for example) 1 day to 1 day + 5 minutes. If you set an expiration
- // that is within the warning period, you should get a warning fairly quickly.
- if (result > 0) {
- result += EXPIRATION_OFFSET_MSEC;
- }
- return result;
- }
-
- /**
- * Record flags (and a sync key for the flags) into an Account
- * Note: the hash code is defined as the encoding used in Account
- *
- * @param account to write the values mSecurityFlags and mSecuritySyncKey
- * @param syncKey the value to write into the account's mSecuritySyncKey
- * @param update if true, also writes the account back to the provider (updating only
- * the fields changed by this API)
- * @param context a context for writing to the provider
- * @return true if the actual policies changed, false if no change (note, sync key
- * does not affect this)
- */
- public boolean writeAccount(Account account, String syncKey, boolean update,
- Context context) {
- long newFlags = getSecurityCode();
- boolean dirty = (newFlags != account.mSecurityFlags);
- account.mSecurityFlags = newFlags;
- account.mSecuritySyncKey = syncKey;
- if (update) {
- if (account.isSaved()) {
- ContentValues cv = new ContentValues();
- cv.put(AccountColumns.SECURITY_FLAGS, account.mSecurityFlags);
- cv.put(AccountColumns.SECURITY_SYNC_KEY, account.mSecuritySyncKey);
- account.update(context, cv);
- } else {
- account.save(context);
- }
- }
- return dirty;
- }
-
- @Override
- public boolean equals(Object o) {
- if (o instanceof PolicySet) {
- PolicySet other = (PolicySet)o;
- return (this.getSecurityCode() == other.getSecurityCode());
- }
- return false;
- }
-
- /**
- * Supports Parcelable
- */
- public int describeContents() {
- return 0;
- }
-
- /**
- * Supports Parcelable
- */
- public static final Parcelable.Creator<PolicySet> CREATOR
- = new Parcelable.Creator<PolicySet>() {
- public PolicySet createFromParcel(Parcel in) {
- return new PolicySet(in);
- }
-
- public PolicySet[] newArray(int size) {
- return new PolicySet[size];
- }
- };
-
- /**
- * Supports Parcelable
- */
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeInt(mMinPasswordLength);
- dest.writeInt(mPasswordMode);
- dest.writeInt(mMaxPasswordFails);
- dest.writeInt(mMaxScreenLockTime);
- dest.writeInt(mRequireRemoteWipe ? 1 : 0);
- dest.writeInt(mPasswordExpirationDays);
- dest.writeInt(mPasswordHistory);
- dest.writeInt(mPasswordComplexChars);
- dest.writeInt(mRequireEncryption ? 1 : 0);
- }
-
- /**
- * Supports Parcelable
- */
- public PolicySet(Parcel in) {
- mMinPasswordLength = in.readInt();
- mPasswordMode = in.readInt();
- mMaxPasswordFails = in.readInt();
- mMaxScreenLockTime = in.readInt();
- mRequireRemoteWipe = in.readInt() == 1;
- mPasswordExpirationDays = in.readInt();
- mPasswordHistory = in.readInt();
- mPasswordComplexChars = in.readInt();
- mRequireEncryption = in.readInt() == 1;
- }
-
- @Override
- public int hashCode() {
- long code = getSecurityCode();
- return (int) code;
- }
-
- public long getSecurityCode() {
- long flags = 0;
- flags = (long)mMinPasswordLength << PASSWORD_LENGTH_SHIFT;
- flags |= mPasswordMode;
- flags |= (long)mMaxPasswordFails << PASSWORD_MAX_FAILS_SHIFT;
- flags |= (long)mMaxScreenLockTime << SCREEN_LOCK_TIME_SHIFT;
- if (mRequireRemoteWipe) flags |= REQUIRE_REMOTE_WIPE;
- flags |= (long)mPasswordHistory << PASSWORD_HISTORY_SHIFT;
- flags |= (long)mPasswordExpirationDays << PASSWORD_EXPIRATION_SHIFT;
- flags |= (long)mPasswordComplexChars << PASSWORD_COMPLEX_CHARS_SHIFT;
- if (mRequireEncryption) flags |= REQUIRE_ENCRYPTION;
- return flags;
- }
-
- @Override
- public String toString() {
- return "{ " + "pw-len-min=" + mMinPasswordLength + " pw-mode=" + mPasswordMode
- + " pw-fails-max=" + mMaxPasswordFails + " screenlock-max="
- + mMaxScreenLockTime + " remote-wipe-req=" + mRequireRemoteWipe
- + " pw-expiration=" + mPasswordExpirationDays
- + " pw-history=" + mPasswordHistory
- + " pw-complex-chars=" + mPasswordComplexChars
- + " require-encryption=" + mRequireEncryption + "}";
- }
-}
-
diff --git a/emailcommon/src/com/android/emailcommon/service/ServiceProxy.java b/emailcommon/src/com/android/emailcommon/service/ServiceProxy.java
deleted file mode 100644
index 4e80c6980..000000000
--- a/emailcommon/src/com/android/emailcommon/service/ServiceProxy.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- /*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.os.Debug;
-import android.os.IBinder;
-import android.os.RemoteException;
-import android.util.Log;
-
-/**
- * The EmailServiceProxy class provides a simple interface for the UI to call into the various
- * EmailService classes (e.g. ExchangeService for EAS). It wraps the service connect/disconnect
- * process so that the caller need not be concerned with it.
- *
- * Use the class like this:
- * new EmailServiceClass(context, class).loadAttachment(attachmentId, callback)
- *
- * Methods without a return value return immediately (i.e. are asynchronous); methods with a
- * return value wait for a result from the Service (i.e. they should not be called from the UI
- * thread) with a default timeout of 30 seconds (settable)
- *
- * An EmailServiceProxy object cannot be reused (trying to do so generates a RemoteException)
- */
-
-public abstract class ServiceProxy {
- private static final boolean DEBUG_PROXY = true; // STOPSHIP DO NOT CHECK THIS IN SET TO TRUE
- private final String mTag;
-
- private final Context mContext;
- protected final Intent mIntent;
- private Runnable mRunnable = new ProxyRunnable();
- private ProxyTask mTask;
- private String mName = " unnamed";
- private final ServiceConnection mConnection = new ProxyConnection();
- // Service call timeout (in seconds)
- private int mTimeout = 45;
- private long mStartTime;
- private boolean mDead = false;
-
- public abstract void onConnected(IBinder binder);
-
- public ServiceProxy(Context _context, Intent _intent) {
- mContext = _context;
- mIntent = _intent;
- mTag = getClass().getSimpleName();
- if (Debug.isDebuggerConnected()) {
- mTimeout <<= 2;
- }
- }
-
- private class ProxyConnection implements ServiceConnection {
- public void onServiceConnected(ComponentName name, IBinder binder) {
- onConnected(binder);
- if (DEBUG_PROXY) {
- Log.v(mTag, "Connected: " + name.getShortClassName());
- }
- // Run our task on a new thread
- new Thread(new Runnable() {
- public void run() {
- runTask();
- }}).start();
- }
-
- public void onServiceDisconnected(ComponentName name) {
- if (DEBUG_PROXY) {
- Log.v(mTag, "Disconnected: " + name.getShortClassName());
- }
- }
- }
-
- public interface ProxyTask {
- public void run() throws RemoteException;
- }
-
- private class ProxyRunnable implements Runnable {
- @Override
- public void run() {
- try {
- mTask.run();
- } catch (RemoteException e) {
- }
- }
- }
-
- public ServiceProxy setTimeout(int secs) {
- mTimeout = secs;
- return this;
- }
-
- public int getTimeout() {
- return mTimeout;
- }
-
- public void endTask() {
- try {
- mContext.unbindService(mConnection);
- } catch (IllegalArgumentException e) {
- // This can happen if the user ended the activity that was using the service
- // This is harmless, but we've got to catch it
- }
-
- mDead = true;
- synchronized(mConnection) {
- if (DEBUG_PROXY) {
- Log.v(mTag, "Task " + mName + " completed; disconnecting");
- }
- mConnection.notify();
- }
- }
-
- private void runTask() {
- Thread thread = new Thread(mRunnable);
- thread.start();
- try {
- thread.join();
- } catch (InterruptedException e) {
- }
- endTask();
- }
-
- public boolean setTask(ProxyTask task, String name) {
- mName = name;
- return setTask(task);
- }
-
- public boolean setTask(ProxyTask task) throws IllegalStateException {
- if (mDead) {
- throw new IllegalStateException();
- }
- mTask = task;
- mStartTime = System.currentTimeMillis();
- if (DEBUG_PROXY) {
- Log.v(mTag, "Bind requested for task " + mName);
- }
- return mContext.bindService(mIntent, mConnection, Context.BIND_AUTO_CREATE);
- }
-
- public void waitForCompletion() {
- synchronized (mConnection) {
- long time = System.currentTimeMillis();
- try {
- if (DEBUG_PROXY) {
- Log.v(mTag, "Waiting for task " + mName + " to complete...");
- }
- mConnection.wait(mTimeout * 1000L);
- } catch (InterruptedException e) {
- // Can be ignored safely
- }
- if (DEBUG_PROXY) {
- Log.v(mTag, "Wait for " + mName + " finished in " +
- (System.currentTimeMillis() - time) + "ms");
- }
- }
- }
-
- public void close() throws RemoteException {
- if (mDead) {
- throw new RemoteException();
- }
- endTask();
- }
-
- /**
- * Connection test; return indicates whether the remote service can be connected to
- * @return the result of trying to connect to the remote service
- */
- public boolean test() {
- try {
- return setTask(new ProxyTask() {
- public void run() throws RemoteException {
- if (DEBUG_PROXY) {
- Log.v(mTag, "Connection test succeeded in " +
- (System.currentTimeMillis() - mStartTime) + "ms");
- }
- }
- }, "test");
- } catch (Exception e) {
- // For any failure, return false.
- return false;
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/service/SyncWindow.java b/emailcommon/src/com/android/emailcommon/service/SyncWindow.java
deleted file mode 100644
index b81834fea..000000000
--- a/emailcommon/src/com/android/emailcommon/service/SyncWindow.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.service;
-
-public class SyncWindow {
- public static final int SYNC_WINDOW_USER = -1;
- public static final int SYNC_WINDOW_1_DAY = 1;
- public static final int SYNC_WINDOW_3_DAYS = 2;
- public static final int SYNC_WINDOW_1_WEEK = 3;
- public static final int SYNC_WINDOW_2_WEEKS = 4;
- public static final int SYNC_WINDOW_1_MONTH = 5;
- public static final int SYNC_WINDOW_ALL = 6;
-}
diff --git a/emailcommon/src/com/android/emailcommon/utility/AccountReconciler.java b/emailcommon/src/com/android/emailcommon/utility/AccountReconciler.java
deleted file mode 100644
index 6958d205c..000000000
--- a/emailcommon/src/com/android/emailcommon/utility/AccountReconciler.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.utility;
-
-import com.android.emailcommon.Logging;
-import com.android.emailcommon.provider.EmailContent.Account;
-
-import android.accounts.AccountManager;
-import android.accounts.AccountManagerFuture;
-import android.accounts.AuthenticatorException;
-import android.accounts.OperationCanceledException;
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.Context;
-import android.util.Log;
-
-import java.io.IOException;
-import java.util.List;
-
-public class AccountReconciler {
- /**
- * Compare our account list (obtained from EmailProvider) with the account list owned by
- * AccountManager. If there are any orphans (an account in one list without a corresponding
- * account in the other list), delete the orphan, as these must remain in sync.
- *
- * Note that the duplication of account information is caused by the Email application's
- * incomplete integration with AccountManager.
- *
- * This function may not be called from the main/UI thread, because it makes blocking calls
- * into the account manager.
- *
- * @param context The context in which to operate
- * @param emailProviderAccounts the exchange provider accounts to work from
- * @param accountManagerAccounts The account manager accounts to work from
- * @param resolver the content resolver for making provider updates (injected for testability)
- */
- public static boolean reconcileAccounts(Context context,
- List<Account> emailProviderAccounts, android.accounts.Account[] accountManagerAccounts,
- ContentResolver resolver) {
- // First, look through our EmailProvider accounts to make sure there's a corresponding
- // AccountManager account
- boolean accountsDeleted = false;
- for (Account providerAccount: emailProviderAccounts) {
- String providerAccountName = providerAccount.mEmailAddress;
- boolean found = false;
- for (android.accounts.Account accountManagerAccount: accountManagerAccounts) {
- if (accountManagerAccount.name.equalsIgnoreCase(providerAccountName)) {
- found = true;
- break;
- }
- }
- if (!found) {
- if ((providerAccount.mFlags & Account.FLAGS_INCOMPLETE) != 0) {
- Log.w(Logging.LOG_TAG,
- "Account reconciler noticed incomplete account; ignoring");
- continue;
- }
- // This account has been deleted in the AccountManager!
- Log.d(Logging.LOG_TAG,
- "Account deleted in AccountManager; deleting from provider: " +
- providerAccountName);
- // TODO This will orphan downloaded attachments; need to handle this
- resolver.delete(ContentUris.withAppendedId(Account.CONTENT_URI,
- providerAccount.mId), null, null);
- accountsDeleted = true;
- }
- }
- // Now, look through AccountManager accounts to make sure we have a corresponding cached EAS
- // account from EmailProvider
- for (android.accounts.Account accountManagerAccount: accountManagerAccounts) {
- String accountManagerAccountName = accountManagerAccount.name;
- boolean found = false;
- for (Account cachedEasAccount: emailProviderAccounts) {
- if (cachedEasAccount.mEmailAddress.equalsIgnoreCase(accountManagerAccountName)) {
- found = true;
- }
- }
- if (!found) {
- // This account has been deleted from the EmailProvider database
- Log.d(Logging.LOG_TAG,
- "Account deleted from provider; deleting from AccountManager: " +
- accountManagerAccountName);
- // Delete the account
- AccountManagerFuture<Boolean> blockingResult = AccountManager.get(context)
- .removeAccount(accountManagerAccount, null, null);
- try {
- // Note: All of the potential errors from removeAccount() are simply logged
- // here, as there is nothing to actually do about them.
- blockingResult.getResult();
- } catch (OperationCanceledException e) {
- Log.w(Logging.LOG_TAG, e.toString());
- } catch (AuthenticatorException e) {
- Log.w(Logging.LOG_TAG, e.toString());
- } catch (IOException e) {
- Log.w(Logging.LOG_TAG, e.toString());
- }
- accountsDeleted = true;
- }
- }
- return accountsDeleted;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java b/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java
deleted file mode 100644
index 12954c667..000000000
--- a/emailcommon/src/com/android/emailcommon/utility/AttachmentUtilities.java
+++ /dev/null
@@ -1,335 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.utility;
-
-import com.android.emailcommon.Logging;
-import com.android.emailcommon.provider.EmailContent.Attachment;
-import com.android.emailcommon.provider.EmailContent.Message;
-import com.android.emailcommon.provider.EmailContent.MessageColumns;
-
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.Context;
-import android.database.Cursor;
-import android.net.Uri;
-import android.text.TextUtils;
-import android.util.Log;
-import android.webkit.MimeTypeMap;
-
-import java.io.File;
-
-public class AttachmentUtilities {
- public static final String AUTHORITY = "com.android.email.attachmentprovider";
- public static final Uri CONTENT_URI = Uri.parse( "content://" + AUTHORITY);
-
- public static final String FORMAT_RAW = "RAW";
- public static final String FORMAT_THUMBNAIL = "THUMBNAIL";
-
- public static class Columns {
- public static final String _ID = "_id";
- public static final String DATA = "_data";
- public static final String DISPLAY_NAME = "_display_name";
- public static final String SIZE = "_size";
- }
-
- /**
- * The MIME type(s) of attachments we're willing to send via attachments.
- *
- * Any attachments may be added via Intents with Intent.ACTION_SEND or ACTION_SEND_MULTIPLE.
- */
- public static final String[] ACCEPTABLE_ATTACHMENT_SEND_INTENT_TYPES = new String[] {
- "*/*",
- };
- /**
- * The MIME type(s) of attachments we're willing to send from the internal UI.
- *
- * NOTE: At the moment it is not possible to open a chooser with a list of filter types, so
- * the chooser is only opened with the first item in the list.
- */
- public static final String[] ACCEPTABLE_ATTACHMENT_SEND_UI_TYPES = new String[] {
- "image/*",
- "video/*",
- };
- /**
- * The MIME type(s) of attachments we're willing to view.
- */
- public static final String[] ACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] {
- "*/*",
- };
- /**
- * The MIME type(s) of attachments we're not willing to view.
- */
- public static final String[] UNACCEPTABLE_ATTACHMENT_VIEW_TYPES = new String[] {
- };
- /**
- * The MIME type(s) of attachments we're willing to download to SD.
- */
- public static final String[] ACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] {
- "*/*",
- };
- /**
- * The MIME type(s) of attachments we're not willing to download to SD.
- */
- public static final String[] UNACCEPTABLE_ATTACHMENT_DOWNLOAD_TYPES = new String[] {
- };
- /**
- * Filename extensions of attachments we're never willing to download (potential malware).
- * Entries in this list are compared to the end of the lower-cased filename, so they must
- * be lower case, and should not include a "."
- */
- public static final String[] UNACCEPTABLE_ATTACHMENT_EXTENSIONS = new String[] {
- // File types that contain malware
- "ade", "adp", "bat", "chm", "cmd", "com", "cpl", "dll", "exe",
- "hta", "ins", "isp", "jse", "lib", "mde", "msc", "msp",
- "mst", "pif", "scr", "sct", "shb", "sys", "vb", "vbe",
- "vbs", "vxd", "wsc", "wsf", "wsh",
- // File types of common compression/container formats (again, to avoid malware)
- "zip", "gz", "z", "tar", "tgz", "bz2",
- };
- /**
- * Filename extensions of attachments that can be installed.
- * Entries in this list are compared to the end of the lower-cased filename, so they must
- * be lower case, and should not include a "."
- */
- public static final String[] INSTALLABLE_ATTACHMENT_EXTENSIONS = new String[] {
- "apk",
- };
- /**
- * The maximum size of an attachment we're willing to download (either View or Save)
- * Attachments that are base64 encoded (most) will be about 1.375x their actual size
- * so we should probably factor that in. A 5MB attachment will generally be around
- * 6.8MB downloaded but only 5MB saved.
- */
- public static final int MAX_ATTACHMENT_DOWNLOAD_SIZE = (5 * 1024 * 1024);
- /**
- * The maximum size of an attachment we're willing to upload (measured as stored on disk).
- * Attachments that are base64 encoded (most) will be about 1.375x their actual size
- * so we should probably factor that in. A 5MB attachment will generally be around
- * 6.8MB uploaded.
- */
- public static final int MAX_ATTACHMENT_UPLOAD_SIZE = (5 * 1024 * 1024);
-
- public static Uri getAttachmentUri(long accountId, long id) {
- return CONTENT_URI.buildUpon()
- .appendPath(Long.toString(accountId))
- .appendPath(Long.toString(id))
- .appendPath(FORMAT_RAW)
- .build();
- }
-
- public static Uri getAttachmentThumbnailUri(long accountId, long id,
- int width, int height) {
- return CONTENT_URI.buildUpon()
- .appendPath(Long.toString(accountId))
- .appendPath(Long.toString(id))
- .appendPath(FORMAT_THUMBNAIL)
- .appendPath(Integer.toString(width))
- .appendPath(Integer.toString(height))
- .build();
- }
-
- /**
- * Return the filename for a given attachment. This should be used by any code that is
- * going to *write* attachments.
- *
- * This does not create or write the file, or even the directories. It simply builds
- * the filename that should be used.
- */
- public static File getAttachmentFilename(Context context, long accountId, long attachmentId) {
- return new File(getAttachmentDirectory(context, accountId), Long.toString(attachmentId));
- }
-
- /**
- * Return the directory for a given attachment. This should be used by any code that is
- * going to *write* attachments.
- *
- * This does not create or write the directory. It simply builds the pathname that should be
- * used.
- */
- public static File getAttachmentDirectory(Context context, long accountId) {
- return context.getDatabasePath(accountId + ".db_att");
- }
-
- /**
- * Helper to convert unknown or unmapped attachments to something useful based on filename
- * extensions. The mime type is inferred based upon the table below. It's not perfect, but
- * it helps.
- *
- * <pre>
- * |---------------------------------------------------------|
- * | E X T E N S I O N |
- * |---------------------------------------------------------|
- * | .eml | known(.png) | unknown(.abc) | none |
- * | M |-----------------------------------------------------------------------|
- * | I | none | msg/rfc822 | image/png | app/abc | app/oct-str |
- * | M |-------------| (always | | | |
- * | E | app/oct-str | overrides | | | |
- * | T |-------------| | |-----------------------------|
- * | Y | text/plain | | | text/plain |
- * | P |-------------| |-------------------------------------------|
- * | E | any/type | | any/type |
- * |---|-----------------------------------------------------------------------|
- * </pre>
- *
- * NOTE: Since mime types on Android are case-*sensitive*, return values are always in
- * lower case.
- *
- * @param fileName The given filename
- * @param mimeType The given mime type
- * @return A likely mime type for the attachment
- */
- public static String inferMimeType(final String fileName, final String mimeType) {
- String resultType = null;
- String fileExtension = getFilenameExtension(fileName);
- boolean isTextPlain = "text/plain".equalsIgnoreCase(mimeType);
-
- if ("eml".equals(fileExtension)) {
- resultType = "message/rfc822";
- } else {
- boolean isGenericType =
- isTextPlain || "application/octet-stream".equalsIgnoreCase(mimeType);
- // If the given mime type is non-empty and non-generic, return it
- if (isGenericType || TextUtils.isEmpty(mimeType)) {
- if (!TextUtils.isEmpty(fileExtension)) {
- // Otherwise, try to find a mime type based upon the file extension
- resultType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);
- if (TextUtils.isEmpty(resultType)) {
- // Finally, if original mimetype is text/plain, use it; otherwise synthesize
- resultType = isTextPlain ? mimeType : "application/" + fileExtension;
- }
- }
- } else {
- resultType = mimeType;
- }
- }
-
- // No good guess could be made; use an appropriate generic type
- if (TextUtils.isEmpty(resultType)) {
- resultType = isTextPlain ? "text/plain" : "application/octet-stream";
- }
- return resultType.toLowerCase();
- }
-
- /**
- * Extract and return filename's extension, converted to lower case, and not including the "."
- *
- * @return extension, or null if not found (or null/empty filename)
- */
- public static String getFilenameExtension(String fileName) {
- String extension = null;
- if (!TextUtils.isEmpty(fileName)) {
- int lastDot = fileName.lastIndexOf('.');
- if ((lastDot > 0) && (lastDot < fileName.length() - 1)) {
- extension = fileName.substring(lastDot + 1).toLowerCase();
- }
- }
- return extension;
- }
-
- /**
- * Resolve attachment id to content URI. Returns the resolved content URI (from the attachment
- * DB) or, if not found, simply returns the incoming value.
- *
- * @param attachmentUri
- * @return resolved content URI
- *
- * TODO: Throws an SQLite exception on a missing DB file (e.g. unknown URI) instead of just
- * returning the incoming uri, as it should.
- */
- public static Uri resolveAttachmentIdToContentUri(ContentResolver resolver, Uri attachmentUri) {
- Cursor c = resolver.query(attachmentUri,
- new String[] { Columns.DATA },
- null, null, null);
- if (c != null) {
- try {
- if (c.moveToFirst()) {
- final String strUri = c.getString(0);
- if (strUri != null) {
- return Uri.parse(strUri);
- }
- }
- } finally {
- c.close();
- }
- }
- return attachmentUri;
- }
-
- /**
- * In support of deleting a message, find all attachments and delete associated attachment
- * files.
- * @param context
- * @param accountId the account for the message
- * @param messageId the message
- */
- public static void deleteAllAttachmentFiles(Context context, long accountId, long messageId) {
- Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
- Cursor c = context.getContentResolver().query(uri, Attachment.ID_PROJECTION,
- null, null, null);
- try {
- while (c.moveToNext()) {
- long attachmentId = c.getLong(Attachment.ID_PROJECTION_COLUMN);
- File attachmentFile = getAttachmentFilename(context, accountId, attachmentId);
- // Note, delete() throws no exceptions for basic FS errors (e.g. file not found)
- // it just returns false, which we ignore, and proceed to the next file.
- // This entire loop is best-effort only.
- attachmentFile.delete();
- }
- } finally {
- c.close();
- }
- }
-
- /**
- * In support of deleting a mailbox, find all messages and delete their attachments.
- *
- * @param context
- * @param accountId the account for the mailbox
- * @param mailboxId the mailbox for the messages
- */
- public static void deleteAllMailboxAttachmentFiles(Context context, long accountId,
- long mailboxId) {
- Cursor c = context.getContentResolver().query(Message.CONTENT_URI,
- Message.ID_COLUMN_PROJECTION, MessageColumns.MAILBOX_KEY + "=?",
- new String[] { Long.toString(mailboxId) }, null);
- try {
- while (c.moveToNext()) {
- long messageId = c.getLong(Message.ID_PROJECTION_COLUMN);
- deleteAllAttachmentFiles(context, accountId, messageId);
- }
- } finally {
- c.close();
- }
- }
-
- /**
- * In support of deleting or wiping an account, delete all related attachments.
- *
- * @param context
- * @param accountId the account to scrub
- */
- public static void deleteAllAccountAttachmentFiles(Context context, long accountId) {
- File[] files = getAttachmentDirectory(context, accountId).listFiles();
- if (files == null) return;
- for (File file : files) {
- boolean result = file.delete();
- if (!result) {
- Log.e(Logging.LOG_TAG, "Failed to delete attachment file " + file.getName());
- }
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/utility/ConversionUtilities.java b/emailcommon/src/com/android/emailcommon/utility/ConversionUtilities.java
deleted file mode 100644
index dca31d647..000000000
--- a/emailcommon/src/com/android/emailcommon/utility/ConversionUtilities.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.utility;
-
-import com.android.emailcommon.internet.MimeHeader;
-import com.android.emailcommon.internet.MimeUtility;
-import com.android.emailcommon.mail.MessagingException;
-import com.android.emailcommon.mail.Part;
-import com.android.emailcommon.mail.Snippet;
-import com.android.emailcommon.provider.EmailContent;
-
-import android.text.TextUtils;
-
-import java.util.ArrayList;
-
-public class ConversionUtilities {
- /**
- * Values for HEADER_ANDROID_BODY_QUOTED_PART to tag body parts
- */
- public static final String BODY_QUOTED_PART_REPLY = "quoted-reply";
- public static final String BODY_QUOTED_PART_FORWARD = "quoted-forward";
- public static final String BODY_QUOTED_PART_INTRO = "quoted-intro";
-
- /**
- * Helper function to append text to a StringBuffer, creating it if necessary.
- * Optimization: The majority of the time we are *not* appending - we should have a path
- * that deals with single strings.
- */
- private static StringBuffer appendTextPart(StringBuffer sb, String newText) {
- if (newText == null) {
- return sb;
- }
- else if (sb == null) {
- sb = new StringBuffer(newText);
- } else {
- if (sb.length() > 0) {
- sb.append('\n');
- }
- sb.append(newText);
- }
- return sb;
- }
-
- /**
- * Copy body text (plain and/or HTML) from MimeMessage to provider Message
- */
- public static boolean updateBodyFields(EmailContent.Body body,
- EmailContent.Message localMessage, ArrayList<Part> viewables)
- throws MessagingException {
-
- body.mMessageKey = localMessage.mId;
-
- StringBuffer sbHtml = null;
- StringBuffer sbText = null;
- StringBuffer sbHtmlReply = null;
- StringBuffer sbTextReply = null;
- StringBuffer sbIntroText = null;
-
- for (Part viewable : viewables) {
- String text = MimeUtility.getTextFromPart(viewable);
- String[] replyTags = viewable.getHeader(MimeHeader.HEADER_ANDROID_BODY_QUOTED_PART);
- String replyTag = null;
- if (replyTags != null && replyTags.length > 0) {
- replyTag = replyTags[0];
- }
- // Deploy text as marked by the various tags
- boolean isHtml = "text/html".equalsIgnoreCase(viewable.getMimeType());
-
- if (replyTag != null) {
- boolean isQuotedReply = BODY_QUOTED_PART_REPLY.equalsIgnoreCase(replyTag);
- boolean isQuotedForward = BODY_QUOTED_PART_FORWARD.equalsIgnoreCase(replyTag);
- boolean isQuotedIntro = BODY_QUOTED_PART_INTRO.equalsIgnoreCase(replyTag);
-
- if (isQuotedReply || isQuotedForward) {
- if (isHtml) {
- sbHtmlReply = appendTextPart(sbHtmlReply, text);
- } else {
- sbTextReply = appendTextPart(sbTextReply, text);
- }
- // Set message flags as well
- localMessage.mFlags &= ~EmailContent.Message.FLAG_TYPE_MASK;
- localMessage.mFlags |= isQuotedReply
- ? EmailContent.Message.FLAG_TYPE_REPLY
- : EmailContent.Message.FLAG_TYPE_FORWARD;
- continue;
- }
- if (isQuotedIntro) {
- sbIntroText = appendTextPart(sbIntroText, text);
- continue;
- }
- }
-
- // Most of the time, just process regular body parts
- if (isHtml) {
- sbHtml = appendTextPart(sbHtml, text);
- } else {
- sbText = appendTextPart(sbText, text);
- }
- }
-
- // write the combined data to the body part
- if (!TextUtils.isEmpty(sbText)) {
- String text = sbText.toString();
- body.mTextContent = text;
- localMessage.mSnippet = Snippet.fromPlainText(text);
- }
- if (!TextUtils.isEmpty(sbHtml)) {
- String text = sbHtml.toString();
- body.mHtmlContent = text;
- if (localMessage.mSnippet == null) {
- localMessage.mSnippet = Snippet.fromHtmlText(text);
- }
- }
- if (sbHtmlReply != null && sbHtmlReply.length() != 0) {
- body.mHtmlReply = sbHtmlReply.toString();
- }
- if (sbTextReply != null && sbTextReply.length() != 0) {
- body.mTextReply = sbTextReply.toString();
- }
- if (sbIntroText != null && sbIntroText.length() != 0) {
- body.mIntroText = sbIntroText.toString();
- }
- return true;
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/utility/LoggingInputStream.java b/emailcommon/src/com/android/emailcommon/utility/LoggingInputStream.java
deleted file mode 100644
index 212efa183..000000000
--- a/emailcommon/src/com/android/emailcommon/utility/LoggingInputStream.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.utility;
-
-import com.android.emailcommon.Logging;
-
-import android.util.Log;
-
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Simple class used for debugging only that affords us a view of the raw IMAP or POP3 stream,
- * in addition to the tokenized version.
- *
- * Use of this class *MUST* be restricted to logging-enabled situations only.
- */
-public class LoggingInputStream extends FilterInputStream {
- private StringBuilder mSb;
- private boolean mDumpEmptyLines;
- private final String mTag;
-
- public LoggingInputStream(InputStream in) {
- this(in, "RAW", false);
- }
-
- public LoggingInputStream(InputStream in, String tag, boolean dumpEmptyLines) {
- super(in);
- mTag = tag + " ";
- mDumpEmptyLines = dumpEmptyLines;
- initBuffer();
- Log.d(Logging.LOG_TAG, mTag + "dump start");
- }
-
- private void initBuffer() {
- mSb = new StringBuilder(mTag);
- }
-
- /**
- * Collect chars as read, and log them when EOL reached.
- */
- @Override
- public int read() throws IOException {
- int oneByte = super.read();
- logRaw(oneByte);
- return oneByte;
- }
-
- /**
- * Collect chars as read, and log them when EOL reached.
- */
- @Override
- public int read(byte[] b, int offset, int length) throws IOException {
- int bytesRead = super.read(b, offset, length);
- int copyBytes = bytesRead;
- while (copyBytes > 0) {
- logRaw(b[offset] & 0xFF);
- copyBytes--;
- offset++;
- }
-
- return bytesRead;
- }
-
- /**
- * Write and clear the buffer
- */
- private void logRaw(int oneByte) {
- if (oneByte == '\r') {
- // Don't log.
- } else if (oneByte == '\n') {
- flushLog();
- } else if (0x20 <= oneByte && oneByte <= 0x7e) { // Printable ASCII.
- mSb.append((char)oneByte);
- } else {
- // email protocols are supposed to be all 7bits, but there are wrong implementations
- // that do send 8 bit characters...
- mSb.append("\\x" + Utility.byteToHex(oneByte));
- }
- }
-
- private void flushLog() {
- if (mDumpEmptyLines || (mSb.length() > mTag.length())) {
- Log.d(Logging.LOG_TAG, mSb.toString());
- initBuffer();
- }
- }
-
- @Override
- public void close() throws IOException {
- super.close();
- flushLog();
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/utility/SSLUtils.java b/emailcommon/src/com/android/emailcommon/utility/SSLUtils.java
deleted file mode 100644
index 4869a0f6a..000000000
--- a/emailcommon/src/com/android/emailcommon/utility/SSLUtils.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright (C) 2010 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.utility;
-
-import android.net.SSLCertificateSocketFactory;
-
-import javax.net.ssl.SSLSocketFactory;
-
-public class SSLUtils {
- private static SSLSocketFactory sInsecureFactory;
- private static SSLSocketFactory sSecureFactory;
-
- /**
- * Returns a {@link SSLSocketFactory}. Optionally bypass all SSL certificate checks.
- *
- * @param insecure if true, bypass all SSL certificate checks
- */
- public synchronized static final SSLSocketFactory getSSLSocketFactory(boolean insecure) {
- if (insecure) {
- if (sInsecureFactory == null) {
- sInsecureFactory = SSLCertificateSocketFactory.getInsecure(0, null);
- }
- return sInsecureFactory;
- } else {
- if (sSecureFactory == null) {
- sSecureFactory = SSLCertificateSocketFactory.getDefault(0, null);
- }
- return sSecureFactory;
- }
- }
-}
diff --git a/emailcommon/src/com/android/emailcommon/utility/Utility.java b/emailcommon/src/com/android/emailcommon/utility/Utility.java
deleted file mode 100644
index f3dc599c2..000000000
--- a/emailcommon/src/com/android/emailcommon/utility/Utility.java
+++ /dev/null
@@ -1,1131 +0,0 @@
-/*
- * Copyright (C) 2008 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.emailcommon.utility;
-
-import com.android.emailcommon.Logging;
-import com.android.emailcommon.provider.EmailContent;
-import com.android.emailcommon.provider.EmailContent.Account;
-import com.android.emailcommon.provider.EmailContent.AccountColumns;
-import com.android.emailcommon.provider.EmailContent.Attachment;
-import com.android.emailcommon.provider.EmailContent.AttachmentColumns;
-import com.android.emailcommon.provider.EmailContent.HostAuth;
-import com.android.emailcommon.provider.EmailContent.HostAuthColumns;
-import com.android.emailcommon.provider.EmailContent.Mailbox;
-import com.android.emailcommon.provider.EmailContent.MailboxColumns;
-import com.android.emailcommon.provider.EmailContent.Message;
-import com.android.emailcommon.provider.EmailContent.MessageColumns;
-
-import android.app.Activity;
-import android.content.ContentResolver;
-import android.content.ContentUris;
-import android.content.ContentValues;
-import android.content.Context;
-import android.content.Intent;
-import android.database.Cursor;
-import android.database.CursorWrapper;
-import android.graphics.Typeface;
-import android.net.Uri;
-import android.os.AsyncTask;
-import android.os.Environment;
-import android.os.Handler;
-import android.os.Parcel;
-import android.os.Parcelable;
-import android.provider.OpenableColumns;
-import android.text.Spannable;
-import android.text.SpannableString;
-import android.text.SpannableStringBuilder;
-import android.text.TextUtils;
-import android.text.style.StyleSpan;
-import android.util.Base64;
-import android.util.Log;
-import android.widget.AbsListView;
-import android.widget.ListView;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import java.io.ByteArrayInputStream;
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.nio.ByteBuffer;
-import java.nio.CharBuffer;
-import java.nio.charset.Charset;
-import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.GregorianCalendar;
-import java.util.TimeZone;
-import java.util.regex.Pattern;
-
-public class Utility {
- public static final Charset UTF_8 = Charset.forName("UTF-8");
- public static final Charset ASCII = Charset.forName("US-ASCII");
-
- public static final String[] EMPTY_STRINGS = new String[0];
- public static final Long[] EMPTY_LONGS = new Long[0];
-
- // "GMT" + "+" or "-" + 4 digits
- private static final Pattern DATE_CLEANUP_PATTERN_WRONG_TIMEZONE =
- Pattern.compile("GMT([-+]\\d{4})$");
-
- public final static String readInputStream(InputStream in, String encoding) throws IOException {
- InputStreamReader reader = new InputStreamReader(in, encoding);
- StringBuffer sb = new StringBuffer();
- int count;
- char[] buf = new char[512];
- while ((count = reader.read(buf)) != -1) {
- sb.append(buf, 0, count);
- }
- return sb.toString();
- }
-
- public final static boolean arrayContains(Object[] a, Object o) {
- for (int i = 0, count = a.length; i < count; i++) {
- if (a[i].equals(o)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Returns a concatenated string containing the output of every Object's
- * toString() method, each separated by the given separator character.
- */
- public static String combine(Object[] parts, char separator) {
- if (parts == null) {
- return null;
- }
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < parts.length; i++) {
- sb.append(parts[i].toString());
- if (i < parts.length - 1) {
- sb.append(separator);
- }
- }
- return sb.toString();
- }
- public static String base64Decode(String encoded) {
- if (encoded == null) {
- return null;
- }
- byte[] decoded = Base64.decode(encoded, Base64.DEFAULT);
- return new String(decoded);
- }
-
- public static String base64Encode(String s) {
- if (s == null) {
- return s;
- }
- return Base64.encodeToString(s.getBytes(), Base64.NO_WRAP);
- }
-
- public static boolean isTextViewNotEmpty(TextView view) {
- return !TextUtils.isEmpty(view.getText());
- }
-
- public static boolean isPortFieldValid(TextView view) {
- CharSequence chars = view.getText();
- if (TextUtils.isEmpty(chars)) return false;
- Integer port;
- // In theory, we can't get an illegal value here, since the field is monitored for valid
- // numeric input. But this might be used elsewhere without such a check.
- try {
- port = Integer.parseInt(chars.toString());
- } catch (NumberFormatException e) {
- return false;
- }
- return port > 0 && port < 65536;
- }
-
- /**
- * Ensures that the given string starts and ends with the double quote character. The string is
- * not modified in any way except to add the double quote character to start and end if it's not
- * already there.
- *
- * TODO: Rename this, because "quoteString()" can mean so many different things.
- *
- * sample -> "sample"
- * "sample" -> "sample"
- * ""sample"" -> "sample"
- * "sample"" -> "sample"
- * sa"mp"le -> "sa"mp"le"
- * "sa"mp"le" -> "sa"mp"le"
- * (empty string) -> ""
- * " -> ""
- */
- public static String quoteString(String s) {
- if (s == null) {
- return null;
- }
- if (!s.matches("^\".*\"$")) {
- return "\"" + s + "\"";
- }
- else {
- return s;
- }
- }
-
- /**
- * Apply quoting rules per IMAP RFC,
- * quoted = DQUOTE *QUOTED-CHAR DQUOTE
- * QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> / "\" quoted-specials
- * quoted-specials = DQUOTE / "\"
- *
- * This is used primarily for IMAP login, but might be useful elsewhere.
- *
- * NOTE: Not very efficient - you may wish to preflight this, or perhaps it should check
- * for trouble chars before calling the replace functions.
- *
- * @param s The string to be quoted.
- * @return A copy of the string, having undergone quoting as described above
- */
- public static String imapQuoted(String s) {
-
- // First, quote any backslashes by replacing \ with \\
- // regex Pattern: \\ (Java string const = \\\\)
- // Substitute: \\\\ (Java string const = \\\\\\\\)
- String result = s.replaceAll("\\\\", "\\\\\\\\");
-
- // Then, quote any double-quotes by replacing " with \"
- // regex Pattern: " (Java string const = \")
- // Substitute: \\" (Java string const = \\\\\")
- result = result.replaceAll("\"", "\\\\\"");
-
- // return string with quotes around it
- return "\"" + result + "\"";
- }
-
- /**
- * A fast version of URLDecoder.decode() that works only with UTF-8 and does only two
- * allocations. This version is around 3x as fast as the standard one and I'm using it
- * hundreds of times in places that slow down the UI, so it helps.
- */
- public static String fastUrlDecode(String s) {
- try {
- byte[] bytes = s.getBytes("UTF-8");
- byte ch;
- int length = 0;
- for (int i = 0, count = bytes.length; i < count; i++) {
- ch = bytes[i];
- if (ch == '%') {
- int h = (bytes[i + 1] - '0');
- int l = (bytes[i + 2] - '0');
- if (h > 9) {
- h -= 7;
- }
- if (l > 9) {
- l -= 7;
- }
- bytes[length] = (byte) ((h << 4) | l);
- i += 2;
- }
- else if (ch == '+') {
- bytes[length] = ' ';
- }
- else {
- bytes[length] = bytes[i];
- }
- length++;
- }
- return new String(bytes, 0, length, "UTF-8");
- }
- catch (UnsupportedEncodingException uee) {
- return null;
- }
- }
-
- /**
- * Returns the where clause for a message list selection.
- *
- * TODO This method needs to be rewritten to use the _SELECTION constants defined in
- * EmailContent.Message.
- *
- * MUST NOT be called on the UI thread.
- */
- public static String buildMailboxIdSelection(Context context, long mailboxId) {
- final ContentResolver resolver = context.getContentResolver();
- final StringBuilder selection = new StringBuilder();
-
- // We don't check "flagLoaded" for messages in Outbox.
- boolean testFlagLoaded = true;
-
- if (mailboxId == Mailbox.QUERY_ALL_INBOXES
- || mailboxId == Mailbox.QUERY_ALL_DRAFTS
- || mailboxId == Mailbox.QUERY_ALL_OUTBOX) {
- // query for all mailboxes of type INBOX, DRAFTS, or OUTBOX
- int type;
- if (mailboxId == Mailbox.QUERY_ALL_INBOXES) {
- type = Mailbox.TYPE_INBOX;
- } else if (mailboxId == Mailbox.QUERY_ALL_DRAFTS) {
- type = Mailbox.TYPE_DRAFTS;
- } else {
- type = Mailbox.TYPE_OUTBOX;
- testFlagLoaded = false;
- }
- StringBuilder inboxes = new StringBuilder();
- Cursor c = resolver.query(Mailbox.CONTENT_URI,
- EmailContent.ID_PROJECTION,
- MailboxColumns.TYPE + "=? AND " + MailboxColumns.FLAG_VISIBLE + "=1",
- new String[] { Integer.toString(type) }, null);
- // build an IN (mailboxId, ...) list
- while (c.moveToNext()) {
- if (inboxes.length() != 0) {
- inboxes.append(",");
- }
- inboxes.append(c.getLong(EmailContent.ID_PROJECTION_COLUMN));
- }
- c.close();
- selection.append(MessageColumns.MAILBOX_KEY + " IN ");
- selection.append("(").append(inboxes).append(")");
- } else if (mailboxId == Mailbox.QUERY_ALL_UNREAD) {
- selection.append(Message.FLAG_READ + "=0");
- } else if (mailboxId == Mailbox.QUERY_ALL_FAVORITES) {
- selection.append(Message.ALL_FAVORITE_SELECTION);
- } else {
- selection.append(MessageColumns.MAILBOX_KEY + "=" + mailboxId);
- if (Mailbox.getMailboxType(context, mailboxId) == Mailbox.TYPE_OUTBOX) {
- testFlagLoaded = false;
- }
- }
-
- if (testFlagLoaded) {
- // POP messages at the initial stage have very little information. (Server UID only)
- // This makes sure they're not visible in the message list.
- // This means unread counts on the mailbox list can be different from the
- // number of messages in the message list, but it should be transient...
- selection.append(" AND ").append(Message.FLAG_LOADED_SELECTION);
- }
-
- return selection.toString();
- }
- private final static String HOSTAUTH_WHERE_CREDENTIALS = HostAuthColumns.ADDRESS + " like ?"
- + " and " + HostAuthColumns.LOGIN + " like ?"
- + " and " + HostAuthColumns.PROTOCOL + " not like \"smtp\"";
- private final static String ACCOUNT_WHERE_HOSTAUTH = AccountColumns.HOST_AUTH_KEY_RECV + "=?";
-
- /**
- * Look for an existing account with the same username & server
- *
- * @param context a system context
- * @param allowAccountId this account Id will not trigger (when editing an existing account)
- * @param hostName the server's address
- * @param userLogin the user's login string
- * @result null = no matching account found. Account = matching account
- */
- public static Account findExistingAccount(Context context, long allowAccountId,
- String hostName, String userLogin) {
- ContentResolver resolver = context.getContentResolver();
- Cursor c = resolver.query(HostAuth.CONTENT_URI, HostAuth.ID_PROJECTION,
- HOSTAUTH_WHERE_CREDENTIALS, new String[] { hostName, userLogin }, null);
- try {
- while (c.moveToNext()) {
- long hostAuthId = c.getLong(HostAuth.ID_PROJECTION_COLUMN);
- // Find account with matching hostauthrecv key, and return it
- Cursor c2 = resolver.query(Account.CONTENT_URI, Account.ID_PROJECTION,
- ACCOUNT_WHERE_HOSTAUTH, new String[] { Long.toString(hostAuthId) }, null);
- try {
- while (c2.moveToNext()) {
- long accountId = c2.getLong(Account.ID_PROJECTION_COLUMN);
- if (accountId != allowAccountId) {
- Account account = Account.restoreAccountWithId(context, accountId);
- if (account != null) {
- return account;
- }
- }
- }
- } finally {
- c2.close();
- }
- }
- } finally {
- c.close();
- }
-
- return null;
- }
-
- /**
- * Generate a random message-id header for locally-generated messages.
- */
- public static String generateMessageId() {
- StringBuffer sb = new StringBuffer();
- sb.append("<");
- for (int i = 0; i < 24; i++) {
- sb.append(Integer.toString((int)(Math.random() * 35), 36));
- }
- sb.append(".");
- sb.append(Long.toString(System.currentTimeMillis()));
- sb.append("@email.android.com>");
- return sb.toString();
- }
-
- /**
- * Generate a time in milliseconds from a date string that represents a date/time in GMT
- * @param date string in format 20090211T180303Z (rfc2445, iCalendar).
- * @return the time in milliseconds (since Jan 1, 1970)
- */
- public static long parseDateTimeToMillis(String date) {
- GregorianCalendar cal = parseDateTimeToCalendar(date);
- return cal.getTimeInMillis();
- }
-
- /**
- * Generate a GregorianCalendar from a date string that represents a date/time in GMT
- * @param date string in format 20090211T180303Z (rfc2445, iCalendar).
- * @return the GregorianCalendar
- */
- public static GregorianCalendar parseDateTimeToCalendar(String date) {
- GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(date.substring(0, 4)),
- Integer.parseInt(date.substring(4, 6)) - 1, Integer.parseInt(date.substring(6, 8)),
- Integer.parseInt(date.substring(9, 11)), Integer.parseInt(date.substring(11, 13)),
- Integer.parseInt(date.substring(13, 15)));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- return cal;
- }
-
- /**
- * Generate a time in milliseconds from an email date string that represents a date/time in GMT
- * @param date string in format 2010-02-23T16:00:00.000Z (ISO 8601, rfc3339)
- * @return the time in milliseconds (since Jan 1, 1970)
- */
- public static long parseEmailDateTimeToMillis(String date) {
- GregorianCalendar cal = new GregorianCalendar(Integer.parseInt(date.substring(0, 4)),
- Integer.parseInt(date.substring(5, 7)) - 1, Integer.parseInt(date.substring(8, 10)),
- Integer.parseInt(date.substring(11, 13)), Integer.parseInt(date.substring(14, 16)),
- Integer.parseInt(date.substring(17, 19)));
- cal.setTimeZone(TimeZone.getTimeZone("GMT"));
- return cal.getTimeInMillis();
- }
-
- private static byte[] encode(Charset charset, String s) {
- if (s == null) {
- return null;
- }
- final ByteBuffer buffer = charset.encode(CharBuffer.wrap(s));
- final byte[] bytes = new byte[buffer.limit()];
- buffer.get(bytes);
- return bytes;
- }
-
- private static String decode(Charset charset, byte[] b) {
- if (b == null) {
- return null;
- }
- final CharBuffer cb = charset.decode(ByteBuffer.wrap(b));
- return new String(cb.array(), 0, cb.length());
- }
-
- /** Converts a String to UTF-8 */
- public static byte[] toUtf8(String s) {
- return encode(UTF_8, s);
- }
-
- /** Builds a String from UTF-8 bytes */
- public static String fromUtf8(byte[] b) {
- return decode(UTF_8, b);
- }
-
- /** Converts a String to ASCII bytes */
- public static byte[] toAscii(String s) {
- return encode(ASCII, s);
- }
-
- /** Builds a String from ASCII bytes */
- public static String fromAscii(byte[] b) {
- return decode(ASCII, b);
- }
-
- /**
- * @return true if the input is the first (or only) byte in a UTF-8 character
- */
- public static boolean isFirstUtf8Byte(byte b) {
- // If the top 2 bits is '10', it's not a first byte.
- return (b & 0xc0) != 0x80;
- }
-
- public static String byteToHex(int b) {
- return byteToHex(new StringBuilder(), b).toString();
- }
-
- public static StringBuilder byteToHex(StringBuilder sb, int b) {
- b &= 0xFF;
- sb.append("0123456789ABCDEF".charAt(b >> 4));
- sb.append("0123456789ABCDEF".charAt(b & 0xF));
- return sb;
- }
-
- public static String replaceBareLfWithCrlf(String str) {
- return str.replace("\r", "").replace("\n", "\r\n");
- }
-
- /**
- * Cancel an {@link AsyncTask}. If it's already running, it'll be interrupted.
- */
- public static void cancelTaskInterrupt(AsyncTask<?, ?, ?> task) {
- cancelTask(task, true);
- }
-
- /**
- * Cancel an {@link AsyncTask}.
- *
- * @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
- * task should be interrupted; otherwise, in-progress tasks are allowed
- * to complete.
- */
- public static void cancelTask(AsyncTask<?, ?, ?> task, boolean mayInterruptIfRunning) {
- if (task != null && task.getStatus() != AsyncTask.Status.FINISHED) {
- task.cancel(mayInterruptIfRunning);
- }
- }
-
- public static String getSmallHash(final String value) {
- final MessageDigest sha;
- try {
- sha = MessageDigest.getInstance("SHA-1");
- } catch (NoSuchAlgorithmException impossible) {
- return null;
- }
- sha.update(Utility.toUtf8(value));
- final int hash = getSmallHashFromSha1(sha.digest());
- return Integer.toString(hash);
- }
-
- /**
- * @return a non-negative integer generated from 20 byte SHA-1 hash.
- */
- /* package for testing */ static int getSmallHashFromSha1(byte[] sha1) {
- final int offset = sha1[19] & 0xf; // SHA1 is 20 bytes.
- return ((sha1[offset] & 0x7f) << 24)
- | ((sha1[offset + 1] & 0xff) << 16)
- | ((sha1[offset + 2] & 0xff) << 8)
- | ((sha1[offset + 3] & 0xff));
- }
-
- /**
- * Try to make a date MIME(RFC 2822/5322)-compliant.
- *
- * It fixes:
- * - "Thu, 10 Dec 09 15:08:08 GMT-0700" to "Thu, 10 Dec 09 15:08:08 -0700"
- * (4 digit zone value can't be preceded by "GMT")
- * We got a report saying eBay sends a date in this format
- */
- public static String cleanUpMimeDate(String date) {
- if (TextUtils.isEmpty(date)) {
- return date;
- }
- date = DATE_CLEANUP_PATTERN_WRONG_TIMEZONE.matcher(date).replaceFirst("$1");
- return date;
- }
-
- public static ByteArrayInputStream streamFromAsciiString(String ascii) {
- return new ByteArrayInputStream(toAscii(ascii));
- }
-
- /**
- * A thread safe way to show a Toast. This method uses {@link Activity#runOnUiThread}, so it
- * can be called on any thread.
- *
- * @param activity Parent activity.
- * @param resId Resource ID of the message string.
- */
- public static void showToast(Activity activity, int resId) {
- showToast(activity, activity.getResources().getString(resId));
- }
-
- /**
- * A thread safe way to show a Toast. This method uses {@link Activity#runOnUiThread}, so it
- * can be called on any thread.
- *
- * @param activity Parent activity.
- * @param message Message to show.
- */
- public static void showToast(final Activity activity, final String message) {
- activity.runOnUiThread(new Runnable() {
- public void run() {
- Toast.makeText(activity, message, Toast.LENGTH_LONG).show();
- }
- });
- }
-
- /**
- * Run {@code r} on a worker thread, returning the AsyncTask
- * @return the AsyncTask; this is primarily for use by unit tests, which require the
- * result of the task
- */
- public static AsyncTask<Void, Void, Void> runAsync(final Runnable r) {
- return new AsyncTask<Void, Void, Void>() {
- @Override protected Void doInBackground(Void... params) {
- r.run();
- return null;
- }
- }.execute();
- }
-
- /**
- * Interface used in {@link #createUniqueFile} instead of {@link File#createNewFile()} to make
- * it testable.
- */
- /* package */ interface NewFileCreator {
- public static final NewFileCreator DEFAULT = new NewFileCreator() {
- @Override public boolean createNewFile(File f) throws IOException {
- return f.createNewFile();
- }
- };
- public boolean createNewFile(File f) throws IOException ;
- }
-
- /**
- * Creates a new empty file with a unique name in the given directory by appending a hyphen and
- * a number to the given filename.
- *
- * @return a new File object, or null if one could not be created
- */
- public static File createUniqueFile(File directory, String filename) throws IOException {
- return createUniqueFileInternal(NewFileCreator.DEFAULT, directory, filename);
- }
-
- /* package */ static File createUniqueFileInternal(NewFileCreator nfc,
- File directory, String filename) throws IOException {
- File file = new File(directory, filename);
- if (nfc.createNewFile(file)) {
- return file;
- }
- // Get the extension of the file, if any.
- int index = filename.lastIndexOf('.');
- String format;
- if (index != -1) {
- String name = filename.substring(0, index);
- String extension = filename.substring(index);
- format = name + "-%d" + extension;
- } else {
- format = filename + "-%d";
- }
-
- for (int i = 2; i < Integer.MAX_VALUE; i++) {
- file = new File(directory, String.format(format, i));
- if (nfc.createNewFile(file)) {
- return file;
- }
- }
- return null;
- }
-
- public interface CursorGetter<T> {
- T get(Cursor cursor, int column);
- }
-
- private static final CursorGetter<Long> LONG_GETTER = new CursorGetter<Long>() {
- public Long get(Cursor cursor, int column) {
- return cursor.getLong(column);
- }
- };
-
- private static final CursorGetter<Integer> INT_GETTER = new CursorGetter<Integer>() {
- public Integer get(Cursor cursor, int column) {
- return cursor.getInt(column);
- }
- };
-
- private static final CursorGetter<String> STRING_GETTER = new CursorGetter<String>() {
- public String get(Cursor cursor, int column) {
- return cursor.getString(column);
- }
- };
-
- private static final CursorGetter<byte[]> BLOB_GETTER = new CursorGetter<byte[]>() {
- public byte[] get(Cursor cursor, int column) {
- return cursor.getBlob(column);
- }
- };
-
- /**
- * @return if {@code original} is to the EmailProvider, add "?limit=1". Otherwise just returns
- * {@code original}.
- *
- * Other providers don't support the limit param. Also, changing URI passed from other apps
- * can cause permission errors.
- */
- /* package */ static Uri buildLimitOneUri(Uri original) {
- if ("content".equals(original.getScheme()) &&
- EmailContent.AUTHORITY.equals(original.getAuthority())) {
- return EmailContent.uriWithLimit(original, 1);
- }
- return original;
- }
-
- /**
- * @return a generic in column {@code column} of the first result row, if the query returns at
- * least 1 row. Otherwise returns {@code defaultValue}.
- */
- public static <T extends Object> T getFirstRowColumn(Context context, Uri uri,
- String[] projection, String selection, String[] selectionArgs, String sortOrder,
- int column, T defaultValue, CursorGetter<T> getter) {
- // Use PARAMETER_LIMIT to restrict the query to the single row we need
- uri = buildLimitOneUri(uri);
- Cursor c = context.getContentResolver().query(uri, projection, selection, selectionArgs,
- sortOrder);
- if (c != null) {
- try {
- if (c.moveToFirst()) {
- return getter.get(c, column);
- }
- } finally {
- c.close();
- }
- }
- return defaultValue;
- }
-
- /**
- * {@link #getFirstRowColumn} for a Long with null as a default value.
- */
- public static Long getFirstRowLong(Context context, Uri uri, String[] projection,
- String selection, String[] selectionArgs, String sortOrder, int column) {
- return getFirstRowColumn(context, uri, projection, selection, selectionArgs,
- sortOrder, column, null, LONG_GETTER);
- }
-
- /**
- * {@link #getFirstRowColumn} for a Long with a provided default value.
- */
- public static Long getFirstRowLong(Context context, Uri uri, String[] projection,
- String selection, String[] selectionArgs, String sortOrder, int column,
- Long defaultValue) {
- return getFirstRowColumn(context, uri, projection, selection, selectionArgs,
- sortOrder, column, defaultValue, LONG_GETTER);
- }
-
- /**
- * {@link #getFirstRowColumn} for an Integer with null as a default value.
- */
- public static Integer getFirstRowInt(Context context, Uri uri, String[] projection,
- String selection, String[] selectionArgs, String sortOrder, int column) {
- return getFirstRowColumn(context, uri, projection, selection, selectionArgs,
- sortOrder, column, null, INT_GETTER);
- }
-
- /**
- * {@link #getFirstRowColumn} for an Integer with a provided default value.
- */
- public static Integer getFirstRowInt(Context context, Uri uri, String[] projection,
- String selection, String[] selectionArgs, String sortOrder, int column,
- Integer defaultValue) {
- return getFirstRowColumn(context, uri, projection, selection, selectionArgs,
- sortOrder, column, defaultValue, INT_GETTER);
- }
-
- /**
- * {@link #getFirstRowColumn} for a String with null as a default value.
- */
- public static String getFirstRowString(Context context, Uri uri, String[] projection,
- String selection, String[] selectionArgs, String sortOrder, int column) {
- return getFirstRowString(context, uri, projection, selection, selectionArgs, sortOrder,
- column, null);
- }
-
- /**
- * {@link #getFirstRowColumn} for a String with a provided default value.
- */
- public static String getFirstRowString(Context context, Uri uri, String[] projection,
- String selection, String[] selectionArgs, String sortOrder, int column,
- String defaultValue) {
- return getFirstRowColumn(context, uri, projection, selection, selectionArgs,
- sortOrder, column, defaultValue, STRING_GETTER);
- }
-
- /**
- * {@link #getFirstRowColumn} for a byte array with a provided default value.
- */
- public static byte[] getFirstRowBlob(Context context, Uri uri, String[] projection,
- String selection, String[] selectionArgs, String sortOrder, int column,
- byte[] defaultValue) {
- return getFirstRowColumn(context, uri, projection, selection, selectionArgs, sortOrder,
- column, defaultValue, BLOB_GETTER);
- }
-
- /**
- * A class used to restore ListView state (e.g. scroll position) when changing adapter.
- */
- public static class ListStateSaver implements Parcelable {
- private final Parcelable mState;
-
- private ListStateSaver(Parcel p) {
- mState = p.readParcelable(getClass().getClassLoader());
- }
-
- public ListStateSaver(AbsListView lv) {
- mState = lv.onSaveInstanceState();
- }
-
- public void restore(AbsListView lv) {
- lv.onRestoreInstanceState(mState);
- }
-
- @Override
- public int describeContents() {
- return 0;
- }
-
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeParcelable(mState, flags);
- }
-
- public static final Parcelable.Creator<ListStateSaver> CREATOR
- = new Parcelable.Creator<ListStateSaver>() {
- public ListStateSaver createFromParcel(Parcel in) {
- return new ListStateSaver(in);
- }
-
- public ListStateSaver[] newArray(int size) {
- return new ListStateSaver[size];
- }
- };
- }
-
- public static boolean attachmentExists(Context context, Attachment attachment) {
- if (attachment == null) {
- return false;
- } else if (attachment.mContentBytes != null) {
- return true;
- } else if (TextUtils.isEmpty(attachment.mContentUri)) {
- return false;
- }
- try {
- Uri fileUri = Uri.parse(attachment.mContentUri);
- try {
- InputStream inStream = context.getContentResolver().openInputStream(fileUri);
- try {
- inStream.close();
- } catch (IOException e) {
- // Nothing to be done if can't close the stream
- }
- return true;
- } catch (FileNotFoundException e) {
- return false;
- }
- } catch (RuntimeException re) {
- Log.w(Logging.LOG_TAG, "attachmentExists RuntimeException=" + re);
- return false;
- }
- }
-
- /**
- * Check whether the message with a given id has unloaded attachments. If the message is
- * a forwarded message, we look instead at the messages's source for the attachments. If the
- * message or forward source can't be found, we return false
- * @param context the caller's context
- * @param messageId the id of the message
- * @return whether or not the message has unloaded attachments
- */
- public static boolean hasUnloadedAttachments(Context context, long messageId) {
- Message msg = Message.restoreMessageWithId(context, messageId);
- if (msg == null) return false;
- Attachment[] atts = Attachment.restoreAttachmentsWithMessageId(context, messageId);
- for (Attachment att: atts) {
- if (!attachmentExists(context, att)) {
- // If the attachment doesn't exist and isn't marked for download, we're in trouble
- // since the outbound message will be stuck indefinitely in the Outbox. Instead,
- // we'll just delete the attachment and continue; this is far better than the
- // alternative. In theory, this situation shouldn't be possible.
- if ((att.mFlags & (Attachment.FLAG_DOWNLOAD_FORWARD |
- Attachment.FLAG_DOWNLOAD_USER_REQUEST)) == 0) {
- Log.d(Logging.LOG_TAG, "Unloaded attachment isn't marked for download: " +
- att.mFileName + ", #" + att.mId);
- Attachment.delete(context, Attachment.CONTENT_URI, att.mId);
- } else if (att.mContentUri != null) {
- // In this case, the attachment file is gone from the cache; let's clear the
- // contentUri; this should be a very unusual case
- ContentValues cv = new ContentValues();
- cv.putNull(AttachmentColumns.CONTENT_URI);
- Attachment.update(context, Attachment.CONTENT_URI, att.mId, cv);
- }
- return true;
- }
- }
- return false;
- }
-
- /**
- * Convenience method wrapping calls to retrieve columns from a single row, via EmailProvider.
- * The arguments are exactly the same as to contentResolver.query(). Results are returned in
- * an array of Strings corresponding to the columns in the projection. If the cursor has no
- * rows, null is returned.
- */
- public static String[] getRowColumns(Context context, Uri contentUri, String[] projection,
- String selection, String[] selectionArgs) {
- String[] values = new String[projection.length];
- ContentResolver cr = context.getContentResolver();
- Cursor c = cr.query(contentUri, projection, selection, selectionArgs, null);
- try {
- if (c.moveToFirst()) {
- for (int i = 0; i < projection.length; i++) {
- values[i] = c.getString(i);
- }
- } else {
- return null;
- }
- } finally {
- c.close();
- }
- return values;
- }
-
- /**
- * Convenience method for retrieving columns from a particular row in EmailProvider.
- * Passed in here are a base uri (e.g. Message.CONTENT_URI), the unique id of a row, and
- * a projection. This method calls the previous one with the appropriate URI.
- */
- public static String[] getRowColumns(Context context, Uri baseUri, long id,
- String ... projection) {
- return getRowColumns(context, ContentUris.withAppendedId(baseUri, id), projection, null,
- null);
- }
-
- public static boolean isExternalStorageMounted() {
- return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
- }
-
- /**
- * Class that supports running any operation for each account.
- */
- public abstract static class ForEachAccount extends AsyncTask<Void, Void, Long[]> {
- private final Context mContext;
-
- public ForEachAccount(Context context) {
- mContext = context;
- }
-
- @Override
- protected final Long[] doInBackground(Void... params) {
- ArrayList<Long> ids = new ArrayList<Long>();
- Cursor c = mContext.getContentResolver().query(EmailContent.Account.CONTENT_URI,
- EmailContent.Account.ID_PROJECTION, null, null, null);
- try {
- while (c.moveToNext()) {
- ids.add(c.getLong(EmailContent.Account.ID_PROJECTION_COLUMN));
- }
- } finally {
- c.close();
- }
- return ids.toArray(EMPTY_LONGS);
- }
-
- @Override
- protected final void onPostExecute(Long[] ids) {
- if (ids != null && !isCancelled()) {
- for (long id : ids) {
- performAction(id);
- }
- }
- onFinished();
- }
-
- /**
- * This method will be called for each account.
- */
- protected abstract void performAction(long accountId);
-
- /**
- * Called when the iteration is finished.
- */
- protected void onFinished() {
- }
- }
-
- public static long[] toPrimitiveLongArray(Collection<Long> collection) {
- final int size = collection.size();
- final long[] ret = new long[size];
- // Collection doesn't have get(i). (Iterable doesn't have size())
- int i = 0;
- for (Long value : collection) {
- ret[i++] = value;
- }
- return ret;
- }
-
- /**
- * Workaround for the {@link ListView#smoothScrollToPosition} randomly scroll the view bug
- * if it's called right after {@link ListView#setAdapter}.
- */
- public static void listViewSmoothScrollToPosition(final Activity activity,
- final ListView listView, final int position) {
- // Workarond: delay-call smoothScrollToPosition()
- new Handler().post(new Runnable() {
- @Override
- public void run() {
- if (activity.isFinishing()) {
- return; // Activity being destroyed
- }
- listView.smoothScrollToPosition(position);
- }
- });
- }
-
- private static final String[] ATTACHMENT_META_NAME_PROJECTION = {
- OpenableColumns.DISPLAY_NAME
- };
- private static final int ATTACHMENT_META_NAME_COLUMN_DISPLAY_NAME = 0;
-
- /**
- * @return Filename of a content of {@code contentUri}. If the provider doesn't provide the
- * filename, returns the last path segment of the URI.
- */
- public static String getContentFileName(Context context, Uri contentUri) {
- String name = getFirstRowString(context, contentUri, ATTACHMENT_META_NAME_PROJECTION, null,
- null, null, ATTACHMENT_META_NAME_COLUMN_DISPLAY_NAME);
- if (name == null) {
- name = contentUri.getLastPathSegment();
- }
- return name;
- }
-
- /**
- * Append a bold span to a {@link SpannableStringBuilder}.
- */
- public static SpannableStringBuilder appendBold(SpannableStringBuilder ssb, String text) {
- if (!TextUtils.isEmpty(text)) {
- SpannableString ss = new SpannableString(text);
- ss.setSpan(new StyleSpan(Typeface.BOLD), 0, ss.length(),
- Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- ssb.append(ss);
- }
-
- return ssb;
- }
-
- /**
- * Stringify a cursor for logging purpose.
- */
- public static String dumpCursor(Cursor c) {
- StringBuilder sb = new StringBuilder();
- sb.append("[");
- while (c != null) {
- sb.append(c.getClass()); // Class name may not be available if toString() is overridden
- sb.append("/");
- sb.append(c.toString());
- if (c.isClosed()) {
- sb.append(" (closed)");
- }
- if (c instanceof CursorWrapper) {
- c = ((CursorWrapper) c).getWrappedCursor();
- sb.append(", ");
- } else {
- break;
- }
- }
- sb.append("]");
- return sb.toString();
- }
-
- /**
- * Cursor wrapper that remembers where it was closed.
- *
- * Use {@link #get} to create a wrapped cursor.
- * USe {@link #getTraceIfAvailable} to get the stack trace.
- * Use {@link #log} to log if/where it was closed.
- */
- public static class CloseTraceCursorWrapper extends CursorWrapper {
- private static final boolean TRACE_ENABLED = false;
-
- private Exception mTrace;
-
- private CloseTraceCursorWrapper(Cursor cursor) {
- super(cursor);
- }
-
- @Override
- public void close() {
- mTrace = new Exception("STACK TRACE");
- super.close();
- }
-
- public static Exception getTraceIfAvailable(Cursor c) {
- if (c instanceof CloseTraceCursorWrapper) {
- return ((CloseTraceCursorWrapper) c).mTrace;
- } else {
- return null;
- }
- }
-
- public static void log(Cursor c) {
- if (c == null) {
- return;
- }
- if (c.isClosed()) {
- Log.w(Logging.LOG_TAG, "Cursor was closed here: Cursor=" + c,
- getTraceIfAvailable(c));
- } else {
- Log.w(Logging.LOG_TAG, "Cursor not closed. Cursor=" + c);
- }
- }
-
- public static Cursor get(Cursor original) {
- return TRACE_ENABLED ? new CloseTraceCursorWrapper(original) : original;
- }
-
- /* package */ static CloseTraceCursorWrapper alwaysCreateForTest(Cursor original) {
- return new CloseTraceCursorWrapper(original);
- }
- }
-
- /**
- * Create an {@link Intent} to launch an activity as the main entry point. Existing activities
- * will all be closed.
- */
- public static Intent createRestartAppIntent(Context context, Class<? extends Activity> clazz) {
- Intent i = new Intent(context, clazz);
- i.setAction(Intent.ACTION_MAIN);
- i.addCategory(Intent.CATEGORY_LAUNCHER);
- i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
- i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- return i;
- }
-
- /**
- * Legacy URI parser. Used in one of three different scenarios:
- * 1. Backup / Restore of account
- * 2. Parsing template from provider.xml
- * 3. Forcefully creating URI for test
- */
- public static void setHostAuthFromString(HostAuth auth, String uriString)
- throws URISyntaxException {
- URI uri = new URI(uriString);
- String path = uri.getPath();
- String domain = null;
- if (path != null && path.length() > 0) {
- domain = path.substring(1);
- }
- auth.mDomain = domain;
- auth.setLogin(uri.getUserInfo());
- auth.setConnection(uri.getScheme(), uri.getHost(), uri.getPort());
- }
-
- /**
- * Test that the given strings are equal in a null-pointer safe fashion.
- */
- public static boolean areStringsEqual(String s1, String s2) {
- return (s1 != null && s1.equals(s2)) || (s1 == null && s2 == null);
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/CopyUtils.java b/emailcommon/src/org/apache/commons/io/CopyUtils.java
deleted file mode 100644
index eab8307e7..000000000
--- a/emailcommon/src/org/apache/commons/io/CopyUtils.java
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Reader;
-import java.io.StringReader;
-import java.io.Writer;
-
-/**
- * This class provides static utility methods for buffered
- * copying between sources (<code>InputStream</code>, <code>Reader</code>,
- * <code>String</code> and <code>byte[]</code>) and destinations
- * (<code>OutputStream</code>, <code>Writer</code>, <code>String</code> and
- * <code>byte[]</code>).
- * <p>
- * Unless otherwise noted, these <code>copy</code> methods do <em>not</em>
- * flush or close the streams. Often doing so would require making non-portable
- * assumptions about the streams' origin and further use. This means that both
- * streams' <code>close()</code> methods must be called after copying. if one
- * omits this step, then the stream resources (sockets, file descriptors) are
- * released when the associated Stream is garbage-collected. It is not a good
- * idea to rely on this mechanism. For a good overview of the distinction
- * between "memory management" and "resource management", see
- * <a href="http://www.unixreview.com/articles/1998/9804/9804ja/ja.htm">this
- * UnixReview article</a>.
- * <p>
- * For byte-to-char methods, a <code>copy</code> variant allows the encoding
- * to be selected (otherwise the platform default is used). We would like to
- * encourage you to always specify the encoding because relying on the platform
- * default can lead to unexpected results.
- * <p
- * We don't provide special variants for the <code>copy</code> methods that
- * let you specify the buffer size because in modern VMs the impact on speed
- * seems to be minimal. We're using a default buffer size of 4 KB.
- * <p>
- * The <code>copy</code> methods use an internal buffer when copying. It is
- * therefore advisable <em>not</em> to deliberately wrap the stream arguments
- * to the <code>copy</code> methods in <code>Buffered*</code> streams. For
- * example, don't do the following:
- * <pre>
- * copy( new BufferedInputStream( in ), new BufferedOutputStream( out ) );
- * </pre>
- * The rationale is as follows:
- * <p>
- * Imagine that an InputStream's read() is a very expensive operation, which
- * would usually suggest wrapping in a BufferedInputStream. The
- * BufferedInputStream works by issuing infrequent
- * {@link java.io.InputStream#read(byte[] b, int off, int len)} requests on the
- * underlying InputStream, to fill an internal buffer, from which further
- * <code>read</code> requests can inexpensively get their data (until the buffer
- * runs out).
- * <p>
- * However, the <code>copy</code> methods do the same thing, keeping an
- * internal buffer, populated by
- * {@link InputStream#read(byte[] b, int off, int len)} requests. Having two
- * buffers (or three if the destination stream is also buffered) is pointless,
- * and the unnecessary buffer management hurts performance slightly (about 3%,
- * according to some simple experiments).
- * <p>
- * Behold, intrepid explorers; a map of this class:
- * <pre>
- * Method Input Output Dependency
- * ------ ----- ------ -------
- * 1 copy InputStream OutputStream (primitive)
- * 2 copy Reader Writer (primitive)
- *
- * 3 copy InputStream Writer 2
- *
- * 4 copy Reader OutputStream 2
- *
- * 5 copy String OutputStream 2
- * 6 copy String Writer (trivial)
- *
- * 7 copy byte[] Writer 3
- * 8 copy byte[] OutputStream (trivial)
- * </pre>
- * <p>
- * Note that only the first two methods shuffle bytes; the rest use these
- * two, or (if possible) copy using native Java copy methods. As there are
- * method variants to specify the encoding, each row may
- * correspond to up to 2 methods.
- * <p>
- * Origin of code: Excalibur.
- *
- * @author Peter Donald
- * @author Jeff Turner
- * @author Matthew Hawthorne
- * @version $Id: CopyUtils.java 437680 2006-08-28 11:57:00Z scolebourne $
- * @deprecated Use IOUtils. Will be removed in 2.0.
- * Methods renamed to IOUtils.write() or IOUtils.copy().
- * Null handling behaviour changed in IOUtils (null data does not
- * throw NullPointerException).
- */
-public class CopyUtils {
-
- /**
- * The default size of the buffer.
- */
- private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
-
- /**
- * Instances should NOT be constructed in standard programming.
- */
- public CopyUtils() { }
-
- // ----------------------------------------------------------------
- // byte[] -> OutputStream
- // ----------------------------------------------------------------
-
- /**
- * Copy bytes from a <code>byte[]</code> to an <code>OutputStream</code>.
- * @param input the byte array to read from
- * @param output the <code>OutputStream</code> to write to
- * @throws IOException In case of an I/O problem
- */
- public static void copy(byte[] input, OutputStream output)
- throws IOException {
- output.write(input);
- }
-
- // ----------------------------------------------------------------
- // byte[] -> Writer
- // ----------------------------------------------------------------
-
- /**
- * Copy and convert bytes from a <code>byte[]</code> to chars on a
- * <code>Writer</code>.
- * The platform's default encoding is used for the byte-to-char conversion.
- * @param input the byte array to read from
- * @param output the <code>Writer</code> to write to
- * @throws IOException In case of an I/O problem
- */
- public static void copy(byte[] input, Writer output)
- throws IOException {
- ByteArrayInputStream in = new ByteArrayInputStream(input);
- copy(in, output);
- }
-
-
- /**
- * Copy and convert bytes from a <code>byte[]</code> to chars on a
- * <code>Writer</code>, using the specified encoding.
- * @param input the byte array to read from
- * @param output the <code>Writer</code> to write to
- * @param encoding The name of a supported character encoding. See the
- * <a href="http://www.iana.org/assignments/character-sets">IANA
- * Charset Registry</a> for a list of valid encoding types.
- * @throws IOException In case of an I/O problem
- */
- public static void copy(
- byte[] input,
- Writer output,
- String encoding)
- throws IOException {
- ByteArrayInputStream in = new ByteArrayInputStream(input);
- copy(in, output, encoding);
- }
-
-
- // ----------------------------------------------------------------
- // Core copy methods
- // ----------------------------------------------------------------
-
- /**
- * Copy bytes from an <code>InputStream</code> to an
- * <code>OutputStream</code>.
- * @param input the <code>InputStream</code> to read from
- * @param output the <code>OutputStream</code> to write to
- * @return the number of bytes copied
- * @throws IOException In case of an I/O problem
- */
- public static int copy(
- InputStream input,
- OutputStream output)
- throws IOException {
- byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
- int count = 0;
- int n = 0;
- while (-1 != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- count += n;
- }
- return count;
- }
-
- // ----------------------------------------------------------------
- // Reader -> Writer
- // ----------------------------------------------------------------
-
- /**
- * Copy chars from a <code>Reader</code> to a <code>Writer</code>.
- * @param input the <code>Reader</code> to read from
- * @param output the <code>Writer</code> to write to
- * @return the number of characters copied
- * @throws IOException In case of an I/O problem
- */
- public static int copy(
- Reader input,
- Writer output)
- throws IOException {
- char[] buffer = new char[DEFAULT_BUFFER_SIZE];
- int count = 0;
- int n = 0;
- while (-1 != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- count += n;
- }
- return count;
- }
-
- // ----------------------------------------------------------------
- // InputStream -> Writer
- // ----------------------------------------------------------------
-
- /**
- * Copy and convert bytes from an <code>InputStream</code> to chars on a
- * <code>Writer</code>.
- * The platform's default encoding is used for the byte-to-char conversion.
- * @param input the <code>InputStream</code> to read from
- * @param output the <code>Writer</code> to write to
- * @throws IOException In case of an I/O problem
- */
- public static void copy(
- InputStream input,
- Writer output)
- throws IOException {
- InputStreamReader in = new InputStreamReader(input);
- copy(in, output);
- }
-
- /**
- * Copy and convert bytes from an <code>InputStream</code> to chars on a
- * <code>Writer</code>, using the specified encoding.
- * @param input the <code>InputStream</code> to read from
- * @param output the <code>Writer</code> to write to
- * @param encoding The name of a supported character encoding. See the
- * <a href="http://www.iana.org/assignments/character-sets">IANA
- * Charset Registry</a> for a list of valid encoding types.
- * @throws IOException In case of an I/O problem
- */
- public static void copy(
- InputStream input,
- Writer output,
- String encoding)
- throws IOException {
- InputStreamReader in = new InputStreamReader(input, encoding);
- copy(in, output);
- }
-
-
- // ----------------------------------------------------------------
- // Reader -> OutputStream
- // ----------------------------------------------------------------
-
- /**
- * Serialize chars from a <code>Reader</code> to bytes on an
- * <code>OutputStream</code>, and flush the <code>OutputStream</code>.
- * @param input the <code>Reader</code> to read from
- * @param output the <code>OutputStream</code> to write to
- * @throws IOException In case of an I/O problem
- */
- public static void copy(
- Reader input,
- OutputStream output)
- throws IOException {
- OutputStreamWriter out = new OutputStreamWriter(output);
- copy(input, out);
- // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
- // have to flush here.
- out.flush();
- }
-
- // ----------------------------------------------------------------
- // String -> OutputStream
- // ----------------------------------------------------------------
-
- /**
- * Serialize chars from a <code>String</code> to bytes on an
- * <code>OutputStream</code>, and
- * flush the <code>OutputStream</code>.
- * @param input the <code>String</code> to read from
- * @param output the <code>OutputStream</code> to write to
- * @throws IOException In case of an I/O problem
- */
- public static void copy(
- String input,
- OutputStream output)
- throws IOException {
- StringReader in = new StringReader(input);
- OutputStreamWriter out = new OutputStreamWriter(output);
- copy(in, out);
- // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
- // have to flush here.
- out.flush();
- }
-
- // ----------------------------------------------------------------
- // String -> Writer
- // ----------------------------------------------------------------
-
- /**
- * Copy chars from a <code>String</code> to a <code>Writer</code>.
- * @param input the <code>String</code> to read from
- * @param output the <code>Writer</code> to write to
- * @throws IOException In case of an I/O problem
- */
- public static void copy(String input, Writer output)
- throws IOException {
- output.write(input);
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/DirectoryWalker.java b/emailcommon/src/org/apache/commons/io/DirectoryWalker.java
deleted file mode 100644
index 9e564ae86..000000000
--- a/emailcommon/src/org/apache/commons/io/DirectoryWalker.java
+++ /dev/null
@@ -1,620 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.IOException;
-import java.util.Collection;
-
-import org.apache.commons.io.filefilter.FileFilterUtils;
-import org.apache.commons.io.filefilter.IOFileFilter;
-import org.apache.commons.io.filefilter.TrueFileFilter;
-
-/**
- * Abstract class that walks through a directory hierarchy and provides
- * subclasses with convenient hooks to add specific behaviour.
- * <p>
- * This class operates with a {@link FileFilter} and maximum depth to
- * limit the files and direcories visited.
- * Commons IO supplies many common filter implementations in the
- * <a href="filefilter/package-summary.html"> filefilter</a> package.
- * <p>
- * The following sections describe:
- * <ul>
- * <li><a href="#example">1. Example Implementation</a> - example
- * <code>FileCleaner</code> implementation.</li>
- * <li><a href="#filter">2. Filter Example</a> - using
- * {@link FileFilter}(s) with <code>DirectoryWalker</code>.</li>
- * <li><a href="#cancel">3. Cancellation</a> - how to implement cancellation
- * behaviour.</li>
- * </ul>
- *
- * <a name="example"></a>
- * <h3>1. Example Implementation</h3>
- *
- * There are many possible extensions, for example, to delete all
- * files and '.svn' directories, and return a list of deleted files:
- * <pre>
- * public class FileCleaner extends DirectoryWalker {
- *
- * public FileCleaner() {
- * super();
- * }
- *
- * public List clean(File startDirectory) {
- * List results = new ArrayList();
- * walk(startDirectory, results);
- * return results;
- * }
- *
- * protected boolean handleDirectory(File directory, int depth, Collection results) {
- * // delete svn directories and then skip
- * if (".svn".equals(directory.getName())) {
- * directory.delete();
- * return false;
- * } else {
- * return true;
- * }
- *
- * }
- *
- * protected void handleFile(File file, int depth, Collection results) {
- * // delete file and add to list of deleted
- * file.delete();
- * results.add(file);
- * }
- * }
- * </pre>
- *
- * <a name="filter"></a>
- * <h3>2. Filter Example</h3>
- *
- * Choosing which directories and files to process can be a key aspect
- * of using this class. This information can be setup in three ways,
- * via three different constructors.
- * <p>
- * The first option is to visit all directories and files.
- * This is achieved via the no-args constructor.
- * <p>
- * The second constructor option is to supply a single {@link FileFilter}
- * that describes the files and directories to visit. Care must be taken
- * with this option as the same filter is used for both directories
- * and files.
- * <p>
- * For example, if you wanted all directories which are not hidden
- * and files which end in ".txt":
- * <pre>
- * public class FooDirectoryWalker extends DirectoryWalker {
- * public FooDirectoryWalker(FileFilter filter) {
- * super(filter, -1);
- * }
- * }
- *
- * // Build up the filters and create the walker
- * // Create a filter for Non-hidden directories
- * IOFileFilter fooDirFilter =
- * FileFilterUtils.andFileFilter(FileFilterUtils.directoryFileFilter,
- * HiddenFileFilter.VISIBLE);
- *
- * // Create a filter for Files ending in ".txt"
- * IOFileFilter fooFileFilter =
- * FileFilterUtils.andFileFilter(FileFilterUtils.fileFileFilter,
- * FileFilterUtils.suffixFileFilter(".txt"));
- *
- * // Combine the directory and file filters using an OR condition
- * java.io.FileFilter fooFilter =
- * FileFilterUtils.orFileFilter(fooDirFilter, fooFileFilter);
- *
- * // Use the filter to construct a DirectoryWalker implementation
- * FooDirectoryWalker walker = new FooDirectoryWalker(fooFilter);
- * </pre>
- * <p>
- * The third constructor option is to specify separate filters, one for
- * directories and one for files. These are combined internally to form
- * the correct <code>FileFilter</code>, something which is very easy to
- * get wrong when attempted manually, particularly when trying to
- * express constructs like 'any file in directories named docs'.
- * <p>
- * For example, if you wanted all directories which are not hidden
- * and files which end in ".txt":
- * <pre>
- * public class FooDirectoryWalker extends DirectoryWalker {
- * public FooDirectoryWalker(IOFileFilter dirFilter, IOFileFilter fileFilter) {
- * super(dirFilter, fileFilter, -1);
- * }
- * }
- *
- * // Use the filters to construct the walker
- * FooDirectoryWalker walker = new FooDirectoryWalker(
- * HiddenFileFilter.VISIBLE,
- * FileFilterUtils.suffixFileFilter(".txt"),
- * );
- * </pre>
- * This is much simpler than the previous example, and is why it is the preferred
- * option for filtering.
- *
- * <a name="cancel"></a>
- * <h3>3. Cancellation</h3>
- *
- * The DirectoryWalker contains some of the logic required for cancel processing.
- * Subclasses must complete the implementation.
- * <p>
- * What <code>DirectoryWalker</code> does provide for cancellation is:
- * <ul>
- * <li>{@link CancelException} which can be thrown in any of the
- * <i>lifecycle</i> methods to stop processing.</li>
- * <li>The <code>walk()</code> method traps thrown {@link CancelException}
- * and calls the <code>handleCancelled()</code> method, providing
- * a place for custom cancel processing.</li>
- * </ul>
- * <p>
- * Implementations need to provide:
- * <ul>
- * <li>The decision logic on whether to cancel processing or not.</li>
- * <li>Constructing and throwing a {@link CancelException}.</li>
- * <li>Custom cancel processing in the <code>handleCancelled()</code> method.
- * </ul>
- * <p>
- * Two possible scenarios are envisaged for cancellation:
- * <ul>
- * <li><a href="#external">3.1 External / Mult-threaded</a> - cancellation being
- * decided/initiated by an external process.</li>
- * <li><a href="#internal">3.2 Internal</a> - cancellation being decided/initiated
- * from within a DirectoryWalker implementation.</li>
- * </ul>
- * <p>
- * The following sections provide example implementations for these two different
- * scenarios.
- *
- * <a name="external"></a>
- * <h4>3.1 External / Multi-threaded</h4>
- *
- * This example provides a public <code>cancel()</code> method that can be
- * called by another thread to stop the processing. A typical example use-case
- * would be a cancel button on a GUI. Calling this method sets a
- * <a href="http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html#36930">
- * volatile</a> flag to ensure it will work properly in a multi-threaded environment.
- * The flag is returned by the <code>handleIsCancelled()</code> method, which
- * will cause the walk to stop immediately. The <code>handleCancelled()</code>
- * method will be the next, and last, callback method received once cancellation
- * has occurred.
- *
- * <pre>
- * public class FooDirectoryWalker extends DirectoryWalker {
- *
- * private volatile boolean cancelled = false;
- *
- * public void cancel() {
- * cancelled = true;
- * }
- *
- * private void handleIsCancelled(File file, int depth, Collection results) {
- * return cancelled;
- * }
- *
- * protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) {
- * // implement processing required when a cancellation occurs
- * }
- * }
- * </pre>
- *
- * <a name="internal"></a>
- * <h4>3.2 Internal</h4>
- *
- * This shows an example of how internal cancellation processing could be implemented.
- * <b>Note</b> the decision logic and throwing a {@link CancelException} could be implemented
- * in any of the <i>lifecycle</i> methods.
- *
- * <pre>
- * public class BarDirectoryWalker extends DirectoryWalker {
- *
- * protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException {
- * // cancel if hidden directory
- * if (directory.isHidden()) {
- * throw new CancelException(file, depth);
- * }
- * return true;
- * }
- *
- * protected void handleFile(File file, int depth, Collection results) throws IOException {
- * // cancel if read-only file
- * if (!file.canWrite()) {
- * throw new CancelException(file, depth);
- * }
- * results.add(file);
- * }
- *
- * protected void handleCancelled(File startDirectory, Collection results, CancelException cancel) {
- * // implement processing required when a cancellation occurs
- * }
- * }
- * </pre>
- *
- * @since Commons IO 1.3
- * @version $Revision: 424748 $
- */
-public abstract class DirectoryWalker {
-
- /**
- * The file filter to use to filter files and directories.
- */
- private final FileFilter filter;
- /**
- * The limit on the directory depth to walk.
- */
- private final int depthLimit;
-
- /**
- * Construct an instance with no filtering and unlimited <i>depth</i>.
- */
- protected DirectoryWalker() {
- this(null, -1);
- }
-
- /**
- * Construct an instance with a filter and limit the <i>depth</i> navigated to.
- * <p>
- * The filter controls which files and directories will be navigated to as
- * part of the walk. The {@link FileFilterUtils} class is useful for combining
- * various filters together. A <code>null</code> filter means that no
- * filtering should occur and all files and directories will be visited.
- *
- * @param filter the filter to apply, null means visit all files
- * @param depthLimit controls how <i>deep</i> the hierarchy is
- * navigated to (less than 0 means unlimited)
- */
- protected DirectoryWalker(FileFilter filter, int depthLimit) {
- this.filter = filter;
- this.depthLimit = depthLimit;
- }
-
- /**
- * Construct an instance with a directory and a file filter and an optional
- * limit on the <i>depth</i> navigated to.
- * <p>
- * The filters control which files and directories will be navigated to as part
- * of the walk. This constructor uses {@link FileFilterUtils#makeDirectoryOnly(IOFileFilter)}
- * and {@link FileFilterUtils#makeFileOnly(IOFileFilter)} internally to combine the filters.
- * A <code>null</code> filter means that no filtering should occur.
- *
- * @param directoryFilter the filter to apply to directories, null means visit all directories
- * @param fileFilter the filter to apply to files, null means visit all files
- * @param depthLimit controls how <i>deep</i> the hierarchy is
- * navigated to (less than 0 means unlimited)
- */
- protected DirectoryWalker(IOFileFilter directoryFilter, IOFileFilter fileFilter, int depthLimit) {
- if (directoryFilter == null && fileFilter == null) {
- this.filter = null;
- } else {
- directoryFilter = (directoryFilter != null ? directoryFilter : TrueFileFilter.TRUE);
- fileFilter = (fileFilter != null ? fileFilter : TrueFileFilter.TRUE);
- directoryFilter = FileFilterUtils.makeDirectoryOnly(directoryFilter);
- fileFilter = FileFilterUtils.makeFileOnly(fileFilter);
- this.filter = FileFilterUtils.orFileFilter(directoryFilter, fileFilter);
- }
- this.depthLimit = depthLimit;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Internal method that walks the directory hierarchy in a depth-first manner.
- * <p>
- * Users of this class do not need to call this method. This method will
- * be called automatically by another (public) method on the specific subclass.
- * <p>
- * Writers of subclasses should call this method to start the directory walk.
- * Once called, this method will emit events as it walks the hierarchy.
- * The event methods have the prefix <code>handle</code>.
- *
- * @param startDirectory the directory to start from, not null
- * @param results the collection of result objects, may be updated
- * @throws NullPointerException if the start directory is null
- * @throws IOException if an I/O Error occurs
- */
- protected final void walk(File startDirectory, Collection results) throws IOException {
- if (startDirectory == null) {
- throw new NullPointerException("Start Directory is null");
- }
- try {
- handleStart(startDirectory, results);
- walk(startDirectory, 0, results);
- handleEnd(results);
- } catch(CancelException cancel) {
- handleCancelled(startDirectory, results, cancel);
- }
- }
-
- /**
- * Main recursive method to examine the directory hierarchy.
- *
- * @param directory the directory to examine, not null
- * @param depth the directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- private void walk(File directory, int depth, Collection results) throws IOException {
- checkIfCancelled(directory, depth, results);
- if (handleDirectory(directory, depth, results)) {
- handleDirectoryStart(directory, depth, results);
- int childDepth = depth + 1;
- if (depthLimit < 0 || childDepth <= depthLimit) {
- checkIfCancelled(directory, depth, results);
- File[] childFiles = (filter == null ? directory.listFiles() : directory.listFiles(filter));
- if (childFiles == null) {
- handleRestricted(directory, childDepth, results);
- } else {
- for (int i = 0; i < childFiles.length; i++) {
- File childFile = childFiles[i];
- if (childFile.isDirectory()) {
- walk(childFile, childDepth, results);
- } else {
- checkIfCancelled(childFile, childDepth, results);
- handleFile(childFile, childDepth, results);
- checkIfCancelled(childFile, childDepth, results);
- }
- }
- }
- }
- handleDirectoryEnd(directory, depth, results);
- }
- checkIfCancelled(directory, depth, results);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks whether the walk has been cancelled by calling {@link #handleIsCancelled},
- * throwing a <code>CancelException</code> if it has.
- * <p>
- * Writers of subclasses should not normally call this method as it is called
- * automatically by the walk of the tree. However, sometimes a single method,
- * typically {@link #handleFile}, may take a long time to run. In that case,
- * you may wish to check for cancellation by calling this method.
- *
- * @param file the current file being processed
- * @param depth the current file level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- protected final void checkIfCancelled(File file, int depth, Collection results) throws IOException {
- if (handleIsCancelled(file, depth, results)) {
- throw new CancelException(file, depth);
- }
- }
-
- /**
- * Overridable callback method invoked to determine if the entire walk
- * operation should be immediately cancelled.
- * <p>
- * This method should be implemented by those subclasses that want to
- * provide a public <code>cancel()</code> method available from another
- * thread. The design pattern for the subclass should be as follows:
- * <pre>
- * public class FooDirectoryWalker extends DirectoryWalker {
- * private volatile boolean cancelled = false;
- *
- * public void cancel() {
- * cancelled = true;
- * }
- * private void handleIsCancelled(File file, int depth, Collection results) {
- * return cancelled;
- * }
- * protected void handleCancelled(File startDirectory,
- * Collection results, CancelException cancel) {
- * // implement processing required when a cancellation occurs
- * }
- * }
- * </pre>
- * <p>
- * If this method returns true, then the directory walk is immediately
- * cancelled. The next callback method will be {@link #handleCancelled}.
- * <p>
- * This implementation returns false.
- *
- * @param file the file or directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @return true if the walk has been cancelled
- * @throws IOException if an I/O Error occurs
- */
- protected boolean handleIsCancelled(
- File file, int depth, Collection results) throws IOException {
- // do nothing - overridable by subclass
- return false; // not cancelled
- }
-
- /**
- * Overridable callback method invoked when the operation is cancelled.
- * The file being processed when the cancellation occurred can be
- * obtained from the exception.
- * <p>
- * This implementation just re-throws the {@link CancelException}.
- *
- * @param startDirectory the directory that the walk started from
- * @param results the collection of result objects, may be updated
- * @param cancel the exception throw to cancel further processing
- * containing details at the point of cancellation.
- * @throws IOException if an I/O Error occurs
- */
- protected void handleCancelled(File startDirectory, Collection results,
- CancelException cancel) throws IOException {
- // re-throw exception - overridable by subclass
- throw cancel;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Overridable callback method invoked at the start of processing.
- * <p>
- * This implementation does nothing.
- *
- * @param startDirectory the directory to start from
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- protected void handleStart(File startDirectory, Collection results) throws IOException {
- // do nothing - overridable by subclass
- }
-
- /**
- * Overridable callback method invoked to determine if a directory should be processed.
- * <p>
- * This method returns a boolean to indicate if the directory should be examined or not.
- * If you return false, the entire directory and any subdirectories will be skipped.
- * Note that this functionality is in addition to the filtering by file filter.
- * <p>
- * This implementation does nothing and returns true.
- *
- * @param directory the current directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @return true to process this directory, false to skip this directory
- * @throws IOException if an I/O Error occurs
- */
- protected boolean handleDirectory(File directory, int depth, Collection results) throws IOException {
- // do nothing - overridable by subclass
- return true; // process directory
- }
-
- /**
- * Overridable callback method invoked at the start of processing each directory.
- * <p>
- * This implementation does nothing.
- *
- * @param directory the current directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- protected void handleDirectoryStart(File directory, int depth, Collection results) throws IOException {
- // do nothing - overridable by subclass
- }
-
- /**
- * Overridable callback method invoked for each (non-directory) file.
- * <p>
- * This implementation does nothing.
- *
- * @param file the current file being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- protected void handleFile(File file, int depth, Collection results) throws IOException {
- // do nothing - overridable by subclass
- }
-
- /**
- * Overridable callback method invoked for each restricted directory.
- * <p>
- * This implementation does nothing.
- *
- * @param directory the restricted directory
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- protected void handleRestricted(File directory, int depth, Collection results) throws IOException {
- // do nothing - overridable by subclass
- }
-
- /**
- * Overridable callback method invoked at the end of processing each directory.
- * <p>
- * This implementation does nothing.
- *
- * @param directory the directory being processed
- * @param depth the current directory level (starting directory = 0)
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- protected void handleDirectoryEnd(File directory, int depth, Collection results) throws IOException {
- // do nothing - overridable by subclass
- }
-
- /**
- * Overridable callback method invoked at the end of processing.
- * <p>
- * This implementation does nothing.
- *
- * @param results the collection of result objects, may be updated
- * @throws IOException if an I/O Error occurs
- */
- protected void handleEnd(Collection results) throws IOException {
- // do nothing - overridable by subclass
- }
-
- //-----------------------------------------------------------------------
- /**
- * CancelException is thrown in DirectoryWalker to cancel the current
- * processing.
- */
- public static class CancelException extends IOException {
-
- /** Serialization id. */
- private static final long serialVersionUID = 1347339620135041008L;
-
- /** The file being processed when the exception was thrown. */
- private File file;
- /** The file depth when the exception was thrown. */
- private int depth = -1;
-
- /**
- * Constructs a <code>CancelException</code> with
- * the file and depth when cancellation occurred.
- *
- * @param file the file when the operation was cancelled, may be null
- * @param depth the depth when the operation was cancelled, may be null
- */
- public CancelException(File file, int depth) {
- this("Operation Cancelled", file, depth);
- }
-
- /**
- * Constructs a <code>CancelException</code> with
- * an appropriate message and the file and depth when
- * cancellation occurred.
- *
- * @param message the detail message
- * @param file the file when the operation was cancelled
- * @param depth the depth when the operation was cancelled
- */
- public CancelException(String message, File file, int depth) {
- super(message);
- this.file = file;
- this.depth = depth;
- }
-
- /**
- * Return the file when the operation was cancelled.
- *
- * @return the file when the operation was cancelled
- */
- public File getFile() {
- return file;
- }
-
- /**
- * Return the depth when the operation was cancelled.
- *
- * @return the depth when the operation was cancelled
- */
- public int getDepth() {
- return depth;
- }
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/EndianUtils.java b/emailcommon/src/org/apache/commons/io/EndianUtils.java
deleted file mode 100644
index 810feac04..000000000
--- a/emailcommon/src/org/apache/commons/io/EndianUtils.java
+++ /dev/null
@@ -1,489 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * Utility code for dealing with different endian systems.
- * <p>
- * Different computer architectures adopt different conventions for
- * byte ordering. In so-called "Little Endian" architectures (eg Intel),
- * the low-order byte is stored in memory at the lowest address, and
- * subsequent bytes at higher addresses. For "Big Endian" architectures
- * (eg Motorola), the situation is reversed.
- * This class helps you solve this incompatability.
- * <p>
- * Origin of code: Excalibur
- *
- * @author <a href="mailto:peter@apache.org">Peter Donald</a>
- * @version $Id: EndianUtils.java 539632 2007-05-18 23:37:59Z bayard $
- * @see org.apache.commons.io.input.SwappedDataInputStream
- */
-public class EndianUtils {
-
- /**
- * Instances should NOT be constructed in standard programming.
- */
- public EndianUtils() {
- super();
- }
-
- // ========================================== Swapping routines
-
- /**
- * Converts a "short" value between endian systems.
- * @param value value to convert
- * @return the converted value
- */
- public static short swapShort(short value) {
- return (short) ( ( ( ( value >> 0 ) & 0xff ) << 8 ) +
- ( ( ( value >> 8 ) & 0xff ) << 0 ) );
- }
-
- /**
- * Converts a "int" value between endian systems.
- * @param value value to convert
- * @return the converted value
- */
- public static int swapInteger(int value) {
- return
- ( ( ( value >> 0 ) & 0xff ) << 24 ) +
- ( ( ( value >> 8 ) & 0xff ) << 16 ) +
- ( ( ( value >> 16 ) & 0xff ) << 8 ) +
- ( ( ( value >> 24 ) & 0xff ) << 0 );
- }
-
- /**
- * Converts a "long" value between endian systems.
- * @param value value to convert
- * @return the converted value
- */
- public static long swapLong(long value) {
- return
- ( ( ( value >> 0 ) & 0xff ) << 56 ) +
- ( ( ( value >> 8 ) & 0xff ) << 48 ) +
- ( ( ( value >> 16 ) & 0xff ) << 40 ) +
- ( ( ( value >> 24 ) & 0xff ) << 32 ) +
- ( ( ( value >> 32 ) & 0xff ) << 24 ) +
- ( ( ( value >> 40 ) & 0xff ) << 16 ) +
- ( ( ( value >> 48 ) & 0xff ) << 8 ) +
- ( ( ( value >> 56 ) & 0xff ) << 0 );
- }
-
- /**
- * Converts a "float" value between endian systems.
- * @param value value to convert
- * @return the converted value
- */
- public static float swapFloat(float value) {
- return Float.intBitsToFloat( swapInteger( Float.floatToIntBits( value ) ) );
- }
-
- /**
- * Converts a "double" value between endian systems.
- * @param value value to convert
- * @return the converted value
- */
- public static double swapDouble(double value) {
- return Double.longBitsToDouble( swapLong( Double.doubleToLongBits( value ) ) );
- }
-
- // ========================================== Swapping read/write routines
-
- /**
- * Writes a "short" value to a byte array at a given offset. The value is
- * converted to the opposed endian system while writing.
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- */
- public static void writeSwappedShort(byte[] data, int offset, short value) {
- data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff );
- data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff );
- }
-
- /**
- * Reads a "short" value from a byte array at a given offset. The value is
- * converted to the opposed endian system while reading.
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- */
- public static short readSwappedShort(byte[] data, int offset) {
- return (short)( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
- ( ( data[ offset + 1 ] & 0xff ) << 8 ) );
- }
-
- /**
- * Reads an unsigned short (16-bit) value from a byte array at a given
- * offset. The value is converted to the opposed endian system while
- * reading.
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- */
- public static int readSwappedUnsignedShort(byte[] data, int offset) {
- return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
- ( ( data[ offset + 1 ] & 0xff ) << 8 ) );
- }
-
- /**
- * Writes a "int" value to a byte array at a given offset. The value is
- * converted to the opposed endian system while writing.
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- */
- public static void writeSwappedInteger(byte[] data, int offset, int value) {
- data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff );
- data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff );
- data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff );
- data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff );
- }
-
- /**
- * Reads a "int" value from a byte array at a given offset. The value is
- * converted to the opposed endian system while reading.
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- */
- public static int readSwappedInteger(byte[] data, int offset) {
- return ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
- ( ( data[ offset + 1 ] & 0xff ) << 8 ) +
- ( ( data[ offset + 2 ] & 0xff ) << 16 ) +
- ( ( data[ offset + 3 ] & 0xff ) << 24 ) );
- }
-
- /**
- * Reads an unsigned integer (32-bit) value from a byte array at a given
- * offset. The value is converted to the opposed endian system while
- * reading.
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- */
- public static long readSwappedUnsignedInteger(byte[] data, int offset) {
- long low = ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
- ( ( data[ offset + 1 ] & 0xff ) << 8 ) +
- ( ( data[ offset + 2 ] & 0xff ) << 16 ) );
-
- long high = data[ offset + 3 ] & 0xff;
-
- return (high << 24) + (0xffffffffL & low);
- }
-
- /**
- * Writes a "long" value to a byte array at a given offset. The value is
- * converted to the opposed endian system while writing.
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- */
- public static void writeSwappedLong(byte[] data, int offset, long value) {
- data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff );
- data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff );
- data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff );
- data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff );
- data[ offset + 4 ] = (byte)( ( value >> 32 ) & 0xff );
- data[ offset + 5 ] = (byte)( ( value >> 40 ) & 0xff );
- data[ offset + 6 ] = (byte)( ( value >> 48 ) & 0xff );
- data[ offset + 7 ] = (byte)( ( value >> 56 ) & 0xff );
- }
-
- /**
- * Reads a "long" value from a byte array at a given offset. The value is
- * converted to the opposed endian system while reading.
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- */
- public static long readSwappedLong(byte[] data, int offset) {
- long low =
- ( ( data[ offset + 0 ] & 0xff ) << 0 ) +
- ( ( data[ offset + 1 ] & 0xff ) << 8 ) +
- ( ( data[ offset + 2 ] & 0xff ) << 16 ) +
- ( ( data[ offset + 3 ] & 0xff ) << 24 );
- long high =
- ( ( data[ offset + 4 ] & 0xff ) << 0 ) +
- ( ( data[ offset + 5 ] & 0xff ) << 8 ) +
- ( ( data[ offset + 6 ] & 0xff ) << 16 ) +
- ( ( data[ offset + 7 ] & 0xff ) << 24 );
- return (high << 32) + (0xffffffffL & low);
- }
-
- /**
- * Writes a "float" value to a byte array at a given offset. The value is
- * converted to the opposed endian system while writing.
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- */
- public static void writeSwappedFloat(byte[] data, int offset, float value) {
- writeSwappedInteger( data, offset, Float.floatToIntBits( value ) );
- }
-
- /**
- * Reads a "float" value from a byte array at a given offset. The value is
- * converted to the opposed endian system while reading.
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- */
- public static float readSwappedFloat(byte[] data, int offset) {
- return Float.intBitsToFloat( readSwappedInteger( data, offset ) );
- }
-
- /**
- * Writes a "double" value to a byte array at a given offset. The value is
- * converted to the opposed endian system while writing.
- * @param data target byte array
- * @param offset starting offset in the byte array
- * @param value value to write
- */
- public static void writeSwappedDouble(byte[] data, int offset, double value) {
- writeSwappedLong( data, offset, Double.doubleToLongBits( value ) );
- }
-
- /**
- * Reads a "double" value from a byte array at a given offset. The value is
- * converted to the opposed endian system while reading.
- * @param data source byte array
- * @param offset starting offset in the byte array
- * @return the value read
- */
- public static double readSwappedDouble(byte[] data, int offset) {
- return Double.longBitsToDouble( readSwappedLong( data, offset ) );
- }
-
- /**
- * Writes a "short" value to an OutputStream. The value is
- * converted to the opposed endian system while writing.
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
- */
- public static void writeSwappedShort(OutputStream output, short value)
- throws IOException
- {
- output.write( (byte)( ( value >> 0 ) & 0xff ) );
- output.write( (byte)( ( value >> 8 ) & 0xff ) );
- }
-
- /**
- * Reads a "short" value from an InputStream. The value is
- * converted to the opposed endian system while reading.
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
- */
- public static short readSwappedShort(InputStream input)
- throws IOException
- {
- return (short)( ( ( read( input ) & 0xff ) << 0 ) +
- ( ( read( input ) & 0xff ) << 8 ) );
- }
-
- /**
- * Reads a unsigned short (16-bit) from an InputStream. The value is
- * converted to the opposed endian system while reading.
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
- */
- public static int readSwappedUnsignedShort(InputStream input)
- throws IOException
- {
- int value1 = read( input );
- int value2 = read( input );
-
- return ( ( ( value1 & 0xff ) << 0 ) +
- ( ( value2 & 0xff ) << 8 ) );
- }
-
- /**
- * Writes a "int" value to an OutputStream. The value is
- * converted to the opposed endian system while writing.
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
- */
- public static void writeSwappedInteger(OutputStream output, int value)
- throws IOException
- {
- output.write( (byte)( ( value >> 0 ) & 0xff ) );
- output.write( (byte)( ( value >> 8 ) & 0xff ) );
- output.write( (byte)( ( value >> 16 ) & 0xff ) );
- output.write( (byte)( ( value >> 24 ) & 0xff ) );
- }
-
- /**
- * Reads a "int" value from an InputStream. The value is
- * converted to the opposed endian system while reading.
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
- */
- public static int readSwappedInteger(InputStream input)
- throws IOException
- {
- int value1 = read( input );
- int value2 = read( input );
- int value3 = read( input );
- int value4 = read( input );
-
- return ( ( value1 & 0xff ) << 0 ) +
- ( ( value2 & 0xff ) << 8 ) +
- ( ( value3 & 0xff ) << 16 ) +
- ( ( value4 & 0xff ) << 24 );
- }
-
- /**
- * Reads a unsigned integer (32-bit) from an InputStream. The value is
- * converted to the opposed endian system while reading.
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
- */
- public static long readSwappedUnsignedInteger(InputStream input)
- throws IOException
- {
- int value1 = read( input );
- int value2 = read( input );
- int value3 = read( input );
- int value4 = read( input );
-
- long low = ( ( ( value1 & 0xff ) << 0 ) +
- ( ( value2 & 0xff ) << 8 ) +
- ( ( value3 & 0xff ) << 16 ) );
-
- long high = value4 & 0xff;
-
- return (high << 24) + (0xffffffffL & low);
- }
-
- /**
- * Writes a "long" value to an OutputStream. The value is
- * converted to the opposed endian system while writing.
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
- */
- public static void writeSwappedLong(OutputStream output, long value)
- throws IOException
- {
- output.write( (byte)( ( value >> 0 ) & 0xff ) );
- output.write( (byte)( ( value >> 8 ) & 0xff ) );
- output.write( (byte)( ( value >> 16 ) & 0xff ) );
- output.write( (byte)( ( value >> 24 ) & 0xff ) );
- output.write( (byte)( ( value >> 32 ) & 0xff ) );
- output.write( (byte)( ( value >> 40 ) & 0xff ) );
- output.write( (byte)( ( value >> 48 ) & 0xff ) );
- output.write( (byte)( ( value >> 56 ) & 0xff ) );
- }
-
- /**
- * Reads a "long" value from an InputStream. The value is
- * converted to the opposed endian system while reading.
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
- */
- public static long readSwappedLong(InputStream input)
- throws IOException
- {
- byte[] bytes = new byte[8];
- for ( int i=0; i<8; i++ ) {
- bytes[i] = (byte) read( input );
- }
- return readSwappedLong( bytes, 0 );
- }
-
- /**
- * Writes a "float" value to an OutputStream. The value is
- * converted to the opposed endian system while writing.
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
- */
- public static void writeSwappedFloat(OutputStream output, float value)
- throws IOException
- {
- writeSwappedInteger( output, Float.floatToIntBits( value ) );
- }
-
- /**
- * Reads a "float" value from an InputStream. The value is
- * converted to the opposed endian system while reading.
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
- */
- public static float readSwappedFloat(InputStream input)
- throws IOException
- {
- return Float.intBitsToFloat( readSwappedInteger( input ) );
- }
-
- /**
- * Writes a "double" value to an OutputStream. The value is
- * converted to the opposed endian system while writing.
- * @param output target OutputStream
- * @param value value to write
- * @throws IOException in case of an I/O problem
- */
- public static void writeSwappedDouble(OutputStream output, double value)
- throws IOException
- {
- writeSwappedLong( output, Double.doubleToLongBits( value ) );
- }
-
- /**
- * Reads a "double" value from an InputStream. The value is
- * converted to the opposed endian system while reading.
- * @param input source InputStream
- * @return the value just read
- * @throws IOException in case of an I/O problem
- */
- public static double readSwappedDouble(InputStream input)
- throws IOException
- {
- return Double.longBitsToDouble( readSwappedLong( input ) );
- }
-
- /**
- * Reads the next byte from the input stream.
- * @param input the stream
- * @return the byte
- * @throws IOException if the end of file is reached
- */
- private static int read(InputStream input)
- throws IOException
- {
- int value = input.read();
-
- if( -1 == value ) {
- throw new EOFException( "Unexpected EOF reached" );
- }
-
- return value;
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/FileCleaner.java b/emailcommon/src/org/apache/commons/io/FileCleaner.java
deleted file mode 100644
index 59c2f4109..000000000
--- a/emailcommon/src/org/apache/commons/io/FileCleaner.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.File;
-
-/**
- * Keeps track of files awaiting deletion, and deletes them when an associated
- * marker object is reclaimed by the garbage collector.
- * <p>
- * This utility creates a background thread to handle file deletion.
- * Each file to be deleted is registered with a handler object.
- * When the handler object is garbage collected, the file is deleted.
- * <p>
- * In an environment with multiple class loaders (a servlet container, for
- * example), you should consider stopping the background thread if it is no
- * longer needed. This is done by invoking the method
- * {@link #exitWhenFinished}, typically in
- * {@link javax.servlet.ServletContextListener#contextDestroyed} or similar.
- *
- * @author Noel Bergman
- * @author Martin Cooper
- * @version $Id: FileCleaner.java 553012 2007-07-03 23:01:07Z ggregory $
- * @deprecated Use {@link FileCleaningTracker}
- */
-public class FileCleaner {
- /**
- * The instance to use for the deprecated, static methods.
- */
- static final FileCleaningTracker theInstance = new FileCleaningTracker();
-
- //-----------------------------------------------------------------------
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
- *
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the file is null
- * @deprecated Use {@link FileCleaningTracker#track(File, Object)}.
- */
- public static void track(File file, Object marker) {
- theInstance.track(file, marker);
- }
-
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The speified deletion strategy is used.
- *
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the file is null
- * @deprecated Use {@link FileCleaningTracker#track(File, Object, FileDeleteStrategy)}.
- */
- public static void track(File file, Object marker, FileDeleteStrategy deleteStrategy) {
- theInstance.track(file, marker, deleteStrategy);
- }
-
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
- *
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the path is null
- * @deprecated Use {@link FileCleaningTracker#track(String, Object)}.
- */
- public static void track(String path, Object marker) {
- theInstance.track(path, marker);
- }
-
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The speified deletion strategy is used.
- *
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the path is null
- * @deprecated Use {@link FileCleaningTracker#track(String, Object, FileDeleteStrategy)}.
- */
- public static void track(String path, Object marker, FileDeleteStrategy deleteStrategy) {
- theInstance.track(path, marker, deleteStrategy);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Retrieve the number of files currently being tracked, and therefore
- * awaiting deletion.
- *
- * @return the number of files being tracked
- * @deprecated Use {@link FileCleaningTracker#getTrackCount()}.
- */
- public static int getTrackCount() {
- return theInstance.getTrackCount();
- }
-
- /**
- * Call this method to cause the file cleaner thread to terminate when
- * there are no more objects being tracked for deletion.
- * <p>
- * In a simple environment, you don't need this method as the file cleaner
- * thread will simply exit when the JVM exits. In a more complex environment,
- * with multiple class loaders (such as an application server), you should be
- * aware that the file cleaner thread will continue running even if the class
- * loader it was started from terminates. This can consitute a memory leak.
- * <p>
- * For example, suppose that you have developed a web application, which
- * contains the commons-io jar file in your WEB-INF/lib directory. In other
- * words, the FileCleaner class is loaded through the class loader of your
- * web application. If the web application is terminated, but the servlet
- * container is still running, then the file cleaner thread will still exist,
- * posing a memory leak.
- * <p>
- * This method allows the thread to be terminated. Simply call this method
- * in the resource cleanup code, such as {@link javax.servlet.ServletContextListener#contextDestroyed}.
- * One called, no new objects can be tracked by the file cleaner.
- * @deprecated Use {@link FileCleaningTracker#exitWhenFinished()}.
- */
- public static synchronized void exitWhenFinished() {
- theInstance.exitWhenFinished();
- }
-
- /**
- * Returns the singleton instance, which is used by the deprecated, static methods.
- * This is mainly useful for code, which wants to support the new
- * {@link FileCleaningTracker} class while maintain compatibility with the
- * deprecated {@link FileCleaner}.
- *
- * @return the singleton instance
- */
- public static FileCleaningTracker getInstance() {
- return theInstance;
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/FileCleaningTracker.java b/emailcommon/src/org/apache/commons/io/FileCleaningTracker.java
deleted file mode 100644
index 4074e6a76..000000000
--- a/emailcommon/src/org/apache/commons/io/FileCleaningTracker.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.File;
-import java.lang.ref.PhantomReference;
-import java.lang.ref.ReferenceQueue;
-import java.util.Collection;
-import java.util.Vector;
-
-/**
- * Keeps track of files awaiting deletion, and deletes them when an associated
- * marker object is reclaimed by the garbage collector.
- * <p>
- * This utility creates a background thread to handle file deletion.
- * Each file to be deleted is registered with a handler object.
- * When the handler object is garbage collected, the file is deleted.
- * <p>
- * In an environment with multiple class loaders (a servlet container, for
- * example), you should consider stopping the background thread if it is no
- * longer needed. This is done by invoking the method
- * {@link #exitWhenFinished}, typically in
- * {@link javax.servlet.ServletContextListener#contextDestroyed} or similar.
- *
- * @author Noel Bergman
- * @author Martin Cooper
- * @version $Id: FileCleaner.java 490987 2006-12-29 12:11:48Z scolebourne $
- */
-public class FileCleaningTracker {
- /**
- * Queue of <code>Tracker</code> instances being watched.
- */
- ReferenceQueue<Object> /* Tracker */ q = new ReferenceQueue<Object>();
- /**
- * Collection of <code>Tracker</code> instances in existence.
- */
- final Collection<Tracker> /* Tracker */ trackers = new Vector<Tracker>(); // synchronized
- /**
- * Whether to terminate the thread when the tracking is complete.
- */
- volatile boolean exitWhenFinished = false;
- /**
- * The thread that will clean up registered files.
- */
- Thread reaper;
-
- //-----------------------------------------------------------------------
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
- *
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the file is null
- */
- public void track(File file, Object marker) {
- track(file, marker, (FileDeleteStrategy) null);
- }
-
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The speified deletion strategy is used.
- *
- * @param file the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the file is null
- */
- public void track(File file, Object marker, FileDeleteStrategy deleteStrategy) {
- if (file == null) {
- throw new NullPointerException("The file must not be null");
- }
- addTracker(file.getPath(), marker, deleteStrategy);
- }
-
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The {@link FileDeleteStrategy#NORMAL normal} deletion strategy will be used.
- *
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @throws NullPointerException if the path is null
- */
- public void track(String path, Object marker) {
- track(path, marker, (FileDeleteStrategy) null);
- }
-
- /**
- * Track the specified file, using the provided marker, deleting the file
- * when the marker instance is garbage collected.
- * The speified deletion strategy is used.
- *
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @throws NullPointerException if the path is null
- */
- public void track(String path, Object marker, FileDeleteStrategy deleteStrategy) {
- if (path == null) {
- throw new NullPointerException("The path must not be null");
- }
- addTracker(path, marker, deleteStrategy);
- }
-
- /**
- * Adds a tracker to the list of trackers.
- *
- * @param path the full path to the file to be tracked, not null
- * @param marker the marker object used to track the file, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- */
- private synchronized void addTracker(String path, Object marker, FileDeleteStrategy deleteStrategy) {
- // synchronized block protects reaper
- if (exitWhenFinished) {
- throw new IllegalStateException("No new trackers can be added once exitWhenFinished() is called");
- }
- if (reaper == null) {
- reaper = new Reaper();
- reaper.start();
- }
- trackers.add(new Tracker(path, deleteStrategy, marker, q));
- }
-
- //-----------------------------------------------------------------------
- /**
- * Retrieve the number of files currently being tracked, and therefore
- * awaiting deletion.
- *
- * @return the number of files being tracked
- */
- public int getTrackCount() {
- return trackers.size();
- }
-
- /**
- * Call this method to cause the file cleaner thread to terminate when
- * there are no more objects being tracked for deletion.
- * <p>
- * In a simple environment, you don't need this method as the file cleaner
- * thread will simply exit when the JVM exits. In a more complex environment,
- * with multiple class loaders (such as an application server), you should be
- * aware that the file cleaner thread will continue running even if the class
- * loader it was started from terminates. This can consitute a memory leak.
- * <p>
- * For example, suppose that you have developed a web application, which
- * contains the commons-io jar file in your WEB-INF/lib directory. In other
- * words, the FileCleaner class is loaded through the class loader of your
- * web application. If the web application is terminated, but the servlet
- * container is still running, then the file cleaner thread will still exist,
- * posing a memory leak.
- * <p>
- * This method allows the thread to be terminated. Simply call this method
- * in the resource cleanup code, such as {@link javax.servlet.ServletContextListener#contextDestroyed}.
- * One called, no new objects can be tracked by the file cleaner.
- */
- public synchronized void exitWhenFinished() {
- // synchronized block protects reaper
- exitWhenFinished = true;
- if (reaper != null) {
- synchronized (reaper) {
- reaper.interrupt();
- }
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * The reaper thread.
- */
- private final class Reaper extends Thread {
- /** Construct a new Reaper */
- Reaper() {
- super("File Reaper");
- setPriority(Thread.MAX_PRIORITY);
- setDaemon(true);
- }
-
- /**
- * Run the reaper thread that will delete files as their associated
- * marker objects are reclaimed by the garbage collector.
- */
- @Override
- public void run() {
- // thread exits when exitWhenFinished is true and there are no more tracked objects
- while (exitWhenFinished == false || trackers.size() > 0) {
- Tracker tracker = null;
- try {
- // Wait for a tracker to remove.
- tracker = (Tracker) q.remove();
- } catch (Exception e) {
- continue;
- }
- if (tracker != null) {
- tracker.delete();
- tracker.clear();
- trackers.remove(tracker);
- }
- }
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Inner class which acts as the reference for a file pending deletion.
- */
- private static final class Tracker extends PhantomReference<Object> {
-
- /**
- * The full path to the file being tracked.
- */
- private final String path;
- /**
- * The strategy for deleting files.
- */
- private final FileDeleteStrategy deleteStrategy;
-
- /**
- * Constructs an instance of this class from the supplied parameters.
- *
- * @param path the full path to the file to be tracked, not null
- * @param deleteStrategy the strategy to delete the file, null means normal
- * @param marker the marker object used to track the file, not null
- * @param queue the queue on to which the tracker will be pushed, not null
- */
- Tracker(String path, FileDeleteStrategy deleteStrategy, Object marker, ReferenceQueue<Object> queue) {
- super(marker, queue);
- this.path = path;
- this.deleteStrategy = (deleteStrategy == null ? FileDeleteStrategy.NORMAL : deleteStrategy);
- }
-
- /**
- * Deletes the file associated with this tracker instance.
- *
- * @return <code>true</code> if the file was deleted successfully;
- * <code>false</code> otherwise.
- */
- public boolean delete() {
- return deleteStrategy.deleteQuietly(new File(path));
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/FileDeleteStrategy.java b/emailcommon/src/org/apache/commons/io/FileDeleteStrategy.java
deleted file mode 100644
index 8b6b4b9aa..000000000
--- a/emailcommon/src/org/apache/commons/io/FileDeleteStrategy.java
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.File;
-import java.io.IOException;
-
-/**
- * Strategy for deleting files.
- * <p>
- * There is more than one way to delete a file.
- * You may want to limit access to certain directories, to only delete
- * directories if they are empty, or maybe to force deletion.
- * <p>
- * This class captures the strategy to use and is designed for user subclassing.
- *
- * @author Stephen Colebourne
- * @version $Id: FileDeleteStrategy.java 453903 2006-10-07 13:47:06Z scolebourne $
- * @since Commons IO 1.3
- */
-public class FileDeleteStrategy {
-
- /**
- * The singleton instance for normal file deletion, which does not permit
- * the deletion of directories that are not empty.
- */
- public static final FileDeleteStrategy NORMAL = new FileDeleteStrategy("Normal");
- /**
- * The singleton instance for forced file deletion, which always deletes,
- * even if the file represents a non-empty directory.
- */
- public static final FileDeleteStrategy FORCE = new ForceFileDeleteStrategy();
-
- /** The name of the strategy. */
- private final String name;
-
- //-----------------------------------------------------------------------
- /**
- * Restricted constructor.
- *
- * @param name the name by which the strategy is known
- */
- protected FileDeleteStrategy(String name) {
- this.name = name;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Deletes the file object, which may be a file or a directory.
- * All <code>IOException</code>s are caught and false returned instead.
- * If the file does not exist or is null, true is returned.
- * <p>
- * Subclass writers should override {@link #doDelete(File)}, not this method.
- *
- * @param fileToDelete the file to delete, null returns true
- * @return true if the file was deleted, or there was no such file
- */
- public boolean deleteQuietly(File fileToDelete) {
- if (fileToDelete == null || fileToDelete.exists() == false) {
- return true;
- }
- try {
- return doDelete(fileToDelete);
- } catch (IOException ex) {
- return false;
- }
- }
-
- /**
- * Deletes the file object, which may be a file or a directory.
- * If the file does not exist, the method just returns.
- * <p>
- * Subclass writers should override {@link #doDelete(File)}, not this method.
- *
- * @param fileToDelete the file to delete, not null
- * @throws NullPointerException if the file is null
- * @throws IOException if an error occurs during file deletion
- */
- public void delete(File fileToDelete) throws IOException {
- if (fileToDelete.exists() && doDelete(fileToDelete) == false) {
- throw new IOException("Deletion failed: " + fileToDelete);
- }
- }
-
- /**
- * Actually deletes the file object, which may be a file or a directory.
- * <p>
- * This method is designed for subclasses to override.
- * The implementation may return either false or an <code>IOException</code>
- * when deletion fails. The {@link #delete(File)} and {@link #deleteQuietly(File)}
- * methods will handle either response appropriately.
- * A check has been made to ensure that the file will exist.
- * <p>
- * This implementation uses {@link File#delete()}.
- *
- * @param fileToDelete the file to delete, exists, not null
- * @return true if the file was deleteds
- * @throws NullPointerException if the file is null
- * @throws IOException if an error occurs during file deletion
- */
- protected boolean doDelete(File fileToDelete) throws IOException {
- return fileToDelete.delete();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Gets a string describing the delete strategy.
- *
- * @return a string describing the delete strategy
- */
- public String toString() {
- return "FileDeleteStrategy[" + name + "]";
- }
-
- //-----------------------------------------------------------------------
- /**
- * Force file deletion strategy.
- */
- static class ForceFileDeleteStrategy extends FileDeleteStrategy {
- /** Default Constructor */
- ForceFileDeleteStrategy() {
- super("Force");
- }
-
- /**
- * Deletes the file object.
- * <p>
- * This implementation uses <code>FileUtils.forceDelete() <code>
- * if the file exists.
- *
- * @param fileToDelete the file to delete, not null
- * @return Always returns <code>true</code>
- * @throws NullPointerException if the file is null
- * @throws IOException if an error occurs during file deletion
- */
- protected boolean doDelete(File fileToDelete) throws IOException {
- FileUtils.forceDelete(fileToDelete);
- return true;
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/FileSystemUtils.java b/emailcommon/src/org/apache/commons/io/FileSystemUtils.java
deleted file mode 100644
index 1765976c4..000000000
--- a/emailcommon/src/org/apache/commons/io/FileSystemUtils.java
+++ /dev/null
@@ -1,457 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.StringTokenizer;
-
-/**
- * General File System utilities.
- * <p>
- * This class provides static utility methods for general file system
- * functions not provided via the JDK {@link java.io.File File} class.
- * <p>
- * The current functions provided are:
- * <ul>
- * <li>Get the free space on a drive
- * </ul>
- *
- * @author Frank W. Zammetti
- * @author Stephen Colebourne
- * @author Thomas Ledoux
- * @author James Urie
- * @author Magnus Grimsell
- * @author Thomas Ledoux
- * @version $Id: FileSystemUtils.java 453889 2006-10-07 11:56:25Z scolebourne $
- * @since Commons IO 1.1
- */
-public class FileSystemUtils {
-
- /** Singleton instance, used mainly for testing. */
- private static final FileSystemUtils INSTANCE = new FileSystemUtils();
-
- /** Operating system state flag for error. */
- private static final int INIT_PROBLEM = -1;
- /** Operating system state flag for neither Unix nor Windows. */
- private static final int OTHER = 0;
- /** Operating system state flag for Windows. */
- private static final int WINDOWS = 1;
- /** Operating system state flag for Unix. */
- private static final int UNIX = 2;
- /** Operating system state flag for Posix flavour Unix. */
- private static final int POSIX_UNIX = 3;
-
- /** The operating system flag. */
- private static final int OS;
- static {
- int os = OTHER;
- try {
- String osName = System.getProperty("os.name");
- if (osName == null) {
- throw new IOException("os.name not found");
- }
- osName = osName.toLowerCase();
- // match
- if (osName.indexOf("windows") != -1) {
- os = WINDOWS;
- } else if (osName.indexOf("linux") != -1 ||
- osName.indexOf("sun os") != -1 ||
- osName.indexOf("sunos") != -1 ||
- osName.indexOf("solaris") != -1 ||
- osName.indexOf("mpe/ix") != -1 ||
- osName.indexOf("freebsd") != -1 ||
- osName.indexOf("irix") != -1 ||
- osName.indexOf("digital unix") != -1 ||
- osName.indexOf("unix") != -1 ||
- osName.indexOf("mac os x") != -1) {
- os = UNIX;
- } else if (osName.indexOf("hp-ux") != -1 ||
- osName.indexOf("aix") != -1) {
- os = POSIX_UNIX;
- } else {
- os = OTHER;
- }
-
- } catch (Exception ex) {
- os = INIT_PROBLEM;
- }
- OS = os;
- }
-
- /**
- * Instances should NOT be constructed in standard programming.
- */
- public FileSystemUtils() {
- super();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns the free space on a drive or volume by invoking
- * the command line.
- * This method does not normalize the result, and typically returns
- * bytes on Windows, 512 byte units on OS X and kilobytes on Unix.
- * As this is not very useful, this method is deprecated in favour
- * of {@link #freeSpaceKb(String)} which returns a result in kilobytes.
- * <p>
- * Note that some OS's are NOT currently supported, including OS/390,
- * OpenVMS and and SunOS 5. (SunOS is supported by <code>freeSpaceKb</code>.)
- * <pre>
- * FileSystemUtils.freeSpace("C:"); // Windows
- * FileSystemUtils.freeSpace("/volume"); // *nix
- * </pre>
- * The free space is calculated via the command line.
- * It uses 'dir /-c' on Windows and 'df' on *nix.
- *
- * @param path the path to get free space for, not null, not empty on Unix
- * @return the amount of free drive space on the drive or volume
- * @throws IllegalArgumentException if the path is invalid
- * @throws IllegalStateException if an error occurred in initialisation
- * @throws IOException if an error occurs when finding the free space
- * @since Commons IO 1.1, enhanced OS support in 1.2 and 1.3
- * @deprecated Use freeSpaceKb(String)
- * Deprecated from 1.3, may be removed in 2.0
- */
- public static long freeSpace(String path) throws IOException {
- return INSTANCE.freeSpaceOS(path, OS, false);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns the free space on a drive or volume in kilobytes by invoking
- * the command line.
- * <pre>
- * FileSystemUtils.freeSpaceKb("C:"); // Windows
- * FileSystemUtils.freeSpaceKb("/volume"); // *nix
- * </pre>
- * The free space is calculated via the command line.
- * It uses 'dir /-c' on Windows, 'df -kP' on AIX/HP-UX and 'df -k' on other Unix.
- * <p>
- * In order to work, you must be running Windows, or have a implementation of
- * Unix df that supports GNU format when passed -k (or -kP). If you are going
- * to rely on this code, please check that it works on your OS by running
- * some simple tests to compare the command line with the output from this class.
- * If your operating system isn't supported, please raise a JIRA call detailing
- * the exact result from df -k and as much other detail as possible, thanks.
- *
- * @param path the path to get free space for, not null, not empty on Unix
- * @return the amount of free drive space on the drive or volume in kilobytes
- * @throws IllegalArgumentException if the path is invalid
- * @throws IllegalStateException if an error occurred in initialisation
- * @throws IOException if an error occurs when finding the free space
- * @since Commons IO 1.2, enhanced OS support in 1.3
- */
- public static long freeSpaceKb(String path) throws IOException {
- return INSTANCE.freeSpaceOS(path, OS, true);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns the free space on a drive or volume in a cross-platform manner.
- * Note that some OS's are NOT currently supported, including OS/390.
- * <pre>
- * FileSystemUtils.freeSpace("C:"); // Windows
- * FileSystemUtils.freeSpace("/volume"); // *nix
- * </pre>
- * The free space is calculated via the command line.
- * It uses 'dir /-c' on Windows and 'df' on *nix.
- *
- * @param path the path to get free space for, not null, not empty on Unix
- * @param os the operating system code
- * @param kb whether to normalize to kilobytes
- * @return the amount of free drive space on the drive or volume
- * @throws IllegalArgumentException if the path is invalid
- * @throws IllegalStateException if an error occurred in initialisation
- * @throws IOException if an error occurs when finding the free space
- */
- long freeSpaceOS(String path, int os, boolean kb) throws IOException {
- if (path == null) {
- throw new IllegalArgumentException("Path must not be empty");
- }
- switch (os) {
- case WINDOWS:
- return (kb ? freeSpaceWindows(path) / 1024 : freeSpaceWindows(path));
- case UNIX:
- return freeSpaceUnix(path, kb, false);
- case POSIX_UNIX:
- return freeSpaceUnix(path, kb, true);
- case OTHER:
- throw new IllegalStateException("Unsupported operating system");
- default:
- throw new IllegalStateException(
- "Exception caught when determining operating system");
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Find free space on the Windows platform using the 'dir' command.
- *
- * @param path the path to get free space for, including the colon
- * @return the amount of free drive space on the drive
- * @throws IOException if an error occurs
- */
- long freeSpaceWindows(String path) throws IOException {
- path = FilenameUtils.normalize(path);
- if (path.length() > 2 && path.charAt(1) == ':') {
- path = path.substring(0, 2); // seems to make it work
- }
-
- // build and run the 'dir' command
- String[] cmdAttribs = new String[] {"cmd.exe", "/C", "dir /-c " + path};
-
- // read in the output of the command to an ArrayList
- List<String> lines = performCommand(cmdAttribs, Integer.MAX_VALUE);
-
- // now iterate over the lines we just read and find the LAST
- // non-empty line (the free space bytes should be in the last element
- // of the ArrayList anyway, but this will ensure it works even if it's
- // not, still assuming it is on the last non-blank line)
- for (int i = lines.size() - 1; i >= 0; i--) {
- String line = lines.get(i);
- if (line.length() > 0) {
- return parseDir(line, path);
- }
- }
- // all lines are blank
- throw new IOException(
- "Command line 'dir /-c' did not return any info " +
- "for path '" + path + "'");
- }
-
- /**
- * Parses the Windows dir response last line
- *
- * @param line the line to parse
- * @param path the path that was sent
- * @return the number of bytes
- * @throws IOException if an error occurs
- */
- long parseDir(String line, String path) throws IOException {
- // read from the end of the line to find the last numeric
- // character on the line, then continue until we find the first
- // non-numeric character, and everything between that and the last
- // numeric character inclusive is our free space bytes count
- int bytesStart = 0;
- int bytesEnd = 0;
- int j = line.length() - 1;
- innerLoop1: while (j >= 0) {
- char c = line.charAt(j);
- if (Character.isDigit(c)) {
- // found the last numeric character, this is the end of
- // the free space bytes count
- bytesEnd = j + 1;
- break innerLoop1;
- }
- j--;
- }
- innerLoop2: while (j >= 0) {
- char c = line.charAt(j);
- if (!Character.isDigit(c) && c != ',' && c != '.') {
- // found the next non-numeric character, this is the
- // beginning of the free space bytes count
- bytesStart = j + 1;
- break innerLoop2;
- }
- j--;
- }
- if (j < 0) {
- throw new IOException(
- "Command line 'dir /-c' did not return valid info " +
- "for path '" + path + "'");
- }
-
- // remove commas and dots in the bytes count
- StringBuffer buf = new StringBuffer(line.substring(bytesStart, bytesEnd));
- for (int k = 0; k < buf.length(); k++) {
- if (buf.charAt(k) == ',' || buf.charAt(k) == '.') {
- buf.deleteCharAt(k--);
- }
- }
- return parseBytes(buf.toString(), path);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Find free space on the *nix platform using the 'df' command.
- *
- * @param path the path to get free space for
- * @param kb whether to normalize to kilobytes
- * @param posix whether to use the posix standard format flag
- * @return the amount of free drive space on the volume
- * @throws IOException if an error occurs
- */
- long freeSpaceUnix(String path, boolean kb, boolean posix) throws IOException {
- if (path.length() == 0) {
- throw new IllegalArgumentException("Path must not be empty");
- }
- path = FilenameUtils.normalize(path);
-
- // build and run the 'dir' command
- String flags = "-";
- if (kb) {
- flags += "k";
- }
- if (posix) {
- flags += "P";
- }
- String[] cmdAttribs =
- (flags.length() > 1 ? new String[] {"df", flags, path} : new String[] {"df", path});
-
- // perform the command, asking for up to 3 lines (header, interesting, overflow)
- List<String> lines = performCommand(cmdAttribs, 3);
- if (lines.size() < 2) {
- // unknown problem, throw exception
- throw new IOException(
- "Command line 'df' did not return info as expected " +
- "for path '" + path + "'- response was " + lines);
- }
- String line2 = lines.get(1); // the line we're interested in
-
- // Now, we tokenize the string. The fourth element is what we want.
- StringTokenizer tok = new StringTokenizer(line2, " ");
- if (tok.countTokens() < 4) {
- // could be long Filesystem, thus data on third line
- if (tok.countTokens() == 1 && lines.size() >= 3) {
- String line3 = lines.get(2); // the line may be interested in
- tok = new StringTokenizer(line3, " ");
- } else {
- throw new IOException(
- "Command line 'df' did not return data as expected " +
- "for path '" + path + "'- check path is valid");
- }
- } else {
- tok.nextToken(); // Ignore Filesystem
- }
- tok.nextToken(); // Ignore 1K-blocks
- tok.nextToken(); // Ignore Used
- String freeSpace = tok.nextToken();
- return parseBytes(freeSpace, path);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Parses the bytes from a string.
- *
- * @param freeSpace the free space string
- * @param path the path
- * @return the number of bytes
- * @throws IOException if an error occurs
- */
- long parseBytes(String freeSpace, String path) throws IOException {
- try {
- long bytes = Long.parseLong(freeSpace);
- if (bytes < 0) {
- throw new IOException(
- "Command line 'df' did not find free space in response " +
- "for path '" + path + "'- check path is valid");
- }
- return bytes;
-
- } catch (NumberFormatException ex) {
- throw new IOException(
- "Command line 'df' did not return numeric data as expected " +
- "for path '" + path + "'- check path is valid");
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Performs the os command.
- *
- * @param cmdAttribs the command line parameters
- * @param max The maximum limit for the lines returned
- * @return the parsed data
- * @throws IOException if an error occurs
- */
- List<String> performCommand(String[] cmdAttribs, int max) throws IOException {
- // this method does what it can to avoid the 'Too many open files' error
- // based on trial and error and these links:
- // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692
- // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4801027
- // http://forum.java.sun.com/thread.jspa?threadID=533029&messageID=2572018
- // however, its still not perfect as the JDK support is so poor
- // (see commond-exec or ant for a better multi-threaded multi-os solution)
-
- List<String> lines = new ArrayList<String>(20);
- Process proc = null;
- InputStream in = null;
- OutputStream out = null;
- InputStream err = null;
- BufferedReader inr = null;
- try {
- proc = openProcess(cmdAttribs);
- in = proc.getInputStream();
- out = proc.getOutputStream();
- err = proc.getErrorStream();
- inr = new BufferedReader(new InputStreamReader(in));
- String line = inr.readLine();
- while (line != null && lines.size() < max) {
- line = line.toLowerCase().trim();
- lines.add(line);
- line = inr.readLine();
- }
-
- proc.waitFor();
- if (proc.exitValue() != 0) {
- // os command problem, throw exception
- throw new IOException(
- "Command line returned OS error code '" + proc.exitValue() +
- "' for command " + Arrays.asList(cmdAttribs));
- }
- if (lines.size() == 0) {
- // unknown problem, throw exception
- throw new IOException(
- "Command line did not return any info " +
- "for command " + Arrays.asList(cmdAttribs));
- }
- return lines;
-
- } catch (InterruptedException ex) {
- throw new IOException(
- "Command line threw an InterruptedException '" + ex.getMessage() +
- "' for command " + Arrays.asList(cmdAttribs));
- } finally {
- IOUtils.closeQuietly(in);
- IOUtils.closeQuietly(out);
- IOUtils.closeQuietly(err);
- IOUtils.closeQuietly(inr);
- if (proc != null) {
- proc.destroy();
- }
- }
- }
-
- /**
- * Opens the process to the operating system.
- *
- * @param cmdAttribs the command line parameters
- * @return the process
- * @throws IOException if an error occurs
- */
- Process openProcess(String[] cmdAttribs) throws IOException {
- return Runtime.getRuntime().exec(cmdAttribs);
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/FileUtils.java b/emailcommon/src/org/apache/commons/io/FileUtils.java
deleted file mode 100644
index d5de771c7..000000000
--- a/emailcommon/src/org/apache/commons/io/FileUtils.java
+++ /dev/null
@@ -1,1890 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Iterator;
-import java.util.List;
-import java.util.zip.CRC32;
-import java.util.zip.CheckedInputStream;
-import java.util.zip.Checksum;
-
-import org.apache.commons.io.filefilter.DirectoryFileFilter;
-import org.apache.commons.io.filefilter.FalseFileFilter;
-import org.apache.commons.io.filefilter.FileFilterUtils;
-import org.apache.commons.io.filefilter.IOFileFilter;
-import org.apache.commons.io.filefilter.SuffixFileFilter;
-import org.apache.commons.io.filefilter.TrueFileFilter;
-import org.apache.commons.io.output.NullOutputStream;
-
-/**
- * General file manipulation utilities.
- * <p>
- * Facilities are provided in the following areas:
- * <ul>
- * <li>writing to a file
- * <li>reading from a file
- * <li>make a directory including parent directories
- * <li>copying files and directories
- * <li>deleting files and directories
- * <li>converting to and from a URL
- * <li>listing files and directories by filter and extension
- * <li>comparing file content
- * <li>file last changed date
- * <li>calculating a checksum
- * </ul>
- * <p>
- * Origin of code: Excalibur, Alexandria, Commons-Utils
- *
- * @author <a href="mailto:burton@relativity.yi.org">Kevin A. Burton</A>
- * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
- * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
- * @author <a href="mailto:Christoph.Reck@dlr.de">Christoph.Reck</a>
- * @author <a href="mailto:peter@apache.org">Peter Donald</a>
- * @author <a href="mailto:jefft@apache.org">Jeff Turner</a>
- * @author Matthew Hawthorne
- * @author <a href="mailto:jeremias@apache.org">Jeremias Maerki</a>
- * @author Stephen Colebourne
- * @author Ian Springer
- * @author Chris Eldredge
- * @author Jim Harrington
- * @author Niall Pemberton
- * @author Sandy McArthur
- * @version $Id: FileUtils.java 610810 2008-01-10 15:04:49Z niallp $
- */
-public class FileUtils {
-
- /**
- * Instances should NOT be constructed in standard programming.
- */
- public FileUtils() {
- super();
- }
-
- /**
- * The number of bytes in a kilobyte.
- */
- public static final long ONE_KB = 1024;
-
- /**
- * The number of bytes in a megabyte.
- */
- public static final long ONE_MB = ONE_KB * ONE_KB;
-
- /**
- * The number of bytes in a gigabyte.
- */
- public static final long ONE_GB = ONE_KB * ONE_MB;
-
- /**
- * An empty array of type <code>File</code>.
- */
- public static final File[] EMPTY_FILE_ARRAY = new File[0];
-
- //-----------------------------------------------------------------------
- /**
- * Opens a {@link FileInputStream} for the specified file, providing better
- * error messages than simply calling <code>new FileInputStream(file)</code>.
- * <p>
- * At the end of the method either the stream will be successfully opened,
- * or an exception will have been thrown.
- * <p>
- * An exception is thrown if the file does not exist.
- * An exception is thrown if the file object exists but is a directory.
- * An exception is thrown if the file exists but cannot be read.
- *
- * @param file the file to open for input, must not be <code>null</code>
- * @return a new {@link FileInputStream} for the specified file
- * @throws FileNotFoundException if the file does not exist
- * @throws IOException if the file object is a directory
- * @throws IOException if the file cannot be read
- * @since Commons IO 1.3
- */
- public static FileInputStream openInputStream(File file) throws IOException {
- if (file.exists()) {
- if (file.isDirectory()) {
- throw new IOException("File '" + file + "' exists but is a directory");
- }
- if (file.canRead() == false) {
- throw new IOException("File '" + file + "' cannot be read");
- }
- } else {
- throw new FileNotFoundException("File '" + file + "' does not exist");
- }
- return new FileInputStream(file);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Opens a {@link FileOutputStream} for the specified file, checking and
- * creating the parent directory if it does not exist.
- * <p>
- * At the end of the method either the stream will be successfully opened,
- * or an exception will have been thrown.
- * <p>
- * The parent directory will be created if it does not exist.
- * The file will be created if it does not exist.
- * An exception is thrown if the file object exists but is a directory.
- * An exception is thrown if the file exists but cannot be written to.
- * An exception is thrown if the parent directory cannot be created.
- *
- * @param file the file to open for output, must not be <code>null</code>
- * @return a new {@link FileOutputStream} for the specified file
- * @throws IOException if the file object is a directory
- * @throws IOException if the file cannot be written to
- * @throws IOException if a parent directory needs creating but that fails
- * @since Commons IO 1.3
- */
- public static FileOutputStream openOutputStream(File file) throws IOException {
- if (file.exists()) {
- if (file.isDirectory()) {
- throw new IOException("File '" + file + "' exists but is a directory");
- }
- if (file.canWrite() == false) {
- throw new IOException("File '" + file + "' cannot be written to");
- }
- } else {
- File parent = file.getParentFile();
- if (parent != null && parent.exists() == false) {
- if (parent.mkdirs() == false) {
- throw new IOException("File '" + file + "' could not be created");
- }
- }
- }
- return new FileOutputStream(file);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns a human-readable version of the file size, where the input
- * represents a specific number of bytes.
- *
- * @param size the number of bytes
- * @return a human-readable display value (includes units)
- */
- public static String byteCountToDisplaySize(long size) {
- String displaySize;
-
- if (size / ONE_GB > 0) {
- displaySize = String.valueOf(size / ONE_GB) + " GB";
- } else if (size / ONE_MB > 0) {
- displaySize = String.valueOf(size / ONE_MB) + " MB";
- } else if (size / ONE_KB > 0) {
- displaySize = String.valueOf(size / ONE_KB) + " KB";
- } else {
- displaySize = String.valueOf(size) + " bytes";
- }
- return displaySize;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Implements the same behaviour as the "touch" utility on Unix. It creates
- * a new file with size 0 or, if the file exists already, it is opened and
- * closed without modifying it, but updating the file date and time.
- * <p>
- * NOTE: As from v1.3, this method throws an IOException if the last
- * modified date of the file cannot be set. Also, as from v1.3 this method
- * creates parent directories if they do not exist.
- *
- * @param file the File to touch
- * @throws IOException If an I/O problem occurs
- */
- public static void touch(File file) throws IOException {
- if (!file.exists()) {
- OutputStream out = openOutputStream(file);
- IOUtils.closeQuietly(out);
- }
- boolean success = file.setLastModified(System.currentTimeMillis());
- if (!success) {
- throw new IOException("Unable to set the last modification time for " + file);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Converts a Collection containing java.io.File instanced into array
- * representation. This is to account for the difference between
- * File.listFiles() and FileUtils.listFiles().
- *
- * @param files a Collection containing java.io.File instances
- * @return an array of java.io.File
- */
- public static File[] convertFileCollectionToFileArray(Collection<File> files) {
- return files.toArray(new File[files.size()]);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Finds files within a given directory (and optionally its
- * subdirectories). All files found are filtered by an IOFileFilter.
- *
- * @param files the collection of files found.
- * @param directory the directory to search in.
- * @param filter the filter to apply to files and directories.
- */
- private static void innerListFiles(Collection<File> files, File directory,
- IOFileFilter filter) {
- File[] found = directory.listFiles((FileFilter) filter);
- if (found != null) {
- for (int i = 0; i < found.length; i++) {
- if (found[i].isDirectory()) {
- innerListFiles(files, found[i], filter);
- } else {
- files.add(found[i]);
- }
- }
- }
- }
-
- /**
- * Finds files within a given directory (and optionally its
- * subdirectories). All files found are filtered by an IOFileFilter.
- * <p>
- * If your search should recurse into subdirectories you can pass in
- * an IOFileFilter for directories. You don't need to bind a
- * DirectoryFileFilter (via logical AND) to this filter. This method does
- * that for you.
- * <p>
- * An example: If you want to search through all directories called
- * "temp" you pass in <code>FileFilterUtils.NameFileFilter("temp")</code>
- * <p>
- * Another common usage of this method is find files in a directory
- * tree but ignoring the directories generated CVS. You can simply pass
- * in <code>FileFilterUtils.makeCVSAware(null)</code>.
- *
- * @param directory the directory to search in
- * @param fileFilter filter to apply when finding files.
- * @param dirFilter optional filter to apply when finding subdirectories.
- * If this parameter is <code>null</code>, subdirectories will not be included in the
- * search. Use TrueFileFilter.INSTANCE to match all directories.
- * @return an collection of java.io.File with the matching files
- * @see org.apache.commons.io.filefilter.FileFilterUtils
- * @see org.apache.commons.io.filefilter.NameFileFilter
- */
- public static Collection<File> listFiles(
- File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
- if (!directory.isDirectory()) {
- throw new IllegalArgumentException(
- "Parameter 'directory' is not a directory");
- }
- if (fileFilter == null) {
- throw new NullPointerException("Parameter 'fileFilter' is null");
- }
-
- //Setup effective file filter
- IOFileFilter effFileFilter = FileFilterUtils.andFileFilter(fileFilter,
- FileFilterUtils.notFileFilter(DirectoryFileFilter.INSTANCE));
-
- //Setup effective directory filter
- IOFileFilter effDirFilter;
- if (dirFilter == null) {
- effDirFilter = FalseFileFilter.INSTANCE;
- } else {
- effDirFilter = FileFilterUtils.andFileFilter(dirFilter,
- DirectoryFileFilter.INSTANCE);
- }
-
- //Find files
- Collection<File> files = new java.util.LinkedList<File>();
- innerListFiles(files, directory,
- FileFilterUtils.orFileFilter(effFileFilter, effDirFilter));
- return files;
- }
-
- /**
- * Allows iteration over the files in given directory (and optionally
- * its subdirectories).
- * <p>
- * All files found are filtered by an IOFileFilter. This method is
- * based on {@link #listFiles(File, IOFileFilter, IOFileFilter)}.
- *
- * @param directory the directory to search in
- * @param fileFilter filter to apply when finding files.
- * @param dirFilter optional filter to apply when finding subdirectories.
- * If this parameter is <code>null</code>, subdirectories will not be included in the
- * search. Use TrueFileFilter.INSTANCE to match all directories.
- * @return an iterator of java.io.File for the matching files
- * @see org.apache.commons.io.filefilter.FileFilterUtils
- * @see org.apache.commons.io.filefilter.NameFileFilter
- * @since Commons IO 1.2
- */
- public static Iterator<File> iterateFiles(
- File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
- return listFiles(directory, fileFilter, dirFilter).iterator();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Converts an array of file extensions to suffixes for use
- * with IOFileFilters.
- *
- * @param extensions an array of extensions. Format: {"java", "xml"}
- * @return an array of suffixes. Format: {".java", ".xml"}
- */
- private static String[] toSuffixes(String[] extensions) {
- String[] suffixes = new String[extensions.length];
- for (int i = 0; i < extensions.length; i++) {
- suffixes[i] = "." + extensions[i];
- }
- return suffixes;
- }
-
-
- /**
- * Finds files within a given directory (and optionally its subdirectories)
- * which match an array of extensions.
- *
- * @param directory the directory to search in
- * @param extensions an array of extensions, ex. {"java","xml"}. If this
- * parameter is <code>null</code>, all files are returned.
- * @param recursive if true all subdirectories are searched as well
- * @return an collection of java.io.File with the matching files
- */
- public static Collection<File> listFiles(
- File directory, String[] extensions, boolean recursive) {
- IOFileFilter filter;
- if (extensions == null) {
- filter = TrueFileFilter.INSTANCE;
- } else {
- String[] suffixes = toSuffixes(extensions);
- filter = new SuffixFileFilter(suffixes);
- }
- return listFiles(directory, filter,
- (recursive ? TrueFileFilter.INSTANCE : FalseFileFilter.INSTANCE));
- }
-
- /**
- * Allows iteration over the files in a given directory (and optionally
- * its subdirectories) which match an array of extensions. This method
- * is based on {@link #listFiles(File, String[], boolean)}.
- *
- * @param directory the directory to search in
- * @param extensions an array of extensions, ex. {"java","xml"}. If this
- * parameter is <code>null</code>, all files are returned.
- * @param recursive if true all subdirectories are searched as well
- * @return an iterator of java.io.File with the matching files
- * @since Commons IO 1.2
- */
- public static Iterator<File> iterateFiles(
- File directory, String[] extensions, boolean recursive) {
- return listFiles(directory, extensions, recursive).iterator();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Compares the contents of two files to determine if they are equal or not.
- * <p>
- * This method checks to see if the two files are different lengths
- * or if they point to the same file, before resorting to byte-by-byte
- * comparison of the contents.
- * <p>
- * Code origin: Avalon
- *
- * @param file1 the first file
- * @param file2 the second file
- * @return true if the content of the files are equal or they both don't
- * exist, false otherwise
- * @throws IOException in case of an I/O error
- */
- public static boolean contentEquals(File file1, File file2) throws IOException {
- boolean file1Exists = file1.exists();
- if (file1Exists != file2.exists()) {
- return false;
- }
-
- if (!file1Exists) {
- // two not existing files are equal
- return true;
- }
-
- if (file1.isDirectory() || file2.isDirectory()) {
- // don't want to compare directory contents
- throw new IOException("Can't compare directories, only files");
- }
-
- if (file1.length() != file2.length()) {
- // lengths differ, cannot be equal
- return false;
- }
-
- if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
- // same file
- return true;
- }
-
- InputStream input1 = null;
- InputStream input2 = null;
- try {
- input1 = new FileInputStream(file1);
- input2 = new FileInputStream(file2);
- return IOUtils.contentEquals(input1, input2);
-
- } finally {
- IOUtils.closeQuietly(input1);
- IOUtils.closeQuietly(input2);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Convert from a <code>URL</code> to a <code>File</code>.
- * <p>
- * From version 1.1 this method will decode the URL.
- * Syntax such as <code>file:///my%20docs/file.txt</code> will be
- * correctly decoded to <code>/my docs/file.txt</code>.
- *
- * @param url the file URL to convert, <code>null</code> returns <code>null</code>
- * @return the equivalent <code>File</code> object, or <code>null</code>
- * if the URL's protocol is not <code>file</code>
- * @throws IllegalArgumentException if the file is incorrectly encoded
- */
- public static File toFile(URL url) {
- if (url == null || !url.getProtocol().equals("file")) {
- return null;
- } else {
- String filename = url.getFile().replace('/', File.separatorChar);
- int pos =0;
- while ((pos = filename.indexOf('%', pos)) >= 0) {
- if (pos + 2 < filename.length()) {
- String hexStr = filename.substring(pos + 1, pos + 3);
- char ch = (char) Integer.parseInt(hexStr, 16);
- filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
- }
- }
- return new File(filename);
- }
- }
-
- /**
- * Converts each of an array of <code>URL</code> to a <code>File</code>.
- * <p>
- * Returns an array of the same size as the input.
- * If the input is <code>null</code>, an empty array is returned.
- * If the input contains <code>null</code>, the output array contains <code>null</code> at the same
- * index.
- * <p>
- * This method will decode the URL.
- * Syntax such as <code>file:///my%20docs/file.txt</code> will be
- * correctly decoded to <code>/my docs/file.txt</code>.
- *
- * @param urls the file URLs to convert, <code>null</code> returns empty array
- * @return a non-<code>null</code> array of Files matching the input, with a <code>null</code> item
- * if there was a <code>null</code> at that index in the input array
- * @throws IllegalArgumentException if any file is not a URL file
- * @throws IllegalArgumentException if any file is incorrectly encoded
- * @since Commons IO 1.1
- */
- public static File[] toFiles(URL[] urls) {
- if (urls == null || urls.length == 0) {
- return EMPTY_FILE_ARRAY;
- }
- File[] files = new File[urls.length];
- for (int i = 0; i < urls.length; i++) {
- URL url = urls[i];
- if (url != null) {
- if (url.getProtocol().equals("file") == false) {
- throw new IllegalArgumentException(
- "URL could not be converted to a File: " + url);
- }
- files[i] = toFile(url);
- }
- }
- return files;
- }
-
- /**
- * Converts each of an array of <code>File</code> to a <code>URL</code>.
- * <p>
- * Returns an array of the same size as the input.
- *
- * @param files the files to convert
- * @return an array of URLs matching the input
- * @throws IOException if a file cannot be converted
- */
- public static URL[] toURLs(File[] files) throws IOException {
- URL[] urls = new URL[files.length];
-
- for (int i = 0; i < urls.length; i++) {
- urls[i] = files[i].toURI().toURL();
- }
-
- return urls;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Copies a file to a directory preserving the file date.
- * <p>
- * This method copies the contents of the specified source file
- * to a file of the same name in the specified destination directory.
- * The destination directory is created if it does not exist.
- * If the destination file exists, then this method will overwrite it.
- *
- * @param srcFile an existing file to copy, must not be <code>null</code>
- * @param destDir the directory to place the copy in, must not be <code>null</code>
- *
- * @throws NullPointerException if source or destination is null
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @see #copyFile(File, File, boolean)
- */
- public static void copyFileToDirectory(File srcFile, File destDir) throws IOException {
- copyFileToDirectory(srcFile, destDir, true);
- }
-
- /**
- * Copies a file to a directory optionally preserving the file date.
- * <p>
- * This method copies the contents of the specified source file
- * to a file of the same name in the specified destination directory.
- * The destination directory is created if it does not exist.
- * If the destination file exists, then this method will overwrite it.
- *
- * @param srcFile an existing file to copy, must not be <code>null</code>
- * @param destDir the directory to place the copy in, must not be <code>null</code>
- * @param preserveFileDate true if the file date of the copy
- * should be the same as the original
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @see #copyFile(File, File, boolean)
- * @since Commons IO 1.3
- */
- public static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) throws IOException {
- if (destDir == null) {
- throw new NullPointerException("Destination must not be null");
- }
- if (destDir.exists() && destDir.isDirectory() == false) {
- throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
- }
- copyFile(srcFile, new File(destDir, srcFile.getName()), preserveFileDate);
- }
-
- /**
- * Copies a file to a new location preserving the file date.
- * <p>
- * This method copies the contents of the specified source file to the
- * specified destination file. The directory holding the destination file is
- * created if it does not exist. If the destination file exists, then this
- * method will overwrite it.
- *
- * @param srcFile an existing file to copy, must not be <code>null</code>
- * @param destFile the new file, must not be <code>null</code>
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @see #copyFileToDirectory(File, File)
- */
- public static void copyFile(File srcFile, File destFile) throws IOException {
- copyFile(srcFile, destFile, true);
- }
-
- /**
- * Copies a file to a new location.
- * <p>
- * This method copies the contents of the specified source file
- * to the specified destination file.
- * The directory holding the destination file is created if it does not exist.
- * If the destination file exists, then this method will overwrite it.
- *
- * @param srcFile an existing file to copy, must not be <code>null</code>
- * @param destFile the new file, must not be <code>null</code>
- * @param preserveFileDate true if the file date of the copy
- * should be the same as the original
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @see #copyFileToDirectory(File, File, boolean)
- */
- public static void copyFile(File srcFile, File destFile,
- boolean preserveFileDate) throws IOException {
- if (srcFile == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (destFile == null) {
- throw new NullPointerException("Destination must not be null");
- }
- if (srcFile.exists() == false) {
- throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
- }
- if (srcFile.isDirectory()) {
- throw new IOException("Source '" + srcFile + "' exists but is a directory");
- }
- if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) {
- throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same");
- }
- if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) {
- if (destFile.getParentFile().mkdirs() == false) {
- throw new IOException("Destination '" + destFile + "' directory cannot be created");
- }
- }
- if (destFile.exists() && destFile.canWrite() == false) {
- throw new IOException("Destination '" + destFile + "' exists but is read-only");
- }
- doCopyFile(srcFile, destFile, preserveFileDate);
- }
-
- /**
- * Internal copy file method.
- *
- * @param srcFile the validated source file, must not be <code>null</code>
- * @param destFile the validated destination file, must not be <code>null</code>
- * @param preserveFileDate whether to preserve the file date
- * @throws IOException if an error occurs
- */
- private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
- if (destFile.exists() && destFile.isDirectory()) {
- throw new IOException("Destination '" + destFile + "' exists but is a directory");
- }
-
- FileInputStream input = new FileInputStream(srcFile);
- try {
- FileOutputStream output = new FileOutputStream(destFile);
- try {
- IOUtils.copy(input, output);
- } finally {
- IOUtils.closeQuietly(output);
- }
- } finally {
- IOUtils.closeQuietly(input);
- }
-
- if (srcFile.length() != destFile.length()) {
- throw new IOException("Failed to copy full contents from '" +
- srcFile + "' to '" + destFile + "'");
- }
- if (preserveFileDate) {
- destFile.setLastModified(srcFile.lastModified());
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Copies a directory to within another directory preserving the file dates.
- * <p>
- * This method copies the source directory and all its contents to a
- * directory of the same name in the specified destination directory.
- * <p>
- * The destination directory is created if it does not exist.
- * If the destination directory did exist, then this method merges
- * the source with the destination, with the source taking precedence.
- *
- * @param srcDir an existing directory to copy, must not be <code>null</code>
- * @param destDir the directory to place the copy in, must not be <code>null</code>
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @since Commons IO 1.2
- */
- public static void copyDirectoryToDirectory(File srcDir, File destDir) throws IOException {
- if (srcDir == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (srcDir.exists() && srcDir.isDirectory() == false) {
- throw new IllegalArgumentException("Source '" + destDir + "' is not a directory");
- }
- if (destDir == null) {
- throw new NullPointerException("Destination must not be null");
- }
- if (destDir.exists() && destDir.isDirectory() == false) {
- throw new IllegalArgumentException("Destination '" + destDir + "' is not a directory");
- }
- copyDirectory(srcDir, new File(destDir, srcDir.getName()), true);
- }
-
- /**
- * Copies a whole directory to a new location preserving the file dates.
- * <p>
- * This method copies the specified directory and all its child
- * directories and files to the specified destination.
- * The destination is the new location and name of the directory.
- * <p>
- * The destination directory is created if it does not exist.
- * If the destination directory did exist, then this method merges
- * the source with the destination, with the source taking precedence.
- *
- * @param srcDir an existing directory to copy, must not be <code>null</code>
- * @param destDir the new directory, must not be <code>null</code>
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @since Commons IO 1.1
- */
- public static void copyDirectory(File srcDir, File destDir) throws IOException {
- copyDirectory(srcDir, destDir, true);
- }
-
- /**
- * Copies a whole directory to a new location.
- * <p>
- * This method copies the contents of the specified source directory
- * to within the specified destination directory.
- * <p>
- * The destination directory is created if it does not exist.
- * If the destination directory did exist, then this method merges
- * the source with the destination, with the source taking precedence.
- *
- * @param srcDir an existing directory to copy, must not be <code>null</code>
- * @param destDir the new directory, must not be <code>null</code>
- * @param preserveFileDate true if the file date of the copy
- * should be the same as the original
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @since Commons IO 1.1
- */
- public static void copyDirectory(File srcDir, File destDir,
- boolean preserveFileDate) throws IOException {
- copyDirectory(srcDir, destDir, null, preserveFileDate);
- }
-
- /**
- * Copies a filtered directory to a new location preserving the file dates.
- * <p>
- * This method copies the contents of the specified source directory
- * to within the specified destination directory.
- * <p>
- * The destination directory is created if it does not exist.
- * If the destination directory did exist, then this method merges
- * the source with the destination, with the source taking precedence.
- *
- * <h4>Example: Copy directories only</h4>
- * <pre>
- * // only copy the directory structure
- * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY);
- * </pre>
- *
- * <h4>Example: Copy directories and txt files</h4>
- * <pre>
- * // Create a filter for ".txt" files
- * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
- * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
- *
- * // Create a filter for either directories or ".txt" files
- * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
- *
- * // Copy using the filter
- * FileUtils.copyDirectory(srcDir, destDir, filter);
- * </pre>
- *
- * @param srcDir an existing directory to copy, must not be <code>null</code>
- * @param destDir the new directory, must not be <code>null</code>
- * @param filter the filter to apply, null means copy all directories and files
- * should be the same as the original
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @since Commons IO 1.4
- */
- public static void copyDirectory(File srcDir, File destDir,
- FileFilter filter) throws IOException {
- copyDirectory(srcDir, destDir, filter, true);
- }
-
- /**
- * Copies a filtered directory to a new location.
- * <p>
- * This method copies the contents of the specified source directory
- * to within the specified destination directory.
- * <p>
- * The destination directory is created if it does not exist.
- * If the destination directory did exist, then this method merges
- * the source with the destination, with the source taking precedence.
- *
- * <h4>Example: Copy directories only</h4>
- * <pre>
- * // only copy the directory structure
- * FileUtils.copyDirectory(srcDir, destDir, DirectoryFileFilter.DIRECTORY, false);
- * </pre>
- *
- * <h4>Example: Copy directories and txt files</h4>
- * <pre>
- * // Create a filter for ".txt" files
- * IOFileFilter txtSuffixFilter = FileFilterUtils.suffixFileFilter(".txt");
- * IOFileFilter txtFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, txtSuffixFilter);
- *
- * // Create a filter for either directories or ".txt" files
- * FileFilter filter = FileFilterUtils.orFileFilter(DirectoryFileFilter.DIRECTORY, txtFiles);
- *
- * // Copy using the filter
- * FileUtils.copyDirectory(srcDir, destDir, filter, false);
- * </pre>
- *
- * @param srcDir an existing directory to copy, must not be <code>null</code>
- * @param destDir the new directory, must not be <code>null</code>
- * @param filter the filter to apply, null means copy all directories and files
- * @param preserveFileDate true if the file date of the copy
- * should be the same as the original
- *
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs during copying
- * @since Commons IO 1.4
- */
- public static void copyDirectory(File srcDir, File destDir,
- FileFilter filter, boolean preserveFileDate) throws IOException {
- if (srcDir == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (destDir == null) {
- throw new NullPointerException("Destination must not be null");
- }
- if (srcDir.exists() == false) {
- throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
- }
- if (srcDir.isDirectory() == false) {
- throw new IOException("Source '" + srcDir + "' exists but is not a directory");
- }
- if (srcDir.getCanonicalPath().equals(destDir.getCanonicalPath())) {
- throw new IOException("Source '" + srcDir + "' and destination '" + destDir + "' are the same");
- }
-
- // Cater for destination being directory within the source directory (see IO-141)
- List<String> exclusionList = null;
- if (destDir.getCanonicalPath().startsWith(srcDir.getCanonicalPath())) {
- File[] srcFiles = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
- if (srcFiles != null && srcFiles.length > 0) {
- exclusionList = new ArrayList<String>(srcFiles.length);
- for (int i = 0; i < srcFiles.length; i++) {
- File copiedFile = new File(destDir, srcFiles[i].getName());
- exclusionList.add(copiedFile.getCanonicalPath());
- }
- }
- }
- doCopyDirectory(srcDir, destDir, filter, preserveFileDate, exclusionList);
- }
-
- /**
- * Internal copy directory method.
- *
- * @param srcDir the validated source directory, must not be <code>null</code>
- * @param destDir the validated destination directory, must not be <code>null</code>
- * @param filter the filter to apply, null means copy all directories and files
- * @param preserveFileDate whether to preserve the file date
- * @param exclusionList List of files and directories to exclude from the copy, may be null
- * @throws IOException if an error occurs
- * @since Commons IO 1.1
- */
- private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter,
- boolean preserveFileDate, List<String> exclusionList) throws IOException {
- if (destDir.exists()) {
- if (destDir.isDirectory() == false) {
- throw new IOException("Destination '" + destDir + "' exists but is not a directory");
- }
- } else {
- if (destDir.mkdirs() == false) {
- throw new IOException("Destination '" + destDir + "' directory cannot be created");
- }
- if (preserveFileDate) {
- destDir.setLastModified(srcDir.lastModified());
- }
- }
- if (destDir.canWrite() == false) {
- throw new IOException("Destination '" + destDir + "' cannot be written to");
- }
- // recurse
- File[] files = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter);
- if (files == null) { // null if security restricted
- throw new IOException("Failed to list contents of " + srcDir);
- }
- for (int i = 0; i < files.length; i++) {
- File copiedFile = new File(destDir, files[i].getName());
- if (exclusionList == null || !exclusionList.contains(files[i].getCanonicalPath())) {
- if (files[i].isDirectory()) {
- doCopyDirectory(files[i], copiedFile, filter, preserveFileDate, exclusionList);
- } else {
- doCopyFile(files[i], copiedFile, preserveFileDate);
- }
- }
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Copies bytes from the URL <code>source</code> to a file
- * <code>destination</code>. The directories up to <code>destination</code>
- * will be created if they don't already exist. <code>destination</code>
- * will be overwritten if it already exists.
- *
- * @param source the <code>URL</code> to copy bytes from, must not be <code>null</code>
- * @param destination the non-directory <code>File</code> to write bytes to
- * (possibly overwriting), must not be <code>null</code>
- * @throws IOException if <code>source</code> URL cannot be opened
- * @throws IOException if <code>destination</code> is a directory
- * @throws IOException if <code>destination</code> cannot be written
- * @throws IOException if <code>destination</code> needs creating but can't be
- * @throws IOException if an IO error occurs during copying
- */
- public static void copyURLToFile(URL source, File destination) throws IOException {
- InputStream input = source.openStream();
- try {
- FileOutputStream output = openOutputStream(destination);
- try {
- IOUtils.copy(input, output);
- } finally {
- IOUtils.closeQuietly(output);
- }
- } finally {
- IOUtils.closeQuietly(input);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Deletes a directory recursively.
- *
- * @param directory directory to delete
- * @throws IOException in case deletion is unsuccessful
- */
- public static void deleteDirectory(File directory) throws IOException {
- if (!directory.exists()) {
- return;
- }
-
- cleanDirectory(directory);
- if (!directory.delete()) {
- String message =
- "Unable to delete directory " + directory + ".";
- throw new IOException(message);
- }
- }
-
- /**
- * Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
- * <p>
- * The difference between File.delete() and this method are:
- * <ul>
- * <li>A directory to be deleted does not have to be empty.</li>
- * <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
- * </ul>
- *
- * @param file file or directory to delete, can be <code>null</code>
- * @return <code>true</code> if the file or directory was deleted, otherwise
- * <code>false</code>
- *
- * @since Commons IO 1.4
- */
- public static boolean deleteQuietly(File file) {
- if (file == null) {
- return false;
- }
- try {
- if (file.isDirectory()) {
- cleanDirectory(file);
- }
- } catch (Exception e) {
- }
-
- try {
- return file.delete();
- } catch (Exception e) {
- return false;
- }
- }
-
- /**
- * Cleans a directory without deleting it.
- *
- * @param directory directory to clean
- * @throws IOException in case cleaning is unsuccessful
- */
- public static void cleanDirectory(File directory) throws IOException {
- if (!directory.exists()) {
- String message = directory + " does not exist";
- throw new IllegalArgumentException(message);
- }
-
- if (!directory.isDirectory()) {
- String message = directory + " is not a directory";
- throw new IllegalArgumentException(message);
- }
-
- File[] files = directory.listFiles();
- if (files == null) { // null if security restricted
- throw new IOException("Failed to list contents of " + directory);
- }
-
- IOException exception = null;
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
- try {
- forceDelete(file);
- } catch (IOException ioe) {
- exception = ioe;
- }
- }
-
- if (null != exception) {
- throw exception;
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Waits for NFS to propagate a file creation, imposing a timeout.
- * <p>
- * This method repeatedly tests {@link File#exists()} until it returns
- * true up to the maximum time specified in seconds.
- *
- * @param file the file to check, must not be <code>null</code>
- * @param seconds the maximum time in seconds to wait
- * @return true if file exists
- * @throws NullPointerException if the file is <code>null</code>
- */
- public static boolean waitFor(File file, int seconds) {
- int timeout = 0;
- int tick = 0;
- while (!file.exists()) {
- if (tick++ >= 10) {
- tick = 0;
- if (timeout++ > seconds) {
- return false;
- }
- }
- try {
- Thread.sleep(100);
- } catch (InterruptedException ignore) {
- // ignore exception
- } catch (Exception ex) {
- break;
- }
- }
- return true;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Reads the contents of a file into a String.
- * The file is always closed.
- *
- * @param file the file to read, must not be <code>null</code>
- * @param encoding the encoding to use, <code>null</code> means platform default
- * @return the file contents, never <code>null</code>
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
- */
- public static String readFileToString(File file, String encoding) throws IOException {
- InputStream in = null;
- try {
- in = openInputStream(file);
- return IOUtils.toString(in, encoding);
- } finally {
- IOUtils.closeQuietly(in);
- }
- }
-
-
- /**
- * Reads the contents of a file into a String using the default encoding for the VM.
- * The file is always closed.
- *
- * @param file the file to read, must not be <code>null</code>
- * @return the file contents, never <code>null</code>
- * @throws IOException in case of an I/O error
- * @since Commons IO 1.3.1
- */
- public static String readFileToString(File file) throws IOException {
- return readFileToString(file, null);
- }
-
- /**
- * Reads the contents of a file into a byte array.
- * The file is always closed.
- *
- * @param file the file to read, must not be <code>null</code>
- * @return the file contents, never <code>null</code>
- * @throws IOException in case of an I/O error
- * @since Commons IO 1.1
- */
- public static byte[] readFileToByteArray(File file) throws IOException {
- InputStream in = null;
- try {
- in = openInputStream(file);
- return IOUtils.toByteArray(in);
- } finally {
- IOUtils.closeQuietly(in);
- }
- }
-
- /**
- * Reads the contents of a file line by line to a List of Strings.
- * The file is always closed.
- *
- * @param file the file to read, must not be <code>null</code>
- * @param encoding the encoding to use, <code>null</code> means platform default
- * @return the list of Strings representing each line in the file, never <code>null</code>
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
- * @since Commons IO 1.1
- */
- public static List<String> readLines(File file, String encoding) throws IOException {
- InputStream in = null;
- try {
- in = openInputStream(file);
- return IOUtils.readLines(in, encoding);
- } finally {
- IOUtils.closeQuietly(in);
- }
- }
-
- /**
- * Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.
- * The file is always closed.
- *
- * @param file the file to read, must not be <code>null</code>
- * @return the list of Strings representing each line in the file, never <code>null</code>
- * @throws IOException in case of an I/O error
- * @since Commons IO 1.3
- */
- public static List<String> readLines(File file) throws IOException {
- return readLines(file, null);
- }
-
- /**
- * Returns an Iterator for the lines in a <code>File</code>.
- * <p>
- * This method opens an <code>InputStream</code> for the file.
- * When you have finished with the iterator you should close the stream
- * to free internal resources. This can be done by calling the
- * {@link LineIterator#close()} or
- * {@link LineIterator#closeQuietly(LineIterator)} method.
- * <p>
- * The recommended usage pattern is:
- * <pre>
- * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
- * try {
- * while (it.hasNext()) {
- * String line = it.nextLine();
- * /// do something with line
- * }
- * } finally {
- * LineIterator.closeQuietly(iterator);
- * }
- * </pre>
- * <p>
- * If an exception occurs during the creation of the iterator, the
- * underlying stream is closed.
- *
- * @param file the file to open for input, must not be <code>null</code>
- * @param encoding the encoding to use, <code>null</code> means platform default
- * @return an Iterator of the lines in the file, never <code>null</code>
- * @throws IOException in case of an I/O error (file closed)
- * @since Commons IO 1.2
- */
- public static LineIterator lineIterator(File file, String encoding) throws IOException {
- InputStream in = null;
- try {
- in = openInputStream(file);
- return IOUtils.lineIterator(in, encoding);
- } catch (IOException ex) {
- IOUtils.closeQuietly(in);
- throw ex;
- } catch (RuntimeException ex) {
- IOUtils.closeQuietly(in);
- throw ex;
- }
- }
-
- /**
- * Returns an Iterator for the lines in a <code>File</code> using the default encoding for the VM.
- *
- * @param file the file to open for input, must not be <code>null</code>
- * @return an Iterator of the lines in the file, never <code>null</code>
- * @throws IOException in case of an I/O error (file closed)
- * @since Commons IO 1.3
- * @see #lineIterator(File, String)
- */
- public static LineIterator lineIterator(File file) throws IOException {
- return lineIterator(file, null);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Writes a String to a file creating the file if it does not exist.
- *
- * NOTE: As from v1.3, the parent directories of the file will be created
- * if they do not exist.
- *
- * @param file the file to write
- * @param data the content to write to the file
- * @param encoding the encoding to use, <code>null</code> means platform default
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
- */
- public static void writeStringToFile(File file, String data, String encoding) throws IOException {
- OutputStream out = null;
- try {
- out = openOutputStream(file);
- IOUtils.write(data, out, encoding);
- } finally {
- IOUtils.closeQuietly(out);
- }
- }
-
- /**
- * Writes a String to a file creating the file if it does not exist using the default encoding for the VM.
- *
- * @param file the file to write
- * @param data the content to write to the file
- * @throws IOException in case of an I/O error
- */
- public static void writeStringToFile(File file, String data) throws IOException {
- writeStringToFile(file, data, null);
- }
-
- /**
- * Writes a byte array to a file creating the file if it does not exist.
- * <p>
- * NOTE: As from v1.3, the parent directories of the file will be created
- * if they do not exist.
- *
- * @param file the file to write to
- * @param data the content to write to the file
- * @throws IOException in case of an I/O error
- * @since Commons IO 1.1
- */
- public static void writeByteArrayToFile(File file, byte[] data) throws IOException {
- OutputStream out = null;
- try {
- out = openOutputStream(file);
- out.write(data);
- } finally {
- IOUtils.closeQuietly(out);
- }
- }
-
- /**
- * Writes the <code>toString()</code> value of each item in a collection to
- * the specified <code>File</code> line by line.
- * The specified character encoding and the default line ending will be used.
- * <p>
- * NOTE: As from v1.3, the parent directories of the file will be created
- * if they do not exist.
- *
- * @param file the file to write to
- * @param encoding the encoding to use, <code>null</code> means platform default
- * @param lines the lines to write, <code>null</code> entries produce blank lines
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
- * @since Commons IO 1.1
- */
- public static void writeLines(File file, String encoding, Collection<Object> lines) throws IOException {
- writeLines(file, encoding, lines, null);
- }
-
- /**
- * Writes the <code>toString()</code> value of each item in a collection to
- * the specified <code>File</code> line by line.
- * The default VM encoding and the default line ending will be used.
- *
- * @param file the file to write to
- * @param lines the lines to write, <code>null</code> entries produce blank lines
- * @throws IOException in case of an I/O error
- * @since Commons IO 1.3
- */
- public static void writeLines(File file, Collection<Object> lines) throws IOException {
- writeLines(file, null, lines, null);
- }
-
- /**
- * Writes the <code>toString()</code> value of each item in a collection to
- * the specified <code>File</code> line by line.
- * The specified character encoding and the line ending will be used.
- * <p>
- * NOTE: As from v1.3, the parent directories of the file will be created
- * if they do not exist.
- *
- * @param file the file to write to
- * @param encoding the encoding to use, <code>null</code> means platform default
- * @param lines the lines to write, <code>null</code> entries produce blank lines
- * @param lineEnding the line separator to use, <code>null</code> is system default
- * @throws IOException in case of an I/O error
- * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
- * @since Commons IO 1.1
- */
- public static void writeLines(File file, String encoding, Collection<Object> lines, String lineEnding) throws IOException {
- OutputStream out = null;
- try {
- out = openOutputStream(file);
- IOUtils.writeLines(lines, lineEnding, out, encoding);
- } finally {
- IOUtils.closeQuietly(out);
- }
- }
-
- /**
- * Writes the <code>toString()</code> value of each item in a collection to
- * the specified <code>File</code> line by line.
- * The default VM encoding and the specified line ending will be used.
- *
- * @param file the file to write to
- * @param lines the lines to write, <code>null</code> entries produce blank lines
- * @param lineEnding the line separator to use, <code>null</code> is system default
- * @throws IOException in case of an I/O error
- * @since Commons IO 1.3
- */
- public static void writeLines(File file, Collection<Object> lines, String lineEnding) throws IOException {
- writeLines(file, null, lines, lineEnding);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Deletes a file. If file is a directory, delete it and all sub-directories.
- * <p>
- * The difference between File.delete() and this method are:
- * <ul>
- * <li>A directory to be deleted does not have to be empty.</li>
- * <li>You get exceptions when a file or directory cannot be deleted.
- * (java.io.File methods returns a boolean)</li>
- * </ul>
- *
- * @param file file or directory to delete, must not be <code>null</code>
- * @throws NullPointerException if the directory is <code>null</code>
- * @throws FileNotFoundException if the file was not found
- * @throws IOException in case deletion is unsuccessful
- */
- public static void forceDelete(File file) throws IOException {
- if (file.isDirectory()) {
- deleteDirectory(file);
- } else {
- boolean filePresent = file.exists();
- if (!file.delete()) {
- if (!filePresent){
- throw new FileNotFoundException("File does not exist: " + file);
- }
- String message =
- "Unable to delete file: " + file;
- throw new IOException(message);
- }
- }
- }
-
- /**
- * Schedules a file to be deleted when JVM exits.
- * If file is directory delete it and all sub-directories.
- *
- * @param file file or directory to delete, must not be <code>null</code>
- * @throws NullPointerException if the file is <code>null</code>
- * @throws IOException in case deletion is unsuccessful
- */
- public static void forceDeleteOnExit(File file) throws IOException {
- if (file.isDirectory()) {
- deleteDirectoryOnExit(file);
- } else {
- file.deleteOnExit();
- }
- }
-
- /**
- * Schedules a directory recursively for deletion on JVM exit.
- *
- * @param directory directory to delete, must not be <code>null</code>
- * @throws NullPointerException if the directory is <code>null</code>
- * @throws IOException in case deletion is unsuccessful
- */
- private static void deleteDirectoryOnExit(File directory) throws IOException {
- if (!directory.exists()) {
- return;
- }
-
- cleanDirectoryOnExit(directory);
- directory.deleteOnExit();
- }
-
- /**
- * Cleans a directory without deleting it.
- *
- * @param directory directory to clean, must not be <code>null</code>
- * @throws NullPointerException if the directory is <code>null</code>
- * @throws IOException in case cleaning is unsuccessful
- */
- private static void cleanDirectoryOnExit(File directory) throws IOException {
- if (!directory.exists()) {
- String message = directory + " does not exist";
- throw new IllegalArgumentException(message);
- }
-
- if (!directory.isDirectory()) {
- String message = directory + " is not a directory";
- throw new IllegalArgumentException(message);
- }
-
- File[] files = directory.listFiles();
- if (files == null) { // null if security restricted
- throw new IOException("Failed to list contents of " + directory);
- }
-
- IOException exception = null;
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
- try {
- forceDeleteOnExit(file);
- } catch (IOException ioe) {
- exception = ioe;
- }
- }
-
- if (null != exception) {
- throw exception;
- }
- }
-
- /**
- * Makes a directory, including any necessary but nonexistent parent
- * directories. If there already exists a file with specified name or
- * the directory cannot be created then an exception is thrown.
- *
- * @param directory directory to create, must not be <code>null</code>
- * @throws NullPointerException if the directory is <code>null</code>
- * @throws IOException if the directory cannot be created
- */
- public static void forceMkdir(File directory) throws IOException {
- if (directory.exists()) {
- if (directory.isFile()) {
- String message =
- "File "
- + directory
- + " exists and is "
- + "not a directory. Unable to create directory.";
- throw new IOException(message);
- }
- } else {
- if (!directory.mkdirs()) {
- String message =
- "Unable to create directory " + directory;
- throw new IOException(message);
- }
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Counts the size of a directory recursively (sum of the length of all files).
- *
- * @param directory directory to inspect, must not be <code>null</code>
- * @return size of directory in bytes, 0 if directory is security restricted
- * @throws NullPointerException if the directory is <code>null</code>
- */
- public static long sizeOfDirectory(File directory) {
- if (!directory.exists()) {
- String message = directory + " does not exist";
- throw new IllegalArgumentException(message);
- }
-
- if (!directory.isDirectory()) {
- String message = directory + " is not a directory";
- throw new IllegalArgumentException(message);
- }
-
- long size = 0;
-
- File[] files = directory.listFiles();
- if (files == null) { // null if security restricted
- return 0L;
- }
- for (int i = 0; i < files.length; i++) {
- File file = files[i];
-
- if (file.isDirectory()) {
- size += sizeOfDirectory(file);
- } else {
- size += file.length();
- }
- }
-
- return size;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests if the specified <code>File</code> is newer than the reference
- * <code>File</code>.
- *
- * @param file the <code>File</code> of which the modification date must
- * be compared, must not be <code>null</code>
- * @param reference the <code>File</code> of which the modification date
- * is used, must not be <code>null</code>
- * @return true if the <code>File</code> exists and has been modified more
- * recently than the reference <code>File</code>
- * @throws IllegalArgumentException if the file is <code>null</code>
- * @throws IllegalArgumentException if the reference file is <code>null</code> or doesn't exist
- */
- public static boolean isFileNewer(File file, File reference) {
- if (reference == null) {
- throw new IllegalArgumentException("No specified reference file");
- }
- if (!reference.exists()) {
- throw new IllegalArgumentException("The reference file '"
- + file + "' doesn't exist");
- }
- return isFileNewer(file, reference.lastModified());
- }
-
- /**
- * Tests if the specified <code>File</code> is newer than the specified
- * <code>Date</code>.
- *
- * @param file the <code>File</code> of which the modification date
- * must be compared, must not be <code>null</code>
- * @param date the date reference, must not be <code>null</code>
- * @return true if the <code>File</code> exists and has been modified
- * after the given <code>Date</code>.
- * @throws IllegalArgumentException if the file is <code>null</code>
- * @throws IllegalArgumentException if the date is <code>null</code>
- */
- public static boolean isFileNewer(File file, Date date) {
- if (date == null) {
- throw new IllegalArgumentException("No specified date");
- }
- return isFileNewer(file, date.getTime());
- }
-
- /**
- * Tests if the specified <code>File</code> is newer than the specified
- * time reference.
- *
- * @param file the <code>File</code> of which the modification date must
- * be compared, must not be <code>null</code>
- * @param timeMillis the time reference measured in milliseconds since the
- * epoch (00:00:00 GMT, January 1, 1970)
- * @return true if the <code>File</code> exists and has been modified after
- * the given time reference.
- * @throws IllegalArgumentException if the file is <code>null</code>
- */
- public static boolean isFileNewer(File file, long timeMillis) {
- if (file == null) {
- throw new IllegalArgumentException("No specified file");
- }
- if (!file.exists()) {
- return false;
- }
- return file.lastModified() > timeMillis;
- }
-
-
- //-----------------------------------------------------------------------
- /**
- * Tests if the specified <code>File</code> is older than the reference
- * <code>File</code>.
- *
- * @param file the <code>File</code> of which the modification date must
- * be compared, must not be <code>null</code>
- * @param reference the <code>File</code> of which the modification date
- * is used, must not be <code>null</code>
- * @return true if the <code>File</code> exists and has been modified before
- * the reference <code>File</code>
- * @throws IllegalArgumentException if the file is <code>null</code>
- * @throws IllegalArgumentException if the reference file is <code>null</code> or doesn't exist
- */
- public static boolean isFileOlder(File file, File reference) {
- if (reference == null) {
- throw new IllegalArgumentException("No specified reference file");
- }
- if (!reference.exists()) {
- throw new IllegalArgumentException("The reference file '"
- + file + "' doesn't exist");
- }
- return isFileOlder(file, reference.lastModified());
- }
-
- /**
- * Tests if the specified <code>File</code> is older than the specified
- * <code>Date</code>.
- *
- * @param file the <code>File</code> of which the modification date
- * must be compared, must not be <code>null</code>
- * @param date the date reference, must not be <code>null</code>
- * @return true if the <code>File</code> exists and has been modified
- * before the given <code>Date</code>.
- * @throws IllegalArgumentException if the file is <code>null</code>
- * @throws IllegalArgumentException if the date is <code>null</code>
- */
- public static boolean isFileOlder(File file, Date date) {
- if (date == null) {
- throw new IllegalArgumentException("No specified date");
- }
- return isFileOlder(file, date.getTime());
- }
-
- /**
- * Tests if the specified <code>File</code> is older than the specified
- * time reference.
- *
- * @param file the <code>File</code> of which the modification date must
- * be compared, must not be <code>null</code>
- * @param timeMillis the time reference measured in milliseconds since the
- * epoch (00:00:00 GMT, January 1, 1970)
- * @return true if the <code>File</code> exists and has been modified before
- * the given time reference.
- * @throws IllegalArgumentException if the file is <code>null</code>
- */
- public static boolean isFileOlder(File file, long timeMillis) {
- if (file == null) {
- throw new IllegalArgumentException("No specified file");
- }
- if (!file.exists()) {
- return false;
- }
- return file.lastModified() < timeMillis;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Computes the checksum of a file using the CRC32 checksum routine.
- * The value of the checksum is returned.
- *
- * @param file the file to checksum, must not be <code>null</code>
- * @return the checksum value
- * @throws NullPointerException if the file or checksum is <code>null</code>
- * @throws IllegalArgumentException if the file is a directory
- * @throws IOException if an IO error occurs reading the file
- * @since Commons IO 1.3
- */
- public static long checksumCRC32(File file) throws IOException {
- CRC32 crc = new CRC32();
- checksum(file, crc);
- return crc.getValue();
- }
-
- /**
- * Computes the checksum of a file using the specified checksum object.
- * Multiple files may be checked using one <code>Checksum</code> instance
- * if desired simply by reusing the same checksum object.
- * For example:
- * <pre>
- * long csum = FileUtils.checksum(file, new CRC32()).getValue();
- * </pre>
- *
- * @param file the file to checksum, must not be <code>null</code>
- * @param checksum the checksum object to be used, must not be <code>null</code>
- * @return the checksum specified, updated with the content of the file
- * @throws NullPointerException if the file or checksum is <code>null</code>
- * @throws IllegalArgumentException if the file is a directory
- * @throws IOException if an IO error occurs reading the file
- * @since Commons IO 1.3
- */
- public static Checksum checksum(File file, Checksum checksum) throws IOException {
- if (file.isDirectory()) {
- throw new IllegalArgumentException("Checksums can't be computed on directories");
- }
- InputStream in = null;
- try {
- in = new CheckedInputStream(new FileInputStream(file), checksum);
- IOUtils.copy(in, new NullOutputStream());
- } finally {
- IOUtils.closeQuietly(in);
- }
- return checksum;
- }
-
- /**
- * Moves a directory.
- * <p>
- * When the destination directory is on another file system, do a "copy and delete".
- *
- * @param srcDir the directory to be moved
- * @param destDir the destination directory
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs moving the file
- * @since Commons IO 1.4
- */
- public static void moveDirectory(File srcDir, File destDir) throws IOException {
- if (srcDir == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (destDir == null) {
- throw new NullPointerException("Destination must not be null");
- }
- if (!srcDir.exists()) {
- throw new FileNotFoundException("Source '" + srcDir + "' does not exist");
- }
- if (!srcDir.isDirectory()) {
- throw new IOException("Source '" + srcDir + "' is not a directory");
- }
- if (destDir.exists()) {
- throw new IOException("Destination '" + destDir + "' already exists");
- }
- boolean rename = srcDir.renameTo(destDir);
- if (!rename) {
- copyDirectory( srcDir, destDir );
- deleteDirectory( srcDir );
- if (srcDir.exists()) {
- throw new IOException("Failed to delete original directory '" + srcDir +
- "' after copy to '" + destDir + "'");
- }
- }
- }
-
- /**
- * Moves a directory to another directory.
- *
- * @param src the file to be moved
- * @param destDir the destination file
- * @param createDestDir If <code>true</code> create the destination directory,
- * otherwise if <code>false</code> throw an IOException
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs moving the file
- * @since Commons IO 1.4
- */
- public static void moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) throws IOException {
- if (src == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (destDir == null) {
- throw new NullPointerException("Destination directory must not be null");
- }
- if (!destDir.exists() && createDestDir) {
- destDir.mkdirs();
- }
- if (!destDir.exists()) {
- throw new FileNotFoundException("Destination directory '" + destDir +
- "' does not exist [createDestDir=" + createDestDir +"]");
- }
- if (!destDir.isDirectory()) {
- throw new IOException("Destination '" + destDir + "' is not a directory");
- }
- moveDirectory(src, new File(destDir, src.getName()));
-
- }
-
- /**
- * Moves a file.
- * <p>
- * When the destination file is on another file system, do a "copy and delete".
- *
- * @param srcFile the file to be moved
- * @param destFile the destination file
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs moving the file
- * @since Commons IO 1.4
- */
- public static void moveFile(File srcFile, File destFile) throws IOException {
- if (srcFile == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (destFile == null) {
- throw new NullPointerException("Destination must not be null");
- }
- if (!srcFile.exists()) {
- throw new FileNotFoundException("Source '" + srcFile + "' does not exist");
- }
- if (srcFile.isDirectory()) {
- throw new IOException("Source '" + srcFile + "' is a directory");
- }
- if (destFile.exists()) {
- throw new IOException("Destination '" + destFile + "' already exists");
- }
- if (destFile.isDirectory()) {
- throw new IOException("Destination '" + destFile + "' is a directory");
- }
- boolean rename = srcFile.renameTo(destFile);
- if (!rename) {
- copyFile( srcFile, destFile );
- if (!srcFile.delete()) {
- FileUtils.deleteQuietly(destFile);
- throw new IOException("Failed to delete original file '" + srcFile +
- "' after copy to '" + destFile + "'");
- }
- }
- }
-
- /**
- * Moves a file to a directory.
- *
- * @param srcFile the file to be moved
- * @param destDir the destination file
- * @param createDestDir If <code>true</code> create the destination directory,
- * otherwise if <code>false</code> throw an IOException
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs moving the file
- * @since Commons IO 1.4
- */
- public static void moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) throws IOException {
- if (srcFile == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (destDir == null) {
- throw new NullPointerException("Destination directory must not be null");
- }
- if (!destDir.exists() && createDestDir) {
- destDir.mkdirs();
- }
- if (!destDir.exists()) {
- throw new FileNotFoundException("Destination directory '" + destDir +
- "' does not exist [createDestDir=" + createDestDir +"]");
- }
- if (!destDir.isDirectory()) {
- throw new IOException("Destination '" + destDir + "' is not a directory");
- }
- moveFile(srcFile, new File(destDir, srcFile.getName()));
- }
-
- /**
- * Moves a file or directory to the destination directory.
- * <p>
- * When the destination is on another file system, do a "copy and delete".
- *
- * @param src the file or directory to be moved
- * @param destDir the destination directory
- * @param createDestDir If <code>true</code> create the destination directory,
- * otherwise if <code>false</code> throw an IOException
- * @throws NullPointerException if source or destination is <code>null</code>
- * @throws IOException if source or destination is invalid
- * @throws IOException if an IO error occurs moving the file
- * @since Commons IO 1.4
- */
- public static void moveToDirectory(File src, File destDir, boolean createDestDir) throws IOException {
- if (src == null) {
- throw new NullPointerException("Source must not be null");
- }
- if (destDir == null) {
- throw new NullPointerException("Destination must not be null");
- }
- if (!src.exists()) {
- throw new FileNotFoundException("Source '" + src + "' does not exist");
- }
- if (src.isDirectory()) {
- moveDirectoryToDirectory(src, destDir, createDestDir);
- } else {
- moveFileToDirectory(src, destDir, createDestDir);
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/FilenameUtils.java b/emailcommon/src/org/apache/commons/io/FilenameUtils.java
deleted file mode 100644
index d8cc78b24..000000000
--- a/emailcommon/src/org/apache/commons/io/FilenameUtils.java
+++ /dev/null
@@ -1,1260 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.File;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Stack;
-
-/**
- * General filename and filepath manipulation utilities.
- * <p>
- * When dealing with filenames you can hit problems when moving from a Windows
- * based development machine to a Unix based production machine.
- * This class aims to help avoid those problems.
- * <p>
- * <b>NOTE</b>: You may be able to avoid using this class entirely simply by
- * using JDK {@link java.io.File File} objects and the two argument constructor
- * {@link java.io.File#File(java.io.File, java.lang.String) File(File,String)}.
- * <p>
- * Most methods on this class are designed to work the same on both Unix and Windows.
- * Those that don't include 'System', 'Unix' or 'Windows' in their name.
- * <p>
- * Most methods recognise both separators (forward and back), and both
- * sets of prefixes. See the javadoc of each method for details.
- * <p>
- * This class defines six components within a filename
- * (example C:\dev\project\file.txt):
- * <ul>
- * <li>the prefix - C:\</li>
- * <li>the path - dev\project\</li>
- * <li>the full path - C:\dev\project\</li>
- * <li>the name - file.txt</li>
- * <li>the base name - file</li>
- * <li>the extension - txt</li>
- * </ul>
- * Note that this class works best if directory filenames end with a separator.
- * If you omit the last separator, it is impossible to determine if the filename
- * corresponds to a file or a directory. As a result, we have chosen to say
- * it corresponds to a file.
- * <p>
- * This class only supports Unix and Windows style names.
- * Prefixes are matched as follows:
- * <pre>
- * Windows:
- * a\b\c.txt --> "" --> relative
- * \a\b\c.txt --> "\" --> current drive absolute
- * C:a\b\c.txt --> "C:" --> drive relative
- * C:\a\b\c.txt --> "C:\" --> absolute
- * \\server\a\b\c.txt --> "\\server\" --> UNC
- *
- * Unix:
- * a/b/c.txt --> "" --> relative
- * /a/b/c.txt --> "/" --> absolute
- * ~/a/b/c.txt --> "~/" --> current user
- * ~ --> "~/" --> current user (slash added)
- * ~user/a/b/c.txt --> "~user/" --> named user
- * ~user --> "~user/" --> named user (slash added)
- * </pre>
- * Both prefix styles are matched always, irrespective of the machine that you are
- * currently running on.
- * <p>
- * Origin of code: Excalibur, Alexandria, Tomcat, Commons-Utils.
- *
- * @author <a href="mailto:burton@relativity.yi.org">Kevin A. Burton</A>
- * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
- * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
- * @author <a href="mailto:Christoph.Reck@dlr.de">Christoph.Reck</a>
- * @author <a href="mailto:peter@apache.org">Peter Donald</a>
- * @author <a href="mailto:jefft@apache.org">Jeff Turner</a>
- * @author Matthew Hawthorne
- * @author Martin Cooper
- * @author <a href="mailto:jeremias@apache.org">Jeremias Maerki</a>
- * @author Stephen Colebourne
- * @version $Id: FilenameUtils.java 609870 2008-01-08 04:46:26Z niallp $
- * @since Commons IO 1.1
- */
-public class FilenameUtils {
-
- /**
- * The extension separator character.
- * @since Commons IO 1.4
- */
- public static final char EXTENSION_SEPARATOR = '.';
-
- /**
- * The extension separator String.
- * @since Commons IO 1.4
- */
- public static final String EXTENSION_SEPARATOR_STR = (new Character(EXTENSION_SEPARATOR)).toString();
-
- /**
- * The Unix separator character.
- */
- private static final char UNIX_SEPARATOR = '/';
-
- /**
- * The Windows separator character.
- */
- private static final char WINDOWS_SEPARATOR = '\\';
-
- /**
- * The system separator character.
- */
- private static final char SYSTEM_SEPARATOR = File.separatorChar;
-
- /**
- * The separator character that is the opposite of the system separator.
- */
- private static final char OTHER_SEPARATOR;
- static {
- if (isSystemWindows()) {
- OTHER_SEPARATOR = UNIX_SEPARATOR;
- } else {
- OTHER_SEPARATOR = WINDOWS_SEPARATOR;
- }
- }
-
- /**
- * Instances should NOT be constructed in standard programming.
- */
- public FilenameUtils() {
- super();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Determines if Windows file system is in use.
- *
- * @return true if the system is Windows
- */
- static boolean isSystemWindows() {
- return SYSTEM_SEPARATOR == WINDOWS_SEPARATOR;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks if the character is a separator.
- *
- * @param ch the character to check
- * @return true if it is a separator character
- */
- private static boolean isSeparator(char ch) {
- return (ch == UNIX_SEPARATOR) || (ch == WINDOWS_SEPARATOR);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Normalizes a path, removing double and single dot path steps.
- * <p>
- * This method normalizes a path to a standard format.
- * The input may contain separators in either Unix or Windows format.
- * The output will contain separators in the format of the system.
- * <p>
- * A trailing slash will be retained.
- * A double slash will be merged to a single slash (but UNC names are handled).
- * A single dot path segment will be removed.
- * A double dot will cause that path segment and the one before to be removed.
- * If the double dot has no parent path segment to work with, <code>null</code>
- * is returned.
- * <p>
- * The output will be the same on both Unix and Windows except
- * for the separator character.
- * <pre>
- * /foo// --> /foo/
- * /foo/./ --> /foo/
- * /foo/../bar --> /bar
- * /foo/../bar/ --> /bar/
- * /foo/../bar/../baz --> /baz
- * //foo//./bar --> /foo/bar
- * /../ --> null
- * ../foo --> null
- * foo/bar/.. --> foo/
- * foo/../../bar --> null
- * foo/../bar --> bar
- * //server/foo/../bar --> //server/bar
- * //server/../bar --> null
- * C:\foo\..\bar --> C:\bar
- * C:\..\bar --> null
- * ~/foo/../bar/ --> ~/bar/
- * ~/../bar --> null
- * </pre>
- * (Note the file separator returned will be correct for Windows/Unix)
- *
- * @param filename the filename to normalize, null returns null
- * @return the normalized filename, or null if invalid
- */
- public static String normalize(String filename) {
- return doNormalize(filename, true);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Normalizes a path, removing double and single dot path steps,
- * and removing any final directory separator.
- * <p>
- * This method normalizes a path to a standard format.
- * The input may contain separators in either Unix or Windows format.
- * The output will contain separators in the format of the system.
- * <p>
- * A trailing slash will be removed.
- * A double slash will be merged to a single slash (but UNC names are handled).
- * A single dot path segment will be removed.
- * A double dot will cause that path segment and the one before to be removed.
- * If the double dot has no parent path segment to work with, <code>null</code>
- * is returned.
- * <p>
- * The output will be the same on both Unix and Windows except
- * for the separator character.
- * <pre>
- * /foo// --> /foo
- * /foo/./ --> /foo
- * /foo/../bar --> /bar
- * /foo/../bar/ --> /bar
- * /foo/../bar/../baz --> /baz
- * //foo//./bar --> /foo/bar
- * /../ --> null
- * ../foo --> null
- * foo/bar/.. --> foo
- * foo/../../bar --> null
- * foo/../bar --> bar
- * //server/foo/../bar --> //server/bar
- * //server/../bar --> null
- * C:\foo\..\bar --> C:\bar
- * C:\..\bar --> null
- * ~/foo/../bar/ --> ~/bar
- * ~/../bar --> null
- * </pre>
- * (Note the file separator returned will be correct for Windows/Unix)
- *
- * @param filename the filename to normalize, null returns null
- * @return the normalized filename, or null if invalid
- */
- public static String normalizeNoEndSeparator(String filename) {
- return doNormalize(filename, false);
- }
-
- /**
- * Internal method to perform the normalization.
- *
- * @param filename the filename
- * @param keepSeparator true to keep the final separator
- * @return the normalized filename
- */
- private static String doNormalize(String filename, boolean keepSeparator) {
- if (filename == null) {
- return null;
- }
- int size = filename.length();
- if (size == 0) {
- return filename;
- }
- int prefix = getPrefixLength(filename);
- if (prefix < 0) {
- return null;
- }
-
- char[] array = new char[size + 2]; // +1 for possible extra slash, +2 for arraycopy
- filename.getChars(0, filename.length(), array, 0);
-
- // fix separators throughout
- for (int i = 0; i < array.length; i++) {
- if (array[i] == OTHER_SEPARATOR) {
- array[i] = SYSTEM_SEPARATOR;
- }
- }
-
- // add extra separator on the end to simplify code below
- boolean lastIsDirectory = true;
- if (array[size - 1] != SYSTEM_SEPARATOR) {
- array[size++] = SYSTEM_SEPARATOR;
- lastIsDirectory = false;
- }
-
- // adjoining slashes
- for (int i = prefix + 1; i < size; i++) {
- if (array[i] == SYSTEM_SEPARATOR && array[i - 1] == SYSTEM_SEPARATOR) {
- System.arraycopy(array, i, array, i - 1, size - i);
- size--;
- i--;
- }
- }
-
- // dot slash
- for (int i = prefix + 1; i < size; i++) {
- if (array[i] == SYSTEM_SEPARATOR && array[i - 1] == '.' &&
- (i == prefix + 1 || array[i - 2] == SYSTEM_SEPARATOR)) {
- if (i == size - 1) {
- lastIsDirectory = true;
- }
- System.arraycopy(array, i + 1, array, i - 1, size - i);
- size -=2;
- i--;
- }
- }
-
- // double dot slash
- outer:
- for (int i = prefix + 2; i < size; i++) {
- if (array[i] == SYSTEM_SEPARATOR && array[i - 1] == '.' && array[i - 2] == '.' &&
- (i == prefix + 2 || array[i - 3] == SYSTEM_SEPARATOR)) {
- if (i == prefix + 2) {
- return null;
- }
- if (i == size - 1) {
- lastIsDirectory = true;
- }
- int j;
- for (j = i - 4 ; j >= prefix; j--) {
- if (array[j] == SYSTEM_SEPARATOR) {
- // remove b/../ from a/b/../c
- System.arraycopy(array, i + 1, array, j + 1, size - i);
- size -= (i - j);
- i = j + 1;
- continue outer;
- }
- }
- // remove a/../ from a/../c
- System.arraycopy(array, i + 1, array, prefix, size - i);
- size -= (i + 1 - prefix);
- i = prefix + 1;
- }
- }
-
- if (size <= 0) { // should never be less than 0
- return "";
- }
- if (size <= prefix) { // should never be less than prefix
- return new String(array, 0, size);
- }
- if (lastIsDirectory && keepSeparator) {
- return new String(array, 0, size); // keep trailing separator
- }
- return new String(array, 0, size - 1); // lose trailing separator
- }
-
- //-----------------------------------------------------------------------
- /**
- * Concatenates a filename to a base path using normal command line style rules.
- * <p>
- * The effect is equivalent to resultant directory after changing
- * directory to the first argument, followed by changing directory to
- * the second argument.
- * <p>
- * The first argument is the base path, the second is the path to concatenate.
- * The returned path is always normalized via {@link #normalize(String)},
- * thus <code>..</code> is handled.
- * <p>
- * If <code>pathToAdd</code> is absolute (has an absolute prefix), then
- * it will be normalized and returned.
- * Otherwise, the paths will be joined, normalized and returned.
- * <p>
- * The output will be the same on both Unix and Windows except
- * for the separator character.
- * <pre>
- * /foo/ + bar --> /foo/bar
- * /foo + bar --> /foo/bar
- * /foo + /bar --> /bar
- * /foo + C:/bar --> C:/bar
- * /foo + C:bar --> C:bar (*)
- * /foo/a/ + ../bar --> foo/bar
- * /foo/ + ../../bar --> null
- * /foo/ + /bar --> /bar
- * /foo/.. + /bar --> /bar
- * /foo + bar/c.txt --> /foo/bar/c.txt
- * /foo/c.txt + bar --> /foo/c.txt/bar (!)
- * </pre>
- * (*) Note that the Windows relative drive prefix is unreliable when
- * used with this method.
- * (!) Note that the first parameter must be a path. If it ends with a name, then
- * the name will be built into the concatenated path. If this might be a problem,
- * use {@link #getFullPath(String)} on the base path argument.
- *
- * @param basePath the base path to attach to, always treated as a path
- * @param fullFilenameToAdd the filename (or path) to attach to the base
- * @return the concatenated path, or null if invalid
- */
- public static String concat(String basePath, String fullFilenameToAdd) {
- int prefix = getPrefixLength(fullFilenameToAdd);
- if (prefix < 0) {
- return null;
- }
- if (prefix > 0) {
- return normalize(fullFilenameToAdd);
- }
- if (basePath == null) {
- return null;
- }
- int len = basePath.length();
- if (len == 0) {
- return normalize(fullFilenameToAdd);
- }
- char ch = basePath.charAt(len - 1);
- if (isSeparator(ch)) {
- return normalize(basePath + fullFilenameToAdd);
- } else {
- return normalize(basePath + '/' + fullFilenameToAdd);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Converts all separators to the Unix separator of forward slash.
- *
- * @param path the path to be changed, null ignored
- * @return the updated path
- */
- public static String separatorsToUnix(String path) {
- if (path == null || path.indexOf(WINDOWS_SEPARATOR) == -1) {
- return path;
- }
- return path.replace(WINDOWS_SEPARATOR, UNIX_SEPARATOR);
- }
-
- /**
- * Converts all separators to the Windows separator of backslash.
- *
- * @param path the path to be changed, null ignored
- * @return the updated path
- */
- public static String separatorsToWindows(String path) {
- if (path == null || path.indexOf(UNIX_SEPARATOR) == -1) {
- return path;
- }
- return path.replace(UNIX_SEPARATOR, WINDOWS_SEPARATOR);
- }
-
- /**
- * Converts all separators to the system separator.
- *
- * @param path the path to be changed, null ignored
- * @return the updated path
- */
- public static String separatorsToSystem(String path) {
- if (path == null) {
- return null;
- }
- if (isSystemWindows()) {
- return separatorsToWindows(path);
- } else {
- return separatorsToUnix(path);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns the length of the filename prefix, such as <code>C:/</code> or <code>~/</code>.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * <p>
- * The prefix length includes the first slash in the full filename
- * if applicable. Thus, it is possible that the length returned is greater
- * than the length of the input string.
- * <pre>
- * Windows:
- * a\b\c.txt --> "" --> relative
- * \a\b\c.txt --> "\" --> current drive absolute
- * C:a\b\c.txt --> "C:" --> drive relative
- * C:\a\b\c.txt --> "C:\" --> absolute
- * \\server\a\b\c.txt --> "\\server\" --> UNC
- *
- * Unix:
- * a/b/c.txt --> "" --> relative
- * /a/b/c.txt --> "/" --> absolute
- * ~/a/b/c.txt --> "~/" --> current user
- * ~ --> "~/" --> current user (slash added)
- * ~user/a/b/c.txt --> "~user/" --> named user
- * ~user --> "~user/" --> named user (slash added)
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- * ie. both Unix and Windows prefixes are matched regardless.
- *
- * @param filename the filename to find the prefix in, null returns -1
- * @return the length of the prefix, -1 if invalid or null
- */
- public static int getPrefixLength(String filename) {
- if (filename == null) {
- return -1;
- }
- int len = filename.length();
- if (len == 0) {
- return 0;
- }
- char ch0 = filename.charAt(0);
- if (ch0 == ':') {
- return -1;
- }
- if (len == 1) {
- if (ch0 == '~') {
- return 2; // return a length greater than the input
- }
- return (isSeparator(ch0) ? 1 : 0);
- } else {
- if (ch0 == '~') {
- int posUnix = filename.indexOf(UNIX_SEPARATOR, 1);
- int posWin = filename.indexOf(WINDOWS_SEPARATOR, 1);
- if (posUnix == -1 && posWin == -1) {
- return len + 1; // return a length greater than the input
- }
- posUnix = (posUnix == -1 ? posWin : posUnix);
- posWin = (posWin == -1 ? posUnix : posWin);
- return Math.min(posUnix, posWin) + 1;
- }
- char ch1 = filename.charAt(1);
- if (ch1 == ':') {
- ch0 = Character.toUpperCase(ch0);
- if (ch0 >= 'A' && ch0 <= 'Z') {
- if (len == 2 || isSeparator(filename.charAt(2)) == false) {
- return 2;
- }
- return 3;
- }
- return -1;
-
- } else if (isSeparator(ch0) && isSeparator(ch1)) {
- int posUnix = filename.indexOf(UNIX_SEPARATOR, 2);
- int posWin = filename.indexOf(WINDOWS_SEPARATOR, 2);
- if ((posUnix == -1 && posWin == -1) || posUnix == 2 || posWin == 2) {
- return -1;
- }
- posUnix = (posUnix == -1 ? posWin : posUnix);
- posWin = (posWin == -1 ? posUnix : posWin);
- return Math.min(posUnix, posWin) + 1;
- } else {
- return (isSeparator(ch0) ? 1 : 0);
- }
- }
- }
-
- /**
- * Returns the index of the last directory separator character.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The position of the last forward or backslash is returned.
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to find the last path separator in, null returns -1
- * @return the index of the last separator character, or -1 if there
- * is no such character
- */
- public static int indexOfLastSeparator(String filename) {
- if (filename == null) {
- return -1;
- }
- int lastUnixPos = filename.lastIndexOf(UNIX_SEPARATOR);
- int lastWindowsPos = filename.lastIndexOf(WINDOWS_SEPARATOR);
- return Math.max(lastUnixPos, lastWindowsPos);
- }
-
- /**
- * Returns the index of the last extension separator character, which is a dot.
- * <p>
- * This method also checks that there is no directory separator after the last dot.
- * To do this it uses {@link #indexOfLastSeparator(String)} which will
- * handle a file in either Unix or Windows format.
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to find the last path separator in, null returns -1
- * @return the index of the last separator character, or -1 if there
- * is no such character
- */
- public static int indexOfExtension(String filename) {
- if (filename == null) {
- return -1;
- }
- int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);
- int lastSeparator = indexOfLastSeparator(filename);
- return (lastSeparator > extensionPos ? -1 : extensionPos);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Gets the prefix from a full filename, such as <code>C:/</code>
- * or <code>~/</code>.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The prefix includes the first slash in the full filename where applicable.
- * <pre>
- * Windows:
- * a\b\c.txt --> "" --> relative
- * \a\b\c.txt --> "\" --> current drive absolute
- * C:a\b\c.txt --> "C:" --> drive relative
- * C:\a\b\c.txt --> "C:\" --> absolute
- * \\server\a\b\c.txt --> "\\server\" --> UNC
- *
- * Unix:
- * a/b/c.txt --> "" --> relative
- * /a/b/c.txt --> "/" --> absolute
- * ~/a/b/c.txt --> "~/" --> current user
- * ~ --> "~/" --> current user (slash added)
- * ~user/a/b/c.txt --> "~user/" --> named user
- * ~user --> "~user/" --> named user (slash added)
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- * ie. both Unix and Windows prefixes are matched regardless.
- *
- * @param filename the filename to query, null returns null
- * @return the prefix of the file, null if invalid
- */
- public static String getPrefix(String filename) {
- if (filename == null) {
- return null;
- }
- int len = getPrefixLength(filename);
- if (len < 0) {
- return null;
- }
- if (len > filename.length()) {
- return filename + UNIX_SEPARATOR; // we know this only happens for unix
- }
- return filename.substring(0, len);
- }
-
- /**
- * Gets the path from a full filename, which excludes the prefix.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before and
- * including the last forward or backslash.
- * <pre>
- * C:\a\b\c.txt --> a\b\
- * ~/a/b/c.txt --> a/b/
- * a.txt --> ""
- * a/b/c --> a/b/
- * a/b/c/ --> a/b/c/
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- * <p>
- * This method drops the prefix from the result.
- * See {@link #getFullPath(String)} for the method that retains the prefix.
- *
- * @param filename the filename to query, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- */
- public static String getPath(String filename) {
- return doGetPath(filename, 1);
- }
-
- /**
- * Gets the path from a full filename, which excludes the prefix, and
- * also excluding the final directory separator.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before the
- * last forward or backslash.
- * <pre>
- * C:\a\b\c.txt --> a\b
- * ~/a/b/c.txt --> a/b
- * a.txt --> ""
- * a/b/c --> a/b
- * a/b/c/ --> a/b/c
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- * <p>
- * This method drops the prefix from the result.
- * See {@link #getFullPathNoEndSeparator(String)} for the method that retains the prefix.
- *
- * @param filename the filename to query, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- */
- public static String getPathNoEndSeparator(String filename) {
- return doGetPath(filename, 0);
- }
-
- /**
- * Does the work of getting the path.
- *
- * @param filename the filename
- * @param separatorAdd 0 to omit the end separator, 1 to return it
- * @return the path
- */
- private static String doGetPath(String filename, int separatorAdd) {
- if (filename == null) {
- return null;
- }
- int prefix = getPrefixLength(filename);
- if (prefix < 0) {
- return null;
- }
- int index = indexOfLastSeparator(filename);
- if (prefix >= filename.length() || index < 0) {
- return "";
- }
- return filename.substring(prefix, index + separatorAdd);
- }
-
- /**
- * Gets the full path from a full filename, which is the prefix + path.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before and
- * including the last forward or backslash.
- * <pre>
- * C:\a\b\c.txt --> C:\a\b\
- * ~/a/b/c.txt --> ~/a/b/
- * a.txt --> ""
- * a/b/c --> a/b/
- * a/b/c/ --> a/b/c/
- * C: --> C:
- * C:\ --> C:\
- * ~ --> ~/
- * ~/ --> ~/
- * ~user --> ~user/
- * ~user/ --> ~user/
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to query, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- */
- public static String getFullPath(String filename) {
- return doGetFullPath(filename, true);
- }
-
- /**
- * Gets the full path from a full filename, which is the prefix + path,
- * and also excluding the final directory separator.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The method is entirely text based, and returns the text before the
- * last forward or backslash.
- * <pre>
- * C:\a\b\c.txt --> C:\a\b
- * ~/a/b/c.txt --> ~/a/b
- * a.txt --> ""
- * a/b/c --> a/b
- * a/b/c/ --> a/b/c
- * C: --> C:
- * C:\ --> C:\
- * ~ --> ~
- * ~/ --> ~
- * ~user --> ~user
- * ~user/ --> ~user
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to query, null returns null
- * @return the path of the file, an empty string if none exists, null if invalid
- */
- public static String getFullPathNoEndSeparator(String filename) {
- return doGetFullPath(filename, false);
- }
-
- /**
- * Does the work of getting the path.
- *
- * @param filename the filename
- * @param includeSeparator true to include the end separator
- * @return the path
- */
- private static String doGetFullPath(String filename, boolean includeSeparator) {
- if (filename == null) {
- return null;
- }
- int prefix = getPrefixLength(filename);
- if (prefix < 0) {
- return null;
- }
- if (prefix >= filename.length()) {
- if (includeSeparator) {
- return getPrefix(filename); // add end slash if necessary
- } else {
- return filename;
- }
- }
- int index = indexOfLastSeparator(filename);
- if (index < 0) {
- return filename.substring(0, prefix);
- }
- int end = index + (includeSeparator ? 1 : 0);
- return filename.substring(0, end);
- }
-
- /**
- * Gets the name minus the path from a full filename.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The text after the last forward or backslash is returned.
- * <pre>
- * a/b/c.txt --> c.txt
- * a.txt --> a.txt
- * a/b/c --> c
- * a/b/c/ --> ""
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to query, null returns null
- * @return the name of the file without the path, or an empty string if none exists
- */
- public static String getName(String filename) {
- if (filename == null) {
- return null;
- }
- int index = indexOfLastSeparator(filename);
- return filename.substring(index + 1);
- }
-
- /**
- * Gets the base name, minus the full path and extension, from a full filename.
- * <p>
- * This method will handle a file in either Unix or Windows format.
- * The text after the last forward or backslash and before the last dot is returned.
- * <pre>
- * a/b/c.txt --> c
- * a.txt --> a
- * a/b/c --> c
- * a/b/c/ --> ""
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to query, null returns null
- * @return the name of the file without the path, or an empty string if none exists
- */
- public static String getBaseName(String filename) {
- return removeExtension(getName(filename));
- }
-
- /**
- * Gets the extension of a filename.
- * <p>
- * This method returns the textual part of the filename after the last dot.
- * There must be no directory separator after the dot.
- * <pre>
- * foo.txt --> "txt"
- * a/b/c.jpg --> "jpg"
- * a/b.txt/c --> ""
- * a/b/c --> ""
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to retrieve the extension of.
- * @return the extension of the file or an empty string if none exists.
- */
- public static String getExtension(String filename) {
- if (filename == null) {
- return null;
- }
- int index = indexOfExtension(filename);
- if (index == -1) {
- return "";
- } else {
- return filename.substring(index + 1);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Removes the extension from a filename.
- * <p>
- * This method returns the textual part of the filename before the last dot.
- * There must be no directory separator after the dot.
- * <pre>
- * foo.txt --> foo
- * a\b\c.jpg --> a\b\c
- * a\b\c --> a\b\c
- * a.b\c --> a.b\c
- * </pre>
- * <p>
- * The output will be the same irrespective of the machine that the code is running on.
- *
- * @param filename the filename to query, null returns null
- * @return the filename minus the extension
- */
- public static String removeExtension(String filename) {
- if (filename == null) {
- return null;
- }
- int index = indexOfExtension(filename);
- if (index == -1) {
- return filename;
- } else {
- return filename.substring(0, index);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks whether two filenames are equal exactly.
- * <p>
- * No processing is performed on the filenames other than comparison,
- * thus this is merely a null-safe case-sensitive equals.
- *
- * @param filename1 the first filename to query, may be null
- * @param filename2 the second filename to query, may be null
- * @return true if the filenames are equal, null equals null
- * @see IOCase#SENSITIVE
- */
- public static boolean equals(String filename1, String filename2) {
- return equals(filename1, filename2, false, IOCase.SENSITIVE);
- }
-
- /**
- * Checks whether two filenames are equal using the case rules of the system.
- * <p>
- * No processing is performed on the filenames other than comparison.
- * The check is case-sensitive on Unix and case-insensitive on Windows.
- *
- * @param filename1 the first filename to query, may be null
- * @param filename2 the second filename to query, may be null
- * @return true if the filenames are equal, null equals null
- * @see IOCase#SYSTEM
- */
- public static boolean equalsOnSystem(String filename1, String filename2) {
- return equals(filename1, filename2, false, IOCase.SYSTEM);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks whether two filenames are equal after both have been normalized.
- * <p>
- * Both filenames are first passed to {@link #normalize(String)}.
- * The check is then performed in a case-sensitive manner.
- *
- * @param filename1 the first filename to query, may be null
- * @param filename2 the second filename to query, may be null
- * @return true if the filenames are equal, null equals null
- * @see IOCase#SENSITIVE
- */
- public static boolean equalsNormalized(String filename1, String filename2) {
- return equals(filename1, filename2, true, IOCase.SENSITIVE);
- }
-
- /**
- * Checks whether two filenames are equal after both have been normalized
- * and using the case rules of the system.
- * <p>
- * Both filenames are first passed to {@link #normalize(String)}.
- * The check is then performed case-sensitive on Unix and
- * case-insensitive on Windows.
- *
- * @param filename1 the first filename to query, may be null
- * @param filename2 the second filename to query, may be null
- * @return true if the filenames are equal, null equals null
- * @see IOCase#SYSTEM
- */
- public static boolean equalsNormalizedOnSystem(String filename1, String filename2) {
- return equals(filename1, filename2, true, IOCase.SYSTEM);
- }
-
- /**
- * Checks whether two filenames are equal, optionally normalizing and providing
- * control over the case-sensitivity.
- *
- * @param filename1 the first filename to query, may be null
- * @param filename2 the second filename to query, may be null
- * @param normalized whether to normalize the filenames
- * @param caseSensitivity what case sensitivity rule to use, null means case-sensitive
- * @return true if the filenames are equal, null equals null
- * @since Commons IO 1.3
- */
- public static boolean equals(
- String filename1, String filename2,
- boolean normalized, IOCase caseSensitivity) {
-
- if (filename1 == null || filename2 == null) {
- return filename1 == filename2;
- }
- if (normalized) {
- filename1 = normalize(filename1);
- filename2 = normalize(filename2);
- if (filename1 == null || filename2 == null) {
- throw new NullPointerException(
- "Error normalizing one or both of the file names");
- }
- }
- if (caseSensitivity == null) {
- caseSensitivity = IOCase.SENSITIVE;
- }
- return caseSensitivity.checkEquals(filename1, filename2);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks whether the extension of the filename is that specified.
- * <p>
- * This method obtains the extension as the textual part of the filename
- * after the last dot. There must be no directory separator after the dot.
- * The extension check is case-sensitive on all platforms.
- *
- * @param filename the filename to query, null returns false
- * @param extension the extension to check for, null or empty checks for no extension
- * @return true if the filename has the specified extension
- */
- public static boolean isExtension(String filename, String extension) {
- if (filename == null) {
- return false;
- }
- if (extension == null || extension.length() == 0) {
- return (indexOfExtension(filename) == -1);
- }
- String fileExt = getExtension(filename);
- return fileExt.equals(extension);
- }
-
- /**
- * Checks whether the extension of the filename is one of those specified.
- * <p>
- * This method obtains the extension as the textual part of the filename
- * after the last dot. There must be no directory separator after the dot.
- * The extension check is case-sensitive on all platforms.
- *
- * @param filename the filename to query, null returns false
- * @param extensions the extensions to check for, null checks for no extension
- * @return true if the filename is one of the extensions
- */
- public static boolean isExtension(String filename, String[] extensions) {
- if (filename == null) {
- return false;
- }
- if (extensions == null || extensions.length == 0) {
- return (indexOfExtension(filename) == -1);
- }
- String fileExt = getExtension(filename);
- for (int i = 0; i < extensions.length; i++) {
- if (fileExt.equals(extensions[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Checks whether the extension of the filename is one of those specified.
- * <p>
- * This method obtains the extension as the textual part of the filename
- * after the last dot. There must be no directory separator after the dot.
- * The extension check is case-sensitive on all platforms.
- *
- * @param filename the filename to query, null returns false
- * @param extensions the extensions to check for, null checks for no extension
- * @return true if the filename is one of the extensions
- */
- public static boolean isExtension(String filename, Collection<String> extensions) {
- if (filename == null) {
- return false;
- }
- if (extensions == null || extensions.isEmpty()) {
- return (indexOfExtension(filename) == -1);
- }
- String fileExt = getExtension(filename);
- for (Iterator<String> it = extensions.iterator(); it.hasNext();) {
- if (fileExt.equals(it.next())) {
- return true;
- }
- }
- return false;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks a filename to see if it matches the specified wildcard matcher,
- * always testing case-sensitive.
- * <p>
- * The wildcard matcher uses the characters '?' and '*' to represent a
- * single or multiple wildcard characters.
- * This is the same as often found on Dos/Unix command lines.
- * The check is case-sensitive always.
- * <pre>
- * wildcardMatch("c.txt", "*.txt") --> true
- * wildcardMatch("c.txt", "*.jpg") --> false
- * wildcardMatch("a/b/c.txt", "a/b/*") --> true
- * wildcardMatch("c.txt", "*.???") --> true
- * wildcardMatch("c.txt", "*.????") --> false
- * </pre>
- *
- * @param filename the filename to match on
- * @param wildcardMatcher the wildcard string to match against
- * @return true if the filename matches the wilcard string
- * @see IOCase#SENSITIVE
- */
- public static boolean wildcardMatch(String filename, String wildcardMatcher) {
- return wildcardMatch(filename, wildcardMatcher, IOCase.SENSITIVE);
- }
-
- /**
- * Checks a filename to see if it matches the specified wildcard matcher
- * using the case rules of the system.
- * <p>
- * The wildcard matcher uses the characters '?' and '*' to represent a
- * single or multiple wildcard characters.
- * This is the same as often found on Dos/Unix command lines.
- * The check is case-sensitive on Unix and case-insensitive on Windows.
- * <pre>
- * wildcardMatch("c.txt", "*.txt") --> true
- * wildcardMatch("c.txt", "*.jpg") --> false
- * wildcardMatch("a/b/c.txt", "a/b/*") --> true
- * wildcardMatch("c.txt", "*.???") --> true
- * wildcardMatch("c.txt", "*.????") --> false
- * </pre>
- *
- * @param filename the filename to match on
- * @param wildcardMatcher the wildcard string to match against
- * @return true if the filename matches the wilcard string
- * @see IOCase#SYSTEM
- */
- public static boolean wildcardMatchOnSystem(String filename, String wildcardMatcher) {
- return wildcardMatch(filename, wildcardMatcher, IOCase.SYSTEM);
- }
-
- /**
- * Checks a filename to see if it matches the specified wildcard matcher
- * allowing control over case-sensitivity.
- * <p>
- * The wildcard matcher uses the characters '?' and '*' to represent a
- * single or multiple wildcard characters.
- *
- * @param filename the filename to match on
- * @param wildcardMatcher the wildcard string to match against
- * @param caseSensitivity what case sensitivity rule to use, null means case-sensitive
- * @return true if the filename matches the wilcard string
- * @since Commons IO 1.3
- */
- public static boolean wildcardMatch(String filename, String wildcardMatcher, IOCase caseSensitivity) {
- if (filename == null && wildcardMatcher == null) {
- return true;
- }
- if (filename == null || wildcardMatcher == null) {
- return false;
- }
- if (caseSensitivity == null) {
- caseSensitivity = IOCase.SENSITIVE;
- }
- filename = caseSensitivity.convertCase(filename);
- wildcardMatcher = caseSensitivity.convertCase(wildcardMatcher);
- String[] wcs = splitOnTokens(wildcardMatcher);
- boolean anyChars = false;
- int textIdx = 0;
- int wcsIdx = 0;
- Stack<int[]> backtrack = new Stack<int[]>();
-
- // loop around a backtrack stack, to handle complex * matching
- do {
- if (backtrack.size() > 0) {
- int[] array = backtrack.pop();
- wcsIdx = array[0];
- textIdx = array[1];
- anyChars = true;
- }
-
- // loop whilst tokens and text left to process
- while (wcsIdx < wcs.length) {
-
- if (wcs[wcsIdx].equals("?")) {
- // ? so move to next text char
- textIdx++;
- anyChars = false;
-
- } else if (wcs[wcsIdx].equals("*")) {
- // set any chars status
- anyChars = true;
- if (wcsIdx == wcs.length - 1) {
- textIdx = filename.length();
- }
-
- } else {
- // matching text token
- if (anyChars) {
- // any chars then try to locate text token
- textIdx = filename.indexOf(wcs[wcsIdx], textIdx);
- if (textIdx == -1) {
- // token not found
- break;
- }
- int repeat = filename.indexOf(wcs[wcsIdx], textIdx + 1);
- if (repeat >= 0) {
- backtrack.push(new int[] {wcsIdx, repeat});
- }
- } else {
- // matching from current position
- if (!filename.startsWith(wcs[wcsIdx], textIdx)) {
- // couldnt match token
- break;
- }
- }
-
- // matched text token, move text index to end of matched token
- textIdx += wcs[wcsIdx].length();
- anyChars = false;
- }
-
- wcsIdx++;
- }
-
- // full match
- if (wcsIdx == wcs.length && textIdx == filename.length()) {
- return true;
- }
-
- } while (backtrack.size() > 0);
-
- return false;
- }
-
- /**
- * Splits a string into a number of tokens.
- *
- * @param text the text to split
- * @return the tokens, never null
- */
- static String[] splitOnTokens(String text) {
- // used by wildcardMatch
- // package level so a unit test may run on this
-
- if (text.indexOf("?") == -1 && text.indexOf("*") == -1) {
- return new String[] { text };
- }
-
- char[] array = text.toCharArray();
- ArrayList<String> list = new ArrayList<String>();
- StringBuffer buffer = new StringBuffer();
- for (int i = 0; i < array.length; i++) {
- if (array[i] == '?' || array[i] == '*') {
- if (buffer.length() != 0) {
- list.add(buffer.toString());
- buffer.setLength(0);
- }
- if (array[i] == '?') {
- list.add("?");
- } else if (list.size() == 0 ||
- (i > 0 && list.get(list.size() - 1).equals("*") == false)) {
- list.add("*");
- }
- } else {
- buffer.append(array[i]);
- }
- }
- if (buffer.length() != 0) {
- list.add(buffer.toString());
- }
-
- return list.toArray( new String[ list.size() ] );
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/HexDump.java b/emailcommon/src/org/apache/commons/io/HexDump.java
deleted file mode 100644
index b0d468d18..000000000
--- a/emailcommon/src/org/apache/commons/io/HexDump.java
+++ /dev/null
@@ -1,149 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * Dumps data in hexadecimal format.
- * <p>
- * Provides a single function to take an array of bytes and display it
- * in hexadecimal form.
- * <p>
- * Origin of code: POI.
- *
- * @author Scott Sanders
- * @author Marc Johnson
- * @version $Id: HexDump.java 596667 2007-11-20 13:50:14Z niallp $
- */
-public class HexDump {
-
- /**
- * Instances should NOT be constructed in standard programming.
- */
- public HexDump() {
- super();
- }
-
- /**
- * Dump an array of bytes to an OutputStream.
- *
- * @param data the byte array to be dumped
- * @param offset its offset, whatever that might mean
- * @param stream the OutputStream to which the data is to be
- * written
- * @param index initial index into the byte array
- *
- * @throws IOException is thrown if anything goes wrong writing
- * the data to stream
- * @throws ArrayIndexOutOfBoundsException if the index is
- * outside the data array's bounds
- * @throws IllegalArgumentException if the output stream is null
- */
-
- public static void dump(byte[] data, long offset,
- OutputStream stream, int index)
- throws IOException, ArrayIndexOutOfBoundsException,
- IllegalArgumentException {
-
- if ((index < 0) || (index >= data.length)) {
- throw new ArrayIndexOutOfBoundsException(
- "illegal index: " + index + " into array of length "
- + data.length);
- }
- if (stream == null) {
- throw new IllegalArgumentException("cannot write to nullstream");
- }
- long display_offset = offset + index;
- StringBuffer buffer = new StringBuffer(74);
-
- for (int j = index; j < data.length; j += 16) {
- int chars_read = data.length - j;
-
- if (chars_read > 16) {
- chars_read = 16;
- }
- dump(buffer, display_offset).append(' ');
- for (int k = 0; k < 16; k++) {
- if (k < chars_read) {
- dump(buffer, data[k + j]);
- } else {
- buffer.append(" ");
- }
- buffer.append(' ');
- }
- for (int k = 0; k < chars_read; k++) {
- if ((data[k + j] >= ' ') && (data[k + j] < 127)) {
- buffer.append((char) data[k + j]);
- } else {
- buffer.append('.');
- }
- }
- buffer.append(EOL);
- stream.write(buffer.toString().getBytes());
- stream.flush();
- buffer.setLength(0);
- display_offset += chars_read;
- }
- }
-
- /**
- * The line-separator (initializes to "line.separator" system property.
- */
- public static final String EOL =
- System.getProperty("line.separator");
- private static final char[] _hexcodes =
- {
- '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
- 'A', 'B', 'C', 'D', 'E', 'F'
- };
- private static final int[] _shifts =
- {
- 28, 24, 20, 16, 12, 8, 4, 0
- };
-
- /**
- * Dump a long value into a StringBuffer.
- *
- * @param _lbuffer the StringBuffer to dump the value in
- * @param value the long value to be dumped
- * @return StringBuffer containing the dumped value.
- */
- private static StringBuffer dump(StringBuffer _lbuffer, long value) {
- for (int j = 0; j < 8; j++) {
- _lbuffer
- .append(_hexcodes[((int) (value >> _shifts[j])) & 15]);
- }
- return _lbuffer;
- }
-
- /**
- * Dump a byte value into a StringBuffer.
- *
- * @param _cbuffer the StringBuffer to dump the value in
- * @param value the byte value to be dumped
- * @return StringBuffer containing the dumped value.
- */
- private static StringBuffer dump(StringBuffer _cbuffer, byte value) {
- for (int j = 0; j < 2; j++) {
- _cbuffer.append(_hexcodes[(value >> _shifts[j + 6]) & 15]);
- }
- return _cbuffer;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/IOCase.java b/emailcommon/src/org/apache/commons/io/IOCase.java
deleted file mode 100644
index 4230f450d..000000000
--- a/emailcommon/src/org/apache/commons/io/IOCase.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.Serializable;
-
-/**
- * Enumeration of IO case sensitivity.
- * <p>
- * Different filing systems have different rules for case-sensitivity.
- * Windows is case-insensitive, Unix is case-sensitive.
- * <p>
- * This class captures that difference, providing an enumeration to
- * control how filename comparisons should be performed. It also provides
- * methods that use the enumeration to perform comparisons.
- * <p>
- * Wherever possible, you should use the <code>check</code> methods in this
- * class to compare filenames.
- *
- * @author Stephen Colebourne
- * @version $Id: IOCase.java 606345 2007-12-21 23:43:01Z ggregory $
- * @since Commons IO 1.3
- */
-public final class IOCase implements Serializable {
-
- /**
- * The constant for case sensitive regardless of operating system.
- */
- public static final IOCase SENSITIVE = new IOCase("Sensitive", true);
-
- /**
- * The constant for case insensitive regardless of operating system.
- */
- public static final IOCase INSENSITIVE = new IOCase("Insensitive", false);
-
- /**
- * The constant for case sensitivity determined by the current operating system.
- * Windows is case-insensitive when comparing filenames, Unix is case-sensitive.
- * <p>
- * If you derialize this constant of Windows, and deserialize on Unix, or vice
- * versa, then the value of the case-sensitivity flag will change.
- */
- public static final IOCase SYSTEM = new IOCase("System", !FilenameUtils.isSystemWindows());
-
- /** Serialization version. */
- private static final long serialVersionUID = -6343169151696340687L;
-
- /** The enumeration name. */
- private final String name;
-
- /** The sensitivity flag. */
- private final transient boolean sensitive;
-
- //-----------------------------------------------------------------------
- /**
- * Factory method to create an IOCase from a name.
- *
- * @param name the name to find
- * @return the IOCase object
- * @throws IllegalArgumentException if the name is invalid
- */
- public static IOCase forName(String name) {
- if (IOCase.SENSITIVE.name.equals(name)){
- return IOCase.SENSITIVE;
- }
- if (IOCase.INSENSITIVE.name.equals(name)){
- return IOCase.INSENSITIVE;
- }
- if (IOCase.SYSTEM.name.equals(name)){
- return IOCase.SYSTEM;
- }
- throw new IllegalArgumentException("Invalid IOCase name: " + name);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Private constructor.
- *
- * @param name the name
- * @param sensitive the sensitivity
- */
- private IOCase(String name, boolean sensitive) {
- this.name = name;
- this.sensitive = sensitive;
- }
-
- /**
- * Replaces the enumeration from the stream with a real one.
- * This ensures that the correct flag is set for SYSTEM.
- *
- * @return the resolved object
- */
- private Object readResolve() {
- return forName(name);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Gets the name of the constant.
- *
- * @return the name of the constant
- */
- public String getName() {
- return name;
- }
-
- /**
- * Does the object represent case sensitive comparison.
- *
- * @return true if case sensitive
- */
- public boolean isCaseSensitive() {
- return sensitive;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Compares two strings using the case-sensitivity rule.
- * <p>
- * This method mimics {@link String#compareTo} but takes case-sensitivity
- * into account.
- *
- * @param str1 the first string to compare, not null
- * @param str2 the second string to compare, not null
- * @return true if equal using the case rules
- * @throws NullPointerException if either string is null
- */
- public int checkCompareTo(String str1, String str2) {
- if (str1 == null || str2 == null) {
- throw new NullPointerException("The strings must not be null");
- }
- return sensitive ? str1.compareTo(str2) : str1.compareToIgnoreCase(str2);
- }
-
- /**
- * Compares two strings using the case-sensitivity rule.
- * <p>
- * This method mimics {@link String#equals} but takes case-sensitivity
- * into account.
- *
- * @param str1 the first string to compare, not null
- * @param str2 the second string to compare, not null
- * @return true if equal using the case rules
- * @throws NullPointerException if either string is null
- */
- public boolean checkEquals(String str1, String str2) {
- if (str1 == null || str2 == null) {
- throw new NullPointerException("The strings must not be null");
- }
- return sensitive ? str1.equals(str2) : str1.equalsIgnoreCase(str2);
- }
-
- /**
- * Checks if one string starts with another using the case-sensitivity rule.
- * <p>
- * This method mimics {@link String#startsWith(String)} but takes case-sensitivity
- * into account.
- *
- * @param str the string to check, not null
- * @param start the start to compare against, not null
- * @return true if equal using the case rules
- * @throws NullPointerException if either string is null
- */
- public boolean checkStartsWith(String str, String start) {
- return str.regionMatches(!sensitive, 0, start, 0, start.length());
- }
-
- /**
- * Checks if one string ends with another using the case-sensitivity rule.
- * <p>
- * This method mimics {@link String#endsWith} but takes case-sensitivity
- * into account.
- *
- * @param str the string to check, not null
- * @param end the end to compare against, not null
- * @return true if equal using the case rules
- * @throws NullPointerException if either string is null
- */
- public boolean checkEndsWith(String str, String end) {
- int endLen = end.length();
- return str.regionMatches(!sensitive, str.length() - endLen, end, 0, endLen);
- }
-
- /**
- * Checks if one string contains another at a specific index using the case-sensitivity rule.
- * <p>
- * This method mimics parts of {@link String#regionMatches(boolean, int, String, int, int)}
- * but takes case-sensitivity into account.
- *
- * @param str the string to check, not null
- * @param strStartIndex the index to start at in str
- * @param search the start to search for, not null
- * @return true if equal using the case rules
- * @throws NullPointerException if either string is null
- */
- public boolean checkRegionMatches(String str, int strStartIndex, String search) {
- return str.regionMatches(!sensitive, strStartIndex, search, 0, search.length());
- }
-
- /**
- * Converts the case of the input String to a standard format.
- * Subsequent operations can then use standard String methods.
- *
- * @param str the string to convert, null returns null
- * @return the lower-case version if case-insensitive
- */
- String convertCase(String str) {
- if (str == null) {
- return null;
- }
- return sensitive ? str : str.toLowerCase();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Gets a string describing the sensitivity.
- *
- * @return a string describing the sensitivity
- */
- public String toString() {
- return name;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/IOExceptionWithCause.java b/emailcommon/src/org/apache/commons/io/IOExceptionWithCause.java
deleted file mode 100644
index a15815a22..000000000
--- a/emailcommon/src/org/apache/commons/io/IOExceptionWithCause.java
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.io;
-
-import java.io.IOException;
-
-/**
- * Subclasses IOException with the {@link Throwable} constructors missing before Java 6. If you are using Java 6,
- * consider this class deprecated and use {@link IOException}.
- *
- * @author <a href="http://commons.apache.org/io/">Apache Commons IO</a>
- * @version $Id$
- * @since Commons IO 1.4
- */
-public class IOExceptionWithCause extends IOException {
-
- /**
- * Defines the serial version UID.
- */
- private static final long serialVersionUID = 1L;
-
- /**
- * Constructs a new instance with the given message and cause.
- * <p>
- * As specified in {@link Throwable}, the message in the given <code>cause</code> is not used in this instance's
- * message.
- * </p>
- *
- * @param message
- * the message (see {@link #getMessage()})
- * @param cause
- * the cause (see {@link #getCause()}). A <code>null</code> value is allowed.
- */
- public IOExceptionWithCause(String message, Throwable cause) {
- super(message);
- this.initCause(cause);
- }
-
- /**
- * Constructs a new instance with the given cause.
- * <p>
- * The message is set to <code>cause==null ? null : cause.toString()</code>, which by default contains the class
- * and message of <code>cause</code>. This constructor is useful for call sites that just wrap another throwable.
- * </p>
- *
- * @param cause
- * the cause (see {@link #getCause()}). A <code>null</code> value is allowed.
- */
- public IOExceptionWithCause(Throwable cause) {
- super(cause == null ? null : cause.toString());
- this.initCause(cause);
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/IOUtils.java b/emailcommon/src/org/apache/commons/io/IOUtils.java
deleted file mode 100644
index 3f6c65c13..000000000
--- a/emailcommon/src/org/apache/commons/io/IOUtils.java
+++ /dev/null
@@ -1,1274 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.CharArrayWriter;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-
-import org.apache.commons.io.output.ByteArrayOutputStream;
-
-/**
- * General IO stream manipulation utilities.
- * <p>
- * This class provides static utility methods for input/output operations.
- * <ul>
- * <li>closeQuietly - these methods close a stream ignoring nulls and exceptions
- * <li>toXxx/read - these methods read data from a stream
- * <li>write - these methods write data to a stream
- * <li>copy - these methods copy all the data from one stream to another
- * <li>contentEquals - these methods compare the content of two streams
- * </ul>
- * <p>
- * The byte-to-char methods and char-to-byte methods involve a conversion step.
- * Two methods are provided in each case, one that uses the platform default
- * encoding and the other which allows you to specify an encoding. You are
- * encouraged to always specify an encoding because relying on the platform
- * default can lead to unexpected results, for example when moving from
- * development to production.
- * <p>
- * All the methods in this class that read a stream are buffered internally.
- * This means that there is no cause to use a <code>BufferedInputStream</code>
- * or <code>BufferedReader</code>. The default buffer size of 4K has been shown
- * to be efficient in tests.
- * <p>
- * Wherever possible, the methods in this class do <em>not</em> flush or close
- * the stream. This is to avoid making non-portable assumptions about the
- * streams' origin and further use. Thus the caller is still responsible for
- * closing streams after use.
- * <p>
- * Origin of code: Excalibur.
- *
- * @author Peter Donald
- * @author Jeff Turner
- * @author Matthew Hawthorne
- * @author Stephen Colebourne
- * @author Gareth Davis
- * @author Ian Springer
- * @author Niall Pemberton
- * @author Sandy McArthur
- * @version $Id: IOUtils.java 481854 2006-12-03 18:30:07Z scolebourne $
- */
-public class IOUtils {
- // NOTE: This class is focussed on InputStream, OutputStream, Reader and
- // Writer. Each method should take at least one of these as a parameter,
- // or return one of them.
-
- /**
- * The Unix directory separator character.
- */
- public static final char DIR_SEPARATOR_UNIX = '/';
- /**
- * The Windows directory separator character.
- */
- public static final char DIR_SEPARATOR_WINDOWS = '\\';
- /**
- * The system directory separator character.
- */
- public static final char DIR_SEPARATOR = File.separatorChar;
- /**
- * The Unix line separator string.
- */
- public static final String LINE_SEPARATOR_UNIX = "\n";
- /**
- * The Windows line separator string.
- */
- public static final String LINE_SEPARATOR_WINDOWS = "\r\n";
- /**
- * The system line separator string.
- */
- public static final String LINE_SEPARATOR;
- static {
- // avoid security issues
- StringWriter buf = new StringWriter(4);
- PrintWriter out = new PrintWriter(buf);
- out.println();
- LINE_SEPARATOR = buf.toString();
- }
-
- /**
- * The default buffer size to use.
- */
- private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
-
- /**
- * Instances should NOT be constructed in standard programming.
- */
- public IOUtils() {
- super();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Unconditionally close an <code>Reader</code>.
- * <p>
- * Equivalent to {@link Reader#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
- *
- * @param input the Reader to close, may be null or already closed
- */
- public static void closeQuietly(Reader input) {
- try {
- if (input != null) {
- input.close();
- }
- } catch (IOException ioe) {
- // ignore
- }
- }
-
- /**
- * Unconditionally close a <code>Writer</code>.
- * <p>
- * Equivalent to {@link Writer#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
- *
- * @param output the Writer to close, may be null or already closed
- */
- public static void closeQuietly(Writer output) {
- try {
- if (output != null) {
- output.close();
- }
- } catch (IOException ioe) {
- // ignore
- }
- }
-
- /**
- * Unconditionally close an <code>InputStream</code>.
- * <p>
- * Equivalent to {@link InputStream#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
- *
- * @param input the InputStream to close, may be null or already closed
- */
- public static void closeQuietly(InputStream input) {
- try {
- if (input != null) {
- input.close();
- }
- } catch (IOException ioe) {
- // ignore
- }
- }
-
- /**
- * Unconditionally close an <code>OutputStream</code>.
- * <p>
- * Equivalent to {@link OutputStream#close()}, except any exceptions will be ignored.
- * This is typically used in finally blocks.
- *
- * @param output the OutputStream to close, may be null or already closed
- */
- public static void closeQuietly(OutputStream output) {
- try {
- if (output != null) {
- output.close();
- }
- } catch (IOException ioe) {
- // ignore
- }
- }
-
- // read toByteArray
- //-----------------------------------------------------------------------
- /**
- * Get the contents of an <code>InputStream</code> as a <code>byte[]</code>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param input the <code>InputStream</code> to read from
- * @return the requested byte array
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- */
- public static byte[] toByteArray(InputStream input) throws IOException {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- copy(input, output);
- return output.toByteArray();
- }
-
- /**
- * Get the contents of a <code>Reader</code> as a <code>byte[]</code>
- * using the default character encoding of the platform.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- *
- * @param input the <code>Reader</code> to read from
- * @return the requested byte array
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- */
- public static byte[] toByteArray(Reader input) throws IOException {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- copy(input, output);
- return output.toByteArray();
- }
-
- /**
- * Get the contents of a <code>Reader</code> as a <code>byte[]</code>
- * using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- *
- * @param input the <code>Reader</code> to read from
- * @param encoding the encoding to use, null means platform default
- * @return the requested byte array
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static byte[] toByteArray(Reader input, String encoding)
- throws IOException {
- ByteArrayOutputStream output = new ByteArrayOutputStream();
- copy(input, output, encoding);
- return output.toByteArray();
- }
-
- /**
- * Get the contents of a <code>String</code> as a <code>byte[]</code>
- * using the default character encoding of the platform.
- * <p>
- * This is the same as {@link String#getBytes()}.
- *
- * @param input the <code>String</code> to convert
- * @return the requested byte array
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs (never occurs)
- * @deprecated Use {@link String#getBytes()}
- */
- public static byte[] toByteArray(String input) throws IOException {
- return input.getBytes();
- }
-
- // read char[]
- //-----------------------------------------------------------------------
- /**
- * Get the contents of an <code>InputStream</code> as a character array
- * using the default character encoding of the platform.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param is the <code>InputStream</code> to read from
- * @return the requested character array
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static char[] toCharArray(InputStream is) throws IOException {
- CharArrayWriter output = new CharArrayWriter();
- copy(is, output);
- return output.toCharArray();
- }
-
- /**
- * Get the contents of an <code>InputStream</code> as a character array
- * using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param is the <code>InputStream</code> to read from
- * @param encoding the encoding to use, null means platform default
- * @return the requested character array
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static char[] toCharArray(InputStream is, String encoding)
- throws IOException {
- CharArrayWriter output = new CharArrayWriter();
- copy(is, output, encoding);
- return output.toCharArray();
- }
-
- /**
- * Get the contents of a <code>Reader</code> as a character array.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- *
- * @param input the <code>Reader</code> to read from
- * @return the requested character array
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static char[] toCharArray(Reader input) throws IOException {
- CharArrayWriter sw = new CharArrayWriter();
- copy(input, sw);
- return sw.toCharArray();
- }
-
- // read toString
- //-----------------------------------------------------------------------
- /**
- * Get the contents of an <code>InputStream</code> as a String
- * using the default character encoding of the platform.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param input the <code>InputStream</code> to read from
- * @return the requested String
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- */
- public static String toString(InputStream input) throws IOException {
- StringWriter sw = new StringWriter();
- copy(input, sw);
- return sw.toString();
- }
-
- /**
- * Get the contents of an <code>InputStream</code> as a String
- * using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param input the <code>InputStream</code> to read from
- * @param encoding the encoding to use, null means platform default
- * @return the requested String
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- */
- public static String toString(InputStream input, String encoding)
- throws IOException {
- StringWriter sw = new StringWriter();
- copy(input, sw, encoding);
- return sw.toString();
- }
-
- /**
- * Get the contents of a <code>Reader</code> as a String.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- *
- * @param input the <code>Reader</code> to read from
- * @return the requested String
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- */
- public static String toString(Reader input) throws IOException {
- StringWriter sw = new StringWriter();
- copy(input, sw);
- return sw.toString();
- }
-
- /**
- * Get the contents of a <code>byte[]</code> as a String
- * using the default character encoding of the platform.
- *
- * @param input the byte array to read from
- * @return the requested String
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs (never occurs)
- * @deprecated Use {@link String#String(byte[])}
- */
- public static String toString(byte[] input) throws IOException {
- return new String(input);
- }
-
- /**
- * Get the contents of a <code>byte[]</code> as a String
- * using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- *
- * @param input the byte array to read from
- * @param encoding the encoding to use, null means platform default
- * @return the requested String
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs (never occurs)
- * @deprecated Use {@link String#String(byte[],String)}
- */
- public static String toString(byte[] input, String encoding)
- throws IOException {
- if (encoding == null) {
- return new String(input);
- } else {
- return new String(input, encoding);
- }
- }
-
- // readLines
- //-----------------------------------------------------------------------
- /**
- * Get the contents of an <code>InputStream</code> as a list of Strings,
- * one entry per line, using the default character encoding of the platform.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param input the <code>InputStream</code> to read from, not null
- * @return the list of Strings, never null
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static List<String> readLines(InputStream input) throws IOException {
- InputStreamReader reader = new InputStreamReader(input);
- return readLines(reader);
- }
-
- /**
- * Get the contents of an <code>InputStream</code> as a list of Strings,
- * one entry per line, using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param input the <code>InputStream</code> to read from, not null
- * @param encoding the encoding to use, null means platform default
- * @return the list of Strings, never null
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static List<String> readLines(InputStream input, String encoding) throws IOException {
- if (encoding == null) {
- return readLines(input);
- } else {
- InputStreamReader reader = new InputStreamReader(input, encoding);
- return readLines(reader);
- }
- }
-
- /**
- * Get the contents of a <code>Reader</code> as a list of Strings,
- * one entry per line.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- *
- * @param input the <code>Reader</code> to read from, not null
- * @return the list of Strings, never null
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static List<String> readLines(Reader input) throws IOException {
- BufferedReader reader = new BufferedReader(input);
- List<String> list = new ArrayList<String>();
- String line = reader.readLine();
- while (line != null) {
- list.add(line);
- line = reader.readLine();
- }
- return list;
- }
-
- // lineIterator
- //-----------------------------------------------------------------------
- /**
- * Return an Iterator for the lines in a <code>Reader</code>.
- * <p>
- * <code>LineIterator</code> holds a reference to the open
- * <code>Reader</code> specified here. When you have finished with the
- * iterator you should close the reader to free internal resources.
- * This can be done by closing the reader directly, or by calling
- * {@link LineIterator#close()} or {@link LineIterator#closeQuietly(LineIterator)}.
- * <p>
- * The recommended usage pattern is:
- * <pre>
- * try {
- * LineIterator it = IOUtils.lineIterator(reader);
- * while (it.hasNext()) {
- * String line = it.nextLine();
- * /// do something with line
- * }
- * } finally {
- * IOUtils.closeQuietly(reader);
- * }
- * </pre>
- *
- * @param reader the <code>Reader</code> to read from, not null
- * @return an Iterator of the lines in the reader, never null
- * @throws IllegalArgumentException if the reader is null
- * @since Commons IO 1.2
- */
- public static LineIterator lineIterator(Reader reader) {
- return new LineIterator(reader);
- }
-
- /**
- * Return an Iterator for the lines in an <code>InputStream</code>, using
- * the character encoding specified (or default encoding if null).
- * <p>
- * <code>LineIterator</code> holds a reference to the open
- * <code>InputStream</code> specified here. When you have finished with
- * the iterator you should close the stream to free internal resources.
- * This can be done by closing the stream directly, or by calling
- * {@link LineIterator#close()} or {@link LineIterator#closeQuietly(LineIterator)}.
- * <p>
- * The recommended usage pattern is:
- * <pre>
- * try {
- * LineIterator it = IOUtils.lineIterator(stream, "UTF-8");
- * while (it.hasNext()) {
- * String line = it.nextLine();
- * /// do something with line
- * }
- * } finally {
- * IOUtils.closeQuietly(stream);
- * }
- * </pre>
- *
- * @param input the <code>InputStream</code> to read from, not null
- * @param encoding the encoding to use, null means platform default
- * @return an Iterator of the lines in the reader, never null
- * @throws IllegalArgumentException if the input is null
- * @throws IOException if an I/O error occurs, such as if the encoding is invalid
- * @since Commons IO 1.2
- */
- public static LineIterator lineIterator(InputStream input, String encoding)
- throws IOException {
- Reader reader = null;
- if (encoding == null) {
- reader = new InputStreamReader(input);
- } else {
- reader = new InputStreamReader(input, encoding);
- }
- return new LineIterator(reader);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Convert the specified string to an input stream, encoded as bytes
- * using the default character encoding of the platform.
- *
- * @param input the string to convert
- * @return an input stream
- * @since Commons IO 1.1
- */
- public static InputStream toInputStream(String input) {
- byte[] bytes = input.getBytes();
- return new ByteArrayInputStream(bytes);
- }
-
- /**
- * Convert the specified string to an input stream, encoded as bytes
- * using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- *
- * @param input the string to convert
- * @param encoding the encoding to use, null means platform default
- * @throws IOException if the encoding is invalid
- * @return an input stream
- * @since Commons IO 1.1
- */
- public static InputStream toInputStream(String input, String encoding) throws IOException {
- byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes();
- return new ByteArrayInputStream(bytes);
- }
-
- // write byte[]
- //-----------------------------------------------------------------------
- /**
- * Writes bytes from a <code>byte[]</code> to an <code>OutputStream</code>.
- *
- * @param data the byte array to write, do not modify during output,
- * null ignored
- * @param output the <code>OutputStream</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(byte[] data, OutputStream output)
- throws IOException {
- if (data != null) {
- output.write(data);
- }
- }
-
- /**
- * Writes bytes from a <code>byte[]</code> to chars on a <code>Writer</code>
- * using the default character encoding of the platform.
- * <p>
- * This method uses {@link String#String(byte[])}.
- *
- * @param data the byte array to write, do not modify during output,
- * null ignored
- * @param output the <code>Writer</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(byte[] data, Writer output) throws IOException {
- if (data != null) {
- output.write(new String(data));
- }
- }
-
- /**
- * Writes bytes from a <code>byte[]</code> to chars on a <code>Writer</code>
- * using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method uses {@link String#String(byte[], String)}.
- *
- * @param data the byte array to write, do not modify during output,
- * null ignored
- * @param output the <code>Writer</code> to write to
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(byte[] data, Writer output, String encoding)
- throws IOException {
- if (data != null) {
- if (encoding == null) {
- write(data, output);
- } else {
- output.write(new String(data, encoding));
- }
- }
- }
-
- // write char[]
- //-----------------------------------------------------------------------
- /**
- * Writes chars from a <code>char[]</code> to a <code>Writer</code>
- * using the default character encoding of the platform.
- *
- * @param data the char array to write, do not modify during output,
- * null ignored
- * @param output the <code>Writer</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(char[] data, Writer output) throws IOException {
- if (data != null) {
- output.write(data);
- }
- }
-
- /**
- * Writes chars from a <code>char[]</code> to bytes on an
- * <code>OutputStream</code>.
- * <p>
- * This method uses {@link String#String(char[])} and
- * {@link String#getBytes()}.
- *
- * @param data the char array to write, do not modify during output,
- * null ignored
- * @param output the <code>OutputStream</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(char[] data, OutputStream output)
- throws IOException {
- if (data != null) {
- output.write(new String(data).getBytes());
- }
- }
-
- /**
- * Writes chars from a <code>char[]</code> to bytes on an
- * <code>OutputStream</code> using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method uses {@link String#String(char[])} and
- * {@link String#getBytes(String)}.
- *
- * @param data the char array to write, do not modify during output,
- * null ignored
- * @param output the <code>OutputStream</code> to write to
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(char[] data, OutputStream output, String encoding)
- throws IOException {
- if (data != null) {
- if (encoding == null) {
- write(data, output);
- } else {
- output.write(new String(data).getBytes(encoding));
- }
- }
- }
-
- // write String
- //-----------------------------------------------------------------------
- /**
- * Writes chars from a <code>String</code> to a <code>Writer</code>.
- *
- * @param data the <code>String</code> to write, null ignored
- * @param output the <code>Writer</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(String data, Writer output) throws IOException {
- if (data != null) {
- output.write(data);
- }
- }
-
- /**
- * Writes chars from a <code>String</code> to bytes on an
- * <code>OutputStream</code> using the default character encoding of the
- * platform.
- * <p>
- * This method uses {@link String#getBytes()}.
- *
- * @param data the <code>String</code> to write, null ignored
- * @param output the <code>OutputStream</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(String data, OutputStream output)
- throws IOException {
- if (data != null) {
- output.write(data.getBytes());
- }
- }
-
- /**
- * Writes chars from a <code>String</code> to bytes on an
- * <code>OutputStream</code> using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method uses {@link String#getBytes(String)}.
- *
- * @param data the <code>String</code> to write, null ignored
- * @param output the <code>OutputStream</code> to write to
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(String data, OutputStream output, String encoding)
- throws IOException {
- if (data != null) {
- if (encoding == null) {
- write(data, output);
- } else {
- output.write(data.getBytes(encoding));
- }
- }
- }
-
- // write StringBuffer
- //-----------------------------------------------------------------------
- /**
- * Writes chars from a <code>StringBuffer</code> to a <code>Writer</code>.
- *
- * @param data the <code>StringBuffer</code> to write, null ignored
- * @param output the <code>Writer</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(StringBuffer data, Writer output)
- throws IOException {
- if (data != null) {
- output.write(data.toString());
- }
- }
-
- /**
- * Writes chars from a <code>StringBuffer</code> to bytes on an
- * <code>OutputStream</code> using the default character encoding of the
- * platform.
- * <p>
- * This method uses {@link String#getBytes()}.
- *
- * @param data the <code>StringBuffer</code> to write, null ignored
- * @param output the <code>OutputStream</code> to write to
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(StringBuffer data, OutputStream output)
- throws IOException {
- if (data != null) {
- output.write(data.toString().getBytes());
- }
- }
-
- /**
- * Writes chars from a <code>StringBuffer</code> to bytes on an
- * <code>OutputStream</code> using the specified character encoding.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method uses {@link String#getBytes(String)}.
- *
- * @param data the <code>StringBuffer</code> to write, null ignored
- * @param output the <code>OutputStream</code> to write to
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void write(StringBuffer data, OutputStream output,
- String encoding) throws IOException {
- if (data != null) {
- if (encoding == null) {
- write(data, output);
- } else {
- output.write(data.toString().getBytes(encoding));
- }
- }
- }
-
- // writeLines
- //-----------------------------------------------------------------------
- /**
- * Writes the <code>toString()</code> value of each item in a collection to
- * an <code>OutputStream</code> line by line, using the default character
- * encoding of the platform and the specified line ending.
- *
- * @param lines the lines to write, null entries produce blank lines
- * @param lineEnding the line separator to use, null is system default
- * @param output the <code>OutputStream</code> to write to, not null, not closed
- * @throws NullPointerException if the output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void writeLines(Collection<Object> lines, String lineEnding,
- OutputStream output) throws IOException {
- if (lines == null) {
- return;
- }
- if (lineEnding == null) {
- lineEnding = LINE_SEPARATOR;
- }
- for (Iterator<Object> it = lines.iterator(); it.hasNext(); ) {
- Object line = it.next();
- if (line != null) {
- output.write(line.toString().getBytes());
- }
- output.write(lineEnding.getBytes());
- }
- }
-
- /**
- * Writes the <code>toString()</code> value of each item in a collection to
- * an <code>OutputStream</code> line by line, using the specified character
- * encoding and the specified line ending.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- *
- * @param lines the lines to write, null entries produce blank lines
- * @param lineEnding the line separator to use, null is system default
- * @param output the <code>OutputStream</code> to write to, not null, not closed
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if the output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void writeLines(Collection<Object> lines, String lineEnding,
- OutputStream output, String encoding) throws IOException {
- if (encoding == null) {
- writeLines(lines, lineEnding, output);
- } else {
- if (lines == null) {
- return;
- }
- if (lineEnding == null) {
- lineEnding = LINE_SEPARATOR;
- }
- for (Iterator<Object> it = lines.iterator(); it.hasNext(); ) {
- Object line = it.next();
- if (line != null) {
- output.write(line.toString().getBytes(encoding));
- }
- output.write(lineEnding.getBytes(encoding));
- }
- }
- }
-
- /**
- * Writes the <code>toString()</code> value of each item in a collection to
- * a <code>Writer</code> line by line, using the specified line ending.
- *
- * @param lines the lines to write, null entries produce blank lines
- * @param lineEnding the line separator to use, null is system default
- * @param writer the <code>Writer</code> to write to, not null, not closed
- * @throws NullPointerException if the input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void writeLines(Collection<Object> lines, String lineEnding,
- Writer writer) throws IOException {
- if (lines == null) {
- return;
- }
- if (lineEnding == null) {
- lineEnding = LINE_SEPARATOR;
- }
- for (Iterator<Object> it = lines.iterator(); it.hasNext(); ) {
- Object line = it.next();
- if (line != null) {
- writer.write(line.toString());
- }
- writer.write(lineEnding);
- }
- }
-
- // copy from InputStream
- //-----------------------------------------------------------------------
- /**
- * Copy bytes from an <code>InputStream</code> to an
- * <code>OutputStream</code>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- * <p>
- * Large streams (over 2GB) will return a bytes copied value of
- * <code>-1</code> after the copy has completed since the correct
- * number of bytes cannot be returned as an int. For large streams
- * use the <code>copyLarge(InputStream, OutputStream)</code> method.
- *
- * @param input the <code>InputStream</code> to read from
- * @param output the <code>OutputStream</code> to write to
- * @return the number of bytes copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @throws ArithmeticException if the byte count is too large
- * @since Commons IO 1.1
- */
- public static int copy(InputStream input, OutputStream output) throws IOException {
- long count = copyLarge(input, output);
- if (count > Integer.MAX_VALUE) {
- return -1;
- }
- return (int) count;
- }
-
- /**
- * Copy bytes from a large (over 2GB) <code>InputStream</code> to an
- * <code>OutputStream</code>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- *
- * @param input the <code>InputStream</code> to read from
- * @param output the <code>OutputStream</code> to write to
- * @return the number of bytes copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.3
- */
- public static long copyLarge(InputStream input, OutputStream output)
- throws IOException {
- byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
- long count = 0;
- int n = 0;
- while (-1 != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- count += n;
- }
- return count;
- }
-
- /**
- * Copy bytes from an <code>InputStream</code> to chars on a
- * <code>Writer</code> using the default character encoding of the platform.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- * <p>
- * This method uses {@link InputStreamReader}.
- *
- * @param input the <code>InputStream</code> to read from
- * @param output the <code>Writer</code> to write to
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void copy(InputStream input, Writer output)
- throws IOException {
- InputStreamReader in = new InputStreamReader(input);
- copy(in, output);
- }
-
- /**
- * Copy bytes from an <code>InputStream</code> to chars on a
- * <code>Writer</code> using the specified character encoding.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedInputStream</code>.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * This method uses {@link InputStreamReader}.
- *
- * @param input the <code>InputStream</code> to read from
- * @param output the <code>Writer</code> to write to
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void copy(InputStream input, Writer output, String encoding)
- throws IOException {
- if (encoding == null) {
- copy(input, output);
- } else {
- InputStreamReader in = new InputStreamReader(input, encoding);
- copy(in, output);
- }
- }
-
- // copy from Reader
- //-----------------------------------------------------------------------
- /**
- * Copy chars from a <code>Reader</code> to a <code>Writer</code>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- * <p>
- * Large streams (over 2GB) will return a chars copied value of
- * <code>-1</code> after the copy has completed since the correct
- * number of chars cannot be returned as an int. For large streams
- * use the <code>copyLarge(Reader, Writer)</code> method.
- *
- * @param input the <code>Reader</code> to read from
- * @param output the <code>Writer</code> to write to
- * @return the number of characters copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @throws ArithmeticException if the character count is too large
- * @since Commons IO 1.1
- */
- public static int copy(Reader input, Writer output) throws IOException {
- long count = copyLarge(input, output);
- if (count > Integer.MAX_VALUE) {
- return -1;
- }
- return (int) count;
- }
-
- /**
- * Copy chars from a large (over 2GB) <code>Reader</code> to a <code>Writer</code>.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- *
- * @param input the <code>Reader</code> to read from
- * @param output the <code>Writer</code> to write to
- * @return the number of characters copied
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.3
- */
- public static long copyLarge(Reader input, Writer output) throws IOException {
- char[] buffer = new char[DEFAULT_BUFFER_SIZE];
- long count = 0;
- int n = 0;
- while (-1 != (n = input.read(buffer))) {
- output.write(buffer, 0, n);
- count += n;
- }
- return count;
- }
-
- /**
- * Copy chars from a <code>Reader</code> to bytes on an
- * <code>OutputStream</code> using the default character encoding of the
- * platform, and calling flush.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- * <p>
- * Due to the implementation of OutputStreamWriter, this method performs a
- * flush.
- * <p>
- * This method uses {@link OutputStreamWriter}.
- *
- * @param input the <code>Reader</code> to read from
- * @param output the <code>OutputStream</code> to write to
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void copy(Reader input, OutputStream output)
- throws IOException {
- OutputStreamWriter out = new OutputStreamWriter(output);
- copy(input, out);
- // XXX Unless anyone is planning on rewriting OutputStreamWriter, we
- // have to flush here.
- out.flush();
- }
-
- /**
- * Copy chars from a <code>Reader</code> to bytes on an
- * <code>OutputStream</code> using the specified character encoding, and
- * calling flush.
- * <p>
- * This method buffers the input internally, so there is no need to use a
- * <code>BufferedReader</code>.
- * <p>
- * Character encoding names can be found at
- * <a href="http://www.iana.org/assignments/character-sets">IANA</a>.
- * <p>
- * Due to the implementation of OutputStreamWriter, this method performs a
- * flush.
- * <p>
- * This method uses {@link OutputStreamWriter}.
- *
- * @param input the <code>Reader</code> to read from
- * @param output the <code>OutputStream</code> to write to
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if the input or output is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static void copy(Reader input, OutputStream output, String encoding)
- throws IOException {
- if (encoding == null) {
- copy(input, output);
- } else {
- OutputStreamWriter out = new OutputStreamWriter(output, encoding);
- copy(input, out);
- // XXX Unless anyone is planning on rewriting OutputStreamWriter,
- // we have to flush here.
- out.flush();
- }
- }
-
- // content equals
- //-----------------------------------------------------------------------
- /**
- * Compare the contents of two Streams to determine if they are equal or
- * not.
- * <p>
- * This method buffers the input internally using
- * <code>BufferedInputStream</code> if they are not already buffered.
- *
- * @param input1 the first stream
- * @param input2 the second stream
- * @return true if the content of the streams are equal or they both don't
- * exist, false otherwise
- * @throws NullPointerException if either input is null
- * @throws IOException if an I/O error occurs
- */
- public static boolean contentEquals(InputStream input1, InputStream input2)
- throws IOException {
- if (!(input1 instanceof BufferedInputStream)) {
- input1 = new BufferedInputStream(input1);
- }
- if (!(input2 instanceof BufferedInputStream)) {
- input2 = new BufferedInputStream(input2);
- }
-
- int ch = input1.read();
- while (-1 != ch) {
- int ch2 = input2.read();
- if (ch != ch2) {
- return false;
- }
- ch = input1.read();
- }
-
- int ch2 = input2.read();
- return (ch2 == -1);
- }
-
- /**
- * Compare the contents of two Readers to determine if they are equal or
- * not.
- * <p>
- * This method buffers the input internally using
- * <code>BufferedReader</code> if they are not already buffered.
- *
- * @param input1 the first reader
- * @param input2 the second reader
- * @return true if the content of the readers are equal or they both don't
- * exist, false otherwise
- * @throws NullPointerException if either input is null
- * @throws IOException if an I/O error occurs
- * @since Commons IO 1.1
- */
- public static boolean contentEquals(Reader input1, Reader input2)
- throws IOException {
- if (!(input1 instanceof BufferedReader)) {
- input1 = new BufferedReader(input1);
- }
- if (!(input2 instanceof BufferedReader)) {
- input2 = new BufferedReader(input2);
- }
-
- int ch = input1.read();
- while (-1 != ch) {
- int ch2 = input2.read();
- if (ch != ch2) {
- return false;
- }
- ch = input1.read();
- }
-
- int ch2 = input2.read();
- return (ch2 == -1);
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/LineIterator.java b/emailcommon/src/org/apache/commons/io/LineIterator.java
deleted file mode 100644
index eac47d23a..000000000
--- a/emailcommon/src/org/apache/commons/io/LineIterator.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io;
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.Reader;
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-/**
- * An Iterator over the lines in a <code>Reader</code>.
- * <p>
- * <code>LineIterator</code> holds a reference to an open <code>Reader</code>.
- * When you have finished with the iterator you should close the reader
- * to free internal resources. This can be done by closing the reader directly,
- * or by calling the {@link #close()} or {@link #closeQuietly(LineIterator)}
- * method on the iterator.
- * <p>
- * The recommended usage pattern is:
- * <pre>
- * LineIterator it = FileUtils.lineIterator(file, "UTF-8");
- * try {
- * while (it.hasNext()) {
- * String line = it.nextLine();
- * /// do something with line
- * }
- * } finally {
- * LineIterator.closeQuietly(iterator);
- * }
- * </pre>
- *
- * @author Niall Pemberton
- * @author Stephen Colebourne
- * @author Sandy McArthur
- * @version $Id: LineIterator.java 437567 2006-08-28 06:39:07Z bayard $
- * @since Commons IO 1.2
- */
-public class LineIterator implements Iterator {
-
- /** The reader that is being read. */
- private final BufferedReader bufferedReader;
- /** The current line. */
- private String cachedLine;
- /** A flag indicating if the iterator has been fully read. */
- private boolean finished = false;
-
- /**
- * Constructs an iterator of the lines for a <code>Reader</code>.
- *
- * @param reader the <code>Reader</code> to read from, not null
- * @throws IllegalArgumentException if the reader is null
- */
- public LineIterator(final Reader reader) throws IllegalArgumentException {
- if (reader == null) {
- throw new IllegalArgumentException("Reader must not be null");
- }
- if (reader instanceof BufferedReader) {
- bufferedReader = (BufferedReader) reader;
- } else {
- bufferedReader = new BufferedReader(reader);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Indicates whether the <code>Reader</code> has more lines.
- * If there is an <code>IOException</code> then {@link #close()} will
- * be called on this instance.
- *
- * @return <code>true</code> if the Reader has more lines
- * @throws IllegalStateException if an IO exception occurs
- */
- public boolean hasNext() {
- if (cachedLine != null) {
- return true;
- } else if (finished) {
- return false;
- } else {
- try {
- while (true) {
- String line = bufferedReader.readLine();
- if (line == null) {
- finished = true;
- return false;
- } else if (isValidLine(line)) {
- cachedLine = line;
- return true;
- }
- }
- } catch(IOException ioe) {
- close();
- throw new IllegalStateException(ioe.toString());
- }
- }
- }
-
- /**
- * Overridable method to validate each line that is returned.
- *
- * @param line the line that is to be validated
- * @return true if valid, false to remove from the iterator
- */
- protected boolean isValidLine(String line) {
- return true;
- }
-
- /**
- * Returns the next line in the wrapped <code>Reader</code>.
- *
- * @return the next line from the input
- * @throws NoSuchElementException if there is no line to return
- */
- public Object next() {
- return nextLine();
- }
-
- /**
- * Returns the next line in the wrapped <code>Reader</code>.
- *
- * @return the next line from the input
- * @throws NoSuchElementException if there is no line to return
- */
- public String nextLine() {
- if (!hasNext()) {
- throw new NoSuchElementException("No more lines");
- }
- String currentLine = cachedLine;
- cachedLine = null;
- return currentLine;
- }
-
- /**
- * Closes the underlying <code>Reader</code> quietly.
- * This method is useful if you only want to process the first few
- * lines of a larger file. If you do not close the iterator
- * then the <code>Reader</code> remains open.
- * This method can safely be called multiple times.
- */
- public void close() {
- finished = true;
- IOUtils.closeQuietly(bufferedReader);
- cachedLine = null;
- }
-
- /**
- * Unsupported.
- *
- * @throws UnsupportedOperationException always
- */
- public void remove() {
- throw new UnsupportedOperationException("Remove unsupported on LineIterator");
- }
-
- //-----------------------------------------------------------------------
- /**
- * Closes the iterator, handling null and ignoring exceptions.
- *
- * @param iterator the iterator to close
- */
- public static void closeQuietly(LineIterator iterator) {
- if (iterator != null) {
- iterator.close();
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/ThirdPartyProject.prop b/emailcommon/src/org/apache/commons/io/ThirdPartyProject.prop
deleted file mode 100644
index b09d3900c..000000000
--- a/emailcommon/src/org/apache/commons/io/ThirdPartyProject.prop
+++ /dev/null
@@ -1,9 +0,0 @@
-# Copyright 2010 Google Inc. All Rights Reserved.
-#Fri Jul 16 10:03:08 PDT 2010
-currentVersion=1.4
-version=1.4
-isNative=false
-name=apache_commons_io
-keywords=apache commons io
-onDevice=true
-homepage=http\://commons.apache.org/io/
diff --git a/emailcommon/src/org/apache/commons/io/comparator/DefaultFileComparator.java b/emailcommon/src/org/apache/commons/io/comparator/DefaultFileComparator.java
deleted file mode 100644
index 8de3cc4e7..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/DefaultFileComparator.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.comparator;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Comparator;
-
-/**
- * Compare two files using the <b>default</b> {@link File#compareTo(File)} method.
- * <p>
- * This comparator can be used to sort lists or arrays of files
- * by using the default file comparison.
- * <p>
- * Example of sorting a list of files using the
- * {@link #DEFAULT_COMPARATOR} singleton instance:
- * <pre>
- * List&lt;File&gt; list = ...
- * Collections.sort(list, DefaultFileComparator.DEFAULT_COMPARATOR);
- * </pre>
- * <p>
- * Example of doing a <i>reverse</i> sort of an array of files using the
- * {@link #DEFAULT_REVERSE} singleton instance:
- * <pre>
- * File[] array = ...
- * Arrays.sort(array, DefaultFileComparator.DEFAULT_REVERSE);
- * </pre>
- * <p>
- *
- * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
- * @since Commons IO 1.4
- */
-public class DefaultFileComparator implements Comparator<File>, Serializable {
-
- /** Singleton default comparator instance */
- public static final Comparator<File> DEFAULT_COMPARATOR = new DefaultFileComparator();
-
- /** Singleton reverse default comparator instance */
- public static final Comparator<File> DEFAULT_REVERSE = new ReverseComparator<File>(DEFAULT_COMPARATOR);
-
- /**
- * Compare the two files using the {@link File#compareTo(File)} method.
- *
- * @param obj1 The first file to compare
- * @param obj2 The second file to compare
- * @return the result of calling file1's
- * {@link File#compareTo(File)} with file2 as the parameter.
- */
- public int compare(File file1, File file2) {
- return file1.compareTo(file2);
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/comparator/ExtensionFileComparator.java b/emailcommon/src/org/apache/commons/io/comparator/ExtensionFileComparator.java
deleted file mode 100644
index 5797b02eb..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/ExtensionFileComparator.java
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.comparator;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Comparator;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOCase;
-
-/**
- * Compare the file name <b>extensions</b> for order
- * (see {@link FilenameUtils#getExtension(String)}).
- * <p>
- * This comparator can be used to sort lists or arrays of files
- * by their file extension either in a case-sensitive, case-insensitive or
- * system dependant case sensitive way. A number of singleton instances
- * are provided for the various case sensitivity options (using {@link IOCase})
- * and the reverse of those options.
- * <p>
- * Example of a <i>case-sensitive</i> file extension sort using the
- * {@link #EXTENSION_COMPARATOR} singleton instance:
- * <pre>
- * List&lt;File&gt; list = ...
- * Collections.sort(list, ExtensionFileComparator.EXTENSION_COMPARATOR);
- * </pre>
- * <p>
- * Example of a <i>reverse case-insensitive</i> file extension sort using the
- * {@link #EXTENSION_INSENSITIVE_REVERSE} singleton instance:
- * <pre>
- * File[] array = ...
- * Arrays.sort(array, ExtensionFileComparator.EXTENSION_INSENSITIVE_REVERSE);
- * </pre>
- * <p>
- *
- * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
- * @since Commons IO 1.4
- */
-public class ExtensionFileComparator implements Comparator<File>, Serializable {
-
- /** Case-sensitive extension comparator instance (see {@link IOCase#SENSITIVE}) */
- public static final Comparator<File> EXTENSION_COMPARATOR = new ExtensionFileComparator();
-
- /** Reverse case-sensitive extension comparator instance (see {@link IOCase#SENSITIVE}) */
- public static final Comparator<File> EXTENSION_REVERSE = new ReverseComparator<File>(EXTENSION_COMPARATOR);
-
- /** Case-insensitive extension comparator instance (see {@link IOCase#INSENSITIVE}) */
- public static final Comparator<File> EXTENSION_INSENSITIVE_COMPARATOR = new ExtensionFileComparator(IOCase.INSENSITIVE);
-
- /** Reverse case-insensitive extension comparator instance (see {@link IOCase#INSENSITIVE}) */
- public static final Comparator<File> EXTENSION_INSENSITIVE_REVERSE
- = new ReverseComparator<File>(EXTENSION_INSENSITIVE_COMPARATOR);
-
- /** System sensitive extension comparator instance (see {@link IOCase#SYSTEM}) */
- public static final Comparator<File> EXTENSION_SYSTEM_COMPARATOR = new ExtensionFileComparator(IOCase.SYSTEM);
-
- /** Reverse system sensitive path comparator instance (see {@link IOCase#SYSTEM}) */
- public static final Comparator<File> EXTENSION_SYSTEM_REVERSE = new ReverseComparator<File>(EXTENSION_SYSTEM_COMPARATOR);
-
- /** Whether the comparison is case sensitive. */
- private final IOCase caseSensitivity;
-
- /**
- * Construct a case sensitive file extension comparator instance.
- */
- public ExtensionFileComparator() {
- this.caseSensitivity = IOCase.SENSITIVE;
- }
-
- /**
- * Construct a file extension comparator instance with the specified case-sensitivity.
- *
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- */
- public ExtensionFileComparator(IOCase caseSensitivity) {
- this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity;
- }
-
- /**
- * Compare the extensions of two files the specified case sensitivity.
- *
- * @param obj1 The first file to compare
- * @param obj2 The second file to compare
- * @return a negative value if the first file's extension
- * is less than the second, zero if the extensions are the
- * same and a positive value if the first files extension
- * is greater than the second file.
- *
- */
- public int compare(File file1, File file2) {
- String suffix1 = FilenameUtils.getExtension(file1.getName());
- String suffix2 = FilenameUtils.getExtension(file2.getName());
- return caseSensitivity.checkCompareTo(suffix1, suffix2);
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/comparator/LastModifiedFileComparator.java b/emailcommon/src/org/apache/commons/io/comparator/LastModifiedFileComparator.java
deleted file mode 100644
index 0dcd0b242..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/LastModifiedFileComparator.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.comparator;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Comparator;
-
-/**
- * Compare the <b>last modified date/time</b> of two files for order
- * (see {@link File#lastModified()}).
- * <p>
- * This comparator can be used to sort lists or arrays of files
- * by their last modified date/time.
- * <p>
- * Example of sorting a list of files using the
- * {@link #LASTMODIFIED_COMPARATOR} singleton instance:
- * <pre>
- * List&lt;File&gt; list = ...
- * Collections.sort(list, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
- * </pre>
- * <p>
- * Example of doing a <i>reverse</i> sort of an array of files using the
- * {@link #LASTMODIFIED_REVERSE} singleton instance:
- * <pre>
- * File[] array = ...
- * Arrays.sort(array, LastModifiedFileComparator.LASTMODIFIED_REVERSE);
- * </pre>
- * <p>
- *
- * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
- * @since Commons IO 1.4
- */
-public class LastModifiedFileComparator implements Comparator<File>, Serializable {
-
- /** Last modified comparator instance */
- public static final Comparator<File> LASTMODIFIED_COMPARATOR = new LastModifiedFileComparator();
-
- /** Reverse last modified comparator instance */
- public static final Comparator<File> LASTMODIFIED_REVERSE = new ReverseComparator<File>(LASTMODIFIED_COMPARATOR);
-
- /**
- * Compare the last the last modified date/time of two files.
- *
- * @param obj1 The first file to compare
- * @param obj2 The second file to compare
- * @return a negative value if the first file's lastmodified date/time
- * is less than the second, zero if the lastmodified date/time are the
- * same and a positive value if the first files lastmodified date/time
- * is greater than the second file.
- *
- */
- public int compare(File file1, File file2) {
- long result = file1.lastModified() - file2.lastModified();
- if (result < 0) {
- return -1;
- } else if (result > 0) {
- return 1;
- } else {
- return 0;
- }
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/comparator/NameFileComparator.java b/emailcommon/src/org/apache/commons/io/comparator/NameFileComparator.java
deleted file mode 100644
index eb64fb589..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/NameFileComparator.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.comparator;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Comparator;
-
-import org.apache.commons.io.IOCase;
-
-/**
- * Compare the <b>names</b> of two files for order (see {@link File#getName()}).
- * <p>
- * This comparator can be used to sort lists or arrays of files
- * by their name either in a case-sensitive, case-insensitive or
- * system dependant case sensitive way. A number of singleton instances
- * are provided for the various case sensitivity options (using {@link IOCase})
- * and the reverse of those options.
- * <p>
- * Example of a <i>case-sensitive</i> file name sort using the
- * {@link #NAME_COMPARATOR} singleton instance:
- * <pre>
- * List&lt;File&gt; list = ...
- * Collections.sort(list, NameFileComparator.NAME_COMPARATOR);
- * </pre>
- * <p>
- * Example of a <i>reverse case-insensitive</i> file name sort using the
- * {@link #NAME_INSENSITIVE_REVERSE} singleton instance:
- * <pre>
- * File[] array = ...
- * Arrays.sort(array, NameFileComparator.NAME_INSENSITIVE_REVERSE);
- * </pre>
- * <p>
- *
- * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
- * @since Commons IO 1.4
- */
-public class NameFileComparator implements Comparator<File>, Serializable {
-
- /** Case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */
- public static final Comparator<File> NAME_COMPARATOR = new NameFileComparator();
-
- /** Reverse case-sensitive name comparator instance (see {@link IOCase#SENSITIVE}) */
- public static final Comparator<File> NAME_REVERSE = new ReverseComparator<File>(NAME_COMPARATOR);
-
- /** Case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */
- public static final Comparator<File> NAME_INSENSITIVE_COMPARATOR = new NameFileComparator(IOCase.INSENSITIVE);
-
- /** Reverse case-insensitive name comparator instance (see {@link IOCase#INSENSITIVE}) */
- public static final Comparator<File> NAME_INSENSITIVE_REVERSE = new ReverseComparator<File>(NAME_INSENSITIVE_COMPARATOR);
-
- /** System sensitive name comparator instance (see {@link IOCase#SYSTEM}) */
- public static final Comparator<File> NAME_SYSTEM_COMPARATOR = new NameFileComparator(IOCase.SYSTEM);
-
- /** Reverse system sensitive name comparator instance (see {@link IOCase#SYSTEM}) */
- public static final Comparator<File> NAME_SYSTEM_REVERSE = new ReverseComparator<File>(NAME_SYSTEM_COMPARATOR);
-
- /** Whether the comparison is case sensitive. */
- private final IOCase caseSensitivity;
-
- /**
- * Construct a case sensitive file name comparator instance.
- */
- public NameFileComparator() {
- this.caseSensitivity = IOCase.SENSITIVE;
- }
-
- /**
- * Construct a file name comparator instance with the specified case-sensitivity.
- *
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- */
- public NameFileComparator(IOCase caseSensitivity) {
- this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity;
- }
-
- /**
- * Compare the names of two files with the specified case sensitivity.
- *
- * @param obj1 The first file to compare
- * @param obj2 The second file to compare
- * @return a negative value if the first file's name
- * is less than the second, zero if the names are the
- * same and a positive value if the first files name
- * is greater than the second file.
- */
- public int compare(File file1, File file2) {
- return caseSensitivity.checkCompareTo(file1.getName(), file2.getName());
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/comparator/PathFileComparator.java b/emailcommon/src/org/apache/commons/io/comparator/PathFileComparator.java
deleted file mode 100644
index e93113825..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/PathFileComparator.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.comparator;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Comparator;
-
-import org.apache.commons.io.IOCase;
-
-/**
- * Compare the <b>path</b> of two files for order (see {@link File#getPath()}).
- * <p>
- * This comparator can be used to sort lists or arrays of files
- * by their path either in a case-sensitive, case-insensitive or
- * system dependant case sensitive way. A number of singleton instances
- * are provided for the various case sensitivity options (using {@link IOCase})
- * and the reverse of those options.
- * <p>
- * Example of a <i>case-sensitive</i> file path sort using the
- * {@link #PATH_COMPARATOR} singleton instance:
- * <pre>
- * List&lt;File&gt; list = ...
- * Collections.sort(list, PathFileComparator.PATH_COMPARATOR);
- * </pre>
- * <p>
- * Example of a <i>reverse case-insensitive</i> file path sort using the
- * {@link #PATH_INSENSITIVE_REVERSE} singleton instance:
- * <pre>
- * File[] array = ...
- * Arrays.sort(array, PathFileComparator.PATH_INSENSITIVE_REVERSE);
- * </pre>
- * <p>
- *
- * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
- * @since Commons IO 1.4
- */
-public class PathFileComparator implements Comparator<File>, Serializable {
-
- /** Case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */
- public static final Comparator<File> PATH_COMPARATOR = new PathFileComparator();
-
- /** Reverse case-sensitive path comparator instance (see {@link IOCase#SENSITIVE}) */
- public static final Comparator<File> PATH_REVERSE = new ReverseComparator<File>(PATH_COMPARATOR);
-
- /** Case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */
- public static final Comparator<File> PATH_INSENSITIVE_COMPARATOR = new PathFileComparator(IOCase.INSENSITIVE);
-
- /** Reverse case-insensitive path comparator instance (see {@link IOCase#INSENSITIVE}) */
- public static final Comparator<File> PATH_INSENSITIVE_REVERSE = new ReverseComparator<File>(PATH_INSENSITIVE_COMPARATOR);
-
- /** System sensitive path comparator instance (see {@link IOCase#SYSTEM}) */
- public static final Comparator<File> PATH_SYSTEM_COMPARATOR = new PathFileComparator(IOCase.SYSTEM);
-
- /** Reverse system sensitive path comparator instance (see {@link IOCase#SYSTEM}) */
- public static final Comparator<File> PATH_SYSTEM_REVERSE = new ReverseComparator<File>(PATH_SYSTEM_COMPARATOR);
-
- /** Whether the comparison is case sensitive. */
- private final IOCase caseSensitivity;
-
- /**
- * Construct a case sensitive file path comparator instance.
- */
- public PathFileComparator() {
- this.caseSensitivity = IOCase.SENSITIVE;
- }
-
- /**
- * Construct a file path comparator instance with the specified case-sensitivity.
- *
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- */
- public PathFileComparator(IOCase caseSensitivity) {
- this.caseSensitivity = caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity;
- }
-
- /**
- * Compare the paths of two files the specified case sensitivity.
- *
- * @param obj1 The first file to compare
- * @param obj2 The second file to compare
- * @return a negative value if the first file's path
- * is less than the second, zero if the paths are the
- * same and a positive value if the first files path
- * is greater than the second file.
- *
- */
- public int compare(File file1, File file2) {
- return caseSensitivity.checkCompareTo(file1.getPath(), file2.getPath());
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/comparator/ReverseComparator.java b/emailcommon/src/org/apache/commons/io/comparator/ReverseComparator.java
deleted file mode 100644
index ab0b38caa..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/ReverseComparator.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.comparator;
-
-import java.io.Serializable;
-import java.util.Comparator;
-
-/**
- * Reverses the result of comparing two objects using
- * the delegate {@link Comparator}.
- *
- * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
- * @since Commons IO 1.4
- */
-class ReverseComparator<T> implements Comparator<T>, Serializable {
-
- private final Comparator<T> delegate;
-
- /**
- * Construct an instance with the sepecified delegate {@link Comparator}.
- *
- * @param delegate The comparator to delegate to
- */
- public ReverseComparator(Comparator<T> delegate) {
- if (delegate == null) {
- throw new IllegalArgumentException("Delegate comparator is missing");
- }
- this.delegate = delegate;
- }
-
- /**
- * Compare using the delegate Comparator, but reversing the result.
- *
- * @param obj1 The first object to compare
- * @param obj2 The second object to compare
- * @return the result from the delegate {@link Comparator#compare(Object, Object)}
- * reversing the value (i.e. positive becomes negative and vice versa)
- */
- public int compare(T obj1, T obj2) {
- return delegate.compare(obj2, obj1); // parameters switched round
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/comparator/SizeFileComparator.java b/emailcommon/src/org/apache/commons/io/comparator/SizeFileComparator.java
deleted file mode 100644
index 609c159c9..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/SizeFileComparator.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.comparator;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Comparator;
-
-import org.apache.commons.io.FileUtils;
-
-/**
- * Compare the <b>length/size</b> of two files for order (see
- * {@link File#length()} and {@link FileUtils#sizeOfDirectory(File)}).
- * <p>
- * This comparator can be used to sort lists or arrays of files
- * by their length/size.
- * <p>
- * Example of sorting a list of files using the
- * {@link #SIZE_COMPARATOR} singleton instance:
- * <pre>
- * List&lt;File&gt; list = ...
- * Collections.sort(list, LengthFileComparator.LENGTH_COMPARATOR);
- * </pre>
- * <p>
- * Example of doing a <i>reverse</i> sort of an array of files using the
- * {@link #SIZE_REVERSE} singleton instance:
- * <pre>
- * File[] array = ...
- * Arrays.sort(array, LengthFileComparator.LENGTH_REVERSE);
- * </pre>
- * <p>
- * <strong>N.B.</strong> Directories are treated as <b>zero size</b> unless
- * <code>sumDirectoryContents</code> is <code>true</code>.
- *
- * @version $Revision: 609243 $ $Date: 2008-01-06 00:30:42 +0000 (Sun, 06 Jan 2008) $
- * @since Commons IO 1.4
- */
-public class SizeFileComparator implements Comparator<File>, Serializable {
-
- /** Size comparator instance - directories are treated as zero size */
- public static final Comparator<File> SIZE_COMPARATOR = new SizeFileComparator();
-
- /** Reverse size comparator instance - directories are treated as zero size */
- public static final Comparator<File> SIZE_REVERSE = new ReverseComparator<File>(SIZE_COMPARATOR);
-
- /**
- * Size comparator instance which sums the size of a directory's contents
- * using {@link FileUtils#sizeOfDirectory(File)}
- */
- public static final Comparator<File> SIZE_SUMDIR_COMPARATOR = new SizeFileComparator(true);
-
- /**
- * Reverse size comparator instance which sums the size of a directory's contents
- * using {@link FileUtils#sizeOfDirectory(File)}
- */
- public static final Comparator<File> SIZE_SUMDIR_REVERSE = new ReverseComparator<File>(SIZE_SUMDIR_COMPARATOR);
-
- /** Whether the sum of the directory's contents should be calculated. */
- private final boolean sumDirectoryContents;
-
- /**
- * Construct a file size comparator instance (directories treated as zero size).
- */
- public SizeFileComparator() {
- this.sumDirectoryContents = false;
- }
-
- /**
- * Construct a file size comparator instance specifying whether the size of
- * the directory contents should be aggregated.
- * <p>
- * If the <code>sumDirectoryContents</code> is <code>true</code> The size of
- * directories is calculated using {@link FileUtils#sizeOfDirectory(File)}.
- *
- * @param sumDirectoryContents <code>true</code> if the sum of the directoryies contents
- * should be calculated, otherwise <code>false</code> if directories should be treated
- * as size zero (see {@link FileUtils#sizeOfDirectory(File)}).
- */
- public SizeFileComparator(boolean sumDirectoryContents) {
- this.sumDirectoryContents = sumDirectoryContents;
- }
-
- /**
- * Compare the length of two files.
- *
- * @param obj1 The first file to compare
- * @param obj2 The second file to compare
- * @return a negative value if the first file's length
- * is less than the second, zero if the lengths are the
- * same and a positive value if the first files length
- * is greater than the second file.
- *
- */
- public int compare(File file1, File file2) {
- long size1 = 0;
- if (file1.isDirectory()) {
- size1 = sumDirectoryContents && file1.exists() ? FileUtils.sizeOfDirectory(file1) : 0;
- } else {
- size1 = file1.length();
- }
- long size2 = 0;
- if (file2.isDirectory()) {
- size2 = sumDirectoryContents && file2.exists() ? FileUtils.sizeOfDirectory(file2) : 0;
- } else {
- size2 = file2.length();
- }
- long result = size1 - size2;
- if (result < 0) {
- return -1;
- } else if (result > 0) {
- return 1;
- } else {
- return 0;
- }
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/comparator/package.html b/emailcommon/src/org/apache/commons/io/comparator/package.html
deleted file mode 100644
index a2f756f18..000000000
--- a/emailcommon/src/org/apache/commons/io/comparator/package.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<!--
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-<html>
-<body>
-<p>This package provides various {@link java.util.Comparator} implementations
-for {@link java.io.File}s.
-</p>
-
-</body>
-</html>
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/AbstractFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/AbstractFileFilter.java
deleted file mode 100644
index 9e188f82e..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/AbstractFileFilter.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-
-/**
- * An abstract class which implements the Java FileFilter and FilenameFilter
- * interfaces via the IOFileFilter interface.
- * <p>
- * Note that a subclass <b>must</b> override one of the accept methods,
- * otherwise your class will infinitely loop.
- *
- * @since Commons IO 1.0
- * @version $Revision: 539231 $ $Date: 2007-05-18 04:10:33 +0100 (Fri, 18 May 2007) $
- *
- * @author Stephen Colebourne
- */
-public abstract class AbstractFileFilter implements IOFileFilter {
-
- /**
- * Checks to see if the File should be accepted by this filter.
- *
- * @param file the File to check
- * @return true if this file matches the test
- */
- public boolean accept(File file) {
- return accept(file.getParentFile(), file.getName());
- }
-
- /**
- * Checks to see if the File should be accepted by this filter.
- *
- * @param dir the directory File to check
- * @param name the filename within the directory to check
- * @return true if this file matches the test
- */
- public boolean accept(File dir, String name) {
- return accept(new File(dir, name));
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- public String toString() {
- String name = getClass().getName();
- int period = name.lastIndexOf('.');
- return (period > 0 ? name.substring(period + 1) : name);
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/AgeFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/AgeFileFilter.java
deleted file mode 100644
index ab73cb840..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/AgeFileFilter.java
+++ /dev/null
@@ -1,150 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Date;
-
-import org.apache.commons.io.FileUtils;
-
-/**
- * Filters files based on a cutoff time, can filter either newer
- * files or files equal to or older.
- * <p>
- * For example, to print all files and directories in the
- * current directory older than one day:
- *
- * <pre>
- * File dir = new File(".");
- * // We are interested in files older than one day
- * long cutoff = System.currentTimeMillis() - (24 * 60 * 60 * 1000);
- * String[] files = dir.list( new AgeFileFilter(cutoff) );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @author Rahul Akolkar
- * @version $Id: AgeFileFilter.java 606381 2007-12-22 02:03:16Z ggregory $
- * @since Commons IO 1.2
- */
-public class AgeFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The cutoff time threshold. */
- private final long cutoff;
- /** Whether the files accepted will be older or newer. */
- private final boolean acceptOlder;
-
- /**
- * Constructs a new age file filter for files equal to or older than
- * a certain cutoff
- *
- * @param cutoff the threshold age of the files
- */
- public AgeFileFilter(long cutoff) {
- this(cutoff, true);
- }
-
- /**
- * Constructs a new age file filter for files on any one side
- * of a certain cutoff.
- *
- * @param cutoff the threshold age of the files
- * @param acceptOlder if true, older files (at or before the cutoff)
- * are accepted, else newer ones (after the cutoff).
- */
- public AgeFileFilter(long cutoff, boolean acceptOlder) {
- this.acceptOlder = acceptOlder;
- this.cutoff = cutoff;
- }
-
- /**
- * Constructs a new age file filter for files older than (at or before)
- * a certain cutoff date.
- *
- * @param cutoffDate the threshold age of the files
- */
- public AgeFileFilter(Date cutoffDate) {
- this(cutoffDate, true);
- }
-
- /**
- * Constructs a new age file filter for files on any one side
- * of a certain cutoff date.
- *
- * @param cutoffDate the threshold age of the files
- * @param acceptOlder if true, older files (at or before the cutoff)
- * are accepted, else newer ones (after the cutoff).
- */
- public AgeFileFilter(Date cutoffDate, boolean acceptOlder) {
- this(cutoffDate.getTime(), acceptOlder);
- }
-
- /**
- * Constructs a new age file filter for files older than (at or before)
- * a certain File (whose last modification time will be used as reference).
- *
- * @param cutoffReference the file whose last modification
- * time is usesd as the threshold age of the files
- */
- public AgeFileFilter(File cutoffReference) {
- this(cutoffReference, true);
- }
-
- /**
- * Constructs a new age file filter for files on any one side
- * of a certain File (whose last modification time will be used as
- * reference).
- *
- * @param cutoffReference the file whose last modification
- * time is usesd as the threshold age of the files
- * @param acceptOlder if true, older files (at or before the cutoff)
- * are accepted, else newer ones (after the cutoff).
- */
- public AgeFileFilter(File cutoffReference, boolean acceptOlder) {
- this(cutoffReference.lastModified(), acceptOlder);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks to see if the last modification of the file matches cutoff
- * favorably.
- * <p>
- * If last modification time equals cutoff and newer files are required,
- * file <b>IS NOT</b> selected.
- * If last modification time equals cutoff and older files are required,
- * file <b>IS</b> selected.
- *
- * @param file the File to check
- * @return true if the filename matches
- */
- public boolean accept(File file) {
- boolean newer = FileUtils.isFileNewer(file, cutoff);
- return acceptOlder ? !newer : newer;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- public String toString() {
- String condition = acceptOlder ? "<=" : ">";
- return super.toString() + "(" + condition + cutoff + ")";
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/AndFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/AndFileFilter.java
deleted file mode 100644
index 9f3bb06ae..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/AndFileFilter.java
+++ /dev/null
@@ -1,171 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * A {@link java.io.FileFilter} providing conditional AND logic across a list of
- * file filters. This filter returns <code>true</code> if all filters in the
- * list return <code>true</code>. Otherwise, it returns <code>false</code>.
- * Checking of the file filter list stops when the first filter returns
- * <code>false</code>.
- *
- * @since Commons IO 1.0
- * @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
- *
- * @author Steven Caswell
- */
-public class AndFileFilter
- extends AbstractFileFilter
- implements ConditionalFileFilter, Serializable {
-
- /** The list of file filters. */
- private List<IOFileFilter> fileFilters;
-
- /**
- * Constructs a new instance of <code>AndFileFilter</code>.
- *
- * @since Commons IO 1.1
- */
- public AndFileFilter() {
- this.fileFilters = new ArrayList<IOFileFilter>();
- }
-
- /**
- * Constructs a new instance of <code>AndFileFilter</code>
- * with the specified list of filters.
- *
- * @param fileFilters a List of IOFileFilter instances, copied, null ignored
- * @since Commons IO 1.1
- */
- public AndFileFilter(final List<IOFileFilter> fileFilters) {
- if (fileFilters == null) {
- this.fileFilters = new ArrayList<IOFileFilter>();
- } else {
- this.fileFilters = new ArrayList<IOFileFilter>(fileFilters);
- }
- }
-
- /**
- * Constructs a new file filter that ANDs the result of two other filters.
- *
- * @param filter1 the first filter, must not be null
- * @param filter2 the second filter, must not be null
- * @throws IllegalArgumentException if either filter is null
- */
- public AndFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
- if (filter1 == null || filter2 == null) {
- throw new IllegalArgumentException("The filters must not be null");
- }
- this.fileFilters = new ArrayList<IOFileFilter>();
- addFileFilter(filter1);
- addFileFilter(filter2);
- }
-
- /**
- * {@inheritDoc}
- */
- public void addFileFilter(final IOFileFilter ioFileFilter) {
- this.fileFilters.add(ioFileFilter);
- }
-
- /**
- * {@inheritDoc}
- */
- public List<IOFileFilter> getFileFilters() {
- return Collections.unmodifiableList(this.fileFilters);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean removeFileFilter(final IOFileFilter ioFileFilter) {
- return this.fileFilters.remove(ioFileFilter);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void setFileFilters(final List<IOFileFilter> fileFilters) {
- this.fileFilters = new ArrayList<IOFileFilter>(fileFilters);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean accept(final File file) {
- if (this.fileFilters.size() == 0) {
- return false;
- }
- for (Iterator<IOFileFilter> iter = this.fileFilters.iterator(); iter.hasNext();) {
- IOFileFilter fileFilter = iter.next();
- if (!fileFilter.accept(file)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean accept(final File file, final String name) {
- if (this.fileFilters.size() == 0) {
- return false;
- }
- for (Iterator<IOFileFilter> iter = this.fileFilters.iterator(); iter.hasNext();) {
- IOFileFilter fileFilter = iter.next();
- if (!fileFilter.accept(file, name)) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- @Override
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(super.toString());
- buffer.append("(");
- if (fileFilters != null) {
- for (int i = 0; i < fileFilters.size(); i++) {
- if (i > 0) {
- buffer.append(",");
- }
- Object filter = fileFilters.get(i);
- buffer.append(filter == null ? "null" : filter.toString());
- }
- }
- buffer.append(")");
- return buffer.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/CanReadFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/CanReadFileFilter.java
deleted file mode 100644
index a9c132570..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/CanReadFileFilter.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * This filter accepts <code>File</code>s that can be read.
- * <p>
- * Example, showing how to print out a list of the
- * current directory's <i>readable</i> files:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( CanReadFileFilter.CAN_READ );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * <p>
- * Example, showing how to print out a list of the
- * current directory's <i>un-readable</i> files:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( CanReadFileFilter.CANNOT_READ );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * <p>
- * Example, showing how to print out a list of the
- * current directory's <i>read-only</i> files:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( CanReadFileFilter.READ_ONLY );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.3
- * @version $Revision: 587916 $
- */
-public class CanReadFileFilter extends AbstractFileFilter implements Serializable {
-
- /** Singleton instance of <i>readable</i> filter */
- public static final IOFileFilter CAN_READ = new CanReadFileFilter();
-
- /** Singleton instance of not <i>readable</i> filter */
- public static final IOFileFilter CANNOT_READ = new NotFileFilter(CAN_READ);
-
- /** Singleton instance of <i>read-only</i> filter */
- public static final IOFileFilter READ_ONLY = new AndFileFilter(CAN_READ,
- CanWriteFileFilter.CANNOT_WRITE);
-
- /**
- * Restrictive consructor.
- */
- protected CanReadFileFilter() {
- }
-
- /**
- * Checks to see if the file can be read.
- *
- * @param file the File to check.
- * @return <code>true</code> if the file can be
- * read, otherwise <code>false</code>.
- */
- public boolean accept(File file) {
- return file.canRead();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/CanWriteFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/CanWriteFileFilter.java
deleted file mode 100644
index da664f25c..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/CanWriteFileFilter.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * This filter accepts <code>File</code>s that can be written to.
- * <p>
- * Example, showing how to print out a list of the
- * current directory's <i>writable</i> files:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( CanWriteFileFilter.CAN_WRITE );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * <p>
- * Example, showing how to print out a list of the
- * current directory's <i>un-writable</i> files:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( CanWriteFileFilter.CANNOT_WRITE );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * <p>
- * <b>N.B.</b> For read-only files, use
- * <code>CanReadFileFilter.READ_ONLY</code>.
- *
- * @since Commons IO 1.3
- * @version $Revision: 587916 $
- */
-public class CanWriteFileFilter extends AbstractFileFilter implements Serializable {
-
- /** Singleton instance of <i>writable</i> filter */
- public static final IOFileFilter CAN_WRITE = new CanWriteFileFilter();
-
- /** Singleton instance of not <i>writable</i> filter */
- public static final IOFileFilter CANNOT_WRITE = new NotFileFilter(CAN_WRITE);
-
- /**
- * Restrictive consructor.
- */
- protected CanWriteFileFilter() {
- }
-
- /**
- * Checks to see if the file can be written to.
- *
- * @param file the File to check
- * @return <code>true</code> if the file can be
- * written to, otherwise <code>false</code>.
- */
- public boolean accept(File file) {
- return file.canWrite();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/ConditionalFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/ConditionalFileFilter.java
deleted file mode 100644
index b1c481368..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/ConditionalFileFilter.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.util.List;
-
-/**
- * Defines operations for conditional file filters.
- *
- * @since Commons IO 1.1
- * @version $Revision: 437567 $ $Date: 2006-08-28 07:39:07 +0100 (Mon, 28 Aug 2006) $
- *
- * @author Steven Caswell
- */
-public interface ConditionalFileFilter {
-
- /**
- * Adds the specified file filter to the list of file filters at the end of
- * the list.
- *
- * @param ioFileFilter the filter to be added
- * @since Commons IO 1.1
- */
- public void addFileFilter(IOFileFilter ioFileFilter);
-
- /**
- * Returns this conditional file filter's list of file filters.
- *
- * @return the file filter list
- * @since Commons IO 1.1
- */
- public List<IOFileFilter> getFileFilters();
-
- /**
- * Removes the specified file filter.
- *
- * @param ioFileFilter filter to be removed
- * @return <code>true</code> if the filter was found in the list,
- * <code>false</code> otherwise
- * @since Commons IO 1.1
- */
- public boolean removeFileFilter(IOFileFilter ioFileFilter);
-
- /**
- * Sets the list of file filters, replacing any previously configured
- * file filters on this filter.
- *
- * @param fileFilters the list of filters
- * @since Commons IO 1.1
- */
- public void setFileFilters(List<IOFileFilter> fileFilters);
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/DelegateFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/DelegateFileFilter.java
deleted file mode 100644
index c2d67c469..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/DelegateFileFilter.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FilenameFilter;
-import java.io.Serializable;
-
-/**
- * This class turns a Java FileFilter or FilenameFilter into an IO FileFilter.
- *
- * @since Commons IO 1.0
- * @version $Revision: 591058 $ $Date: 2007-11-01 15:47:05 +0000 (Thu, 01 Nov 2007) $
- *
- * @author Stephen Colebourne
- */
-public class DelegateFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The Filename filter */
- private final FilenameFilter filenameFilter;
- /** The File filter */
- private final FileFilter fileFilter;
-
- /**
- * Constructs a delegate file filter around an existing FilenameFilter.
- *
- * @param filter the filter to decorate
- */
- public DelegateFileFilter(FilenameFilter filter) {
- if (filter == null) {
- throw new IllegalArgumentException("The FilenameFilter must not be null");
- }
- this.filenameFilter = filter;
- this.fileFilter = null;
- }
-
- /**
- * Constructs a delegate file filter around an existing FileFilter.
- *
- * @param filter the filter to decorate
- */
- public DelegateFileFilter(FileFilter filter) {
- if (filter == null) {
- throw new IllegalArgumentException("The FileFilter must not be null");
- }
- this.fileFilter = filter;
- this.filenameFilter = null;
- }
-
- /**
- * Checks the filter.
- *
- * @param file the file to check
- * @return true if the filter matches
- */
- public boolean accept(File file) {
- if (fileFilter != null) {
- return fileFilter.accept(file);
- } else {
- return super.accept(file);
- }
- }
-
- /**
- * Checks the filter.
- *
- * @param dir the directory
- * @param name the filename in the directory
- * @return true if the filter matches
- */
- public boolean accept(File dir, String name) {
- if (filenameFilter != null) {
- return filenameFilter.accept(dir, name);
- } else {
- return super.accept(dir, name);
- }
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- public String toString() {
- String delegate = (fileFilter != null ? fileFilter.toString() : filenameFilter.toString());
- return super.toString() + "(" + delegate + ")";
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/DirectoryFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/DirectoryFileFilter.java
deleted file mode 100644
index 3412e7bef..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/DirectoryFileFilter.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * This filter accepts <code>File</code>s that are directories.
- * <p>
- * For example, here is how to print out a list of the
- * current directory's subdirectories:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( DirectoryFileFilter.INSTANCE );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.0
- * @version $Revision: 587916 $ $Date: 2007-10-24 16:53:07 +0100 (Wed, 24 Oct 2007) $
- *
- * @author Stephen Colebourne
- * @author Peter Donald
- */
-public class DirectoryFileFilter extends AbstractFileFilter implements Serializable {
-
- /**
- * Singleton instance of directory filter.
- * @since Commons IO 1.3
- */
- public static final IOFileFilter DIRECTORY = new DirectoryFileFilter();
- /**
- * Singleton instance of directory filter.
- * Please use the identical DirectoryFileFilter.DIRECTORY constant.
- * The new name is more JDK 1.5 friendly as it doesn't clash with other
- * values when using static imports.
- */
- public static final IOFileFilter INSTANCE = DIRECTORY;
-
- /**
- * Restrictive consructor.
- */
- protected DirectoryFileFilter() {
- }
-
- /**
- * Checks to see if the file is a directory.
- *
- * @param file the File to check
- * @return true if the file is a directory
- */
- public boolean accept(File file) {
- return file.isDirectory();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/EmptyFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/EmptyFileFilter.java
deleted file mode 100644
index e88a862d4..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/EmptyFileFilter.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * This filter accepts files or directories that are empty.
- * <p>
- * If the <code>File</code> is a directory it checks that
- * it contains no files.
- * <p>
- * Example, showing how to print out a list of the
- * current directory's empty files/directories:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( EmptyFileFilter.EMPTY );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * <p>
- * Example, showing how to print out a list of the
- * current directory's non-empty files/directories:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( EmptyFileFilter.NOT_EMPTY );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.3
- * @version $Revision: 587916 $
- */
-public class EmptyFileFilter extends AbstractFileFilter implements Serializable {
-
- /** Singleton instance of <i>empty</i> filter */
- public static final IOFileFilter EMPTY = new EmptyFileFilter();
-
- /** Singleton instance of <i>not-empty</i> filter */
- public static final IOFileFilter NOT_EMPTY = new NotFileFilter(EMPTY);
-
- /**
- * Restrictive consructor.
- */
- protected EmptyFileFilter() {
- }
-
- /**
- * Checks to see if the file is empty.
- *
- * @param file the file or directory to check
- * @return <code>true</code> if the file or directory
- * is <i>empty</i>, otherwise <code>false</code>.
- */
- public boolean accept(File file) {
- if (file.isDirectory()) {
- File[] files = file.listFiles();
- return (files == null || files.length == 0);
- } else {
- return (file.length() == 0);
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/FalseFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/FalseFileFilter.java
deleted file mode 100644
index 8a87d4092..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/FalseFileFilter.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * A file filter that always returns false.
- *
- * @since Commons IO 1.0
- * @version $Revision: 587978 $ $Date: 2007-10-24 20:36:51 +0100 (Wed, 24 Oct 2007) $
- *
- * @author Stephen Colebourne
- */
-public class FalseFileFilter implements IOFileFilter, Serializable {
-
- /**
- * Singleton instance of false filter.
- * @since Commons IO 1.3
- */
- public static final IOFileFilter FALSE = new FalseFileFilter();
- /**
- * Singleton instance of false filter.
- * Please use the identical FalseFileFilter.FALSE constant.
- * The new name is more JDK 1.5 friendly as it doesn't clash with other
- * values when using static imports.
- */
- public static final IOFileFilter INSTANCE = FALSE;
-
- /**
- * Restrictive consructor.
- */
- protected FalseFileFilter() {
- }
-
- /**
- * Returns false.
- *
- * @param file the file to check
- * @return false
- */
- public boolean accept(File file) {
- return false;
- }
-
- /**
- * Returns false.
- *
- * @param dir the directory to check
- * @param name the filename
- * @return false
- */
- public boolean accept(File dir, String name) {
- return false;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/FileFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/FileFileFilter.java
deleted file mode 100644
index 0d49eddd4..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/FileFileFilter.java
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * This filter accepts <code>File</code>s that are files (not directories).
- * <p>
- * For example, here is how to print out a list of the real files
- * within the current directory:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( FileFileFilter.FILE );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.3
- * @version $Revision: 155419 $ $Date: 2007-10-24 16:53:07 +0100 (Wed, 24 Oct 2007) $
- */
-public class FileFileFilter extends AbstractFileFilter implements Serializable {
-
- /** Singleton instance of file filter */
- public static final IOFileFilter FILE = new FileFileFilter();
-
- /**
- * Restrictive consructor.
- */
- protected FileFileFilter() {
- }
-
- /**
- * Checks to see if the file is a file.
- *
- * @param file the File to check
- * @return true if the file is a file
- */
- public boolean accept(File file) {
- return file.isFile();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/FileFilterUtils.java b/emailcommon/src/org/apache/commons/io/filefilter/FileFilterUtils.java
deleted file mode 100644
index 71c37b1d2..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/FileFilterUtils.java
+++ /dev/null
@@ -1,361 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FilenameFilter;
-import java.util.Date;
-
-/**
- * Useful utilities for working with file filters. It provides access to all
- * file filter implementations in this package so you don't have to import
- * every class you use.
- *
- * @since Commons IO 1.0
- * @version $Id: FileFilterUtils.java 609286 2008-01-06 10:01:26Z scolebourne $
- *
- * @author Stephen Colebourne
- * @author Jeremias Maerki
- * @author Masato Tezuka
- * @author Rahul Akolkar
- */
-public class FileFilterUtils {
-
- /**
- * FileFilterUtils is not normally instantiated.
- */
- public FileFilterUtils() {
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns a filter that returns true if the filename starts with the specified text.
- *
- * @param prefix the filename prefix
- * @return a prefix checking filter
- */
- public static IOFileFilter prefixFileFilter(String prefix) {
- return new PrefixFileFilter(prefix);
- }
-
- /**
- * Returns a filter that returns true if the filename ends with the specified text.
- *
- * @param suffix the filename suffix
- * @return a suffix checking filter
- */
- public static IOFileFilter suffixFileFilter(String suffix) {
- return new SuffixFileFilter(suffix);
- }
-
- /**
- * Returns a filter that returns true if the filename matches the specified text.
- *
- * @param name the filename
- * @return a name checking filter
- */
- public static IOFileFilter nameFileFilter(String name) {
- return new NameFileFilter(name);
- }
-
- /**
- * Returns a filter that checks if the file is a directory.
- *
- * @return file filter that accepts only directories and not files
- */
- public static IOFileFilter directoryFileFilter() {
- return DirectoryFileFilter.DIRECTORY;
- }
-
- /**
- * Returns a filter that checks if the file is a file (and not a directory).
- *
- * @return file filter that accepts only files and not directories
- */
- public static IOFileFilter fileFileFilter() {
- return FileFileFilter.FILE;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns a filter that ANDs the two specified filters.
- *
- * @param filter1 the first filter
- * @param filter2 the second filter
- * @return a filter that ANDs the two specified filters
- */
- public static IOFileFilter andFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
- return new AndFileFilter(filter1, filter2);
- }
-
- /**
- * Returns a filter that ORs the two specified filters.
- *
- * @param filter1 the first filter
- * @param filter2 the second filter
- * @return a filter that ORs the two specified filters
- */
- public static IOFileFilter orFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
- return new OrFileFilter(filter1, filter2);
- }
-
- /**
- * Returns a filter that NOTs the specified filter.
- *
- * @param filter the filter to invert
- * @return a filter that NOTs the specified filter
- */
- public static IOFileFilter notFileFilter(IOFileFilter filter) {
- return new NotFileFilter(filter);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns a filter that always returns true.
- *
- * @return a true filter
- */
- public static IOFileFilter trueFileFilter() {
- return TrueFileFilter.TRUE;
- }
-
- /**
- * Returns a filter that always returns false.
- *
- * @return a false filter
- */
- public static IOFileFilter falseFileFilter() {
- return FalseFileFilter.FALSE;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns an <code>IOFileFilter</code> that wraps the
- * <code>FileFilter</code> instance.
- *
- * @param filter the filter to be wrapped
- * @return a new filter that implements IOFileFilter
- */
- public static IOFileFilter asFileFilter(FileFilter filter) {
- return new DelegateFileFilter(filter);
- }
-
- /**
- * Returns an <code>IOFileFilter</code> that wraps the
- * <code>FilenameFilter</code> instance.
- *
- * @param filter the filter to be wrapped
- * @return a new filter that implements IOFileFilter
- */
- public static IOFileFilter asFileFilter(FilenameFilter filter) {
- return new DelegateFileFilter(filter);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns a filter that returns true if the file was last modified after
- * the specified cutoff time.
- *
- * @param cutoff the time threshold
- * @return an appropriately configured age file filter
- * @since Commons IO 1.2
- */
- public static IOFileFilter ageFileFilter(long cutoff) {
- return new AgeFileFilter(cutoff);
- }
-
- /**
- * Returns a filter that filters files based on a cutoff time.
- *
- * @param cutoff the time threshold
- * @param acceptOlder if true, older files get accepted, if false, newer
- * @return an appropriately configured age file filter
- * @since Commons IO 1.2
- */
- public static IOFileFilter ageFileFilter(long cutoff, boolean acceptOlder) {
- return new AgeFileFilter(cutoff, acceptOlder);
- }
-
- /**
- * Returns a filter that returns true if the file was last modified after
- * the specified cutoff date.
- *
- * @param cutoffDate the time threshold
- * @return an appropriately configured age file filter
- * @since Commons IO 1.2
- */
- public static IOFileFilter ageFileFilter(Date cutoffDate) {
- return new AgeFileFilter(cutoffDate);
- }
-
- /**
- * Returns a filter that filters files based on a cutoff date.
- *
- * @param cutoffDate the time threshold
- * @param acceptOlder if true, older files get accepted, if false, newer
- * @return an appropriately configured age file filter
- * @since Commons IO 1.2
- */
- public static IOFileFilter ageFileFilter(Date cutoffDate, boolean acceptOlder) {
- return new AgeFileFilter(cutoffDate, acceptOlder);
- }
-
- /**
- * Returns a filter that returns true if the file was last modified after
- * the specified reference file.
- *
- * @param cutoffReference the file whose last modification
- * time is usesd as the threshold age of the files
- * @return an appropriately configured age file filter
- * @since Commons IO 1.2
- */
- public static IOFileFilter ageFileFilter(File cutoffReference) {
- return new AgeFileFilter(cutoffReference);
- }
-
- /**
- * Returns a filter that filters files based on a cutoff reference file.
- *
- * @param cutoffReference the file whose last modification
- * time is usesd as the threshold age of the files
- * @param acceptOlder if true, older files get accepted, if false, newer
- * @return an appropriately configured age file filter
- * @since Commons IO 1.2
- */
- public static IOFileFilter ageFileFilter(File cutoffReference, boolean acceptOlder) {
- return new AgeFileFilter(cutoffReference, acceptOlder);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Returns a filter that returns true if the file is bigger than a certain size.
- *
- * @param threshold the file size threshold
- * @return an appropriately configured SizeFileFilter
- * @since Commons IO 1.2
- */
- public static IOFileFilter sizeFileFilter(long threshold) {
- return new SizeFileFilter(threshold);
- }
-
- /**
- * Returns a filter that filters based on file size.
- *
- * @param threshold the file size threshold
- * @param acceptLarger if true, larger files get accepted, if false, smaller
- * @return an appropriately configured SizeFileFilter
- * @since Commons IO 1.2
- */
- public static IOFileFilter sizeFileFilter(long threshold, boolean acceptLarger) {
- return new SizeFileFilter(threshold, acceptLarger);
- }
-
- /**
- * Returns a filter that accepts files whose size is &gt;= minimum size
- * and &lt;= maximum size.
- *
- * @param minSizeInclusive the minimum file size (inclusive)
- * @param maxSizeInclusive the maximum file size (inclusive)
- * @return an appropriately configured IOFileFilter
- * @since Commons IO 1.3
- */
- public static IOFileFilter sizeRangeFileFilter(long minSizeInclusive, long maxSizeInclusive ) {
- IOFileFilter minimumFilter = new SizeFileFilter(minSizeInclusive, true);
- IOFileFilter maximumFilter = new SizeFileFilter(maxSizeInclusive + 1L, false);
- return new AndFileFilter(minimumFilter, maximumFilter);
- }
-
- //-----------------------------------------------------------------------
- /* Constructed on demand and then cached */
- private static IOFileFilter cvsFilter;
-
- /* Constructed on demand and then cached */
- private static IOFileFilter svnFilter;
-
- /**
- * Decorates a filter to make it ignore CVS directories.
- * Passing in <code>null</code> will return a filter that accepts everything
- * except CVS directories.
- *
- * @param filter the filter to decorate, null means an unrestricted filter
- * @return the decorated filter, never null
- * @since Commons IO 1.1 (method existed but had bug in 1.0)
- */
- public static IOFileFilter makeCVSAware(IOFileFilter filter) {
- if (cvsFilter == null) {
- cvsFilter = notFileFilter(
- andFileFilter(directoryFileFilter(), nameFileFilter("CVS")));
- }
- if (filter == null) {
- return cvsFilter;
- } else {
- return andFileFilter(filter, cvsFilter);
- }
- }
-
- /**
- * Decorates a filter to make it ignore SVN directories.
- * Passing in <code>null</code> will return a filter that accepts everything
- * except SVN directories.
- *
- * @param filter the filter to decorate, null means an unrestricted filter
- * @return the decorated filter, never null
- * @since Commons IO 1.1
- */
- public static IOFileFilter makeSVNAware(IOFileFilter filter) {
- if (svnFilter == null) {
- svnFilter = notFileFilter(
- andFileFilter(directoryFileFilter(), nameFileFilter(".svn")));
- }
- if (filter == null) {
- return svnFilter;
- } else {
- return andFileFilter(filter, svnFilter);
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Decorates a filter so that it only applies to directories and not to files.
- *
- * @param filter the filter to decorate, null means an unrestricted filter
- * @return the decorated filter, never null
- * @since Commons IO 1.3
- */
- public static IOFileFilter makeDirectoryOnly(IOFileFilter filter) {
- if (filter == null) {
- return DirectoryFileFilter.DIRECTORY;
- }
- return new AndFileFilter(DirectoryFileFilter.DIRECTORY, filter);
- }
-
- /**
- * Decorates a filter so that it only applies to files and not to directories.
- *
- * @param filter the filter to decorate, null means an unrestricted filter
- * @return the decorated filter, never null
- * @since Commons IO 1.3
- */
- public static IOFileFilter makeFileOnly(IOFileFilter filter) {
- if (filter == null) {
- return FileFileFilter.FILE;
- }
- return new AndFileFilter(FileFileFilter.FILE, filter);
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/HiddenFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/HiddenFileFilter.java
deleted file mode 100644
index 244153d5e..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/HiddenFileFilter.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * This filter accepts <code>File</code>s that are hidden.
- * <p>
- * Example, showing how to print out a list of the
- * current directory's <i>hidden</i> files:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( HiddenFileFilter.HIDDEN );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * <p>
- * Example, showing how to print out a list of the
- * current directory's <i>visible</i> (i.e. not hidden) files:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( HiddenFileFilter.VISIBLE );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.3
- * @version $Revision: 587916 $
- */
-public class HiddenFileFilter extends AbstractFileFilter implements Serializable {
-
- /** Singleton instance of <i>hidden</i> filter */
- public static final IOFileFilter HIDDEN = new HiddenFileFilter();
-
- /** Singleton instance of <i>visible</i> filter */
- public static final IOFileFilter VISIBLE = new NotFileFilter(HIDDEN);
-
- /**
- * Restrictive consructor.
- */
- protected HiddenFileFilter() {
- }
-
- /**
- * Checks to see if the file is hidden.
- *
- * @param file the File to check
- * @return <code>true</code> if the file is
- * <i>hidden</i>, otherwise <code>false</code>.
- */
- public boolean accept(File file) {
- return file.isHidden();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/IOFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/IOFileFilter.java
deleted file mode 100644
index 5ebd82751..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/IOFileFilter.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.FileFilter;
-import java.io.FilenameFilter;
-
-/**
- * An interface which brings the FileFilter and FilenameFilter
- * interfaces together.
- *
- * @since Commons IO 1.0
- * @version $Revision: 471628 $ $Date: 2006-11-06 04:06:45 +0000 (Mon, 06 Nov 2006) $
- *
- * @author Stephen Colebourne
- */
-public interface IOFileFilter extends FileFilter, FilenameFilter {
-
- /**
- * Checks to see if the File should be accepted by this filter.
- * <p>
- * Defined in {@link java.io.FileFilter}.
- *
- * @param file the File to check
- * @return true if this file matches the test
- */
- public boolean accept(File file);
-
- /**
- * Checks to see if the File should be accepted by this filter.
- * <p>
- * Defined in {@link java.io.FilenameFilter}.
- *
- * @param dir the directory File to check
- * @param name the filename within the directory to check
- * @return true if this file matches the test
- */
- public boolean accept(File dir, String name);
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/NameFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/NameFileFilter.java
deleted file mode 100644
index 19fe380e1..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/NameFileFilter.java
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.List;
-
-import org.apache.commons.io.IOCase;
-
-/**
- * Filters filenames for a certain name.
- * <p>
- * For example, to print all files and directories in the
- * current directory whose name is <code>Test</code>:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( new NameFileFilter("Test") );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.0
- * @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
- *
- * @author Stephen Colebourne
- * @author Federico Barbieri
- * @author Serge Knystautas
- * @author Peter Donald
- */
-public class NameFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The filenames to search for */
- private final String[] names;
- /** Whether the comparison is case sensitive. */
- private final IOCase caseSensitivity;
-
- /**
- * Constructs a new case-sensitive name file filter for a single name.
- *
- * @param name the name to allow, must not be null
- * @throws IllegalArgumentException if the name is null
- */
- public NameFileFilter(String name) {
- this(name, null);
- }
-
- /**
- * Construct a new name file filter specifying case-sensitivity.
- *
- * @param name the name to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the name is null
- */
- public NameFileFilter(String name, IOCase caseSensitivity) {
- if (name == null) {
- throw new IllegalArgumentException("The wildcard must not be null");
- }
- this.names = new String[] {name};
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Constructs a new case-sensitive name file filter for an array of names.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param names the names to allow, must not be null
- * @throws IllegalArgumentException if the names array is null
- */
- public NameFileFilter(String[] names) {
- this(names, null);
- }
-
- /**
- * Constructs a new name file filter for an array of names specifying case-sensitivity.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param names the names to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the names array is null
- */
- public NameFileFilter(String[] names, IOCase caseSensitivity) {
- if (names == null) {
- throw new IllegalArgumentException("The array of names must not be null");
- }
- this.names = names;
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Constructs a new case-sensitive name file filter for a list of names.
- *
- * @param names the names to allow, must not be null
- * @throws IllegalArgumentException if the name list is null
- * @throws ClassCastException if the list does not contain Strings
- */
- public NameFileFilter(List<String> names) {
- this(names, null);
- }
-
- /**
- * Constructs a new name file filter for a list of names specifying case-sensitivity.
- *
- * @param names the names to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the name list is null
- * @throws ClassCastException if the list does not contain Strings
- */
- public NameFileFilter(List<String> names, IOCase caseSensitivity) {
- if (names == null) {
- throw new IllegalArgumentException("The list of names must not be null");
- }
- this.names = names.toArray(new String[names.size()]);
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks to see if the filename matches.
- *
- * @param file the File to check
- * @return true if the filename matches
- */
- @Override
- public boolean accept(File file) {
- String name = file.getName();
- for (int i = 0; i < this.names.length; i++) {
- if (caseSensitivity.checkEquals(name, names[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Checks to see if the filename matches.
- *
- * @param file the File directory
- * @param name the filename
- * @return true if the filename matches
- */
- @Override
- public boolean accept(File file, String name) {
- for (int i = 0; i < names.length; i++) {
- if (caseSensitivity.checkEquals(name, names[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- @Override
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(super.toString());
- buffer.append("(");
- if (names != null) {
- for (int i = 0; i < names.length; i++) {
- if (i > 0) {
- buffer.append(",");
- }
- buffer.append(names[i]);
- }
- }
- buffer.append(")");
- return buffer.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/NotFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/NotFileFilter.java
deleted file mode 100644
index 710c8ecf3..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/NotFileFilter.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * This filter produces a logical NOT of the filters specified.
- *
- * @since Commons IO 1.0
- * @version $Revision: 591058 $ $Date: 2007-11-01 15:47:05 +0000 (Thu, 01 Nov 2007) $
- *
- * @author Stephen Colebourne
- */
-public class NotFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The filter */
- private final IOFileFilter filter;
-
- /**
- * Constructs a new file filter that NOTs the result of another filters.
- *
- * @param filter the filter, must not be null
- * @throws IllegalArgumentException if the filter is null
- */
- public NotFileFilter(IOFileFilter filter) {
- if (filter == null) {
- throw new IllegalArgumentException("The filter must not be null");
- }
- this.filter = filter;
- }
-
- /**
- * Checks to see if both filters are true.
- *
- * @param file the File to check
- * @return true if the filter returns false
- */
- public boolean accept(File file) {
- return ! filter.accept(file);
- }
-
- /**
- * Checks to see if both filters are true.
- *
- * @param file the File directory
- * @param name the filename
- * @return true if the filter returns false
- */
- public boolean accept(File file, String name) {
- return ! filter.accept(file, name);
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- public String toString() {
- return super.toString() + "(" + filter.toString() + ")";
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/OrFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/OrFileFilter.java
deleted file mode 100644
index 520eefa4f..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/OrFileFilter.java
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.List;
-
-/**
- * A {@link java.io.FileFilter} providing conditional OR logic across a list of
- * file filters. This filter returns <code>true</code> if any filters in the
- * list return <code>true</code>. Otherwise, it returns <code>false</code>.
- * Checking of the file filter list stops when the first filter returns
- * <code>true</code>.
- *
- * @since Commons IO 1.0
- * @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
- *
- * @author Steven Caswell
- */
-public class OrFileFilter
- extends AbstractFileFilter
- implements ConditionalFileFilter, Serializable {
-
- /** The list of file filters. */
- private List<IOFileFilter> fileFilters;
-
- /**
- * Constructs a new instance of <code>OrFileFilter</code>.
- *
- * @since Commons IO 1.1
- */
- public OrFileFilter() {
- this.fileFilters = new ArrayList<IOFileFilter>();
- }
-
- /**
- * Constructs a new instance of <code>OrFileFilter</code>
- * with the specified filters.
- *
- * @param fileFilters the file filters for this filter, copied, null ignored
- * @since Commons IO 1.1
- */
- public OrFileFilter(final List<IOFileFilter> fileFilters) {
- if (fileFilters == null) {
- this.fileFilters = new ArrayList<IOFileFilter>();
- } else {
- this.fileFilters = new ArrayList<IOFileFilter>(fileFilters);
- }
- }
-
- /**
- * Constructs a new file filter that ORs the result of two other filters.
- *
- * @param filter1 the first filter, must not be null
- * @param filter2 the second filter, must not be null
- * @throws IllegalArgumentException if either filter is null
- */
- public OrFileFilter(IOFileFilter filter1, IOFileFilter filter2) {
- if (filter1 == null || filter2 == null) {
- throw new IllegalArgumentException("The filters must not be null");
- }
- this.fileFilters = new ArrayList<IOFileFilter>();
- addFileFilter(filter1);
- addFileFilter(filter2);
- }
-
- /**
- * {@inheritDoc}
- */
- public void addFileFilter(final IOFileFilter ioFileFilter) {
- this.fileFilters.add(ioFileFilter);
- }
-
- /**
- * {@inheritDoc}
- */
- public List<IOFileFilter> getFileFilters() {
- return Collections.unmodifiableList(this.fileFilters);
- }
-
- /**
- * {@inheritDoc}
- */
- public boolean removeFileFilter(IOFileFilter ioFileFilter) {
- return this.fileFilters.remove(ioFileFilter);
- }
-
- /**
- * {@inheritDoc}
- */
- public void setFileFilters(final List<IOFileFilter> fileFilters) {
- this.fileFilters = fileFilters;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean accept(final File file) {
- for (Iterator<IOFileFilter> iter = this.fileFilters.iterator(); iter.hasNext();) {
- IOFileFilter fileFilter = iter.next();
- if (fileFilter.accept(file)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean accept(final File file, final String name) {
- for (Iterator<IOFileFilter> iter = this.fileFilters.iterator(); iter.hasNext();) {
- IOFileFilter fileFilter = iter.next();
- if (fileFilter.accept(file, name)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- @Override
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(super.toString());
- buffer.append("(");
- if (fileFilters != null) {
- for (int i = 0; i < fileFilters.size(); i++) {
- if (i > 0) {
- buffer.append(",");
- }
- Object filter = fileFilters.get(i);
- buffer.append(filter == null ? "null" : filter.toString());
- }
- }
- buffer.append(")");
- return buffer.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/PrefixFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/PrefixFileFilter.java
deleted file mode 100644
index 8c6b737fb..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/PrefixFileFilter.java
+++ /dev/null
@@ -1,200 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.List;
-
-import org.apache.commons.io.IOCase;
-
-/**
- * Filters filenames for a certain prefix.
- * <p>
- * For example, to print all files and directories in the
- * current directory whose name starts with <code>Test</code>:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( new PrefixFileFilter("Test") );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.0
- * @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
- *
- * @author Stephen Colebourne
- * @author Federico Barbieri
- * @author Serge Knystautas
- * @author Peter Donald
- */
-public class PrefixFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The filename prefixes to search for */
- private final String[] prefixes;
-
- /** Whether the comparison is case sensitive. */
- private final IOCase caseSensitivity;
-
- /**
- * Constructs a new Prefix file filter for a single prefix.
- *
- * @param prefix the prefix to allow, must not be null
- * @throws IllegalArgumentException if the prefix is null
- */
- public PrefixFileFilter(String prefix) {
- this(prefix, IOCase.SENSITIVE);
- }
-
- /**
- * Constructs a new Prefix file filter for a single prefix
- * specifying case-sensitivity.
- *
- * @param prefix the prefix to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the prefix is null
- * @since Commons IO 1.4
- */
- public PrefixFileFilter(String prefix, IOCase caseSensitivity) {
- if (prefix == null) {
- throw new IllegalArgumentException("The prefix must not be null");
- }
- this.prefixes = new String[] {prefix};
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Constructs a new Prefix file filter for any of an array of prefixes.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param prefixes the prefixes to allow, must not be null
- * @throws IllegalArgumentException if the prefix array is null
- */
- public PrefixFileFilter(String[] prefixes) {
- this(prefixes, IOCase.SENSITIVE);
- }
-
- /**
- * Constructs a new Prefix file filter for any of an array of prefixes
- * specifying case-sensitivity.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param prefixes the prefixes to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the prefix is null
- * @since Commons IO 1.4
- */
- public PrefixFileFilter(String[] prefixes, IOCase caseSensitivity) {
- if (prefixes == null) {
- throw new IllegalArgumentException("The array of prefixes must not be null");
- }
- this.prefixes = prefixes;
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Constructs a new Prefix file filter for a list of prefixes.
- *
- * @param prefixes the prefixes to allow, must not be null
- * @throws IllegalArgumentException if the prefix list is null
- * @throws ClassCastException if the list does not contain Strings
- */
- public PrefixFileFilter(List<String> prefixes) {
- this(prefixes, IOCase.SENSITIVE);
- }
-
- /**
- * Constructs a new Prefix file filter for a list of prefixes
- * specifying case-sensitivity.
- *
- * @param prefixes the prefixes to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the prefix list is null
- * @throws ClassCastException if the list does not contain Strings
- * @since Commons IO 1.4
- */
- public PrefixFileFilter(List<String> prefixes, IOCase caseSensitivity) {
- if (prefixes == null) {
- throw new IllegalArgumentException("The list of prefixes must not be null");
- }
- this.prefixes = prefixes.toArray(new String[prefixes.size()]);
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Checks to see if the filename starts with the prefix.
- *
- * @param file the File to check
- * @return true if the filename starts with one of our prefixes
- */
- @Override
- public boolean accept(File file) {
- String name = file.getName();
- for (int i = 0; i < this.prefixes.length; i++) {
- if (caseSensitivity.checkStartsWith(name, prefixes[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Checks to see if the filename starts with the prefix.
- *
- * @param file the File directory
- * @param name the filename
- * @return true if the filename starts with one of our prefixes
- */
- @Override
- public boolean accept(File file, String name) {
- for (int i = 0; i < prefixes.length; i++) {
- if (caseSensitivity.checkStartsWith(name, prefixes[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- @Override
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(super.toString());
- buffer.append("(");
- if (prefixes != null) {
- for (int i = 0; i < prefixes.length; i++) {
- if (i > 0) {
- buffer.append(",");
- }
- buffer.append(prefixes[i]);
- }
- }
- buffer.append(")");
- return buffer.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/RegexFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/RegexFileFilter.java
deleted file mode 100644
index b49a1bd3b..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/RegexFileFilter.java
+++ /dev/null
@@ -1,122 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.regex.Pattern;
-
-import org.apache.commons.io.IOCase;
-
-/**
- * Filters files using supplied regular expression(s).
- * <p/>
- * See java.util.regex.Pattern for regex matching rules
- * <p/>
- *
- * <p/>
- * e.g.
- * <pre>
- * File dir = new File(".");
- * FileFilter fileFilter = new RegexFileFilter("^.*[tT]est(-\\d+)?\\.java$");
- * File[] files = dir.listFiles(fileFilter);
- * for (int i = 0; i < files.length; i++) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @author Oliver Siegmar
- * @version $Revision: 606381 $
- * @since Commons IO 1.4
- */
-public class RegexFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The regular expression pattern that will be used to match filenames */
- private final Pattern pattern;
-
- /**
- * Construct a new regular expression filter.
- *
- * @param pattern regular string expression to match
- * @throws IllegalArgumentException if the pattern is null
- */
- public RegexFileFilter(String pattern) {
- if (pattern == null) {
- throw new IllegalArgumentException("Pattern is missing");
- }
-
- this.pattern = Pattern.compile(pattern);
- }
-
- /**
- * Construct a new regular expression filter with the specified flags case sensitivity.
- *
- * @param pattern regular string expression to match
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the pattern is null
- */
- public RegexFileFilter(String pattern, IOCase caseSensitivity) {
- if (pattern == null) {
- throw new IllegalArgumentException("Pattern is missing");
- }
- int flags = 0;
- if (caseSensitivity != null && !caseSensitivity.isCaseSensitive()) {
- flags = Pattern.CASE_INSENSITIVE;
- }
- this.pattern = Pattern.compile(pattern, flags);
- }
-
- /**
- * Construct a new regular expression filter with the specified flags.
- *
- * @param pattern regular string expression to match
- * @param flags pattern flags - e.g. {@link Pattern#CASE_INSENSITIVE}
- * @throws IllegalArgumentException if the pattern is null
- */
- public RegexFileFilter(String pattern, int flags) {
- if (pattern == null) {
- throw new IllegalArgumentException("Pattern is missing");
- }
- this.pattern = Pattern.compile(pattern, flags);
- }
-
- /**
- * Construct a new regular expression filter for a compiled regular expression
- *
- * @param pattern regular expression to match
- * @throws IllegalArgumentException if the pattern is null
- */
- public RegexFileFilter(Pattern pattern) {
- if (pattern == null) {
- throw new IllegalArgumentException("Pattern is missing");
- }
-
- this.pattern = pattern;
- }
-
- /**
- * Checks to see if the filename matches one of the regular expressions.
- *
- * @param dir the file directory
- * @param name the filename
- * @return true if the filename matches one of the regular expressions
- */
- public boolean accept(File dir, String name) {
- return (pattern.matcher(name).matches());
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/SizeFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/SizeFileFilter.java
deleted file mode 100644
index 614e4243f..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/SizeFileFilter.java
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * Filters files based on size, can filter either smaller files or
- * files equal to or larger than a given threshold.
- * <p>
- * For example, to print all files and directories in the
- * current directory whose size is greater than 1 MB:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( new SizeFileFilter(1024 * 1024) );
- * for ( int i = 0; i &lt; files.length; i++ ) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @author Rahul Akolkar
- * @version $Id: SizeFileFilter.java 591058 2007-11-01 15:47:05Z niallp $
- * @since Commons IO 1.2
- */
-public class SizeFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The size threshold. */
- private final long size;
- /** Whether the files accepted will be larger or smaller. */
- private final boolean acceptLarger;
-
- /**
- * Constructs a new size file filter for files equal to or
- * larger than a certain size.
- *
- * @param size the threshold size of the files
- * @throws IllegalArgumentException if the size is negative
- */
- public SizeFileFilter(long size) {
- this(size, true);
- }
-
- /**
- * Constructs a new size file filter for files based on a certain size
- * threshold.
- *
- * @param size the threshold size of the files
- * @param acceptLarger if true, files equal to or larger are accepted,
- * otherwise smaller ones (but not equal to)
- * @throws IllegalArgumentException if the size is negative
- */
- public SizeFileFilter(long size, boolean acceptLarger) {
- if (size < 0) {
- throw new IllegalArgumentException("The size must be non-negative");
- }
- this.size = size;
- this.acceptLarger = acceptLarger;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks to see if the size of the file is favorable.
- * <p>
- * If size equals threshold and smaller files are required,
- * file <b>IS NOT</b> selected.
- * If size equals threshold and larger files are required,
- * file <b>IS</b> selected.
- *
- * @param file the File to check
- * @return true if the filename matches
- */
- public boolean accept(File file) {
- boolean smaller = file.length() < size;
- return acceptLarger ? !smaller : smaller;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- public String toString() {
- String condition = acceptLarger ? ">=" : "<";
- return super.toString() + "(" + condition + size + ")";
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/SuffixFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/SuffixFileFilter.java
deleted file mode 100644
index 8bdf781a4..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/SuffixFileFilter.java
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.List;
-
-import org.apache.commons.io.IOCase;
-
-/**
- * Filters files based on the suffix (what the filename ends with).
- * This is used in retrieving all the files of a particular type.
- * <p>
- * For example, to retrieve and print all <code>*.java</code> files
- * in the current directory:
- *
- * <pre>
- * File dir = new File(".");
- * String[] files = dir.list( new SuffixFileFilter(".java") );
- * for (int i = 0; i &lt; files.length; i++) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @since Commons IO 1.0
- * @version $Revision: 606381 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
- *
- * @author Stephen Colebourne
- * @author Federico Barbieri
- * @author Serge Knystautas
- * @author Peter Donald
- */
-public class SuffixFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The filename suffixes to search for */
- private final String[] suffixes;
-
- /** Whether the comparison is case sensitive. */
- private final IOCase caseSensitivity;
-
- /**
- * Constructs a new Suffix file filter for a single extension.
- *
- * @param suffix the suffix to allow, must not be null
- * @throws IllegalArgumentException if the suffix is null
- */
- public SuffixFileFilter(String suffix) {
- this(suffix, IOCase.SENSITIVE);
- }
-
- /**
- * Constructs a new Suffix file filter for a single extension
- * specifying case-sensitivity.
- *
- * @param suffix the suffix to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the suffix is null
- * @since Commons IO 1.4
- */
- public SuffixFileFilter(String suffix, IOCase caseSensitivity) {
- if (suffix == null) {
- throw new IllegalArgumentException("The suffix must not be null");
- }
- this.suffixes = new String[] {suffix};
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Constructs a new Suffix file filter for an array of suffixs.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param suffixes the suffixes to allow, must not be null
- * @throws IllegalArgumentException if the suffix array is null
- */
- public SuffixFileFilter(String[] suffixes) {
- this(suffixes, IOCase.SENSITIVE);
- }
-
- /**
- * Constructs a new Suffix file filter for an array of suffixs
- * specifying case-sensitivity.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param suffixes the suffixes to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the suffix array is null
- * @since Commons IO 1.4
- */
- public SuffixFileFilter(String[] suffixes, IOCase caseSensitivity) {
- if (suffixes == null) {
- throw new IllegalArgumentException("The array of suffixes must not be null");
- }
- this.suffixes = suffixes;
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Constructs a new Suffix file filter for a list of suffixes.
- *
- * @param suffixes the suffixes to allow, must not be null
- * @throws IllegalArgumentException if the suffix list is null
- * @throws ClassCastException if the list does not contain Strings
- */
- public SuffixFileFilter(List<String> suffixes) {
- this(suffixes, IOCase.SENSITIVE);
- }
-
- /**
- * Constructs a new Suffix file filter for a list of suffixes
- * specifying case-sensitivity.
- *
- * @param suffixes the suffixes to allow, must not be null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the suffix list is null
- * @throws ClassCastException if the list does not contain Strings
- * @since Commons IO 1.4
- */
- public SuffixFileFilter(List<String> suffixes, IOCase caseSensitivity) {
- if (suffixes == null) {
- throw new IllegalArgumentException("The list of suffixes must not be null");
- }
- this.suffixes = suffixes.toArray(new String[suffixes.size()]);
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Checks to see if the filename ends with the suffix.
- *
- * @param file the File to check
- * @return true if the filename ends with one of our suffixes
- */
- @Override
- public boolean accept(File file) {
- String name = file.getName();
- for (int i = 0; i < this.suffixes.length; i++) {
- if (caseSensitivity.checkEndsWith(name, suffixes[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Checks to see if the filename ends with the suffix.
- *
- * @param file the File directory
- * @param name the filename
- * @return true if the filename ends with one of our suffixes
- */
- @Override
- public boolean accept(File file, String name) {
- for (int i = 0; i < this.suffixes.length; i++) {
- if (caseSensitivity.checkEndsWith(name, suffixes[i])) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- @Override
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(super.toString());
- buffer.append("(");
- if (suffixes != null) {
- for (int i = 0; i < suffixes.length; i++) {
- if (i > 0) {
- buffer.append(",");
- }
- buffer.append(suffixes[i]);
- }
- }
- buffer.append(")");
- return buffer.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/TrueFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/TrueFileFilter.java
deleted file mode 100644
index be1b13a7e..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/TrueFileFilter.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * A file filter that always returns true.
- *
- * @since Commons IO 1.0
- * @version $Revision: 587978 $ $Date: 2007-10-24 20:36:51 +0100 (Wed, 24 Oct 2007) $
- *
- * @author Stephen Colebourne
- */
-public class TrueFileFilter implements IOFileFilter, Serializable {
-
- /**
- * Singleton instance of true filter.
- * @since Commons IO 1.3
- */
- public static final IOFileFilter TRUE = new TrueFileFilter();
- /**
- * Singleton instance of true filter.
- * Please use the identical TrueFileFilter.TRUE constant.
- * The new name is more JDK 1.5 friendly as it doesn't clash with other
- * values when using static imports.
- */
- public static final IOFileFilter INSTANCE = TRUE;
-
- /**
- * Restrictive consructor.
- */
- protected TrueFileFilter() {
- }
-
- /**
- * Returns true.
- *
- * @param file the file to check
- * @return true
- */
- public boolean accept(File file) {
- return true;
- }
-
- /**
- * Returns true.
- *
- * @param dir the directory to check
- * @param name the filename
- * @return true
- */
- public boolean accept(File dir, String name) {
- return true;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/WildcardFileFilter.java b/emailcommon/src/org/apache/commons/io/filefilter/WildcardFileFilter.java
deleted file mode 100644
index f3a1ee930..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/WildcardFileFilter.java
+++ /dev/null
@@ -1,199 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.filefilter;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.List;
-
-import org.apache.commons.io.FilenameUtils;
-import org.apache.commons.io.IOCase;
-
-/**
- * Filters files using the supplied wildcards.
- * <p>
- * This filter selects files and directories based on one or more wildcards.
- * Testing is case-sensitive by default, but this can be configured.
- * <p>
- * The wildcard matcher uses the characters '?' and '*' to represent a
- * single or multiple wildcard characters.
- * This is the same as often found on Dos/Unix command lines.
- * The extension check is case-sensitive by .
- * See {@link FilenameUtils#wildcardMatchOnSystem} for more information.
- * <p>
- * For example:
- * <pre>
- * File dir = new File(".");
- * FileFilter fileFilter = new WildcardFileFilter("*test*.java~*~");
- * File[] files = dir.listFiles(fileFilter);
- * for (int i = 0; i < files.length; i++) {
- * System.out.println(files[i]);
- * }
- * </pre>
- *
- * @author Jason Anderson
- * @version $Revision: 155419 $ $Date: 2007-12-22 02:03:16 +0000 (Sat, 22 Dec 2007) $
- * @since Commons IO 1.3
- */
-public class WildcardFileFilter extends AbstractFileFilter implements Serializable {
-
- /** The wildcards that will be used to match filenames. */
- private final String[] wildcards;
- /** Whether the comparison is case sensitive. */
- private final IOCase caseSensitivity;
-
- /**
- * Construct a new case-sensitive wildcard filter for a single wildcard.
- *
- * @param wildcard the wildcard to match
- * @throws IllegalArgumentException if the pattern is null
- */
- public WildcardFileFilter(String wildcard) {
- this(wildcard, null);
- }
-
- /**
- * Construct a new wildcard filter for a single wildcard specifying case-sensitivity.
- *
- * @param wildcard the wildcard to match, not null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the pattern is null
- */
- public WildcardFileFilter(String wildcard, IOCase caseSensitivity) {
- if (wildcard == null) {
- throw new IllegalArgumentException("The wildcard must not be null");
- }
- this.wildcards = new String[] { wildcard };
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Construct a new case-sensitive wildcard filter for an array of wildcards.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param wildcards the array of wildcards to match
- * @throws IllegalArgumentException if the pattern array is null
- */
- public WildcardFileFilter(String[] wildcards) {
- this(wildcards, null);
- }
-
- /**
- * Construct a new wildcard filter for an array of wildcards specifying case-sensitivity.
- * <p>
- * The array is not cloned, so could be changed after constructing the
- * instance. This would be inadvisable however.
- *
- * @param wildcards the array of wildcards to match, not null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the pattern array is null
- */
- public WildcardFileFilter(String[] wildcards, IOCase caseSensitivity) {
- if (wildcards == null) {
- throw new IllegalArgumentException("The wildcard array must not be null");
- }
- this.wildcards = wildcards;
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- /**
- * Construct a new case-sensitive wildcard filter for a list of wildcards.
- *
- * @param wildcards the list of wildcards to match, not null
- * @throws IllegalArgumentException if the pattern list is null
- * @throws ClassCastException if the list does not contain Strings
- */
- public WildcardFileFilter(List<String> wildcards) {
- this(wildcards, null);
- }
-
- /**
- * Construct a new wildcard filter for a list of wildcards specifying case-sensitivity.
- *
- * @param wildcards the list of wildcards to match, not null
- * @param caseSensitivity how to handle case sensitivity, null means case-sensitive
- * @throws IllegalArgumentException if the pattern list is null
- * @throws ClassCastException if the list does not contain Strings
- */
- public WildcardFileFilter(List<String> wildcards, IOCase caseSensitivity) {
- if (wildcards == null) {
- throw new IllegalArgumentException("The wildcard list must not be null");
- }
- this.wildcards = wildcards.toArray(new String[wildcards.size()]);
- this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Checks to see if the filename matches one of the wildcards.
- *
- * @param dir the file directory
- * @param name the filename
- * @return true if the filename matches one of the wildcards
- */
- @Override
- public boolean accept(File dir, String name) {
- for (int i = 0; i < wildcards.length; i++) {
- if (FilenameUtils.wildcardMatch(name, wildcards[i], caseSensitivity)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Checks to see if the filename matches one of the wildcards.
- *
- * @param file the file to check
- * @return true if the filename matches one of the wildcards
- */
- @Override
- public boolean accept(File file) {
- String name = file.getName();
- for (int i = 0; i < wildcards.length; i++) {
- if (FilenameUtils.wildcardMatch(name, wildcards[i], caseSensitivity)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Provide a String representaion of this file filter.
- *
- * @return a String representaion
- */
- @Override
- public String toString() {
- StringBuffer buffer = new StringBuffer();
- buffer.append(super.toString());
- buffer.append("(");
- if (wildcards != null) {
- for (int i = 0; i < wildcards.length; i++) {
- if (i > 0) {
- buffer.append(",");
- }
- buffer.append(wildcards[i]);
- }
- }
- buffer.append(")");
- return buffer.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/filefilter/package.html b/emailcommon/src/org/apache/commons/io/filefilter/package.html
deleted file mode 100644
index 7a45f251d..000000000
--- a/emailcommon/src/org/apache/commons/io/filefilter/package.html
+++ /dev/null
@@ -1,143 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<!--
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-<html>
-<body>
-<p>This package defines an interface (IOFileFilter) that combines both
-{@link java.io.FileFilter} and {@link java.io.FilenameFilter}. Besides
-that the package offers a series of ready-to-use implementations of the
-IOFileFilter interface including implementation that allow you to combine
-other such filters.</p>
-<p>These filter can be used to list files or in {@link java.awt.FileDialog},
-for example.</p>
-
-<p>There are a number of 'primitive' filters:</p>
-
-<table>
- <tbody>
- <tr>
- <td><a href="DirectoryFileFilter.html">DirectoryFilter</a></td>
- <td>Only accept directories</td>
- </tr>
- <tr>
- <td><a href="PrefixFileFilter.html">PrefixFileFilter</a></td>
- <td>Filter based on a prefix</td>
- </tr>
- <tr>
- <td><a href="SuffixFileFilter.html">SuffixFileFilter</a></td>
- <td>Filter based on a suffix</td>
- </tr>
- <tr>
- <td><a href="NameFileFilter.html">NameFileFilter</a></td>
- <td>Filter based on a filename</td>
- </tr>
- <tr>
- <td><a href="WildcardFileFilter.html">WildcardFileFilter</a></td>
- <td>Filter based on wildcards</td>
- </tr>
- <tr>
- <td><a href="AgeFileFilter.html">AgeFileFilter</a></td>
- <td>Filter based on last modified time of file</td>
- </tr>
- <tr>
- <td><a href="SizeFileFilter.html">SizeFileFilter</a></td>
- <td>Filter based on file size</td>
- </tr>
- </tbody>
-</table>
-
-<p>And there are five 'boolean' filters:</p>
-
-<table>
- <tbody>
- <tr>
- <td><a href="TrueFileFilter.html">TrueFileFilter</a></td>
- <td>Accept all files</td>
- </tr>
- <tr>
- <td><a href="FalseFileFilter.html">FalseFileFilter</a></td>
- <td>Accept no files</td>
- </tr>
- <tr>
- <td><a href="NotFileFilter.html">NotFileFilter</a></td>
- <td>Applies a logical NOT to an existing filter</td>
- </tr>
- <tr>
- <td><a href="AndFileFilter.html">AndFileFilter</a></td>
- <td>Combines two filters using a logical AND</td>
- </tr>
- <tr>
- <td><a href="OrFileFilter.html">OrFileFilter</a></td>
- <td>Combines two filter using a logical OR</td>
- </tr>
-
- </tbody>
-</table>
-
-<p>These boolean FilenameFilters can be nested, to allow arbitrary expressions.
-For example, here is how one could print all non-directory files in the
-current directory, starting with "A", and ending in ".java" or ".class":</p>
-
-<pre>
- File dir = new File(".");
- String[] files = dir.list(
- new AndFileFilter(
- new AndFileFilter(
- new PrefixFileFilter("A"),
- new OrFileFilter(
- new SuffixFileFilter(".class"),
- new SuffixFileFilter(".java")
- )
- ),
- new NotFileFilter(
- new DirectoryFileFilter()
- )
- )
- );
- for ( int i=0; i&lt;files.length; i++ ) {
- System.out.println(files[i]);
- }
-</pre>
-
-<p>This package also contains a utility class:
-<a href="FileFilterUtils.html">FileFilterUtils</a>. It allows you to use all
-file filters without having to put them in the import section. Here's how the
-above example will look using FileFilterUtils:</p>
-<pre>
- File dir = new File(".");
- String[] files = dir.list(
- FileFilterUtils.andFileFilter(
- FileFilterUtils.andFileFilter(
- FileFilterUtils.prefixFileFilter("A"),
- FileFilterUtils.orFileFilter(
- FileFilterUtils.suffixFileFilter(".class"),
- FileFilterUtils.suffixFileFilter(".java")
- )
- ),
- FileFilterUtils.notFileFilter(
- FileFilterUtils.directoryFileFilter()
- )
- )
- );
- for ( int i=0; i&lt;files.length; i++ ) {
- System.out.println(files[i]);
- }
-</pre>
-<p>There are a few other goodies in that class so please have a look at the
-documentation in detail.</p>
- </body>
-</html>
diff --git a/emailcommon/src/org/apache/commons/io/input/AutoCloseInputStream.java b/emailcommon/src/org/apache/commons/io/input/AutoCloseInputStream.java
deleted file mode 100644
index bb62358f7..000000000
--- a/emailcommon/src/org/apache/commons/io/input/AutoCloseInputStream.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Proxy stream that closes and discards the underlying stream as soon as the
- * end of input has been reached or when the stream is explicitly closed.
- * Not even a reference to the underlying stream is kept after it has been
- * closed, so any allocated in-memory buffers can be freed even if the
- * client application still keeps a reference to the proxy stream.
- * <p>
- * This class is typically used to release any resources related to an open
- * stream as soon as possible even if the client application (by not explicitly
- * closing the stream when no longer needed) or the underlying stream (by not
- * releasing resources once the last byte has been read) do not do that.
- *
- * @version $Id: AutoCloseInputStream.java 610010 2008-01-08 14:50:59Z niallp $
- * @since Commons IO 1.4
- */
-public class AutoCloseInputStream extends ProxyInputStream {
-
- /**
- * Creates an automatically closing proxy for the given input stream.
- *
- * @param in underlying input stream
- */
- public AutoCloseInputStream(InputStream in) {
- super(in);
- }
-
- /**
- * Closes the underlying input stream and replaces the reference to it
- * with a {@link ClosedInputStream} instance.
- * <p>
- * This method is automatically called by the read methods when the end
- * of input has been reached.
- * <p>
- * Note that it is safe to call this method any number of times. The original
- * underlying input stream is closed and discarded only once when this
- * method is first called.
- *
- * @throws IOException if the underlying input stream can not be closed
- */
- public void close() throws IOException {
- in.close();
- in = new ClosedInputStream();
- }
-
- /**
- * Reads and returns a single byte from the underlying input stream.
- * If the underlying stream returns -1, the {@link #close()} method is
- * called to automatically close and discard the stream.
- *
- * @return next byte in the stream, or -1 if no more bytes are available
- * @throws IOException if the stream could not be read or closed
- */
- public int read() throws IOException {
- int n = in.read();
- if (n == -1) {
- close();
- }
- return n;
- }
-
- /**
- * Reads and returns bytes from the underlying input stream to the given
- * buffer. If the underlying stream returns -1, the {@link #close()} method
- * i called to automatically close and discard the stream.
- *
- * @param b buffer to which bytes from the stream are written
- * @return number of bytes read, or -1 if no more bytes are available
- * @throws IOException if the stream could not be read or closed
- */
- public int read(byte[] b) throws IOException {
- int n = in.read(b);
- if (n == -1) {
- close();
- }
- return n;
- }
-
- /**
- * Reads and returns bytes from the underlying input stream to the given
- * buffer. If the underlying stream returns -1, the {@link #close()} method
- * i called to automatically close and discard the stream.
- *
- * @param b buffer to which bytes from the stream are written
- * @param off start offset within the buffer
- * @param len maximum number of bytes to read
- * @return number of bytes read, or -1 if no more bytes are available
- * @throws IOException if the stream could not be read or closed
- */
- public int read(byte[] b, int off, int len) throws IOException {
- int n = in.read(b, off, len);
- if (n == -1) {
- close();
- }
- return n;
- }
-
- /**
- * Ensures that the stream is closed before it gets garbage-collected.
- * As mentioned in {@link #close()}, this is a no-op if the stream has
- * already been closed.
- * @throws Throwable if an error occurs
- */
- protected void finalize() throws Throwable {
- close();
- super.finalize();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/CharSequenceReader.java b/emailcommon/src/org/apache/commons/io/input/CharSequenceReader.java
deleted file mode 100644
index 6ee11d87d..000000000
--- a/emailcommon/src/org/apache/commons/io/input/CharSequenceReader.java
+++ /dev/null
@@ -1,155 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.Reader;
-import java.io.Serializable;
-
-/**
- * {@link Reader} implementation that can read from String, StringBuffer,
- * StringBuilder or CharBuffer.
- * <p>
- * <strong>Note:</strong> Supports {@link #mark(int)} and {@link #reset()}.
- *
- * @version $Revision: 610516 $ $Date: 2008-01-09 19:05:05 +0000 (Wed, 09 Jan 2008) $
- * @since Commons IO 1.4
- */
-public class CharSequenceReader extends Reader implements Serializable {
-
- private final CharSequence charSequence;
- private int idx;
- private int mark;
-
- /**
- * Construct a new instance with the specified character sequence.
- *
- * @param charSequence The character sequence, may be <code>null</code>
- */
- public CharSequenceReader(CharSequence charSequence) {
- this.charSequence = (charSequence != null ? charSequence : "");
- }
-
- /**
- * Close resets the file back to the start and removes any marked position.
- */
- public void close() {
- idx = 0;
- mark = 0;
- }
-
- /**
- * Mark the current position.
- *
- * @param readAheadLimit ignored
- */
- public void mark(int readAheadLimit) {
- mark = idx;
- }
-
- /**
- * Mark is supported (returns true).
- *
- * @return <code>true</code>
- */
- public boolean markSupported() {
- return true;
- }
-
- /**
- * Read a single character.
- *
- * @return the next character from the character sequence
- * or -1 if the end has been reached.
- */
- public int read() {
- if (idx >= charSequence.length()) {
- return -1;
- } else {
- return charSequence.charAt(idx++);
- }
- }
-
- /**
- * Read the sepcified number of characters into the array.
- *
- * @param array The array to store the characters in
- * @param offset The starting position in the array to store
- * @param length The maximum number of characters to read
- * @return The number of characters read or -1 if there are
- * no more
- */
- public int read(char[] array, int offset, int length) {
- if (idx >= charSequence.length()) {
- return -1;
- }
- if (array == null) {
- throw new NullPointerException("Character array is missing");
- }
- if (length < 0 || (offset + length) > array.length) {
- throw new IndexOutOfBoundsException("Array Size=" + array.length +
- ", offset=" + offset + ", length=" + length);
- }
- int count = 0;
- for (int i = 0; i < length; i++) {
- int c = read();
- if (c == -1) {
- return count;
- }
- array[offset + i] = (char)c;
- count++;
- }
- return count;
- }
-
- /**
- * Reset the reader to the last marked position (or the beginning if
- * mark has not been called).
- */
- public void reset() {
- idx = mark;
- }
-
- /**
- * Skip the specified number of characters.
- *
- * @param n The number of characters to skip
- * @return The actual number of characters skipped
- */
- public long skip(long n) {
- if (n < 0) {
- throw new IllegalArgumentException(
- "Number of characters to skip is less than zero: " + n);
- }
- if (idx >= charSequence.length()) {
- return -1;
- }
- int dest = (int)Math.min(charSequence.length(), (idx + n));
- int count = dest - idx;
- idx = dest;
- return count;
- }
-
- /**
- * Return a String representation of the underlying
- * character sequence.
- *
- * @return The contents of the character sequence
- */
- public String toString() {
- return charSequence.toString();
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/ClassLoaderObjectInputStream.java b/emailcommon/src/org/apache/commons/io/input/ClassLoaderObjectInputStream.java
deleted file mode 100644
index 13d048946..000000000
--- a/emailcommon/src/org/apache/commons/io/input/ClassLoaderObjectInputStream.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectStreamClass;
-import java.io.StreamCorruptedException;
-
-/**
- * A special ObjectInputStream that loads a class based on a specified
- * <code>ClassLoader</code> rather than the system default.
- * <p>
- * This is useful in dynamic container environments.
- *
- * @author Paul Hammant
- * @version $Id: ClassLoaderObjectInputStream.java 437567 2006-08-28 06:39:07Z bayard $
- * @since Commons IO 1.1
- */
-public class ClassLoaderObjectInputStream extends ObjectInputStream {
-
- /** The class loader to use. */
- private ClassLoader classLoader;
-
- /**
- * Constructs a new ClassLoaderObjectInputStream.
- *
- * @param classLoader the ClassLoader from which classes should be loaded
- * @param inputStream the InputStream to work on
- * @throws IOException in case of an I/O error
- * @throws StreamCorruptedException if the stream is corrupted
- */
- public ClassLoaderObjectInputStream(
- ClassLoader classLoader, InputStream inputStream)
- throws IOException, StreamCorruptedException {
- super(inputStream);
- this.classLoader = classLoader;
- }
-
- /**
- * Resolve a class specified by the descriptor using the
- * specified ClassLoader or the super ClassLoader.
- *
- * @param objectStreamClass descriptor of the class
- * @return the Class object described by the ObjectStreamClass
- * @throws IOException in case of an I/O error
- * @throws ClassNotFoundException if the Class cannot be found
- */
- protected Class resolveClass(ObjectStreamClass objectStreamClass)
- throws IOException, ClassNotFoundException {
-
- Class clazz = Class.forName(objectStreamClass.getName(), false, classLoader);
-
- if (clazz != null) {
- // the classloader knows of the class
- return clazz;
- } else {
- // classloader knows not of class, let the super classloader do it
- return super.resolveClass(objectStreamClass);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/CloseShieldInputStream.java b/emailcommon/src/org/apache/commons/io/input/CloseShieldInputStream.java
deleted file mode 100644
index 2058beeb2..000000000
--- a/emailcommon/src/org/apache/commons/io/input/CloseShieldInputStream.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.InputStream;
-
-/**
- * Proxy stream that prevents the underlying input stream from being closed.
- * <p>
- * This class is typically used in cases where an input stream needs to be
- * passed to a component that wants to explicitly close the stream even if
- * more input would still be available to other components.
- *
- * @version $Id: CloseShieldInputStream.java 587913 2007-10-24 15:47:30Z niallp $
- * @since Commons IO 1.4
- */
-public class CloseShieldInputStream extends ProxyInputStream {
-
- /**
- * Creates a proxy that shields the given input stream from being
- * closed.
- *
- * @param in underlying input stream
- */
- public CloseShieldInputStream(InputStream in) {
- super(in);
- }
-
- /**
- * Replaces the underlying input stream with a {@link ClosedInputStream}
- * sentinel. The original input stream will remain open, but this proxy
- * will appear closed.
- */
- public void close() {
- in = new ClosedInputStream();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/ClosedInputStream.java b/emailcommon/src/org/apache/commons/io/input/ClosedInputStream.java
deleted file mode 100644
index 86c83c903..000000000
--- a/emailcommon/src/org/apache/commons/io/input/ClosedInputStream.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.InputStream;
-
-/**
- * Closed input stream. This stream returns -1 to all attempts to read
- * something from the stream.
- * <p>
- * Typically uses of this class include testing for corner cases in methods
- * that accept input streams and acting as a sentinel value instead of a
- * <code>null</code> input stream.
- *
- * @version $Id: ClosedInputStream.java 601751 2007-12-06 14:55:45Z niallp $
- * @since Commons IO 1.4
- */
-public class ClosedInputStream extends InputStream {
-
- /**
- * A singleton.
- */
- public static final ClosedInputStream CLOSED_INPUT_STREAM = new ClosedInputStream();
-
- /**
- * Returns -1 to indicate that the stream is closed.
- *
- * @return always -1
- */
- public int read() {
- return -1;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/CountingInputStream.java b/emailcommon/src/org/apache/commons/io/input/CountingInputStream.java
deleted file mode 100644
index 2782276c8..000000000
--- a/emailcommon/src/org/apache/commons/io/input/CountingInputStream.java
+++ /dev/null
@@ -1,175 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * A decorating input stream that counts the number of bytes that have passed
- * through the stream so far.
- * <p>
- * A typical use case would be during debugging, to ensure that data is being
- * read as expected.
- *
- * @author Marcelo Liberato
- * @version $Id: CountingInputStream.java 471628 2006-11-06 04:06:45Z bayard $
- */
-public class CountingInputStream extends ProxyInputStream {
-
- /** The count of bytes that have passed. */
- private long count;
-
- /**
- * Constructs a new CountingInputStream.
- *
- * @param in the InputStream to delegate to
- */
- public CountingInputStream(InputStream in) {
- super(in);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Reads a number of bytes into the byte array, keeping count of the
- * number read.
- *
- * @param b the buffer into which the data is read, not null
- * @return the total number of bytes read into the buffer, -1 if end of stream
- * @throws IOException if an I/O error occurs
- * @see java.io.InputStream#read(byte[])
- */
- public int read(byte[] b) throws IOException {
- int found = super.read(b);
- this.count += (found >= 0) ? found : 0;
- return found;
- }
-
- /**
- * Reads a number of bytes into the byte array at a specific offset,
- * keeping count of the number read.
- *
- * @param b the buffer into which the data is read, not null
- * @param off the start offset in the buffer
- * @param len the maximum number of bytes to read
- * @return the total number of bytes read into the buffer, -1 if end of stream
- * @throws IOException if an I/O error occurs
- * @see java.io.InputStream#read(byte[], int, int)
- */
- public int read(byte[] b, int off, int len) throws IOException {
- int found = super.read(b, off, len);
- this.count += (found >= 0) ? found : 0;
- return found;
- }
-
- /**
- * Reads the next byte of data adding to the count of bytes received
- * if a byte is successfully read.
- *
- * @return the byte read, -1 if end of stream
- * @throws IOException if an I/O error occurs
- * @see java.io.InputStream#read()
- */
- public int read() throws IOException {
- int found = super.read();
- this.count += (found >= 0) ? 1 : 0;
- return found;
- }
-
- /**
- * Skips the stream over the specified number of bytes, adding the skipped
- * amount to the count.
- *
- * @param length the number of bytes to skip
- * @return the actual number of bytes skipped
- * @throws IOException if an I/O error occurs
- * @see java.io.InputStream#skip(long)
- */
- public long skip(final long length) throws IOException {
- final long skip = super.skip(length);
- this.count += skip;
- return skip;
- }
-
- //-----------------------------------------------------------------------
- /**
- * The number of bytes that have passed through this stream.
- * <p>
- * NOTE: From v1.3 this method throws an ArithmeticException if the
- * count is greater than can be expressed by an <code>int</code>.
- * See {@link #getByteCount()} for a method using a <code>long</code>.
- *
- * @return the number of bytes accumulated
- * @throws ArithmeticException if the byte count is too large
- */
- public synchronized int getCount() {
- long result = getByteCount();
- if (result > Integer.MAX_VALUE) {
- throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
- }
- return (int) result;
- }
-
- /**
- * Set the byte count back to 0.
- * <p>
- * NOTE: From v1.3 this method throws an ArithmeticException if the
- * count is greater than can be expressed by an <code>int</code>.
- * See {@link #resetByteCount()} for a method using a <code>long</code>.
- *
- * @return the count previous to resetting
- * @throws ArithmeticException if the byte count is too large
- */
- public synchronized int resetCount() {
- long result = resetByteCount();
- if (result > Integer.MAX_VALUE) {
- throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
- }
- return (int) result;
- }
-
- /**
- * The number of bytes that have passed through this stream.
- * <p>
- * NOTE: This method is an alternative for <code>getCount()</code>
- * and was added because that method returns an integer which will
- * result in incorrect count for files over 2GB.
- *
- * @return the number of bytes accumulated
- * @since Commons IO 1.3
- */
- public synchronized long getByteCount() {
- return this.count;
- }
-
- /**
- * Set the byte count back to 0.
- * <p>
- * NOTE: This method is an alternative for <code>resetCount()</code>
- * and was added because that method returns an integer which will
- * result in incorrect count for files over 2GB.
- *
- * @return the count previous to resetting
- * @since Commons IO 1.3
- */
- public synchronized long resetByteCount() {
- long tmp = this.count;
- this.count = 0;
- return tmp;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/DemuxInputStream.java b/emailcommon/src/org/apache/commons/io/input/DemuxInputStream.java
deleted file mode 100644
index 64b41c4d4..000000000
--- a/emailcommon/src/org/apache/commons/io/input/DemuxInputStream.java
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Data written to this stream is forwarded to a stream that has been associated
- * with this thread.
- *
- * @author <a href="mailto:peter@apache.org">Peter Donald</a>
- * @version $Revision: 437567 $ $Date: 2006-08-28 07:39:07 +0100 (Mon, 28 Aug 2006) $
- */
-public class DemuxInputStream
- extends InputStream
-{
- private InheritableThreadLocal<InputStream> m_streams = new InheritableThreadLocal<InputStream>();
-
- /**
- * Bind the specified stream to the current thread.
- *
- * @param input the stream to bind
- * @return the InputStream that was previously active
- */
- public InputStream bindStream( InputStream input )
- {
- InputStream oldValue = getStream();
- m_streams.set( input );
- return oldValue;
- }
-
- /**
- * Closes stream associated with current thread.
- *
- * @throws IOException if an error occurs
- */
- @Override
- public void close()
- throws IOException
- {
- InputStream input = getStream();
- if( null != input )
- {
- input.close();
- }
- }
-
- /**
- * Read byte from stream associated with current thread.
- *
- * @return the byte read from stream
- * @throws IOException if an error occurs
- */
- @Override
- public int read()
- throws IOException
- {
- InputStream input = getStream();
- if( null != input )
- {
- return input.read();
- }
- else
- {
- return -1;
- }
- }
-
- /**
- * Utility method to retrieve stream bound to current thread (if any).
- *
- * @return the input stream
- */
- private InputStream getStream()
- {
- return m_streams.get();
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/NullInputStream.java b/emailcommon/src/org/apache/commons/io/input/NullInputStream.java
deleted file mode 100644
index 7cee2c6d0..000000000
--- a/emailcommon/src/org/apache/commons/io/input/NullInputStream.java
+++ /dev/null
@@ -1,329 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * A functional, light weight {@link InputStream} that emulates
- * a stream of a specified size.
- * <p>
- * This implementation provides a light weight
- * object for testing with an {@link InputStream}
- * where the contents don't matter.
- * <p>
- * One use case would be for testing the handling of
- * large {@link InputStream} as it can emulate that
- * scenario without the overhead of actually processing
- * large numbers of bytes - significantly speeding up
- * test execution times.
- * <p>
- * This implementation returns zero from the method that
- * reads a byte and leaves the array unchanged in the read
- * methods that are passed a byte array.
- * If alternative data is required the <code>processByte()</code> and
- * <code>processBytes()</code> methods can be implemented to generate
- * data, for example:
- *
- * <pre>
- * public class TestInputStream extends NullInputStream {
- * public TestInputStream(int size) {
- * super(size);
- * }
- * protected int processByte() {
- * return ... // return required value here
- * }
- * protected void processBytes(byte[] bytes, int offset, int length) {
- * for (int i = offset; i < length; i++) {
- * bytes[i] = ... // set array value here
- * }
- * }
- * }
- * </pre>
- *
- * @since Commons IO 1.3
- * @version $Revision: 463529 $
- */
-public class NullInputStream extends InputStream {
-
- private long size;
- private long position;
- private long mark = -1;
- private long readlimit;
- private boolean eof;
- private boolean throwEofException;
- private boolean markSupported;
-
- /**
- * Create an {@link InputStream} that emulates a specified size
- * which supports marking and does not throw EOFException.
- *
- * @param size The size of the input stream to emulate.
- */
- public NullInputStream(long size) {
- this(size, true, false);
- }
-
- /**
- * Create an {@link InputStream} that emulates a specified
- * size with option settings.
- *
- * @param size The size of the input stream to emulate.
- * @param markSupported Whether this instance will support
- * the <code>mark()</code> functionality.
- * @param throwEofException Whether this implementation
- * will throw an {@link EOFException} or return -1 when the
- * end of file is reached.
- */
- public NullInputStream(long size, boolean markSupported, boolean throwEofException) {
- this.size = size;
- this.markSupported = markSupported;
- this.throwEofException = throwEofException;
- }
-
- /**
- * Return the current position.
- *
- * @return the current position.
- */
- public long getPosition() {
- return position;
- }
-
- /**
- * Return the size this {@link InputStream} emulates.
- *
- * @return The size of the input stream to emulate.
- */
- public long getSize() {
- return size;
- }
-
- /**
- * Return the number of bytes that can be read.
- *
- * @return The number of bytes that can be read.
- */
- public int available() {
- long avail = size - position;
- if (avail <= 0) {
- return 0;
- } else if (avail > Integer.MAX_VALUE) {
- return Integer.MAX_VALUE;
- } else {
- return (int)avail;
- }
- }
-
- /**
- * Close this input stream - resets the internal state to
- * the initial values.
- *
- * @throws IOException If an error occurs.
- */
- public void close() throws IOException {
- eof = false;
- position = 0;
- mark = -1;
- }
-
- /**
- * Mark the current position.
- *
- * @param readlimit The number of bytes before this marked position
- * is invalid.
- * @throws UnsupportedOperationException if mark is not supported.
- */
- public synchronized void mark(int readlimit) {
- if (!markSupported) {
- throw new UnsupportedOperationException("Mark not supported");
- }
- mark = position;
- this.readlimit = readlimit;
- }
-
- /**
- * Indicates whether <i>mark</i> is supported.
- *
- * @return Whether <i>mark</i> is supported or not.
- */
- public boolean markSupported() {
- return markSupported;
- }
-
- /**
- * Read a byte.
- *
- * @return Either The byte value returned by <code>processByte()</code>
- * or <code>-1</code> if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public int read() throws IOException {
- if (eof) {
- throw new IOException("Read after end of file");
- }
- if (position == size) {
- return doEndOfFile();
- }
- position++;
- return processByte();
- }
-
- /**
- * Read some bytes into the specified array.
- *
- * @param bytes The byte array to read into
- * @return The number of bytes read or <code>-1</code>
- * if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public int read(byte[] bytes) throws IOException {
- return read(bytes, 0, bytes.length);
- }
-
- /**
- * Read the specified number bytes into an array.
- *
- * @param bytes The byte array to read into.
- * @param offset The offset to start reading bytes into.
- * @param length The number of bytes to read.
- * @return The number of bytes read or <code>-1</code>
- * if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public int read(byte[] bytes, int offset, int length) throws IOException {
- if (eof) {
- throw new IOException("Read after end of file");
- }
- if (position == size) {
- return doEndOfFile();
- }
- position += length;
- int returnLength = length;
- if (position > size) {
- returnLength = length - (int)(position - size);
- position = size;
- }
- processBytes(bytes, offset, returnLength);
- return returnLength;
- }
-
- /**
- * Reset the stream to the point when mark was last called.
- *
- * @throws UnsupportedOperationException if mark is not supported.
- * @throws IOException If no position has been marked
- * or the read limit has been exceed since the last position was
- * marked.
- */
- public synchronized void reset() throws IOException {
- if (!markSupported) {
- throw new UnsupportedOperationException("Mark not supported");
- }
- if (mark < 0) {
- throw new IOException("No position has been marked");
- }
- if (position > (mark + readlimit)) {
- throw new IOException("Marked position [" + mark +
- "] is no longer valid - passed the read limit [" +
- readlimit + "]");
- }
- position = mark;
- eof = false;
- }
-
- /**
- * Skip a specified number of bytes.
- *
- * @param numberOfBytes The number of bytes to skip.
- * @return The number of bytes skipped or <code>-1</code>
- * if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public long skip(long numberOfBytes) throws IOException {
- if (eof) {
- throw new IOException("Skip after end of file");
- }
- if (position == size) {
- return doEndOfFile();
- }
- position += numberOfBytes;
- long returnLength = numberOfBytes;
- if (position > size) {
- returnLength = numberOfBytes - (position - size);
- position = size;
- }
- return returnLength;
- }
-
- /**
- * Return a byte value for the <code>read()</code> method.
- * <p>
- * This implementation returns zero.
- *
- * @return This implementation always returns zero.
- */
- protected int processByte() {
- // do nothing - overridable by subclass
- return 0;
- }
-
- /**
- * Process the bytes for the <code>read(byte[], offset, length)</code>
- * method.
- * <p>
- * This implementation leaves the byte array unchanged.
- *
- * @param bytes The byte array
- * @param offset The offset to start at.
- * @param length The number of bytes.
- */
- protected void processBytes(byte[] bytes, int offset, int length) {
- // do nothing - overridable by subclass
- }
-
- /**
- * Handle End of File.
- *
- * @return <code>-1</code> if <code>throwEofException</code> is
- * set to <code>false</code>
- * @throws EOFException if <code>throwEofException</code> is set
- * to <code>true</code>.
- */
- private int doEndOfFile() throws EOFException {
- eof = true;
- if (throwEofException) {
- throw new EOFException();
- }
- return -1;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/NullReader.java b/emailcommon/src/org/apache/commons/io/input/NullReader.java
deleted file mode 100644
index 159e39021..000000000
--- a/emailcommon/src/org/apache/commons/io/input/NullReader.java
+++ /dev/null
@@ -1,313 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.Reader;
-
-/**
- * A functional, light weight {@link Reader} that emulates
- * a reader of a specified size.
- * <p>
- * This implementation provides a light weight
- * object for testing with an {@link Reader}
- * where the contents don't matter.
- * <p>
- * One use case would be for testing the handling of
- * large {@link Reader} as it can emulate that
- * scenario without the overhead of actually processing
- * large numbers of characters - significantly speeding up
- * test execution times.
- * <p>
- * This implementation returns a space from the method that
- * reads a character and leaves the array unchanged in the read
- * methods that are passed a character array.
- * If alternative data is required the <code>processChar()</code> and
- * <code>processChars()</code> methods can be implemented to generate
- * data, for example:
- *
- * <pre>
- * public class TestReader extends NullReader {
- * public TestReader(int size) {
- * super(size);
- * }
- * protected char processChar() {
- * return ... // return required value here
- * }
- * protected void processChars(char[] chars, int offset, int length) {
- * for (int i = offset; i < length; i++) {
- * chars[i] = ... // set array value here
- * }
- * }
- * }
- * </pre>
- *
- * @since Commons IO 1.3
- * @version $Revision: 463529 $
- */
-public class NullReader extends Reader {
-
- private long size;
- private long position;
- private long mark = -1;
- private long readlimit;
- private boolean eof;
- private boolean throwEofException;
- private boolean markSupported;
-
- /**
- * Create a {@link Reader} that emulates a specified size
- * which supports marking and does not throw EOFException.
- *
- * @param size The size of the reader to emulate.
- */
- public NullReader(long size) {
- this(size, true, false);
- }
-
- /**
- * Create a {@link Reader} that emulates a specified
- * size with option settings.
- *
- * @param size The size of the reader to emulate.
- * @param markSupported Whether this instance will support
- * the <code>mark()</code> functionality.
- * @param throwEofException Whether this implementation
- * will throw an {@link EOFException} or return -1 when the
- * end of file is reached.
- */
- public NullReader(long size, boolean markSupported, boolean throwEofException) {
- this.size = size;
- this.markSupported = markSupported;
- this.throwEofException = throwEofException;
- }
-
- /**
- * Return the current position.
- *
- * @return the current position.
- */
- public long getPosition() {
- return position;
- }
-
- /**
- * Return the size this {@link Reader} emulates.
- *
- * @return The size of the reader to emulate.
- */
- public long getSize() {
- return size;
- }
-
- /**
- * Close this Reader - resets the internal state to
- * the initial values.
- *
- * @throws IOException If an error occurs.
- */
- public void close() throws IOException {
- eof = false;
- position = 0;
- mark = -1;
- }
-
- /**
- * Mark the current position.
- *
- * @param readlimit The number of characters before this marked position
- * is invalid.
- * @throws UnsupportedOperationException if mark is not supported.
- */
- public synchronized void mark(int readlimit) {
- if (!markSupported) {
- throw new UnsupportedOperationException("Mark not supported");
- }
- mark = position;
- this.readlimit = readlimit;
- }
-
- /**
- * Indicates whether <i>mark</i> is supported.
- *
- * @return Whether <i>mark</i> is supported or not.
- */
- public boolean markSupported() {
- return markSupported;
- }
-
- /**
- * Read a character.
- *
- * @return Either The character value returned by <code>processChar()</code>
- * or <code>-1</code> if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public int read() throws IOException {
- if (eof) {
- throw new IOException("Read after end of file");
- }
- if (position == size) {
- return doEndOfFile();
- }
- position++;
- return processChar();
- }
-
- /**
- * Read some characters into the specified array.
- *
- * @param chars The character array to read into
- * @return The number of characters read or <code>-1</code>
- * if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public int read(char[] chars) throws IOException {
- return read(chars, 0, chars.length);
- }
-
- /**
- * Read the specified number characters into an array.
- *
- * @param chars The character array to read into.
- * @param offset The offset to start reading characters into.
- * @param length The number of characters to read.
- * @return The number of characters read or <code>-1</code>
- * if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public int read(char[] chars, int offset, int length) throws IOException {
- if (eof) {
- throw new IOException("Read after end of file");
- }
- if (position == size) {
- return doEndOfFile();
- }
- position += length;
- int returnLength = length;
- if (position > size) {
- returnLength = length - (int)(position - size);
- position = size;
- }
- processChars(chars, offset, returnLength);
- return returnLength;
- }
-
- /**
- * Reset the stream to the point when mark was last called.
- *
- * @throws UnsupportedOperationException if mark is not supported.
- * @throws IOException If no position has been marked
- * or the read limit has been exceed since the last position was
- * marked.
- */
- public synchronized void reset() throws IOException {
- if (!markSupported) {
- throw new UnsupportedOperationException("Mark not supported");
- }
- if (mark < 0) {
- throw new IOException("No position has been marked");
- }
- if (position > (mark + readlimit)) {
- throw new IOException("Marked position [" + mark +
- "] is no longer valid - passed the read limit [" +
- readlimit + "]");
- }
- position = mark;
- eof = false;
- }
-
- /**
- * Skip a specified number of characters.
- *
- * @param numberOfChars The number of characters to skip.
- * @return The number of characters skipped or <code>-1</code>
- * if the end of file has been reached and
- * <code>throwEofException</code> is set to <code>false</code>.
- * @throws EOFException if the end of file is reached and
- * <code>throwEofException</code> is set to <code>true</code>.
- * @throws IOException if trying to read past the end of file.
- */
- public long skip(long numberOfChars) throws IOException {
- if (eof) {
- throw new IOException("Skip after end of file");
- }
- if (position == size) {
- return doEndOfFile();
- }
- position += numberOfChars;
- long returnLength = numberOfChars;
- if (position > size) {
- returnLength = numberOfChars - (position - size);
- position = size;
- }
- return returnLength;
- }
-
- /**
- * Return a character value for the <code>read()</code> method.
- * <p>
- * This implementation returns zero.
- *
- * @return This implementation always returns zero.
- */
- protected int processChar() {
- // do nothing - overridable by subclass
- return 0;
- }
-
- /**
- * Process the characters for the <code>read(char[], offset, length)</code>
- * method.
- * <p>
- * This implementation leaves the character array unchanged.
- *
- * @param chars The character array
- * @param offset The offset to start at.
- * @param length The number of characters.
- */
- protected void processChars(char[] chars, int offset, int length) {
- // do nothing - overridable by subclass
- }
-
- /**
- * Handle End of File.
- *
- * @return <code>-1</code> if <code>throwEofException</code> is
- * set to <code>false</code>
- * @throws EOFException if <code>throwEofException</code> is set
- * to <code>true</code>.
- */
- private int doEndOfFile() throws EOFException {
- eof = true;
- if (throwEofException) {
- throw new EOFException();
- }
- return -1;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/ProxyInputStream.java b/emailcommon/src/org/apache/commons/io/input/ProxyInputStream.java
deleted file mode 100644
index a08ad92d0..000000000
--- a/emailcommon/src/org/apache/commons/io/input/ProxyInputStream.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.FilterInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * A Proxy stream which acts as expected, that is it passes the method
- * calls on to the proxied stream and doesn't change which methods are
- * being called.
- * <p>
- * It is an alternative base class to FilterInputStream
- * to increase reusability, because FilterInputStream changes the
- * methods being called, such as read(byte[]) to read(byte[], int, int).
- *
- * @author Stephen Colebourne
- * @version $Id: ProxyInputStream.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public abstract class ProxyInputStream extends FilterInputStream {
-
- /**
- * Constructs a new ProxyInputStream.
- *
- * @param proxy the InputStream to delegate to
- */
- public ProxyInputStream(InputStream proxy) {
- super(proxy);
- // the proxy is stored in a protected superclass variable named 'in'
- }
-
- /**
- * Invokes the delegate's <code>read()</code> method.
- * @return the byte read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public int read() throws IOException {
- return in.read();
- }
-
- /**
- * Invokes the delegate's <code>read(byte[])</code> method.
- * @param bts the buffer to read the bytes into
- * @return the number of bytes read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public int read(byte[] bts) throws IOException {
- return in.read(bts);
- }
-
- /**
- * Invokes the delegate's <code>read(byte[], int, int)</code> method.
- * @param bts the buffer to read the bytes into
- * @param st The start offset
- * @param end The number of bytes to read
- * @return the number of bytes read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public int read(byte[] bts, int st, int end) throws IOException {
- return in.read(bts, st, end);
- }
-
- /**
- * Invokes the delegate's <code>skip(long)</code> method.
- * @param ln the number of bytes to skip
- * @return the number of bytes to skipped or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public long skip(long ln) throws IOException {
- return in.skip(ln);
- }
-
- /**
- * Invokes the delegate's <code>available()</code> method.
- * @return the number of available bytes
- * @throws IOException if an I/O error occurs
- */
- public int available() throws IOException {
- return in.available();
- }
-
- /**
- * Invokes the delegate's <code>close()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public void close() throws IOException {
- in.close();
- }
-
- /**
- * Invokes the delegate's <code>mark(int)</code> method.
- * @param idx read ahead limit
- */
- public synchronized void mark(int idx) {
- in.mark(idx);
- }
-
- /**
- * Invokes the delegate's <code>reset()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public synchronized void reset() throws IOException {
- in.reset();
- }
-
- /**
- * Invokes the delegate's <code>markSupported()</code> method.
- * @return true if mark is supported, otherwise false
- */
- public boolean markSupported() {
- return in.markSupported();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/ProxyReader.java b/emailcommon/src/org/apache/commons/io/input/ProxyReader.java
deleted file mode 100644
index d55290f5a..000000000
--- a/emailcommon/src/org/apache/commons/io/input/ProxyReader.java
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.FilterReader;
-import java.io.IOException;
-import java.io.Reader;
-
-/**
- * A Proxy stream which acts as expected, that is it passes the method
- * calls on to the proxied stream and doesn't change which methods are
- * being called.
- * <p>
- * It is an alternative base class to FilterReader
- * to increase reusability, because FilterReader changes the
- * methods being called, such as read(char[]) to read(char[], int, int).
- *
- * @author Stephen Colebourne
- * @version $Id: ProxyReader.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public abstract class ProxyReader extends FilterReader {
-
- /**
- * Constructs a new ProxyReader.
- *
- * @param proxy the Reader to delegate to
- */
- public ProxyReader(Reader proxy) {
- super(proxy);
- // the proxy is stored in a protected superclass variable named 'in'
- }
-
- /**
- * Invokes the delegate's <code>read()</code> method.
- * @return the character read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public int read() throws IOException {
- return in.read();
- }
-
- /**
- * Invokes the delegate's <code>read(char[])</code> method.
- * @param chr the buffer to read the characters into
- * @return the number of characters read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public int read(char[] chr) throws IOException {
- return in.read(chr);
- }
-
- /**
- * Invokes the delegate's <code>read(char[], int, int)</code> method.
- * @param chr the buffer to read the characters into
- * @param st The start offset
- * @param end The number of bytes to read
- * @return the number of characters read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public int read(char[] chr, int st, int end) throws IOException {
- return in.read(chr, st, end);
- }
-
- /**
- * Invokes the delegate's <code>skip(long)</code> method.
- * @param ln the number of bytes to skip
- * @return the number of bytes to skipped or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- */
- public long skip(long ln) throws IOException {
- return in.skip(ln);
- }
-
- /**
- * Invokes the delegate's <code>ready()</code> method.
- * @return true if the stream is ready to be read
- * @throws IOException if an I/O error occurs
- */
- public boolean ready() throws IOException {
- return in.ready();
- }
-
- /**
- * Invokes the delegate's <code>close()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public void close() throws IOException {
- in.close();
- }
-
- /**
- * Invokes the delegate's <code>mark(int)</code> method.
- * @param idx read ahead limit
- * @throws IOException if an I/O error occurs
- */
- public synchronized void mark(int idx) throws IOException {
- in.mark(idx);
- }
-
- /**
- * Invokes the delegate's <code>reset()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public synchronized void reset() throws IOException {
- in.reset();
- }
-
- /**
- * Invokes the delegate's <code>markSupported()</code> method.
- * @return true if mark is supported, otherwise false
- */
- public boolean markSupported() {
- return in.markSupported();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/SwappedDataInputStream.java b/emailcommon/src/org/apache/commons/io/input/SwappedDataInputStream.java
deleted file mode 100644
index 5b65b1eee..000000000
--- a/emailcommon/src/org/apache/commons/io/input/SwappedDataInputStream.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.DataInput;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-
-import org.apache.commons.io.EndianUtils;
-
-/**
- * DataInput for systems relying on little endian data formats.
- * When read, values will be changed from little endian to big
- * endian formats for internal usage.
- * <p>
- * <b>Origin of code: </b>Avalon Excalibur (IO)
- *
- * @author <a href="mailto:peter@apache.org">Peter Donald</a>
- * @version CVS $Revision: 610010 $ $Date: 2008-01-08 14:50:59 +0000 (Tue, 08 Jan 2008) $
- */
-public class SwappedDataInputStream extends ProxyInputStream
- implements DataInput
-{
-
- /**
- * Constructs a SwappedDataInputStream.
- *
- * @param input InputStream to read from
- */
- public SwappedDataInputStream( InputStream input )
- {
- super( input );
- }
-
- /**
- * Return <code>{@link #readByte()} == 0</code>
- * @return the true if the byte read is zero, otherwise false
- * @throws IOException if an I/O error occurs
- * @throws EOFException if an end of file is reached unexpectedly
- */
- public boolean readBoolean()
- throws IOException, EOFException
- {
- return ( 0 == readByte() );
- }
-
- /**
- * Invokes the delegate's <code>read()</code> method.
- * @return the byte read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- * @throws EOFException if an end of file is reached unexpectedly
- */
- public byte readByte()
- throws IOException, EOFException
- {
- return (byte)in.read();
- }
-
- /**
- * Reads a character delegating to {@link #readShort()}.
- * @return the byte read or -1 if the end of stream
- * @throws IOException if an I/O error occurs
- * @throws EOFException if an end of file is reached unexpectedly
- */
- public char readChar()
- throws IOException, EOFException
- {
- return (char)readShort();
- }
-
- /**
- * Delegates to {@link EndianUtils#readSwappedDouble(InputStream)}.
- * @return the read long
- * @throws IOException if an I/O error occurs
- * @throws EOFException if an end of file is reached unexpectedly
- */
- public double readDouble()
- throws IOException, EOFException
- {
- return EndianUtils.readSwappedDouble( in );
- }
-
- /**
- * Delegates to {@link EndianUtils#readSwappedFloat(InputStream)}.
- * @return the read long
- * @throws IOException if an I/O error occurs
- * @throws EOFException if an end of file is reached unexpectedly
- */
- public float readFloat()
- throws IOException, EOFException
- {
- return EndianUtils.readSwappedFloat( in );
- }
-
- /**
- * Invokes the delegate's <code>read(byte[] data, int, int)</code> method.
- *
- * @param data the buffer to read the bytes into
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public void readFully( byte[] data )
- throws IOException, EOFException
- {
- readFully( data, 0, data.length );
- }
-
-
- /**
- * Invokes the delegate's <code>read(byte[] data, int, int)</code> method.
- *
- * @param data the buffer to read the bytes into
- * @param offset The start offset
- * @param length The number of bytes to read
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public void readFully( byte[] data, int offset, int length )
- throws IOException, EOFException
- {
- int remaining = length;
-
- while( remaining > 0 )
- {
- int location = offset + ( length - remaining );
- int count = read( data, location, remaining );
-
- if( -1 == count )
- {
- throw new EOFException();
- }
-
- remaining -= count;
- }
- }
-
- /**
- * Delegates to {@link EndianUtils#readSwappedInteger(InputStream)}.
- * @return the read long
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public int readInt()
- throws IOException, EOFException
- {
- return EndianUtils.readSwappedInteger( in );
- }
-
- /**
- * Not currently supported - throws {@link UnsupportedOperationException}.
- * @return the line read
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public String readLine()
- throws IOException, EOFException
- {
- throw new UnsupportedOperationException(
- "Operation not supported: readLine()" );
- }
-
- /**
- * Delegates to {@link EndianUtils#readSwappedLong(InputStream)}.
- * @return the read long
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public long readLong()
- throws IOException, EOFException
- {
- return EndianUtils.readSwappedLong( in );
- }
-
- /**
- * Delegates to {@link EndianUtils#readSwappedShort(InputStream)}.
- * @return the read long
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public short readShort()
- throws IOException, EOFException
- {
- return EndianUtils.readSwappedShort( in );
- }
-
- /**
- * Invokes the delegate's <code>read()</code> method.
- * @return the byte read or -1 if the end of stream
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public int readUnsignedByte()
- throws IOException, EOFException
- {
- return in.read();
- }
-
- /**
- * Delegates to {@link EndianUtils#readSwappedUnsignedShort(InputStream)}.
- * @return the read long
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public int readUnsignedShort()
- throws IOException, EOFException
- {
- return EndianUtils.readSwappedUnsignedShort( in );
- }
-
- /**
- * Not currently supported - throws {@link UnsupportedOperationException}.
- * @return UTF String read
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public String readUTF()
- throws IOException, EOFException
- {
- throw new UnsupportedOperationException(
- "Operation not supported: readUTF()" );
- }
-
- /**
- * Invokes the delegate's <code>skip(int)</code> method.
- * @param count the number of bytes to skip
- * @return the number of bytes to skipped or -1 if the end of stream
- * @throws EOFException if an end of file is reached unexpectedly
- * @throws IOException if an I/O error occurs
- */
- public int skipBytes( int count )
- throws IOException, EOFException
- {
- return (int)in.skip( count );
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/TeeInputStream.java b/emailcommon/src/org/apache/commons/io/input/TeeInputStream.java
deleted file mode 100644
index fed000ed6..000000000
--- a/emailcommon/src/org/apache/commons/io/input/TeeInputStream.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.input;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * InputStream proxy that transparently writes a copy of all bytes read
- * from the proxied stream to a given OutputStream. Using {@link #skip(long)}
- * or {@link #mark(int)}/{@link #reset()} on the stream will result on some
- * bytes from the input stream being skipped or duplicated in the output
- * stream.
- * <p>
- * The proxied input stream is closed when the {@link #close()} method is
- * called on this proxy. It is configurable whether the associated output
- * stream will also closed.
- *
- * @version $Id: TeeInputStream.java 587913 2007-10-24 15:47:30Z niallp $
- * @since Commons IO 1.4
- */
-public class TeeInputStream extends ProxyInputStream {
-
- /**
- * The output stream that will receive a copy of all bytes read from the
- * proxied input stream.
- */
- private final OutputStream branch;
-
- /**
- * Flag for closing also the associated output stream when this
- * stream is closed.
- */
- private final boolean closeBranch;
-
- /**
- * Creates a TeeInputStream that proxies the given {@link InputStream}
- * and copies all read bytes to the given {@link OutputStream}. The given
- * output stream will not be closed when this stream gets closed.
- *
- * @param input input stream to be proxied
- * @param branch output stream that will receive a copy of all bytes read
- */
- public TeeInputStream(InputStream input, OutputStream branch) {
- this(input, branch, false);
- }
-
- /**
- * Creates a TeeInputStream that proxies the given {@link InputStream}
- * and copies all read bytes to the given {@link OutputStream}. The given
- * output stream will be closed when this stream gets closed if the
- * closeBranch parameter is <code>true</code>.
- *
- * @param input input stream to be proxied
- * @param branch output stream that will receive a copy of all bytes read
- * @param closeBranch flag for closing also the output stream when this
- * stream is closed
- */
- public TeeInputStream(
- InputStream input, OutputStream branch, boolean closeBranch) {
- super(input);
- this.branch = branch;
- this.closeBranch = closeBranch;
- }
-
- /**
- * Closes the proxied input stream and, if so configured, the associated
- * output stream. An exception thrown from one stream will not prevent
- * closing of the other stream.
- *
- * @throws IOException if either of the streams could not be closed
- */
- public void close() throws IOException {
- try {
- super.close();
- } finally {
- if (closeBranch) {
- branch.close();
- }
- }
- }
-
- /**
- * Reads a single byte from the proxied input stream and writes it to
- * the associated output stream.
- *
- * @return next byte from the stream, or -1 if the stream has ended
- * @throws IOException if the stream could not be read (or written)
- */
- public int read() throws IOException {
- int ch = super.read();
- if (ch != -1) {
- branch.write(ch);
- }
- return ch;
- }
-
- /**
- * Reads bytes from the proxied input stream and writes the read bytes
- * to the associated output stream.
- *
- * @param bts byte buffer
- * @param st start offset within the buffer
- * @param end maximum number of bytes to read
- * @return number of bytes read, or -1 if the stream has ended
- * @throws IOException if the stream could not be read (or written)
- */
- public int read(byte[] bts, int st, int end) throws IOException {
- int n = super.read(bts, st, end);
- if (n != -1) {
- branch.write(bts, st, n);
- }
- return n;
- }
-
- /**
- * Reads bytes from the proxied input stream and writes the read bytes
- * to the associated output stream.
- *
- * @param bts byte buffer
- * @return number of bytes read, or -1 if the stream has ended
- * @throws IOException if the stream could not be read (or written)
- */
- public int read(byte[] bts) throws IOException {
- int n = super.read(bts);
- if (n != -1) {
- branch.write(bts, 0, n);
- }
- return n;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/input/package.html b/emailcommon/src/org/apache/commons/io/input/package.html
deleted file mode 100644
index 9aa8b15ba..000000000
--- a/emailcommon/src/org/apache/commons/io/input/package.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<!--
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-<html>
-<body>
-<p>
-This package provides implementations of input classes, such as
-<code>InputStream</code> and <code>Reader</code>.
-</p>
-</body>
-</html>
diff --git a/emailcommon/src/org/apache/commons/io/output/ByteArrayOutputStream.java b/emailcommon/src/org/apache/commons/io/output/ByteArrayOutputStream.java
deleted file mode 100644
index 906a41dd4..000000000
--- a/emailcommon/src/org/apache/commons/io/output/ByteArrayOutputStream.java
+++ /dev/null
@@ -1,312 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.UnsupportedEncodingException;
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This class implements an output stream in which the data is
- * written into a byte array. The buffer automatically grows as data
- * is written to it.
- * <p>
- * The data can be retrieved using <code>toByteArray()</code> and
- * <code>toString()</code>.
- * <p>
- * Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
- * this class can be called after the stream has been closed without
- * generating an <tt>IOException</tt>.
- * <p>
- * This is an alternative implementation of the java.io.ByteArrayOutputStream
- * class. The original implementation only allocates 32 bytes at the beginning.
- * As this class is designed for heavy duty it starts at 1024 bytes. In contrast
- * to the original it doesn't reallocate the whole memory block but allocates
- * additional buffers. This way no buffers need to be garbage collected and
- * the contents don't have to be copied to the new buffer. This class is
- * designed to behave exactly like the original. The only exception is the
- * deprecated toString(int) method that has been ignored.
- *
- * @author <a href="mailto:jeremias@apache.org">Jeremias Maerki</a>
- * @author Holger Hoffstatte
- * @version $Id: ByteArrayOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public class ByteArrayOutputStream extends OutputStream {
-
- /** A singleton empty byte array. */
- private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
-
- /** The list of buffers, which grows and never reduces. */
- private List<byte[]> buffers = new ArrayList<byte[]>();
- /** The index of the current buffer. */
- private int currentBufferIndex;
- /** The total count of bytes in all the filled buffers. */
- private int filledBufferSum;
- /** The current buffer. */
- private byte[] currentBuffer;
- /** The total count of bytes written. */
- private int count;
-
- /**
- * Creates a new byte array output stream. The buffer capacity is
- * initially 1024 bytes, though its size increases if necessary.
- */
- public ByteArrayOutputStream() {
- this(1024);
- }
-
- /**
- * Creates a new byte array output stream, with a buffer capacity of
- * the specified size, in bytes.
- *
- * @param size the initial size
- * @throws IllegalArgumentException if size is negative
- */
- public ByteArrayOutputStream(int size) {
- if (size < 0) {
- throw new IllegalArgumentException(
- "Negative initial size: " + size);
- }
- needNewBuffer(size);
- }
-
- /**
- * Return the appropriate <code>byte[]</code> buffer
- * specified by index.
- *
- * @param index the index of the buffer required
- * @return the buffer
- */
- private byte[] getBuffer(int index) {
- return buffers.get(index);
- }
-
- /**
- * Makes a new buffer available either by allocating
- * a new one or re-cycling an existing one.
- *
- * @param newcount the size of the buffer if one is created
- */
- private void needNewBuffer(int newcount) {
- if (currentBufferIndex < buffers.size() - 1) {
- //Recycling old buffer
- filledBufferSum += currentBuffer.length;
-
- currentBufferIndex++;
- currentBuffer = getBuffer(currentBufferIndex);
- } else {
- //Creating new buffer
- int newBufferSize;
- if (currentBuffer == null) {
- newBufferSize = newcount;
- filledBufferSum = 0;
- } else {
- newBufferSize = Math.max(
- currentBuffer.length << 1,
- newcount - filledBufferSum);
- filledBufferSum += currentBuffer.length;
- }
-
- currentBufferIndex++;
- currentBuffer = new byte[newBufferSize];
- buffers.add(currentBuffer);
- }
- }
-
- /**
- * Write the bytes to byte array.
- * @param b the bytes to write
- * @param off The start offset
- * @param len The number of bytes to write
- */
- @Override
- public void write(byte[] b, int off, int len) {
- if ((off < 0)
- || (off > b.length)
- || (len < 0)
- || ((off + len) > b.length)
- || ((off + len) < 0)) {
- throw new IndexOutOfBoundsException();
- } else if (len == 0) {
- return;
- }
- synchronized (this) {
- int newcount = count + len;
- int remaining = len;
- int inBufferPos = count - filledBufferSum;
- while (remaining > 0) {
- int part = Math.min(remaining, currentBuffer.length - inBufferPos);
- System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part);
- remaining -= part;
- if (remaining > 0) {
- needNewBuffer(newcount);
- inBufferPos = 0;
- }
- }
- count = newcount;
- }
- }
-
- /**
- * Write a byte to byte array.
- * @param b the byte to write
- */
- @Override
- public synchronized void write(int b) {
- int inBufferPos = count - filledBufferSum;
- if (inBufferPos == currentBuffer.length) {
- needNewBuffer(count + 1);
- inBufferPos = 0;
- }
- currentBuffer[inBufferPos] = (byte) b;
- count++;
- }
-
- /**
- * Writes the entire contents of the specified input stream to this
- * byte stream. Bytes from the input stream are read directly into the
- * internal buffers of this streams.
- *
- * @param in the input stream to read from
- * @return total number of bytes read from the input stream
- * (and written to this stream)
- * @throws IOException if an I/O error occurs while reading the input stream
- * @since Commons IO 1.4
- */
- public synchronized int write(InputStream in) throws IOException {
- int readCount = 0;
- int inBufferPos = count - filledBufferSum;
- int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
- while (n != -1) {
- readCount += n;
- inBufferPos += n;
- count += n;
- if (inBufferPos == currentBuffer.length) {
- needNewBuffer(currentBuffer.length);
- inBufferPos = 0;
- }
- n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos);
- }
- return readCount;
- }
-
- /**
- * Return the current size of the byte array.
- * @return the current size of the byte array
- */
- public synchronized int size() {
- return count;
- }
-
- /**
- * Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
- * this class can be called after the stream has been closed without
- * generating an <tt>IOException</tt>.
- *
- * @throws IOException never (this method should not declare this exception
- * but it has to now due to backwards compatability)
- */
- @Override
- public void close() throws IOException {
- //nop
- }
-
- /**
- * @see java.io.ByteArrayOutputStream#reset()
- */
- public synchronized void reset() {
- count = 0;
- filledBufferSum = 0;
- currentBufferIndex = 0;
- currentBuffer = getBuffer(currentBufferIndex);
- }
-
- /**
- * Writes the entire contents of this byte stream to the
- * specified output stream.
- *
- * @param out the output stream to write to
- * @throws IOException if an I/O error occurs, such as if the stream is closed
- * @see java.io.ByteArrayOutputStream#writeTo(OutputStream)
- */
- public synchronized void writeTo(OutputStream out) throws IOException {
- int remaining = count;
- for (int i = 0; i < buffers.size(); i++) {
- byte[] buf = getBuffer(i);
- int c = Math.min(buf.length, remaining);
- out.write(buf, 0, c);
- remaining -= c;
- if (remaining == 0) {
- break;
- }
- }
- }
-
- /**
- * Gets the curent contents of this byte stream as a byte array.
- * The result is independent of this stream.
- *
- * @return the current contents of this output stream, as a byte array
- * @see java.io.ByteArrayOutputStream#toByteArray()
- */
- public synchronized byte[] toByteArray() {
- int remaining = count;
- if (remaining == 0) {
- return EMPTY_BYTE_ARRAY;
- }
- byte newbuf[] = new byte[remaining];
- int pos = 0;
- for (int i = 0; i < buffers.size(); i++) {
- byte[] buf = getBuffer(i);
- int c = Math.min(buf.length, remaining);
- System.arraycopy(buf, 0, newbuf, pos, c);
- pos += c;
- remaining -= c;
- if (remaining == 0) {
- break;
- }
- }
- return newbuf;
- }
-
- /**
- * Gets the curent contents of this byte stream as a string.
- * @return the contents of the byte array as a String
- * @see java.io.ByteArrayOutputStream#toString()
- */
- @Override
- public String toString() {
- return new String(toByteArray());
- }
-
- /**
- * Gets the curent contents of this byte stream as a string
- * using the specified encoding.
- *
- * @param enc the name of the character encoding
- * @return the string converted from the byte array
- * @throws UnsupportedEncodingException if the encoding is not supported
- * @see java.io.ByteArrayOutputStream#toString(String)
- */
- public String toString(String enc) throws UnsupportedEncodingException {
- return new String(toByteArray(), enc);
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/CloseShieldOutputStream.java b/emailcommon/src/org/apache/commons/io/output/CloseShieldOutputStream.java
deleted file mode 100644
index 63f44be40..000000000
--- a/emailcommon/src/org/apache/commons/io/output/CloseShieldOutputStream.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.OutputStream;
-
-/**
- * Proxy stream that prevents the underlying output stream from being closed.
- * <p>
- * This class is typically used in cases where an output stream needs to be
- * passed to a component that wants to explicitly close the stream even if
- * other components would still use the stream for output.
- *
- * @version $Id: CloseShieldOutputStream.java 587913 2007-10-24 15:47:30Z niallp $
- * @since Commons IO 1.4
- */
-public class CloseShieldOutputStream extends ProxyOutputStream {
-
- /**
- * Creates a proxy that shields the given output stream from being
- * closed.
- *
- * @param out underlying output stream
- */
- public CloseShieldOutputStream(OutputStream out) {
- super(out);
- }
-
- /**
- * Replaces the underlying output stream with a {@link ClosedOutputStream}
- * sentinel. The original output stream will remain open, but this proxy
- * will appear closed.
- */
- public void close() {
- out = new ClosedOutputStream();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/ClosedOutputStream.java b/emailcommon/src/org/apache/commons/io/output/ClosedOutputStream.java
deleted file mode 100644
index b585c0cf4..000000000
--- a/emailcommon/src/org/apache/commons/io/output/ClosedOutputStream.java
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * Closed output stream. This stream throws an exception on all attempts to
- * write something to the stream.
- * <p>
- * Typically uses of this class include testing for corner cases in methods
- * that accept an output stream and acting as a sentinel value instead of
- * a <code>null</code> output stream.
- *
- * @version $Id: ClosedOutputStream.java 601751 2007-12-06 14:55:45Z niallp $
- * @since Commons IO 1.4
- */
-public class ClosedOutputStream extends OutputStream {
-
- /**
- * A singleton.
- */
- public static final ClosedOutputStream CLOSED_OUTPUT_STREAM = new ClosedOutputStream();
-
- /**
- * Throws an {@link IOException} to indicate that the stream is closed.
- *
- * @param b ignored
- * @throws IOException always thrown
- */
- public void write(int b) throws IOException {
- throw new IOException("write(" + b + ") failed: stream is closed");
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/CountingOutputStream.java b/emailcommon/src/org/apache/commons/io/output/CountingOutputStream.java
deleted file mode 100644
index 672882860..000000000
--- a/emailcommon/src/org/apache/commons/io/output/CountingOutputStream.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * A decorating output stream that counts the number of bytes that have passed
- * through the stream so far.
- * <p>
- * A typical use case would be during debugging, to ensure that data is being
- * written as expected.
- *
- * @version $Id: CountingOutputStream.java 471628 2006-11-06 04:06:45Z bayard $
- */
-public class CountingOutputStream extends ProxyOutputStream {
-
- /** The count of bytes that have passed. */
- private long count;
-
- /**
- * Constructs a new CountingOutputStream.
- *
- * @param out the OutputStream to write to
- */
- public CountingOutputStream( OutputStream out ) {
- super(out);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Writes the contents of the specified byte array to this output stream
- * keeping count of the number of bytes written.
- *
- * @param b the bytes to write, not null
- * @throws IOException if an I/O error occurs
- * @see java.io.OutputStream#write(byte[])
- */
- public void write(byte[] b) throws IOException {
- count += b.length;
- super.write(b);
- }
-
- /**
- * Writes a portion of the specified byte array to this output stream
- * keeping count of the number of bytes written.
- *
- * @param b the bytes to write, not null
- * @param off the start offset in the buffer
- * @param len the maximum number of bytes to write
- * @throws IOException if an I/O error occurs
- * @see java.io.OutputStream#write(byte[], int, int)
- */
- public void write(byte[] b, int off, int len) throws IOException {
- count += len;
- super.write(b, off, len);
- }
-
- /**
- * Writes a single byte to the output stream adding to the count of the
- * number of bytes written.
- *
- * @param b the byte to write
- * @throws IOException if an I/O error occurs
- * @see java.io.OutputStream#write(int)
- */
- public void write(int b) throws IOException {
- count++;
- super.write(b);
- }
-
- //-----------------------------------------------------------------------
- /**
- * The number of bytes that have passed through this stream.
- * <p>
- * NOTE: From v1.3 this method throws an ArithmeticException if the
- * count is greater than can be expressed by an <code>int</code>.
- * See {@link #getByteCount()} for a method using a <code>long</code>.
- *
- * @return the number of bytes accumulated
- * @throws ArithmeticException if the byte count is too large
- */
- public synchronized int getCount() {
- long result = getByteCount();
- if (result > Integer.MAX_VALUE) {
- throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
- }
- return (int) result;
- }
-
- /**
- * Set the byte count back to 0.
- * <p>
- * NOTE: From v1.3 this method throws an ArithmeticException if the
- * count is greater than can be expressed by an <code>int</code>.
- * See {@link #resetByteCount()} for a method using a <code>long</code>.
- *
- * @return the count previous to resetting
- * @throws ArithmeticException if the byte count is too large
- */
- public synchronized int resetCount() {
- long result = resetByteCount();
- if (result > Integer.MAX_VALUE) {
- throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int");
- }
- return (int) result;
- }
-
- /**
- * The number of bytes that have passed through this stream.
- * <p>
- * NOTE: This method is an alternative for <code>getCount()</code>.
- * It was added because that method returns an integer which will
- * result in incorrect count for files over 2GB.
- *
- * @return the number of bytes accumulated
- * @since Commons IO 1.3
- */
- public synchronized long getByteCount() {
- return this.count;
- }
-
- /**
- * Set the byte count back to 0.
- * <p>
- * NOTE: This method is an alternative for <code>resetCount()</code>.
- * It was added because that method returns an integer which will
- * result in incorrect count for files over 2GB.
- *
- * @return the count previous to resetting
- * @since Commons IO 1.3
- */
- public synchronized long resetByteCount() {
- long tmp = this.count;
- this.count = 0;
- return tmp;
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/DeferredFileOutputStream.java b/emailcommon/src/org/apache/commons/io/output/DeferredFileOutputStream.java
deleted file mode 100644
index b8a9e9607..000000000
--- a/emailcommon/src/org/apache/commons/io/output/DeferredFileOutputStream.java
+++ /dev/null
@@ -1,269 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-import org.apache.commons.io.IOUtils;
-
-
-/**
- * An output stream which will retain data in memory until a specified
- * threshold is reached, and only then commit it to disk. If the stream is
- * closed before the threshold is reached, the data will not be written to
- * disk at all.
- * <p>
- * This class originated in FileUpload processing. In this use case, you do
- * not know in advance the size of the file being uploaded. If the file is small
- * you want to store it in memory (for speed), but if the file is large you want
- * to store it to file (to avoid memory issues).
- *
- * @author <a href="mailto:martinc@apache.org">Martin Cooper</a>
- * @author gaxzerow
- *
- * @version $Id: DeferredFileOutputStream.java 606381 2007-12-22 02:03:16Z ggregory $
- */
-public class DeferredFileOutputStream
- extends ThresholdingOutputStream
-{
-
- // ----------------------------------------------------------- Data members
-
-
- /**
- * The output stream to which data will be written prior to the theshold
- * being reached.
- */
- private ByteArrayOutputStream memoryOutputStream;
-
-
- /**
- * The output stream to which data will be written at any given time. This
- * will always be one of <code>memoryOutputStream</code> or
- * <code>diskOutputStream</code>.
- */
- private OutputStream currentOutputStream;
-
-
- /**
- * The file to which output will be directed if the threshold is exceeded.
- */
- private File outputFile;
-
- /**
- * The temporary file prefix.
- */
- private String prefix;
-
- /**
- * The temporary file suffix.
- */
- private String suffix;
-
- /**
- * The directory to use for temporary files.
- */
- private File directory;
-
-
- /**
- * True when close() has been called successfully.
- */
- private boolean closed = false;
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Constructs an instance of this class which will trigger an event at the
- * specified threshold, and save data to a file beyond that point.
- *
- * @param threshold The number of bytes at which to trigger an event.
- * @param outputFile The file to which data is saved beyond the threshold.
- */
- public DeferredFileOutputStream(int threshold, File outputFile)
- {
- super(threshold);
- this.outputFile = outputFile;
-
- memoryOutputStream = new ByteArrayOutputStream();
- currentOutputStream = memoryOutputStream;
- }
-
-
- /**
- * Constructs an instance of this class which will trigger an event at the
- * specified threshold, and save data to a temporary file beyond that point.
- *
- * @param threshold The number of bytes at which to trigger an event.
- * @param prefix Prefix to use for the temporary file.
- * @param suffix Suffix to use for the temporary file.
- * @param directory Temporary file directory.
- *
- * @since Commons IO 1.4
- */
- public DeferredFileOutputStream(int threshold, String prefix, String suffix, File directory)
- {
- this(threshold, (File)null);
- if (prefix == null) {
- throw new IllegalArgumentException("Temporary file prefix is missing");
- }
- this.prefix = prefix;
- this.suffix = suffix;
- this.directory = directory;
- }
-
-
- // --------------------------------------- ThresholdingOutputStream methods
-
-
- /**
- * Returns the current output stream. This may be memory based or disk
- * based, depending on the current state with respect to the threshold.
- *
- * @return The underlying output stream.
- *
- * @exception IOException if an error occurs.
- */
- protected OutputStream getStream() throws IOException
- {
- return currentOutputStream;
- }
-
-
- /**
- * Switches the underlying output stream from a memory based stream to one
- * that is backed by disk. This is the point at which we realise that too
- * much data is being written to keep in memory, so we elect to switch to
- * disk-based storage.
- *
- * @exception IOException if an error occurs.
- */
- protected void thresholdReached() throws IOException
- {
- if (prefix != null) {
- outputFile = File.createTempFile(prefix, suffix, directory);
- }
- FileOutputStream fos = new FileOutputStream(outputFile);
- memoryOutputStream.writeTo(fos);
- currentOutputStream = fos;
- memoryOutputStream = null;
- }
-
-
- // --------------------------------------------------------- Public methods
-
-
- /**
- * Determines whether or not the data for this output stream has been
- * retained in memory.
- *
- * @return <code>true</code> if the data is available in memory;
- * <code>false</code> otherwise.
- */
- public boolean isInMemory()
- {
- return (!isThresholdExceeded());
- }
-
-
- /**
- * Returns the data for this output stream as an array of bytes, assuming
- * that the data has been retained in memory. If the data was written to
- * disk, this method returns <code>null</code>.
- *
- * @return The data for this output stream, or <code>null</code> if no such
- * data is available.
- */
- public byte[] getData()
- {
- if (memoryOutputStream != null)
- {
- return memoryOutputStream.toByteArray();
- }
- return null;
- }
-
-
- /**
- * Returns either the output file specified in the constructor or
- * the temporary file created or null.
- * <p>
- * If the constructor specifying the file is used then it returns that
- * same output file, even when threashold has not been reached.
- * <p>
- * If constructor specifying a temporary file prefix/suffix is used
- * then the temporary file created once the threashold is reached is returned
- * If the threshold was not reached then <code>null</code> is returned.
- *
- * @return The file for this output stream, or <code>null</code> if no such
- * file exists.
- */
- public File getFile()
- {
- return outputFile;
- }
-
-
- /**
- * Closes underlying output stream, and mark this as closed
- *
- * @exception IOException if an error occurs.
- */
- public void close() throws IOException
- {
- super.close();
- closed = true;
- }
-
-
- /**
- * Writes the data from this output stream to the specified output stream,
- * after it has been closed.
- *
- * @param out output stream to write to.
- * @exception IOException if this stream is not yet closed or an error occurs.
- */
- public void writeTo(OutputStream out) throws IOException
- {
- // we may only need to check if this is closed if we are working with a file
- // but we should force the habit of closing wether we are working with
- // a file or memory.
- if (!closed)
- {
- throw new IOException("Stream not closed");
- }
-
- if(isInMemory())
- {
- memoryOutputStream.writeTo(out);
- }
- else
- {
- FileInputStream fis = new FileInputStream(outputFile);
- try {
- IOUtils.copy(fis, out);
- } finally {
- IOUtils.closeQuietly(fis);
- }
- }
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/DemuxOutputStream.java b/emailcommon/src/org/apache/commons/io/output/DemuxOutputStream.java
deleted file mode 100644
index 280df14d3..000000000
--- a/emailcommon/src/org/apache/commons/io/output/DemuxOutputStream.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * Data written to this stream is forwarded to a stream that has been associated
- * with this thread.
- *
- * @author <a href="mailto:peter@apache.org">Peter Donald</a>
- * @version $Revision: 437567 $ $Date: 2006-08-28 07:39:07 +0100 (Mon, 28 Aug 2006) $
- */
-public class DemuxOutputStream
- extends OutputStream
-{
- private InheritableThreadLocal<OutputStream> m_streams = new InheritableThreadLocal<OutputStream>();
-
- /**
- * Bind the specified stream to the current thread.
- *
- * @param output the stream to bind
- * @return the OutputStream that was previously active
- */
- public OutputStream bindStream( OutputStream output )
- {
- OutputStream stream = getStream();
- m_streams.set( output );
- return stream;
- }
-
- /**
- * Closes stream associated with current thread.
- *
- * @throws IOException if an error occurs
- */
- @Override
- public void close()
- throws IOException
- {
- OutputStream output = getStream();
- if( null != output )
- {
- output.close();
- }
- }
-
- /**
- * Flushes stream associated with current thread.
- *
- * @throws IOException if an error occurs
- */
- @Override
- public void flush()
- throws IOException
- {
- OutputStream output = getStream();
- if( null != output )
- {
- output.flush();
- }
- }
-
- /**
- * Writes byte to stream associated with current thread.
- *
- * @param ch the byte to write to stream
- * @throws IOException if an error occurs
- */
- @Override
- public void write( int ch )
- throws IOException
- {
- OutputStream output = getStream();
- if( null != output )
- {
- output.write( ch );
- }
- }
-
- /**
- * Utility method to retrieve stream bound to current thread (if any).
- *
- * @return the output stream
- */
- private OutputStream getStream()
- {
- return m_streams.get();
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/FileWriterWithEncoding.java b/emailcommon/src/org/apache/commons/io/output/FileWriterWithEncoding.java
deleted file mode 100644
index a8f89334b..000000000
--- a/emailcommon/src/org/apache/commons/io/output/FileWriterWithEncoding.java
+++ /dev/null
@@ -1,324 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.nio.charset.Charset;
-import java.nio.charset.CharsetEncoder;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-
-/**
- * Writer of files that allows the encoding to be set.
- * <p>
- * This class provides a simple alternative to <code>FileWriter</code>
- * that allows an encoding to be set. Unfortunately, it cannot subclass
- * <code>FileWriter</code>.
- * <p>
- * By default, the file will be overwritten, but this may be changed to append.
- * <p>
- * The encoding must be specified using either the name of the {@link Charset},
- * the {@link Charset}, or a {@link CharsetEncoder}. If the default encoding
- * is required then use the {@link java.io.FileWriter} directly, rather than
- * this implementation.
- * <p>
- *
- *
- * @since Commons IO 1.4
- * @version $Id: FileWriterWithEncoding.java 611634 2008-01-13 20:35:00Z niallp $
- */
-public class FileWriterWithEncoding extends Writer {
- // Cannot extend ProxyWriter, as requires writer to be
- // known when super() is called
-
- /** The writer to decorate. */
- private final Writer out;
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param filename the name of the file to write to, not null
- * @param encoding the encoding to use, not null
- * @throws NullPointerException if the file name or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(String filename, String encoding) throws IOException {
- this(new File(filename), encoding, false);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param filename the name of the file to write to, not null
- * @param encoding the encoding to use, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file name or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(String filename, String encoding, boolean append) throws IOException {
- this(new File(filename), encoding, append);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param filename the name of the file to write to, not null
- * @param encoding the encoding to use, not null
- * @throws NullPointerException if the file name or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(String filename, Charset encoding) throws IOException {
- this(new File(filename), encoding, false);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param filename the name of the file to write to, not null
- * @param encoding the encoding to use, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file name or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(String filename, Charset encoding, boolean append) throws IOException {
- this(new File(filename), encoding, append);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param filename the name of the file to write to, not null
- * @param encoding the encoding to use, not null
- * @throws NullPointerException if the file name or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(String filename, CharsetEncoder encoding) throws IOException {
- this(new File(filename), encoding, false);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param filename the name of the file to write to, not null
- * @param encoding the encoding to use, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file name or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(String filename, CharsetEncoder encoding, boolean append) throws IOException {
- this(new File(filename), encoding, append);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, not null
- * @throws NullPointerException if the file or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(File file, String encoding) throws IOException {
- this(file, encoding, false);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(File file, String encoding, boolean append) throws IOException {
- super();
- this.out = initWriter(file, encoding, append);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, not null
- * @throws NullPointerException if the file or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(File file, Charset encoding) throws IOException {
- this(file, encoding, false);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(File file, Charset encoding, boolean append) throws IOException {
- super();
- this.out = initWriter(file, encoding, append);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, not null
- * @throws NullPointerException if the file or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(File file, CharsetEncoder encoding) throws IOException {
- this(file, encoding, false);
- }
-
- /**
- * Constructs a FileWriterWithEncoding with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file or encoding is null
- * @throws IOException in case of an I/O error
- */
- public FileWriterWithEncoding(File file, CharsetEncoder encoding, boolean append) throws IOException {
- super();
- this.out = initWriter(file, encoding, append);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Initialise the wrapped file writer.
- * Ensure that a cleanup occurs if the writer creation fails.
- *
- * @param file the file to be accessed
- * @param encoding the encoding to use - may be Charset, CharsetEncoder or String
- * @param append true to append
- * @return the initialised writer
- * @throws NullPointerException if the file or encoding is null
- * @throws IOException if an error occurs
- */
- private static Writer initWriter(File file, Object encoding, boolean append) throws IOException {
- if (file == null) {
- throw new NullPointerException("File is missing");
- }
- if (encoding == null) {
- throw new NullPointerException("Encoding is missing");
- }
- boolean fileExistedAlready = file.exists();
- OutputStream stream = null;
- Writer writer = null;
- try {
- stream = new FileOutputStream(file, append);
- if (encoding instanceof Charset) {
- writer = new OutputStreamWriter(stream, (Charset)encoding);
- } else if (encoding instanceof CharsetEncoder) {
- writer = new OutputStreamWriter(stream, (CharsetEncoder)encoding);
- } else {
- writer = new OutputStreamWriter(stream, (String)encoding);
- }
- } catch (IOException ex) {
- IOUtils.closeQuietly(writer);
- IOUtils.closeQuietly(stream);
- if (fileExistedAlready == false) {
- FileUtils.deleteQuietly(file);
- }
- throw ex;
- } catch (RuntimeException ex) {
- IOUtils.closeQuietly(writer);
- IOUtils.closeQuietly(stream);
- if (fileExistedAlready == false) {
- FileUtils.deleteQuietly(file);
- }
- throw ex;
- }
- return writer;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Write a character.
- * @param idx the character to write
- * @throws IOException if an I/O error occurs
- */
- public void write(int idx) throws IOException {
- out.write(idx);
- }
-
- /**
- * Write the characters from an array.
- * @param chr the characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(char[] chr) throws IOException {
- out.write(chr);
- }
-
- /**
- * Write the specified characters from an array.
- * @param chr the characters to write
- * @param st The start offset
- * @param end The number of characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(char[] chr, int st, int end) throws IOException {
- out.write(chr, st, end);
- }
-
- /**
- * Write the characters from a string.
- * @param str the string to write
- * @throws IOException if an I/O error occurs
- */
- public void write(String str) throws IOException {
- out.write(str);
- }
-
- /**
- * Write the specified characters from a string.
- * @param str the string to write
- * @param st The start offset
- * @param end The number of characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(String str, int st, int end) throws IOException {
- out.write(str, st, end);
- }
-
- /**
- * Flush the stream.
- * @throws IOException if an I/O error occurs
- */
- public void flush() throws IOException {
- out.flush();
- }
-
- /**
- * Close the stream.
- * @throws IOException if an I/O error occurs
- */
- public void close() throws IOException {
- out.close();
- }
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/LockableFileWriter.java b/emailcommon/src/org/apache/commons/io/output/LockableFileWriter.java
deleted file mode 100644
index 6b10bd282..000000000
--- a/emailcommon/src/org/apache/commons/io/output/LockableFileWriter.java
+++ /dev/null
@@ -1,333 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.FileWriter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.io.IOUtils;
-
-/**
- * FileWriter that will create and honor lock files to allow simple
- * cross thread file lock handling.
- * <p>
- * This class provides a simple alternative to <code>FileWriter</code>
- * that will use a lock file to prevent duplicate writes.
- * <p>
- * By default, the file will be overwritten, but this may be changed to append.
- * The lock directory may be specified, but defaults to the system property
- * <code>java.io.tmpdir</code>.
- * The encoding may also be specified, and defaults to the platform default.
- *
- * @author <a href="mailto:sanders@apache.org">Scott Sanders</a>
- * @author <a href="mailto:ms@collab.net">Michael Salmon</a>
- * @author <a href="mailto:jon@collab.net">Jon S. Stevens</a>
- * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
- * @author Stephen Colebourne
- * @author Andy Lehane
- * @version $Id: LockableFileWriter.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public class LockableFileWriter extends Writer {
- // Cannot extend ProxyWriter, as requires writer to be
- // known when super() is called
-
- /** The extension for the lock file. */
- private static final String LCK = ".lck";
-
- /** The writer to decorate. */
- private final Writer out;
- /** The lock file. */
- private final File lockFile;
-
- /**
- * Constructs a LockableFileWriter.
- * If the file exists, it is overwritten.
- *
- * @param fileName the file to write to, not null
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(String fileName) throws IOException {
- this(fileName, false, null);
- }
-
- /**
- * Constructs a LockableFileWriter.
- *
- * @param fileName file to write to, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(String fileName, boolean append) throws IOException {
- this(fileName, append, null);
- }
-
- /**
- * Constructs a LockableFileWriter.
- *
- * @param fileName the file to write to, not null
- * @param append true if content should be appended, false to overwrite
- * @param lockDir the directory in which the lock file should be held
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(String fileName, boolean append, String lockDir) throws IOException {
- this(new File(fileName), append, lockDir);
- }
-
- /**
- * Constructs a LockableFileWriter.
- * If the file exists, it is overwritten.
- *
- * @param file the file to write to, not null
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(File file) throws IOException {
- this(file, false, null);
- }
-
- /**
- * Constructs a LockableFileWriter.
- *
- * @param file the file to write to, not null
- * @param append true if content should be appended, false to overwrite
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(File file, boolean append) throws IOException {
- this(file, append, null);
- }
-
- /**
- * Constructs a LockableFileWriter.
- *
- * @param file the file to write to, not null
- * @param append true if content should be appended, false to overwrite
- * @param lockDir the directory in which the lock file should be held
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(File file, boolean append, String lockDir) throws IOException {
- this(file, null, append, lockDir);
- }
-
- /**
- * Constructs a LockableFileWriter with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, null means platform default
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(File file, String encoding) throws IOException {
- this(file, encoding, false, null);
- }
-
- /**
- * Constructs a LockableFileWriter with a file encoding.
- *
- * @param file the file to write to, not null
- * @param encoding the encoding to use, null means platform default
- * @param append true if content should be appended, false to overwrite
- * @param lockDir the directory in which the lock file should be held
- * @throws NullPointerException if the file is null
- * @throws IOException in case of an I/O error
- */
- public LockableFileWriter(File file, String encoding, boolean append,
- String lockDir) throws IOException {
- super();
- // init file to create/append
- file = file.getAbsoluteFile();
- if (file.getParentFile() != null) {
- FileUtils.forceMkdir(file.getParentFile());
- }
- if (file.isDirectory()) {
- throw new IOException("File specified is a directory");
- }
-
- // init lock file
- if (lockDir == null) {
- lockDir = System.getProperty("java.io.tmpdir");
- }
- File lockDirFile = new File(lockDir);
- FileUtils.forceMkdir(lockDirFile);
- testLockDir(lockDirFile);
- lockFile = new File(lockDirFile, file.getName() + LCK);
-
- // check if locked
- createLock();
-
- // init wrapped writer
- out = initWriter(file, encoding, append);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Tests that we can write to the lock directory.
- *
- * @param lockDir the File representing the lock directory
- * @throws IOException if we cannot write to the lock directory
- * @throws IOException if we cannot find the lock file
- */
- private void testLockDir(File lockDir) throws IOException {
- if (!lockDir.exists()) {
- throw new IOException(
- "Could not find lockDir: " + lockDir.getAbsolutePath());
- }
- if (!lockDir.canWrite()) {
- throw new IOException(
- "Could not write to lockDir: " + lockDir.getAbsolutePath());
- }
- }
-
- /**
- * Creates the lock file.
- *
- * @throws IOException if we cannot create the file
- */
- private void createLock() throws IOException {
- synchronized (LockableFileWriter.class) {
- if (!lockFile.createNewFile()) {
- throw new IOException("Can't write file, lock " +
- lockFile.getAbsolutePath() + " exists");
- }
- lockFile.deleteOnExit();
- }
- }
-
- /**
- * Initialise the wrapped file writer.
- * Ensure that a cleanup occurs if the writer creation fails.
- *
- * @param file the file to be accessed
- * @param encoding the encoding to use
- * @param append true to append
- * @return The initialised writer
- * @throws IOException if an error occurs
- */
- private Writer initWriter(File file, String encoding, boolean append) throws IOException {
- boolean fileExistedAlready = file.exists();
- OutputStream stream = null;
- Writer writer = null;
- try {
- if (encoding == null) {
- writer = new FileWriter(file.getAbsolutePath(), append);
- } else {
- stream = new FileOutputStream(file.getAbsolutePath(), append);
- writer = new OutputStreamWriter(stream, encoding);
- }
- } catch (IOException ex) {
- IOUtils.closeQuietly(writer);
- IOUtils.closeQuietly(stream);
- lockFile.delete();
- if (fileExistedAlready == false) {
- file.delete();
- }
- throw ex;
- } catch (RuntimeException ex) {
- IOUtils.closeQuietly(writer);
- IOUtils.closeQuietly(stream);
- lockFile.delete();
- if (fileExistedAlready == false) {
- file.delete();
- }
- throw ex;
- }
- return writer;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Closes the file writer.
- *
- * @throws IOException if an I/O error occurs
- */
- public void close() throws IOException {
- try {
- out.close();
- } finally {
- lockFile.delete();
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Write a character.
- * @param idx the character to write
- * @throws IOException if an I/O error occurs
- */
- public void write(int idx) throws IOException {
- out.write(idx);
- }
-
- /**
- * Write the characters from an array.
- * @param chr the characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(char[] chr) throws IOException {
- out.write(chr);
- }
-
- /**
- * Write the specified characters from an array.
- * @param chr the characters to write
- * @param st The start offset
- * @param end The number of characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(char[] chr, int st, int end) throws IOException {
- out.write(chr, st, end);
- }
-
- /**
- * Write the characters from a string.
- * @param str the string to write
- * @throws IOException if an I/O error occurs
- */
- public void write(String str) throws IOException {
- out.write(str);
- }
-
- /**
- * Write the specified characters from a string.
- * @param str the string to write
- * @param st The start offset
- * @param end The number of characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(String str, int st, int end) throws IOException {
- out.write(str, st, end);
- }
-
- /**
- * Flush the stream.
- * @throws IOException if an I/O error occurs
- */
- public void flush() throws IOException {
- out.flush();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/NullOutputStream.java b/emailcommon/src/org/apache/commons/io/output/NullOutputStream.java
deleted file mode 100644
index 7e3cdaf2c..000000000
--- a/emailcommon/src/org/apache/commons/io/output/NullOutputStream.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * This OutputStream writes all data to the famous <b>/dev/null</b>.
- * <p>
- * This output stream has no destination (file/socket etc.) and all
- * bytes written to it are ignored and lost.
- *
- * @author Jeremias Maerki
- * @version $Id: NullOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public class NullOutputStream extends OutputStream {
-
- /**
- * A singleton.
- */
- public static final NullOutputStream NULL_OUTPUT_STREAM = new NullOutputStream();
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param b The bytes to write
- * @param off The start offset
- * @param len The number of bytes to write
- */
- public void write(byte[] b, int off, int len) {
- //to /dev/null
- }
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param b The byte to write
- */
- public void write(int b) {
- //to /dev/null
- }
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param b The bytes to write
- * @throws IOException never
- */
- public void write(byte[] b) throws IOException {
- //to /dev/null
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/NullWriter.java b/emailcommon/src/org/apache/commons/io/output/NullWriter.java
deleted file mode 100644
index aed52aba8..000000000
--- a/emailcommon/src/org/apache/commons/io/output/NullWriter.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.Writer;
-
-/**
- * This {@link Writer} writes all data to the famous <b>/dev/null</b>.
- * <p>
- * This <code>Writer</code> has no destination (file/socket etc.) and all
- * characters written to it are ignored and lost.
- *
- * @version $Id: NullWriter.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public class NullWriter extends Writer {
-
- /**
- * A singleton.
- */
- public static final NullWriter NULL_WRITER = new NullWriter();
-
- /**
- * Constructs a new NullWriter.
- */
- public NullWriter() {
- }
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param idx The character to write
- */
- public void write(int idx) {
- //to /dev/null
- }
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param chr The characters to write
- */
- public void write(char[] chr) {
- //to /dev/null
- }
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param chr The characters to write
- * @param st The start offset
- * @param end The number of characters to write
- */
- public void write(char[] chr, int st, int end) {
- //to /dev/null
- }
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param str The string to write
- */
- public void write(String str) {
- //to /dev/null
- }
-
- /**
- * Does nothing - output to <code>/dev/null</code>.
- * @param str The string to write
- * @param st The start offset
- * @param end The number of characters to write
- */
- public void write(String str, int st, int end) {
- //to /dev/null
- }
-
- /** @see java.io.Writer#flush() */
- public void flush() {
- //to /dev/null
- }
-
- /** @see java.io.Writer#close() */
- public void close() {
- //to /dev/null
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/ProxyOutputStream.java b/emailcommon/src/org/apache/commons/io/output/ProxyOutputStream.java
deleted file mode 100644
index b63d72317..000000000
--- a/emailcommon/src/org/apache/commons/io/output/ProxyOutputStream.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.FilterOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * A Proxy stream which acts as expected, that is it passes the method
- * calls on to the proxied stream and doesn't change which methods are
- * being called. It is an alternative base class to FilterOutputStream
- * to increase reusability.
- *
- * @author Stephen Colebourne
- * @version $Id: ProxyOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public class ProxyOutputStream extends FilterOutputStream {
-
- /**
- * Constructs a new ProxyOutputStream.
- *
- * @param proxy the OutputStream to delegate to
- */
- public ProxyOutputStream(OutputStream proxy) {
- super(proxy);
- // the proxy is stored in a protected superclass variable named 'out'
- }
-
- /**
- * Invokes the delegate's <code>write(int)</code> method.
- * @param idx the byte to write
- * @throws IOException if an I/O error occurs
- */
- public void write(int idx) throws IOException {
- out.write(idx);
- }
-
- /**
- * Invokes the delegate's <code>write(byte[])</code> method.
- * @param bts the bytes to write
- * @throws IOException if an I/O error occurs
- */
- public void write(byte[] bts) throws IOException {
- out.write(bts);
- }
-
- /**
- * Invokes the delegate's <code>write(byte[])</code> method.
- * @param bts the bytes to write
- * @param st The start offset
- * @param end The number of bytes to write
- * @throws IOException if an I/O error occurs
- */
- public void write(byte[] bts, int st, int end) throws IOException {
- out.write(bts, st, end);
- }
-
- /**
- * Invokes the delegate's <code>flush()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public void flush() throws IOException {
- out.flush();
- }
-
- /**
- * Invokes the delegate's <code>close()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public void close() throws IOException {
- out.close();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/ProxyWriter.java b/emailcommon/src/org/apache/commons/io/output/ProxyWriter.java
deleted file mode 100644
index fbec62885..000000000
--- a/emailcommon/src/org/apache/commons/io/output/ProxyWriter.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.FilterWriter;
-import java.io.IOException;
-import java.io.Writer;
-
-/**
- * A Proxy stream which acts as expected, that is it passes the method
- * calls on to the proxied stream and doesn't change which methods are
- * being called. It is an alternative base class to FilterWriter
- * to increase reusability, because FilterWriter changes the
- * methods being called, such as write(char[]) to write(char[], int, int)
- * and write(String) to write(String, int, int).
- *
- * @author Stephen Colebourne
- * @version $Id: ProxyWriter.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public class ProxyWriter extends FilterWriter {
-
- /**
- * Constructs a new ProxyWriter.
- *
- * @param proxy the Writer to delegate to
- */
- public ProxyWriter(Writer proxy) {
- super(proxy);
- // the proxy is stored in a protected superclass variable named 'out'
- }
-
- /**
- * Invokes the delegate's <code>write(int)</code> method.
- * @param idx the character to write
- * @throws IOException if an I/O error occurs
- */
- public void write(int idx) throws IOException {
- out.write(idx);
- }
-
- /**
- * Invokes the delegate's <code>write(char[])</code> method.
- * @param chr the characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(char[] chr) throws IOException {
- out.write(chr);
- }
-
- /**
- * Invokes the delegate's <code>write(char[], int, int)</code> method.
- * @param chr the characters to write
- * @param st The start offset
- * @param end The number of characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(char[] chr, int st, int end) throws IOException {
- out.write(chr, st, end);
- }
-
- /**
- * Invokes the delegate's <code>write(String)</code> method.
- * @param str the string to write
- * @throws IOException if an I/O error occurs
- */
- public void write(String str) throws IOException {
- out.write(str);
- }
-
- /**
- * Invokes the delegate's <code>write(String)</code> method.
- * @param str the string to write
- * @param st The start offset
- * @param end The number of characters to write
- * @throws IOException if an I/O error occurs
- */
- public void write(String str, int st, int end) throws IOException {
- out.write(str, st, end);
- }
-
- /**
- * Invokes the delegate's <code>flush()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public void flush() throws IOException {
- out.flush();
- }
-
- /**
- * Invokes the delegate's <code>close()</code> method.
- * @throws IOException if an I/O error occurs
- */
- public void close() throws IOException {
- out.close();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/TeeOutputStream.java b/emailcommon/src/org/apache/commons/io/output/TeeOutputStream.java
deleted file mode 100644
index ee957fb3b..000000000
--- a/emailcommon/src/org/apache/commons/io/output/TeeOutputStream.java
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * Classic splitter of OutputStream. Named after the unix 'tee'
- * command. It allows a stream to be branched off so there
- * are now two streams.
- *
- * @version $Id: TeeOutputStream.java 610010 2008-01-08 14:50:59Z niallp $
- */
-public class TeeOutputStream extends ProxyOutputStream {
-
- /** the second OutputStream to write to */
- protected OutputStream branch;
-
- /**
- * Constructs a TeeOutputStream.
- * @param out the main OutputStream
- * @param branch the second OutputStream
- */
- public TeeOutputStream( OutputStream out, OutputStream branch ) {
- super(out);
- this.branch = branch;
- }
-
- /**
- * Write the bytes to both streams.
- * @param b the bytes to write
- * @throws IOException if an I/O error occurs
- */
- public synchronized void write(byte[] b) throws IOException {
- super.write(b);
- this.branch.write(b);
- }
-
- /**
- * Write the specified bytes to both streams.
- * @param b the bytes to write
- * @param off The start offset
- * @param len The number of bytes to write
- * @throws IOException if an I/O error occurs
- */
- public synchronized void write(byte[] b, int off, int len) throws IOException {
- super.write(b, off, len);
- this.branch.write(b, off, len);
- }
-
- /**
- * Write a byte to both streams.
- * @param b the byte to write
- * @throws IOException if an I/O error occurs
- */
- public synchronized void write(int b) throws IOException {
- super.write(b);
- this.branch.write(b);
- }
-
- /**
- * Flushes both streams.
- * @throws IOException if an I/O error occurs
- */
- public void flush() throws IOException {
- super.flush();
- this.branch.flush();
- }
-
- /**
- * Closes both streams.
- * @throws IOException if an I/O error occurs
- */
- public void close() throws IOException {
- super.close();
- this.branch.close();
- }
-
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/ThresholdingOutputStream.java b/emailcommon/src/org/apache/commons/io/output/ThresholdingOutputStream.java
deleted file mode 100644
index fa69a804c..000000000
--- a/emailcommon/src/org/apache/commons/io/output/ThresholdingOutputStream.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.io.output;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-
-/**
- * An output stream which triggers an event when a specified number of bytes of
- * data have been written to it. The event can be used, for example, to throw
- * an exception if a maximum has been reached, or to switch the underlying
- * stream type when the threshold is exceeded.
- * <p>
- * This class overrides all <code>OutputStream</code> methods. However, these
- * overrides ultimately call the corresponding methods in the underlying output
- * stream implementation.
- * <p>
- * NOTE: This implementation may trigger the event <em>before</em> the threshold
- * is actually reached, since it triggers when a pending write operation would
- * cause the threshold to be exceeded.
- *
- * @author <a href="mailto:martinc@apache.org">Martin Cooper</a>
- *
- * @version $Id: ThresholdingOutputStream.java 540714 2007-05-22 19:39:44Z niallp $
- */
-public abstract class ThresholdingOutputStream
- extends OutputStream
-{
-
- // ----------------------------------------------------------- Data members
-
-
- /**
- * The threshold at which the event will be triggered.
- */
- private int threshold;
-
-
- /**
- * The number of bytes written to the output stream.
- */
- private long written;
-
-
- /**
- * Whether or not the configured threshold has been exceeded.
- */
- private boolean thresholdExceeded;
-
-
- // ----------------------------------------------------------- Constructors
-
-
- /**
- * Constructs an instance of this class which will trigger an event at the
- * specified threshold.
- *
- * @param threshold The number of bytes at which to trigger an event.
- */
- public ThresholdingOutputStream(int threshold)
- {
- this.threshold = threshold;
- }
-
-
- // --------------------------------------------------- OutputStream methods
-
-
- /**
- * Writes the specified byte to this output stream.
- *
- * @param b The byte to be written.
- *
- * @exception IOException if an error occurs.
- */
- public void write(int b) throws IOException
- {
- checkThreshold(1);
- getStream().write(b);
- written++;
- }
-
-
- /**
- * Writes <code>b.length</code> bytes from the specified byte array to this
- * output stream.
- *
- * @param b The array of bytes to be written.
- *
- * @exception IOException if an error occurs.
- */
- public void write(byte b[]) throws IOException
- {
- checkThreshold(b.length);
- getStream().write(b);
- written += b.length;
- }
-
-
- /**
- * Writes <code>len</code> bytes from the specified byte array starting at
- * offset <code>off</code> to this output stream.
- *
- * @param b The byte array from which the data will be written.
- * @param off The start offset in the byte array.
- * @param len The number of bytes to write.
- *
- * @exception IOException if an error occurs.
- */
- public void write(byte b[], int off, int len) throws IOException
- {
- checkThreshold(len);
- getStream().write(b, off, len);
- written += len;
- }
-
-
- /**
- * Flushes this output stream and forces any buffered output bytes to be
- * written out.
- *
- * @exception IOException if an error occurs.
- */
- public void flush() throws IOException
- {
- getStream().flush();
- }
-
-
- /**
- * Closes this output stream and releases any system resources associated
- * with this stream.
- *
- * @exception IOException if an error occurs.
- */
- public void close() throws IOException
- {
- try
- {
- flush();
- }
- catch (IOException ignored)
- {
- // ignore
- }
- getStream().close();
- }
-
-
- // --------------------------------------------------------- Public methods
-
-
- /**
- * Returns the threshold, in bytes, at which an event will be triggered.
- *
- * @return The threshold point, in bytes.
- */
- public int getThreshold()
- {
- return threshold;
- }
-
-
- /**
- * Returns the number of bytes that have been written to this output stream.
- *
- * @return The number of bytes written.
- */
- public long getByteCount()
- {
- return written;
- }
-
-
- /**
- * Determines whether or not the configured threshold has been exceeded for
- * this output stream.
- *
- * @return <code>true</code> if the threshold has been reached;
- * <code>false</code> otherwise.
- */
- public boolean isThresholdExceeded()
- {
- return (written > threshold);
- }
-
-
- // ------------------------------------------------------ Protected methods
-
-
- /**
- * Checks to see if writing the specified number of bytes would cause the
- * configured threshold to be exceeded. If so, triggers an event to allow
- * a concrete implementation to take action on this.
- *
- * @param count The number of bytes about to be written to the underlying
- * output stream.
- *
- * @exception IOException if an error occurs.
- */
- protected void checkThreshold(int count) throws IOException
- {
- if (!thresholdExceeded && (written + count > threshold))
- {
- thresholdExceeded = true;
- thresholdReached();
- }
- }
-
- /**
- * Resets the byteCount to zero. You can call this from
- * {@link #thresholdReached()} if you want the event to be triggered again.
- */
- protected void resetByteCount()
- {
- this.thresholdExceeded = false;
- this.written = 0;
- }
-
- // ------------------------------------------------------- Abstract methods
-
-
- /**
- * Returns the underlying output stream, to which the corresponding
- * <code>OutputStream</code> methods in this class will ultimately delegate.
- *
- * @return The underlying output stream.
- *
- * @exception IOException if an error occurs.
- */
- protected abstract OutputStream getStream() throws IOException;
-
-
- /**
- * Indicates that the configured threshold has been reached, and that a
- * subclass should take whatever action necessary on this event. This may
- * include changing the underlying output stream.
- *
- * @exception IOException if an error occurs.
- */
- protected abstract void thresholdReached() throws IOException;
-}
diff --git a/emailcommon/src/org/apache/commons/io/output/package.html b/emailcommon/src/org/apache/commons/io/output/package.html
deleted file mode 100644
index db2cbce59..000000000
--- a/emailcommon/src/org/apache/commons/io/output/package.html
+++ /dev/null
@@ -1,25 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<!--
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-<html>
-<body>
-<p>
-This package provides implementations of output classes, such as
-<code>OutputStream</code> and <code>Writer</code>.
-</p>
-</body>
-</html>
diff --git a/emailcommon/src/org/apache/commons/io/overview.html b/emailcommon/src/org/apache/commons/io/overview.html
deleted file mode 100644
index 31311b5e9..000000000
--- a/emailcommon/src/org/apache/commons/io/overview.html
+++ /dev/null
@@ -1,32 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<!--
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-<html>
-<body bgcolor="white">
-<p>
-The commons-io component contains utility classes,
-filters, streams, readers and writers.
-</p>
-<p>
-These classes aim to add to the standard JDK IO classes.
-The utilities provide convenience wrappers around the JDK, simplifying
-various operations into pre-tested units of code.
-The filters and streams provide useful implementations that perhaps should
-be in the JDK itself.
-</p>
-</body>
-</html>
diff --git a/emailcommon/src/org/apache/commons/io/package.html b/emailcommon/src/org/apache/commons/io/package.html
deleted file mode 100644
index e5ba9b0aa..000000000
--- a/emailcommon/src/org/apache/commons/io/package.html
+++ /dev/null
@@ -1,47 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
-<!--
-Licensed to the Apache Software Foundation (ASF) under one or more
-contributor license agreements. See the NOTICE file distributed with
-this work for additional information regarding copyright ownership.
-The ASF licenses this file to You under the Apache License, Version 2.0
-(the "License"); you may not use this file except in compliance with
-the License. You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
--->
-<html>
-<body bgcolor="white">
-<p>
-This package defines utility classes for working with streams, readers,
-writers and files. The most commonly used classes are described here:
-</p>
-<p>
-<b>IOUtils</b> is the most frequently used class.
-It provides operations to read, write, copy and close streams.
-</p>
-<p>
-<b>FileUtils</b> provides operations based around the JDK File class.
-These include reading, writing, copying, comparing and deleting.
-</p>
-<p>
-<b>FilenameUtils</b> provides utilities based on filenames.
-This utility class manipulates filenames without using File objects.
-It aims to simplify the transition between Windows and Unix.
-Before using this class however, you should consider whether you should
-be using File objects.
-</p>
-<p>
-<b>FileSystemUtils</b> allows access to the filing system in ways the JDK
-does not support. At present this allows you to get the free space on a drive.
-</p>
-<p>
-<b>EndianUtils</b> swaps data between Big-Endian and Little-Endian formats.
-</p>
-</body>
-</html>
diff --git a/emailcommon/src/org/apache/james/mime4j/AbstractContentHandler.java b/emailcommon/src/org/apache/james/mime4j/AbstractContentHandler.java
deleted file mode 100644
index 06c9b90a0..000000000
--- a/emailcommon/src/org/apache/james/mime4j/AbstractContentHandler.java
+++ /dev/null
@@ -1,113 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Abstract <code>ContentHandler</code> with default implementations of all
- * the methods of the <code>ContentHandler</code> interface.
- *
- * The default is to todo nothing.
- *
- *
- * @version $Id: AbstractContentHandler.java,v 1.3 2004/10/02 12:41:10 ntherning Exp $
- */
-public abstract class AbstractContentHandler implements ContentHandler {
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endMultipart()
- */
- public void endMultipart() {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startMultipart(org.apache.james.mime4j.BodyDescriptor)
- */
- public void startMultipart(BodyDescriptor bd) {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#body(org.apache.james.mime4j.BodyDescriptor, java.io.InputStream)
- */
- public void body(BodyDescriptor bd, InputStream is) throws IOException {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endBodyPart()
- */
- public void endBodyPart() {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endHeader()
- */
- public void endHeader() {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endMessage()
- */
- public void endMessage() {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#epilogue(java.io.InputStream)
- */
- public void epilogue(InputStream is) throws IOException {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#field(java.lang.String)
- */
- public void field(String fieldData) {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#preamble(java.io.InputStream)
- */
- public void preamble(InputStream is) throws IOException {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startBodyPart()
- */
- public void startBodyPart() {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startHeader()
- */
- public void startHeader() {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startMessage()
- */
- public void startMessage() {
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#raw(java.io.InputStream)
- */
- public void raw(InputStream is) throws IOException {
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/BodyDescriptor.java b/emailcommon/src/org/apache/james/mime4j/BodyDescriptor.java
deleted file mode 100644
index 2fef0be04..000000000
--- a/emailcommon/src/org/apache/james/mime4j/BodyDescriptor.java
+++ /dev/null
@@ -1,392 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import java.util.HashMap;
-import java.util.Map;
-
-/**
- * Encapsulates the values of the MIME-specific header fields
- * (which starts with <code>Content-</code>).
- *
- *
- * @version $Id: BodyDescriptor.java,v 1.4 2005/02/11 10:08:37 ntherning Exp $
- */
-public class BodyDescriptor {
- private static Log log = LogFactory.getLog(BodyDescriptor.class);
-
- private String mimeType = "text/plain";
- private String boundary = null;
- private String charset = "us-ascii";
- private String transferEncoding = "7bit";
- private Map<String, String> parameters = new HashMap<String, String>();
- private boolean contentTypeSet = false;
- private boolean contentTransferEncSet = false;
-
- /**
- * Creates a new root <code>BodyDescriptor</code> instance.
- */
- public BodyDescriptor() {
- this(null);
- }
-
- /**
- * Creates a new <code>BodyDescriptor</code> instance.
- *
- * @param parent the descriptor of the parent or <code>null</code> if this
- * is the root descriptor.
- */
- public BodyDescriptor(BodyDescriptor parent) {
- if (parent != null && parent.isMimeType("multipart/digest")) {
- mimeType = "message/rfc822";
- } else {
- mimeType = "text/plain";
- }
- }
-
- /**
- * Should be called for each <code>Content-</code> header field of
- * a MIME message or part.
- *
- * @param name the field name.
- * @param value the field value.
- */
- public void addField(String name, String value) {
-
- name = name.trim().toLowerCase();
-
- if (name.equals("content-transfer-encoding") && !contentTransferEncSet) {
- contentTransferEncSet = true;
-
- value = value.trim().toLowerCase();
- if (value.length() > 0) {
- transferEncoding = value;
- }
-
- } else if (name.equals("content-type") && !contentTypeSet) {
- contentTypeSet = true;
-
- value = value.trim();
-
- /*
- * Unfold Content-Type value
- */
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < value.length(); i++) {
- char c = value.charAt(i);
- if (c == '\r' || c == '\n') {
- continue;
- }
- sb.append(c);
- }
-
- Map<String, String> params = getHeaderParams(sb.toString());
-
- String main = params.get("");
- if (main != null) {
- main = main.toLowerCase().trim();
- int index = main.indexOf('/');
- boolean valid = false;
- if (index != -1) {
- String type = main.substring(0, index).trim();
- String subtype = main.substring(index + 1).trim();
- if (type.length() > 0 && subtype.length() > 0) {
- main = type + "/" + subtype;
- valid = true;
- }
- }
-
- if (!valid) {
- main = null;
- }
- }
- String b = params.get("boundary");
-
- if (main != null
- && ((main.startsWith("multipart/") && b != null)
- || !main.startsWith("multipart/"))) {
-
- mimeType = main;
- }
-
- if (isMultipart()) {
- boundary = b;
- }
-
- String c = params.get("charset");
- if (c != null) {
- c = c.trim();
- if (c.length() > 0) {
- charset = c.toLowerCase();
- }
- }
-
- /*
- * Add all other parameters to parameters.
- */
- parameters.putAll(params);
- parameters.remove("");
- parameters.remove("boundary");
- parameters.remove("charset");
- }
- }
-
- private Map<String, String> getHeaderParams(String headerValue) {
- Map<String, String> result = new HashMap<String, String>();
-
- // split main value and parameters
- String main;
- String rest;
- if (headerValue.indexOf(";") == -1) {
- main = headerValue;
- rest = null;
- } else {
- main = headerValue.substring(0, headerValue.indexOf(";"));
- rest = headerValue.substring(main.length() + 1);
- }
-
- result.put("", main);
- if (rest != null) {
- char[] chars = rest.toCharArray();
- StringBuffer paramName = new StringBuffer();
- StringBuffer paramValue = new StringBuffer();
-
- final byte READY_FOR_NAME = 0;
- final byte IN_NAME = 1;
- final byte READY_FOR_VALUE = 2;
- final byte IN_VALUE = 3;
- final byte IN_QUOTED_VALUE = 4;
- final byte VALUE_DONE = 5;
- final byte ERROR = 99;
-
- byte state = READY_FOR_NAME;
- boolean escaped = false;
- for (int i = 0; i < chars.length; i++) {
- char c = chars[i];
-
- switch (state) {
- case ERROR:
- if (c == ';')
- state = READY_FOR_NAME;
- break;
-
- case READY_FOR_NAME:
- if (c == '=') {
- log.error("Expected header param name, got '='");
- state = ERROR;
- break;
- }
-
- paramName = new StringBuffer();
- paramValue = new StringBuffer();
-
- state = IN_NAME;
- // $FALL-THROUGH$
-
- case IN_NAME:
- if (c == '=') {
- if (paramName.length() == 0)
- state = ERROR;
- else
- state = READY_FOR_VALUE;
- break;
- }
-
- // not '='... just add to name
- paramName.append(c);
- break;
-
- case READY_FOR_VALUE:
- boolean fallThrough = false;
- switch (c) {
- case ' ':
- case '\t':
- break; // ignore spaces, especially before '"'
-
- case '"':
- state = IN_QUOTED_VALUE;
- break;
-
- default:
- state = IN_VALUE;
- fallThrough = true;
- break;
- }
- if (!fallThrough)
- break;
-
- // $FALL-THROUGH$
-
- case IN_VALUE:
- fallThrough = false;
- switch (c) {
- case ';':
- case ' ':
- case '\t':
- result.put(
- paramName.toString().trim().toLowerCase(),
- paramValue.toString().trim());
- state = VALUE_DONE;
- fallThrough = true;
- break;
- default:
- paramValue.append(c);
- break;
- }
- if (!fallThrough)
- break;
-
- // $FALL-THROUGH$
-
- case VALUE_DONE:
- switch (c) {
- case ';':
- state = READY_FOR_NAME;
- break;
-
- case ' ':
- case '\t':
- break;
-
- default:
- state = ERROR;
- break;
- }
- break;
-
- case IN_QUOTED_VALUE:
- switch (c) {
- case '"':
- if (!escaped) {
- // don't trim quoted strings; the spaces could be intentional.
- result.put(
- paramName.toString().trim().toLowerCase(),
- paramValue.toString());
- state = VALUE_DONE;
- } else {
- escaped = false;
- paramValue.append(c);
- }
- break;
-
- case '\\':
- if (escaped) {
- paramValue.append('\\');
- }
- escaped = !escaped;
- break;
-
- default:
- if (escaped) {
- paramValue.append('\\');
- }
- escaped = false;
- paramValue.append(c);
- break;
- }
- break;
-
- }
- }
-
- // done looping. check if anything is left over.
- if (state == IN_VALUE) {
- result.put(
- paramName.toString().trim().toLowerCase(),
- paramValue.toString().trim());
- }
- }
-
- return result;
- }
-
-
- public boolean isMimeType(String mimeType) {
- return this.mimeType.equals(mimeType.toLowerCase());
- }
-
- /**
- * Return true if the BodyDescriptor belongs to a message
- */
- public boolean isMessage() {
- return mimeType.equals("message/rfc822");
- }
-
- /**
- * Return true if the BodyDescripotro belongs to a multipart
- */
- public boolean isMultipart() {
- return mimeType.startsWith("multipart/");
- }
-
- /**
- * Return the MimeType
- */
- public String getMimeType() {
- return mimeType;
- }
-
- /**
- * Return the boundary
- */
- public String getBoundary() {
- return boundary;
- }
-
- /**
- * Return the charset
- */
- public String getCharset() {
- return charset;
- }
-
- /**
- * Return all parameters for the BodyDescriptor
- */
- public Map<String, String> getParameters() {
- return parameters;
- }
-
- /**
- * Return the TransferEncoding
- */
- public String getTransferEncoding() {
- return transferEncoding;
- }
-
- /**
- * Return true if it's base64 encoded
- */
- public boolean isBase64Encoded() {
- return "base64".equals(transferEncoding);
- }
-
- /**
- * Return true if it's quoted-printable
- */
- public boolean isQuotedPrintableEncoded() {
- return "quoted-printable".equals(transferEncoding);
- }
-
- @Override
- public String toString() {
- return mimeType;
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/CloseShieldInputStream.java b/emailcommon/src/org/apache/james/mime4j/CloseShieldInputStream.java
deleted file mode 100644
index 94995d110..000000000
--- a/emailcommon/src/org/apache/james/mime4j/CloseShieldInputStream.java
+++ /dev/null
@@ -1,129 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import java.io.InputStream;
-import java.io.IOException;
-
-/**
- * InputStream that shields its underlying input stream from
- * being closed.
- *
- *
- * @version $Id: CloseShieldInputStream.java,v 1.2 2004/10/02 12:41:10 ntherning Exp $
- */
-public class CloseShieldInputStream extends InputStream {
-
- /**
- * Underlying InputStream
- */
- private InputStream is;
-
- public CloseShieldInputStream(InputStream is) {
- this.is = is;
- }
-
- public InputStream getUnderlyingStream() {
- return is;
- }
-
- /**
- * @see java.io.InputStream#read()
- */
- public int read() throws IOException {
- checkIfClosed();
- return is.read();
- }
-
- /**
- * @see java.io.InputStream#available()
- */
- public int available() throws IOException {
- checkIfClosed();
- return is.available();
- }
-
-
- /**
- * Set the underlying InputStream to null
- */
- public void close() throws IOException {
- is = null;
- }
-
- /**
- * @see java.io.FilterInputStream#reset()
- */
- public synchronized void reset() throws IOException {
- checkIfClosed();
- is.reset();
- }
-
- /**
- * @see java.io.FilterInputStream#markSupported()
- */
- public boolean markSupported() {
- if (is == null)
- return false;
- return is.markSupported();
- }
-
- /**
- * @see java.io.FilterInputStream#mark(int)
- */
- public synchronized void mark(int readlimit) {
- if (is != null)
- is.mark(readlimit);
- }
-
- /**
- * @see java.io.FilterInputStream#skip(long)
- */
- public long skip(long n) throws IOException {
- checkIfClosed();
- return is.skip(n);
- }
-
- /**
- * @see java.io.FilterInputStream#read(byte[])
- */
- public int read(byte b[]) throws IOException {
- checkIfClosed();
- return is.read(b);
- }
-
- /**
- * @see java.io.FilterInputStream#read(byte[], int, int)
- */
- public int read(byte b[], int off, int len) throws IOException {
- checkIfClosed();
- return is.read(b, off, len);
- }
-
- /**
- * Check if the underlying InputStream is null. If so throw an Exception
- *
- * @throws IOException if the underlying InputStream is null
- */
- private void checkIfClosed() throws IOException {
- if (is == null)
- throw new IOException("Stream is closed");
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/ContentHandler.java b/emailcommon/src/org/apache/james/mime4j/ContentHandler.java
deleted file mode 100644
index 946c89401..000000000
--- a/emailcommon/src/org/apache/james/mime4j/ContentHandler.java
+++ /dev/null
@@ -1,177 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * <p>
- * Receives notifications of the content of a plain RFC822 or MIME message.
- * Implement this interface and register an instance of that implementation
- * with a <code>MimeStreamParser</code> instance using its
- * {@link org.apache.james.mime4j.MimeStreamParser#setContentHandler(ContentHandler)}
- * method. The parser uses the <code>ContentHandler</code> instance to report
- * basic message-related events like the start and end of the body of a
- * part in a multipart MIME entity.
- * </p>
- * <p>
- * Events will be generated in the order the corresponding elements occur in
- * the message stream parsed by the parser. E.g.:
- * <pre>
- * startMessage()
- * startHeader()
- * field(...)
- * field(...)
- * ...
- * endHeader()
- * startMultipart()
- * preamble(...)
- * startBodyPart()
- * startHeader()
- * field(...)
- * field(...)
- * ...
- * endHeader()
- * body()
- * endBodyPart()
- * startBodyPart()
- * startHeader()
- * field(...)
- * field(...)
- * ...
- * endHeader()
- * body()
- * endBodyPart()
- * epilogue(...)
- * endMultipart()
- * endMessage()
- * </pre>
- * The above shows an example of a MIME message consisting of a multipart
- * body containing two body parts.
- * </p>
- * <p>
- * See MIME RFCs 2045-2049 for more information on the structure of MIME
- * messages and RFC 822 and 2822 for the general structure of Internet mail
- * messages.
- * </p>
- *
- *
- * @version $Id: ContentHandler.java,v 1.3 2004/10/02 12:41:10 ntherning Exp $
- */
-public interface ContentHandler {
- /**
- * Called when a new message starts (a top level message or an embedded
- * rfc822 message).
- */
- void startMessage();
-
- /**
- * Called when a message ends.
- */
- void endMessage();
-
- /**
- * Called when a new body part starts inside a
- * <code>multipart/*</code> entity.
- */
- void startBodyPart();
-
- /**
- * Called when a body part ends.
- */
- void endBodyPart();
-
- /**
- * Called when a header (of a message or body part) is about to be parsed.
- */
- void startHeader();
-
- /**
- * Called for each field of a header.
- *
- * @param fieldData the raw contents of the field
- * (<code>Field-Name: field value</code>). The value will not be
- * unfolded.
- */
- void field(String fieldData);
-
- /**
- * Called when there are no more header fields in a message or body part.
- */
- void endHeader();
-
- /**
- * Called for the preamble (whatever comes before the first body part)
- * of a <code>multipart/*</code> entity.
- *
- * @param is used to get the contents of the preamble.
- * @throws IOException should be thrown on I/O errors.
- */
- void preamble(InputStream is) throws IOException;
-
- /**
- * Called for the epilogue (whatever comes after the final body part)
- * of a <code>multipart/*</code> entity.
- *
- * @param is used to get the contents of the epilogue.
- * @throws IOException should be thrown on I/O errors.
- */
- void epilogue(InputStream is) throws IOException;
-
- /**
- * Called when the body of a multipart entity is about to be parsed.
- *
- * @param bd encapsulates the values (either read from the
- * message stream or, if not present, determined implictly
- * as described in the
- * MIME rfc:s) of the <code>Content-Type</code> and
- * <code>Content-Transfer-Encoding</code> header fields.
- */
- void startMultipart(BodyDescriptor bd);
-
- /**
- * Called when the body of an entity has been parsed.
- */
- void endMultipart();
-
- /**
- * Called when the body of a discrete (non-multipart) entity is about to
- * be parsed.
- *
- * @param bd see {@link #startMultipart(BodyDescriptor)}
- * @param is the contents of the body. NOTE: this is the raw body contents
- * - it will not be decoded if encoded. The <code>bd</code>
- * parameter should be used to determine how the stream data
- * should be decoded.
- * @throws IOException should be thrown on I/O errors.
- */
- void body(BodyDescriptor bd, InputStream is) throws IOException;
-
- /**
- * Called when a new entity (message or body part) starts and the
- * parser is in <code>raw</code> mode.
- *
- * @param is the raw contents of the entity.
- * @throws IOException should be thrown on I/O errors.
- * @see MimeStreamParser#setRaw(boolean)
- */
- void raw(InputStream is) throws IOException;
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/EOLConvertingInputStream.java b/emailcommon/src/org/apache/james/mime4j/EOLConvertingInputStream.java
deleted file mode 100644
index 7d5009ca5..000000000
--- a/emailcommon/src/org/apache/james/mime4j/EOLConvertingInputStream.java
+++ /dev/null
@@ -1,108 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PushbackInputStream;
-
-/**
- * InputStream which converts <code>\r</code>
- * bytes not followed by <code>\n</code> and <code>\n</code> not
- * preceded by <code>\r</code> to <code>\r\n</code>.
- *
- *
- * @version $Id: EOLConvertingInputStream.java,v 1.4 2004/11/29 13:15:42 ntherning Exp $
- */
-public class EOLConvertingInputStream extends InputStream {
- /** Converts single '\r' to '\r\n' */
- public static final int CONVERT_CR = 1;
- /** Converts single '\n' to '\r\n' */
- public static final int CONVERT_LF = 2;
- /** Converts single '\r' and '\n' to '\r\n' */
- public static final int CONVERT_BOTH = 3;
-
- private PushbackInputStream in = null;
- private int previous = 0;
- private int flags = CONVERT_BOTH;
-
- /**
- * Creates a new <code>EOLConvertingInputStream</code>
- * instance converting bytes in the given <code>InputStream</code>.
- * The flag <code>CONVERT_BOTH</code> is the default.
- *
- * @param in the <code>InputStream</code> to read from.
- */
- public EOLConvertingInputStream(InputStream in) {
- this(in, CONVERT_BOTH);
- }
- /**
- * Creates a new <code>EOLConvertingInputStream</code>
- * instance converting bytes in the given <code>InputStream</code>.
- *
- * @param in the <code>InputStream</code> to read from.
- * @param flags one of <code>CONVERT_CR</code>, <code>CONVERT_LF</code> or
- * <code>CONVERT_BOTH</code>.
- */
- public EOLConvertingInputStream(InputStream in, int flags) {
- super();
-
- this.in = new PushbackInputStream(in, 2);
- this.flags = flags;
- }
-
- /**
- * Closes the underlying stream.
- *
- * @throws IOException on I/O errors.
- */
- public void close() throws IOException {
- in.close();
- }
-
- /**
- * @see java.io.InputStream#read()
- */
- public int read() throws IOException {
- int b = in.read();
-
- if (b == -1) {
- return -1;
- }
-
- if ((flags & CONVERT_CR) != 0 && b == '\r') {
- int c = in.read();
- if (c != -1) {
- in.unread(c);
- }
- if (c != '\n') {
- in.unread('\n');
- }
- } else if ((flags & CONVERT_LF) != 0 && b == '\n' && previous != '\r') {
- b = '\r';
- in.unread('\n');
- }
-
- previous = b;
-
- return b;
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/Log.java b/emailcommon/src/org/apache/james/mime4j/Log.java
deleted file mode 100644
index e7f33fcc7..000000000
--- a/emailcommon/src/org/apache/james/mime4j/Log.java
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.james.mime4j;
-
-import com.android.emailcommon.Logging;
-
-/**
- * Empty stub for the apache logging library.
- */
-public class Log {
- public Log(Class mClazz) {
- }
-
- public boolean isDebugEnabled() {
- return false;
- }
-
- public boolean isErrorEnabled() {
- return true;
- }
-
- public boolean isFatalEnabled() {
- return true;
- }
-
- public boolean isInfoEnabled() {
- return false;
- }
-
- public boolean isTraceEnabled() {
- return false;
- }
-
- public boolean isWarnEnabled() {
- return true;
- }
-
- public void trace(Object message) {
- if (!isTraceEnabled()) return;
- android.util.Log.v(Logging.LOG_TAG, toString(message, null));
- }
-
- public void trace(Object message, Throwable t) {
- if (!isTraceEnabled()) return;
- android.util.Log.v(Logging.LOG_TAG, toString(message, t));
- }
-
- public void debug(Object message) {
- if (!isDebugEnabled()) return;
- android.util.Log.d(Logging.LOG_TAG, toString(message, null));
- }
-
- public void debug(Object message, Throwable t) {
- if (!isDebugEnabled()) return;
- android.util.Log.d(Logging.LOG_TAG, toString(message, t));
- }
-
- public void info(Object message) {
- if (!isInfoEnabled()) return;
- android.util.Log.i(Logging.LOG_TAG, toString(message, null));
- }
-
- public void info(Object message, Throwable t) {
- if (!isInfoEnabled()) return;
- android.util.Log.i(Logging.LOG_TAG, toString(message, t));
- }
-
- public void warn(Object message) {
- android.util.Log.w(Logging.LOG_TAG, toString(message, null));
- }
-
- public void warn(Object message, Throwable t) {
- android.util.Log.w(Logging.LOG_TAG, toString(message, t));
- }
-
- public void error(Object message) {
- android.util.Log.e(Logging.LOG_TAG, toString(message, null));
- }
-
- public void error(Object message, Throwable t) {
- android.util.Log.e(Logging.LOG_TAG, toString(message, t));
- }
-
- public void fatal(Object message) {
- android.util.Log.e(Logging.LOG_TAG, toString(message, null));
- }
-
- public void fatal(Object message, Throwable t) {
- android.util.Log.e(Logging.LOG_TAG, toString(message, t));
- }
-
- private static String toString(Object o, Throwable t) {
- String m = (o == null) ? "(null)" : o.toString();
- if (t == null) {
- return m;
- } else {
- return m + " " + t.getMessage();
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/LogFactory.java b/emailcommon/src/org/apache/james/mime4j/LogFactory.java
deleted file mode 100644
index c8f00d1d3..000000000
--- a/emailcommon/src/org/apache/james/mime4j/LogFactory.java
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (C) 2009 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.james.mime4j;
-
-/**
- * Empty stub for the apache logging library.
- */
-public final class LogFactory {
- private LogFactory() {
- }
-
- public static Log getLog(Class clazz) {
- return new Log(clazz);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/MimeBoundaryInputStream.java b/emailcommon/src/org/apache/james/mime4j/MimeBoundaryInputStream.java
deleted file mode 100644
index 0fffb7820..000000000
--- a/emailcommon/src/org/apache/james/mime4j/MimeBoundaryInputStream.java
+++ /dev/null
@@ -1,184 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.PushbackInputStream;
-
-/**
- * Stream that constrains itself to a single MIME body part.
- * After the stream ends (i.e. read() returns -1) {@link #hasMoreParts()}
- * can be used to determine if a final boundary has been seen or not.
- * If {@link #parentEOF()} is <code>true</code> an unexpected end of stream
- * has been detected in the parent stream.
- *
- *
- *
- * @version $Id: MimeBoundaryInputStream.java,v 1.2 2004/11/29 13:15:42 ntherning Exp $
- */
-public class MimeBoundaryInputStream extends InputStream {
-
- private PushbackInputStream s = null;
- private byte[] boundary = null;
- private boolean first = true;
- private boolean eof = false;
- private boolean parenteof = false;
- private boolean moreParts = true;
-
- /**
- * Creates a new MimeBoundaryInputStream.
- * @param s The underlying stream.
- * @param boundary Boundary string (not including leading hyphens).
- */
- public MimeBoundaryInputStream(InputStream s, String boundary)
- throws IOException {
-
- this.s = new PushbackInputStream(s, boundary.length() + 4);
-
- boundary = "--" + boundary;
- this.boundary = new byte[boundary.length()];
- for (int i = 0; i < this.boundary.length; i++) {
- this.boundary[i] = (byte) boundary.charAt(i);
- }
-
- /*
- * By reading one byte we will update moreParts to be as expected
- * before any bytes have been read.
- */
- int b = read();
- if (b != -1) {
- this.s.unread(b);
- }
- }
-
- /**
- * Closes the underlying stream.
- *
- * @throws IOException on I/O errors.
- */
- public void close() throws IOException {
- s.close();
- }
-
- /**
- * Determines if the underlying stream has more parts (this stream has
- * not seen an end boundary).
- *
- * @return <code>true</code> if there are more parts in the underlying
- * stream, <code>false</code> otherwise.
- */
- public boolean hasMoreParts() {
- return moreParts;
- }
-
- /**
- * Determines if the parent stream has reached EOF
- *
- * @return <code>true</code> if EOF has been reached for the parent stream,
- * <code>false</code> otherwise.
- */
- public boolean parentEOF() {
- return parenteof;
- }
-
- /**
- * Consumes all unread bytes of this stream. After a call to this method
- * this stream will have reached EOF.
- *
- * @throws IOException on I/O errors.
- */
- public void consume() throws IOException {
- while (read() != -1) {
- }
- }
-
- /**
- * @see java.io.InputStream#read()
- */
- public int read() throws IOException {
- if (eof) {
- return -1;
- }
-
- if (first) {
- first = false;
- if (matchBoundary()) {
- return -1;
- }
- }
-
- int b1 = s.read();
- int b2 = s.read();
-
- if (b1 == '\r' && b2 == '\n') {
- if (matchBoundary()) {
- return -1;
- }
- }
-
- if (b2 != -1) {
- s.unread(b2);
- }
-
- parenteof = b1 == -1;
- eof = parenteof;
-
- return b1;
- }
-
- private boolean matchBoundary() throws IOException {
-
- for (int i = 0; i < boundary.length; i++) {
- int b = s.read();
- if (b != boundary[i]) {
- if (b != -1) {
- s.unread(b);
- }
- for (int j = i - 1; j >= 0; j--) {
- s.unread(boundary[j]);
- }
- return false;
- }
- }
-
- /*
- * We have a match. Is it an end boundary?
- */
- int prev = s.read();
- int curr = s.read();
- moreParts = !(prev == '-' && curr == '-');
- do {
- if (curr == '\n' && prev == '\r') {
- break;
- }
- prev = curr;
- } while ((curr = s.read()) != -1);
-
- if (curr == -1) {
- moreParts = false;
- parenteof = true;
- }
-
- eof = true;
-
- return true;
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/MimeStreamParser.java b/emailcommon/src/org/apache/james/mime4j/MimeStreamParser.java
deleted file mode 100644
index e5fe97cdd..000000000
--- a/emailcommon/src/org/apache/james/mime4j/MimeStreamParser.java
+++ /dev/null
@@ -1,325 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import com.android.emailcommon.utility.LoggingInputStream;
-
-import org.apache.james.mime4j.decoder.Base64InputStream;
-import org.apache.james.mime4j.decoder.QuotedPrintableInputStream;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.BitSet;
-import java.util.LinkedList;
-
-/**
- * <p>
- * Parses MIME (or RFC822) message streams of bytes or characters and reports
- * parsing events to a <code>ContentHandler</code> instance.
- * </p>
- * <p>
- * Typical usage:<br/>
- * <pre>
- * ContentHandler handler = new MyHandler();
- * MimeStreamParser parser = new MimeStreamParser();
- * parser.setContentHandler(handler);
- * parser.parse(new BufferedInputStream(new FileInputStream("mime.msg")));
- * </pre>
- * <strong>NOTE:</strong> All lines must end with CRLF
- * (<code>\r\n</code>). If you are unsure of the line endings in your stream
- * you should wrap it in a {@link org.apache.james.mime4j.EOLConvertingInputStream} instance.
- *
- *
- * @version $Id: MimeStreamParser.java,v 1.8 2005/02/11 10:12:02 ntherning Exp $
- */
-public class MimeStreamParser {
- private static final Log log = LogFactory.getLog(MimeStreamParser.class);
-
- private static final boolean DEBUG_LOG_MESSAGE = false; //DO NOT RELEASE AS 'TRUE'
-
- private static BitSet fieldChars = null;
-
- private RootInputStream rootStream = null;
- private LinkedList<BodyDescriptor> bodyDescriptors = new LinkedList<BodyDescriptor>();
- private ContentHandler handler = null;
- private boolean raw = false;
-
- static {
- fieldChars = new BitSet();
- for (int i = 0x21; i <= 0x39; i++) {
- fieldChars.set(i);
- }
- for (int i = 0x3b; i <= 0x7e; i++) {
- fieldChars.set(i);
- }
- }
-
- /**
- * Creates a new <code>MimeStreamParser</code> instance.
- */
- public MimeStreamParser() {
- }
-
- /**
- * Parses a stream of bytes containing a MIME message.
- *
- * @param is the stream to parse.
- * @throws IOException on I/O errors.
- */
- public void parse(InputStream is) throws IOException {
- if (DEBUG_LOG_MESSAGE) {
- is = new LoggingInputStream(is, "MIME", true);
- }
- rootStream = new RootInputStream(is);
- parseMessage(rootStream);
- }
-
- /**
- * Determines if this parser is currently in raw mode.
- *
- * @return <code>true</code> if in raw mode, <code>false</code>
- * otherwise.
- * @see #setRaw(boolean)
- */
- public boolean isRaw() {
- return raw;
- }
-
- /**
- * Enables or disables raw mode. In raw mode all future entities
- * (messages or body parts) in the stream will be reported to the
- * {@link ContentHandler#raw(InputStream)} handler method only.
- * The stream will contain the entire unparsed entity contents
- * including header fields and whatever is in the body.
- *
- * @param raw <code>true</code> enables raw mode, <code>false</code>
- * disables it.
- */
- public void setRaw(boolean raw) {
- this.raw = raw;
- }
-
- /**
- * Finishes the parsing and stops reading lines.
- * NOTE: No more lines will be parsed but the parser
- * will still call
- * {@link ContentHandler#endMultipart()},
- * {@link ContentHandler#endBodyPart()},
- * {@link ContentHandler#endMessage()}, etc to match previous calls
- * to
- * {@link ContentHandler#startMultipart(BodyDescriptor)},
- * {@link ContentHandler#startBodyPart()},
- * {@link ContentHandler#startMessage()}, etc.
- */
- public void stop() {
- rootStream.truncate();
- }
-
- /**
- * Parses an entity which consists of a header followed by a body containing
- * arbitrary data, body parts or an embedded message.
- *
- * @param is the stream to parse.
- * @throws IOException on I/O errors.
- */
- private void parseEntity(InputStream is) throws IOException {
- BodyDescriptor bd = parseHeader(is);
-
- if (bd.isMultipart()) {
- bodyDescriptors.addFirst(bd);
-
- handler.startMultipart(bd);
-
- MimeBoundaryInputStream tempIs =
- new MimeBoundaryInputStream(is, bd.getBoundary());
- handler.preamble(new CloseShieldInputStream(tempIs));
- tempIs.consume();
-
- while (tempIs.hasMoreParts()) {
- tempIs = new MimeBoundaryInputStream(is, bd.getBoundary());
- parseBodyPart(tempIs);
- tempIs.consume();
- if (tempIs.parentEOF()) {
- if (log.isWarnEnabled()) {
- log.warn("Line " + rootStream.getLineNumber()
- + ": Body part ended prematurely. "
- + "Higher level boundary detected or "
- + "EOF reached.");
- }
- break;
- }
- }
-
- handler.epilogue(new CloseShieldInputStream(is));
-
- handler.endMultipart();
-
- bodyDescriptors.removeFirst();
-
- } else if (bd.isMessage()) {
- if (bd.isBase64Encoded()) {
- log.warn("base64 encoded message/rfc822 detected");
- is = new EOLConvertingInputStream(
- new Base64InputStream(is));
- } else if (bd.isQuotedPrintableEncoded()) {
- log.warn("quoted-printable encoded message/rfc822 detected");
- is = new EOLConvertingInputStream(
- new QuotedPrintableInputStream(is));
- }
- bodyDescriptors.addFirst(bd);
- parseMessage(is);
- bodyDescriptors.removeFirst();
- } else {
- handler.body(bd, new CloseShieldInputStream(is));
- }
-
- /*
- * Make sure the stream has been consumed.
- */
- while (is.read() != -1) {
- }
- }
-
- private void parseMessage(InputStream is) throws IOException {
- if (raw) {
- handler.raw(new CloseShieldInputStream(is));
- } else {
- handler.startMessage();
- parseEntity(is);
- handler.endMessage();
- }
- }
-
- private void parseBodyPart(InputStream is) throws IOException {
- if (raw) {
- handler.raw(new CloseShieldInputStream(is));
- } else {
- handler.startBodyPart();
- parseEntity(is);
- handler.endBodyPart();
- }
- }
-
- /**
- * Parses a header.
- *
- * @param is the stream to parse.
- * @return a <code>BodyDescriptor</code> describing the body following
- * the header.
- */
- private BodyDescriptor parseHeader(InputStream is) throws IOException {
- BodyDescriptor bd = new BodyDescriptor(bodyDescriptors.isEmpty()
- ? null : (BodyDescriptor) bodyDescriptors.getFirst());
-
- handler.startHeader();
-
- int lineNumber = rootStream.getLineNumber();
-
- StringBuffer sb = new StringBuffer();
- int curr = 0;
- int prev = 0;
- while ((curr = is.read()) != -1) {
- if (curr == '\n' && (prev == '\n' || prev == 0)) {
- /*
- * [\r]\n[\r]\n or an immediate \r\n have been seen.
- */
- sb.deleteCharAt(sb.length() - 1);
- break;
- }
- sb.append((char) curr);
- prev = curr == '\r' ? prev : curr;
- }
-
- if (curr == -1 && log.isWarnEnabled()) {
- log.warn("Line " + rootStream.getLineNumber()
- + ": Unexpected end of headers detected. "
- + "Boundary detected in header or EOF reached.");
- }
-
- int start = 0;
- int pos = 0;
- int startLineNumber = lineNumber;
- while (pos < sb.length()) {
- while (pos < sb.length() && sb.charAt(pos) != '\r') {
- pos++;
- }
- if (pos < sb.length() - 1 && sb.charAt(pos + 1) != '\n') {
- pos++;
- continue;
- }
-
- if (pos >= sb.length() - 2 || fieldChars.get(sb.charAt(pos + 2))) {
-
- /*
- * field should be the complete field data excluding the
- * trailing \r\n.
- */
- String field = sb.substring(start, pos);
- start = pos + 2;
-
- /*
- * Check for a valid field.
- */
- int index = field.indexOf(':');
- boolean valid = false;
- if (index != -1 && fieldChars.get(field.charAt(0))) {
- valid = true;
- String fieldName = field.substring(0, index).trim();
- for (int i = 0; i < fieldName.length(); i++) {
- if (!fieldChars.get(fieldName.charAt(i))) {
- valid = false;
- break;
- }
- }
-
- if (valid) {
- handler.field(field);
- bd.addField(fieldName, field.substring(index + 1));
- }
- }
-
- if (!valid && log.isWarnEnabled()) {
- log.warn("Line " + startLineNumber
- + ": Ignoring invalid field: '" + field.trim() + "'");
- }
-
- startLineNumber = lineNumber;
- }
-
- pos += 2;
- lineNumber++;
- }
-
- handler.endHeader();
-
- return bd;
- }
-
- /**
- * Sets the <code>ContentHandler</code> to use when reporting
- * parsing events.
- *
- * @param h the <code>ContentHandler</code>.
- */
- public void setContentHandler(ContentHandler h) {
- this.handler = h;
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/RootInputStream.java b/emailcommon/src/org/apache/james/mime4j/RootInputStream.java
deleted file mode 100644
index fa848df18..000000000
--- a/emailcommon/src/org/apache/james/mime4j/RootInputStream.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * <code>InputStream</code> used by the parser to wrap the original user
- * supplied stream. This stream keeps track of the current line number and
- * can also be truncated. When truncated the stream will appear to have
- * reached end of file. This is used by the parser's
- * {@link org.apache.james.mime4j.MimeStreamParser#stop()} method.
- *
- *
- * @version $Id: RootInputStream.java,v 1.2 2004/10/02 12:41:10 ntherning Exp $
- */
-class RootInputStream extends InputStream {
- private InputStream is = null;
- private int lineNumber = 1;
- private int prev = -1;
- private boolean truncated = false;
-
- /**
- * Creates a new <code>RootInputStream</code>.
- *
- * @param in the stream to read from.
- */
- public RootInputStream(InputStream is) {
- this.is = is;
- }
-
- /**
- * Gets the current line number starting at 1
- * (the number of <code>\r\n</code> read so far plus 1).
- *
- * @return the current line number.
- */
- public int getLineNumber() {
- return lineNumber;
- }
-
- /**
- * Truncates this <code>InputStream</code>. After this call any
- * call to {@link #read()}, {@link #read(byte[]) or
- * {@link #read(byte[], int, int)} will return
- * -1 as if end-of-file had been reached.
- */
- public void truncate() {
- this.truncated = true;
- }
-
- /**
- * @see java.io.InputStream#read()
- */
- public int read() throws IOException {
- if (truncated) {
- return -1;
- }
-
- int b = is.read();
- if (prev == '\r' && b == '\n') {
- lineNumber++;
- }
- prev = b;
- return b;
- }
-
- /**
- *
- * @see java.io.InputStream#read(byte[], int, int)
- */
- public int read(byte[] b, int off, int len) throws IOException {
- if (truncated) {
- return -1;
- }
-
- int n = is.read(b, off, len);
- for (int i = off; i < off + n; i++) {
- if (prev == '\r' && b[i] == '\n') {
- lineNumber++;
- }
- prev = b[i];
- }
- return n;
- }
-
- /**
- * @see java.io.InputStream#read(byte[])
- */
- public int read(byte[] b) throws IOException {
- return read(b, 0, b.length);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/SimpleContentHandler.java b/emailcommon/src/org/apache/james/mime4j/SimpleContentHandler.java
deleted file mode 100644
index 13f1fd2c6..000000000
--- a/emailcommon/src/org/apache/james/mime4j/SimpleContentHandler.java
+++ /dev/null
@@ -1,100 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j;
-
-import org.apache.james.mime4j.decoder.Base64InputStream;
-import org.apache.james.mime4j.decoder.QuotedPrintableInputStream;
-import org.apache.james.mime4j.field.Field;
-import org.apache.james.mime4j.message.Header;
-
-import java.io.InputStream;
-import java.io.IOException;
-
-/**
- * Abstract implementation of ContentHandler that automates common
- * tasks. Currently performs header parsing and applies content-transfer
- * decoding to body parts.
- *
- *
- */
-public abstract class SimpleContentHandler extends AbstractContentHandler {
-
- /**
- * Called after headers are parsed.
- */
- public abstract void headers(Header header);
-
- /**
- * Called when the body of a discrete (non-multipart) entity is encountered.
-
- * @param bd encapsulates the values (either read from the
- * message stream or, if not present, determined implictly
- * as described in the
- * MIME rfc:s) of the <code>Content-Type</code> and
- * <code>Content-Transfer-Encoding</code> header fields.
- * @param is the contents of the body. Base64 or quoted-printable
- * decoding will be applied transparently.
- * @throws IOException should be thrown on I/O errors.
- */
- public abstract void bodyDecoded(BodyDescriptor bd, InputStream is) throws IOException;
-
-
- /* Implement introduced callbacks. */
-
- private Header currHeader;
-
- /**
- * @see org.apache.james.mime4j.AbstractContentHandler#startHeader()
- */
- public final void startHeader() {
- currHeader = new Header();
- }
-
- /**
- * @see org.apache.james.mime4j.AbstractContentHandler#field(java.lang.String)
- */
- public final void field(String fieldData) {
- currHeader.addField(Field.parse(fieldData));
- }
-
- /**
- * @see org.apache.james.mime4j.AbstractContentHandler#endHeader()
- */
- public final void endHeader() {
- Header tmp = currHeader;
- currHeader = null;
- headers(tmp);
- }
-
- /**
- * @see org.apache.james.mime4j.AbstractContentHandler#body(org.apache.james.mime4j.BodyDescriptor, java.io.InputStream)
- */
- public final void body(BodyDescriptor bd, InputStream is) throws IOException {
- if (bd.isBase64Encoded()) {
- bodyDecoded(bd, new Base64InputStream(is));
- }
- else if (bd.isQuotedPrintableEncoded()) {
- bodyDecoded(bd, new QuotedPrintableInputStream(is));
- }
- else {
- bodyDecoded(bd, is);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/ThirdPartyProject.prop b/emailcommon/src/org/apache/james/mime4j/ThirdPartyProject.prop
deleted file mode 100644
index 525791c21..000000000
--- a/emailcommon/src/org/apache/james/mime4j/ThirdPartyProject.prop
+++ /dev/null
@@ -1,10 +0,0 @@
-# Copyright 2010 Google Inc. All Rights Reserved.
-#Fri Jul 16 10:03:08 PDT 2010
-currentVersion=0.6
-version=Unknown / modified locally
-isNative=false
-feedurl=https\://issues.apache.org/jira/secure/ReleaseNote.jspa
-name=apache_mime4j
-keywords=apache mime4j
-onDevice=true
-homepage=http\://james.apache.org/index.html
diff --git a/emailcommon/src/org/apache/james/mime4j/codec/EncoderUtil.java b/emailcommon/src/org/apache/james/mime4j/codec/EncoderUtil.java
deleted file mode 100644
index 6841bc998..000000000
--- a/emailcommon/src/org/apache/james/mime4j/codec/EncoderUtil.java
+++ /dev/null
@@ -1,630 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.codec;
-
-import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
-import java.util.BitSet;
-import java.util.Locale;
-
-import org.apache.james.mime4j.util.CharsetUtil;
-
-/**
- * ANDROID: THIS CLASS IS COPIED FROM A NEWER VERSION OF MIME4J
- */
-
-/**
- * Static methods for encoding header field values. This includes encoded-words
- * as defined in <a href='http://www.faqs.org/rfcs/rfc2047.html'>RFC 2047</a>
- * or display-names of an e-mail address, for example.
- *
- */
-public class EncoderUtil {
-
- // This array is a lookup table that translates 6-bit positive integer index
- // values into their "Base64 Alphabet" equivalents as specified in Table 1
- // of RFC 2045.
- // ANDROID: THIS TABLE IS COPIED FROM BASE64OUTPUTSTREAM
- static final byte[] BASE64_TABLE = { 'A', 'B', 'C', 'D', 'E', 'F',
- 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
- 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
- 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
- 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
- '6', '7', '8', '9', '+', '/' };
-
- // Byte used to pad output.
- private static final byte BASE64_PAD = '=';
-
- private static final BitSet Q_REGULAR_CHARS = initChars("=_?");
-
- private static final BitSet Q_RESTRICTED_CHARS = initChars("=_?\"#$%&'(),.:;<>@[\\]^`{|}~");
-
- private static final int MAX_USED_CHARACTERS = 50;
-
- private static final String ENC_WORD_PREFIX = "=?";
- private static final String ENC_WORD_SUFFIX = "?=";
-
- private static final int ENCODED_WORD_MAX_LENGTH = 75; // RFC 2047
-
- private static final BitSet TOKEN_CHARS = initChars("()<>@,;:\\\"/[]?=");
-
- private static final BitSet ATEXT_CHARS = initChars("()<>@.,;:\\\"[]");
-
- private static BitSet initChars(String specials) {
- BitSet bs = new BitSet(128);
- for (char ch = 33; ch < 127; ch++) {
- if (specials.indexOf(ch) == -1) {
- bs.set(ch);
- }
- }
- return bs;
- }
-
- /**
- * Selects one of the two encodings specified in RFC 2047.
- */
- public enum Encoding {
- /** The B encoding (identical to base64 defined in RFC 2045). */
- B,
- /** The Q encoding (similar to quoted-printable defined in RFC 2045). */
- Q
- }
-
- /**
- * Indicates the intended usage of an encoded word.
- */
- public enum Usage {
- /**
- * Encoded word is used to replace a 'text' token in any Subject or
- * Comments header field.
- */
- TEXT_TOKEN,
- /**
- * Encoded word is used to replace a 'word' entity within a 'phrase',
- * for example, one that precedes an address in a From, To, or Cc
- * header.
- */
- WORD_ENTITY
- }
-
- private EncoderUtil() {
- }
-
- /**
- * Encodes the display-name portion of an address. See <a
- * href='http://www.faqs.org/rfcs/rfc5322.html'>RFC 5322</a> section 3.4
- * and <a href='http://www.faqs.org/rfcs/rfc2047.html'>RFC 2047</a> section
- * 5.3. The specified string should not be folded.
- *
- * @param displayName
- * display-name to encode.
- * @return encoded display-name.
- */
- public static String encodeAddressDisplayName(String displayName) {
- // display-name = phrase
- // phrase = 1*( encoded-word / word )
- // word = atom / quoted-string
- // atom = [CFWS] 1*atext [CFWS]
- // CFWS = comment or folding white space
-
- if (isAtomPhrase(displayName)) {
- return displayName;
- } else if (hasToBeEncoded(displayName, 0)) {
- return encodeEncodedWord(displayName, Usage.WORD_ENTITY);
- } else {
- return quote(displayName);
- }
- }
-
- /**
- * Encodes the local part of an address specification as described in RFC
- * 5322 section 3.4.1. Leading and trailing CFWS should have been removed
- * before calling this method. The specified string should not contain any
- * illegal (control or non-ASCII) characters.
- *
- * @param localPart
- * the local part to encode
- * @return the encoded local part.
- */
- public static String encodeAddressLocalPart(String localPart) {
- // local-part = dot-atom / quoted-string
- // dot-atom = [CFWS] dot-atom-text [CFWS]
- // CFWS = comment or folding white space
-
- if (isDotAtomText(localPart)) {
- return localPart;
- } else {
- return quote(localPart);
- }
- }
-
- /**
- * Encodes the specified strings into a header parameter as described in RFC
- * 2045 section 5.1 and RFC 2183 section 2. The specified strings should not
- * contain any illegal (control or non-ASCII) characters.
- *
- * @param name
- * parameter name.
- * @param value
- * parameter value.
- * @return encoded result.
- */
- public static String encodeHeaderParameter(String name, String value) {
- name = name.toLowerCase(Locale.US);
-
- // value := token / quoted-string
- if (isToken(value)) {
- return name + "=" + value;
- } else {
- return name + "=" + quote(value);
- }
- }
-
- /**
- * Shortcut method that encodes the specified text into an encoded-word if
- * the text has to be encoded.
- *
- * @param text
- * text to encode.
- * @param usage
- * whether the encoded-word is to be used to replace a text token
- * or a word entity (see RFC 822).
- * @param usedCharacters
- * number of characters already used up (<code>0 <= usedCharacters <= 50</code>).
- * @return the specified text if encoding is not necessary or an encoded
- * word or a sequence of encoded words otherwise.
- */
- public static String encodeIfNecessary(String text, Usage usage,
- int usedCharacters) {
- if (hasToBeEncoded(text, usedCharacters))
- return encodeEncodedWord(text, usage, usedCharacters);
- else
- return text;
- }
-
- /**
- * Determines if the specified string has to encoded into an encoded-word.
- * Returns <code>true</code> if the text contains characters that don't
- * fall into the printable ASCII character set or if the text contains a
- * 'word' (sequence of non-whitespace characters) longer than 77 characters
- * (including characters already used up in the line).
- *
- * @param text
- * text to analyze.
- * @param usedCharacters
- * number of characters already used up (<code>0 <= usedCharacters <= 50</code>).
- * @return <code>true</code> if the specified text has to be encoded into
- * an encoded-word, <code>false</code> otherwise.
- */
- public static boolean hasToBeEncoded(String text, int usedCharacters) {
- if (text == null)
- throw new IllegalArgumentException();
- if (usedCharacters < 0 || usedCharacters > MAX_USED_CHARACTERS)
- throw new IllegalArgumentException();
-
- int nonWhiteSpaceCount = usedCharacters;
-
- for (int idx = 0; idx < text.length(); idx++) {
- char ch = text.charAt(idx);
- if (ch == '\t' || ch == ' ') {
- nonWhiteSpaceCount = 0;
- } else {
- nonWhiteSpaceCount++;
- if (nonWhiteSpaceCount > 77) {
- // Line cannot be folded into multiple lines with no more
- // than 78 characters each. Encoding as encoded-words makes
- // that possible. One character has to be reserved for
- // folding white space; that leaves 77 characters.
- return true;
- }
-
- if (ch < 32 || ch >= 127) {
- // non-printable ascii character has to be encoded
- return true;
- }
- }
- }
-
- return false;
- }
-
- /**
- * Encodes the specified text into an encoded word or a sequence of encoded
- * words separated by space. The text is separated into a sequence of
- * encoded words if it does not fit in a single one.
- * <p>
- * The charset to encode the specified text into a byte array and the
- * encoding to use for the encoded-word are detected automatically.
- * <p>
- * This method assumes that zero characters have already been used up in the
- * current line.
- *
- * @param text
- * text to encode.
- * @param usage
- * whether the encoded-word is to be used to replace a text token
- * or a word entity (see RFC 822).
- * @return the encoded word (or sequence of encoded words if the given text
- * does not fit in a single encoded word).
- * @see #hasToBeEncoded(String, int)
- */
- public static String encodeEncodedWord(String text, Usage usage) {
- return encodeEncodedWord(text, usage, 0, null, null);
- }
-
- /**
- * Encodes the specified text into an encoded word or a sequence of encoded
- * words separated by space. The text is separated into a sequence of
- * encoded words if it does not fit in a single one.
- * <p>
- * The charset to encode the specified text into a byte array and the
- * encoding to use for the encoded-word are detected automatically.
- *
- * @param text
- * text to encode.
- * @param usage
- * whether the encoded-word is to be used to replace a text token
- * or a word entity (see RFC 822).
- * @param usedCharacters
- * number of characters already used up (<code>0 <= usedCharacters <= 50</code>).
- * @return the encoded word (or sequence of encoded words if the given text
- * does not fit in a single encoded word).
- * @see #hasToBeEncoded(String, int)
- */
- public static String encodeEncodedWord(String text, Usage usage,
- int usedCharacters) {
- return encodeEncodedWord(text, usage, usedCharacters, null, null);
- }
-
- /**
- * Encodes the specified text into an encoded word or a sequence of encoded
- * words separated by space. The text is separated into a sequence of
- * encoded words if it does not fit in a single one.
- *
- * @param text
- * text to encode.
- * @param usage
- * whether the encoded-word is to be used to replace a text token
- * or a word entity (see RFC 822).
- * @param usedCharacters
- * number of characters already used up (<code>0 <= usedCharacters <= 50</code>).
- * @param charset
- * the Java charset that should be used to encode the specified
- * string into a byte array. A suitable charset is detected
- * automatically if this parameter is <code>null</code>.
- * @param encoding
- * the encoding to use for the encoded-word (either B or Q). A
- * suitable encoding is automatically chosen if this parameter is
- * <code>null</code>.
- * @return the encoded word (or sequence of encoded words if the given text
- * does not fit in a single encoded word).
- * @see #hasToBeEncoded(String, int)
- */
- public static String encodeEncodedWord(String text, Usage usage,
- int usedCharacters, Charset charset, Encoding encoding) {
- if (text == null)
- throw new IllegalArgumentException();
- if (usedCharacters < 0 || usedCharacters > MAX_USED_CHARACTERS)
- throw new IllegalArgumentException();
-
- if (charset == null)
- charset = determineCharset(text);
-
- String mimeCharset = CharsetUtil.toMimeCharset(charset.name());
- if (mimeCharset == null) {
- // cannot happen if charset was originally null
- throw new IllegalArgumentException("Unsupported charset");
- }
-
- byte[] bytes = encode(text, charset);
-
- if (encoding == null)
- encoding = determineEncoding(bytes, usage);
-
- if (encoding == Encoding.B) {
- String prefix = ENC_WORD_PREFIX + mimeCharset + "?B?";
- return encodeB(prefix, text, usedCharacters, charset, bytes);
- } else {
- String prefix = ENC_WORD_PREFIX + mimeCharset + "?Q?";
- return encodeQ(prefix, text, usage, usedCharacters, charset, bytes);
- }
- }
-
- /**
- * Encodes the specified byte array using the B encoding defined in RFC
- * 2047.
- *
- * @param bytes
- * byte array to encode.
- * @return encoded string.
- */
- public static String encodeB(byte[] bytes) {
- StringBuilder sb = new StringBuilder();
-
- int idx = 0;
- final int end = bytes.length;
- for (; idx < end - 2; idx += 3) {
- int data = (bytes[idx] & 0xff) << 16 | (bytes[idx + 1] & 0xff) << 8
- | bytes[idx + 2] & 0xff;
- sb.append((char) BASE64_TABLE[data >> 18 & 0x3f]);
- sb.append((char) BASE64_TABLE[data >> 12 & 0x3f]);
- sb.append((char) BASE64_TABLE[data >> 6 & 0x3f]);
- sb.append((char) BASE64_TABLE[data & 0x3f]);
- }
-
- if (idx == end - 2) {
- int data = (bytes[idx] & 0xff) << 16 | (bytes[idx + 1] & 0xff) << 8;
- sb.append((char) BASE64_TABLE[data >> 18 & 0x3f]);
- sb.append((char) BASE64_TABLE[data >> 12 & 0x3f]);
- sb.append((char) BASE64_TABLE[data >> 6 & 0x3f]);
- sb.append((char) BASE64_PAD);
-
- } else if (idx == end - 1) {
- int data = (bytes[idx] & 0xff) << 16;
- sb.append((char) BASE64_TABLE[data >> 18 & 0x3f]);
- sb.append((char) BASE64_TABLE[data >> 12 & 0x3f]);
- sb.append((char) BASE64_PAD);
- sb.append((char) BASE64_PAD);
- }
-
- return sb.toString();
- }
-
- /**
- * Encodes the specified byte array using the Q encoding defined in RFC
- * 2047.
- *
- * @param bytes
- * byte array to encode.
- * @param usage
- * whether the encoded-word is to be used to replace a text token
- * or a word entity (see RFC 822).
- * @return encoded string.
- */
- public static String encodeQ(byte[] bytes, Usage usage) {
- BitSet qChars = usage == Usage.TEXT_TOKEN ? Q_REGULAR_CHARS
- : Q_RESTRICTED_CHARS;
-
- StringBuilder sb = new StringBuilder();
-
- final int end = bytes.length;
- for (int idx = 0; idx < end; idx++) {
- int v = bytes[idx] & 0xff;
- if (v == 32) {
- sb.append('_');
- } else if (!qChars.get(v)) {
- sb.append('=');
- sb.append(hexDigit(v >>> 4));
- sb.append(hexDigit(v & 0xf));
- } else {
- sb.append((char) v);
- }
- }
-
- return sb.toString();
- }
-
- /**
- * Tests whether the specified string is a token as defined in RFC 2045
- * section 5.1.
- *
- * @param str
- * string to test.
- * @return <code>true</code> if the specified string is a RFC 2045 token,
- * <code>false</code> otherwise.
- */
- public static boolean isToken(String str) {
- // token := 1*<any (US-ASCII) CHAR except SPACE, CTLs, or tspecials>
- // tspecials := "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "\" /
- // <"> / "/" / "[" / "]" / "?" / "="
- // CTL := 0.- 31., 127.
-
- final int length = str.length();
- if (length == 0)
- return false;
-
- for (int idx = 0; idx < length; idx++) {
- char ch = str.charAt(idx);
- if (!TOKEN_CHARS.get(ch))
- return false;
- }
-
- return true;
- }
-
- private static boolean isAtomPhrase(String str) {
- // atom = [CFWS] 1*atext [CFWS]
-
- boolean containsAText = false;
-
- final int length = str.length();
- for (int idx = 0; idx < length; idx++) {
- char ch = str.charAt(idx);
- if (ATEXT_CHARS.get(ch)) {
- containsAText = true;
- } else if (!CharsetUtil.isWhitespace(ch)) {
- return false;
- }
- }
-
- return containsAText;
- }
-
- // RFC 5322 section 3.2.3
- private static boolean isDotAtomText(String str) {
- // dot-atom-text = 1*atext *("." 1*atext)
- // atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" /
- // "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~"
-
- char prev = '.';
-
- final int length = str.length();
- if (length == 0)
- return false;
-
- for (int idx = 0; idx < length; idx++) {
- char ch = str.charAt(idx);
-
- if (ch == '.') {
- if (prev == '.' || idx == length - 1)
- return false;
- } else {
- if (!ATEXT_CHARS.get(ch))
- return false;
- }
-
- prev = ch;
- }
-
- return true;
- }
-
- // RFC 5322 section 3.2.4
- private static String quote(String str) {
- // quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS]
- // qcontent = qtext / quoted-pair
- // qtext = %d33 / %d35-91 / %d93-126
- // quoted-pair = ("\" (VCHAR / WSP))
- // VCHAR = %x21-7E
- // DQUOTE = %x22
-
- String escaped = str.replaceAll("[\\\\\"]", "\\\\$0");
- return "\"" + escaped + "\"";
- }
-
- private static String encodeB(String prefix, String text,
- int usedCharacters, Charset charset, byte[] bytes) {
- int encodedLength = bEncodedLength(bytes);
-
- int totalLength = prefix.length() + encodedLength
- + ENC_WORD_SUFFIX.length();
- if (totalLength <= ENCODED_WORD_MAX_LENGTH - usedCharacters) {
- return prefix + encodeB(bytes) + ENC_WORD_SUFFIX;
- } else {
- int splitOffset = text.offsetByCodePoints(text.length() / 2, -1);
-
- String part1 = text.substring(0, splitOffset);
- byte[] bytes1 = encode(part1, charset);
- String word1 = encodeB(prefix, part1, usedCharacters, charset,
- bytes1);
-
- String part2 = text.substring(splitOffset);
- byte[] bytes2 = encode(part2, charset);
- String word2 = encodeB(prefix, part2, 0, charset, bytes2);
-
- return word1 + " " + word2;
- }
- }
-
- private static int bEncodedLength(byte[] bytes) {
- return (bytes.length + 2) / 3 * 4;
- }
-
- private static String encodeQ(String prefix, String text, Usage usage,
- int usedCharacters, Charset charset, byte[] bytes) {
- int encodedLength = qEncodedLength(bytes, usage);
-
- int totalLength = prefix.length() + encodedLength
- + ENC_WORD_SUFFIX.length();
- if (totalLength <= ENCODED_WORD_MAX_LENGTH - usedCharacters) {
- return prefix + encodeQ(bytes, usage) + ENC_WORD_SUFFIX;
- } else {
- int splitOffset = text.offsetByCodePoints(text.length() / 2, -1);
-
- String part1 = text.substring(0, splitOffset);
- byte[] bytes1 = encode(part1, charset);
- String word1 = encodeQ(prefix, part1, usage, usedCharacters,
- charset, bytes1);
-
- String part2 = text.substring(splitOffset);
- byte[] bytes2 = encode(part2, charset);
- String word2 = encodeQ(prefix, part2, usage, 0, charset, bytes2);
-
- return word1 + " " + word2;
- }
- }
-
- private static int qEncodedLength(byte[] bytes, Usage usage) {
- BitSet qChars = usage == Usage.TEXT_TOKEN ? Q_REGULAR_CHARS
- : Q_RESTRICTED_CHARS;
-
- int count = 0;
-
- for (int idx = 0; idx < bytes.length; idx++) {
- int v = bytes[idx] & 0xff;
- if (v == 32) {
- count++;
- } else if (!qChars.get(v)) {
- count += 3;
- } else {
- count++;
- }
- }
-
- return count;
- }
-
- private static byte[] encode(String text, Charset charset) {
- ByteBuffer buffer = charset.encode(text);
- byte[] bytes = new byte[buffer.limit()];
- buffer.get(bytes);
- return bytes;
- }
-
- private static Charset determineCharset(String text) {
- // it is an important property of iso-8859-1 that it directly maps
- // unicode code points 0000 to 00ff to byte values 00 to ff.
- boolean ascii = true;
- final int len = text.length();
- for (int index = 0; index < len; index++) {
- char ch = text.charAt(index);
- if (ch > 0xff) {
- return CharsetUtil.UTF_8;
- }
- if (ch > 0x7f) {
- ascii = false;
- }
- }
- return ascii ? CharsetUtil.US_ASCII : CharsetUtil.ISO_8859_1;
- }
-
- private static Encoding determineEncoding(byte[] bytes, Usage usage) {
- if (bytes.length == 0)
- return Encoding.Q;
-
- BitSet qChars = usage == Usage.TEXT_TOKEN ? Q_REGULAR_CHARS
- : Q_RESTRICTED_CHARS;
-
- int qEncoded = 0;
- for (int i = 0; i < bytes.length; i++) {
- int v = bytes[i] & 0xff;
- if (v != 32 && !qChars.get(v)) {
- qEncoded++;
- }
- }
-
- int percentage = qEncoded * 100 / bytes.length;
- return percentage > 30 ? Encoding.B : Encoding.Q;
- }
-
- private static char hexDigit(int i) {
- return i < 10 ? (char) (i + '0') : (char) (i - 10 + 'A');
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/decoder/Base64InputStream.java b/emailcommon/src/org/apache/james/mime4j/decoder/Base64InputStream.java
deleted file mode 100644
index 2461ed571..000000000
--- a/emailcommon/src/org/apache/james/mime4j/decoder/Base64InputStream.java
+++ /dev/null
@@ -1,151 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-/**
- * Modified to improve efficiency by Android 21-Aug-2009
- */
-
-package org.apache.james.mime4j.decoder;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * Performs Base-64 decoding on an underlying stream.
- *
- *
- * @version $Id: Base64InputStream.java,v 1.3 2004/11/29 13:15:47 ntherning Exp $
- */
-public class Base64InputStream extends InputStream {
- private final InputStream s;
- private int outCount = 0;
- private int outIndex = 0;
- private final int[] outputBuffer = new int[3];
- private final byte[] inputBuffer = new byte[4];
- private boolean done = false;
-
- public Base64InputStream(InputStream s) {
- this.s = s;
- }
-
- /**
- * Closes the underlying stream.
- *
- * @throws IOException on I/O errors.
- */
- @Override
- public void close() throws IOException {
- s.close();
- }
-
- @Override
- public int read() throws IOException {
- if (outIndex == outCount) {
- fillBuffer();
- if (outIndex == outCount) {
- return -1;
- }
- }
-
- return outputBuffer[outIndex++];
- }
-
- /**
- * Retrieve data from the underlying stream, decode it,
- * and put the results in the byteq.
- * @throws IOException
- */
- private void fillBuffer() throws IOException {
- outCount = 0;
- outIndex = 0;
- int inCount = 0;
-
- int i;
- // "done" is needed for the two successive '=' at the end
- while (!done) {
- switch (i = s.read()) {
- case -1:
- // No more input - just return, let outputBuffer drain out, and be done
- return;
- case '=':
- // once we meet the first '=', avoid reading the second '='
- done = true;
- decodeAndEnqueue(inCount);
- return;
- default:
- byte sX = TRANSLATION[i];
- if (sX < 0) continue;
- inputBuffer[inCount++] = sX;
- if (inCount == 4) {
- decodeAndEnqueue(inCount);
- return;
- }
- break;
- }
- }
- }
-
- private void decodeAndEnqueue(int len) {
- int accum = 0;
- accum |= inputBuffer[0] << 18;
- accum |= inputBuffer[1] << 12;
- accum |= inputBuffer[2] << 6;
- accum |= inputBuffer[3];
-
- // There's a bit of duplicated code here because we want to have straight-through operation
- // for the most common case of len==4
- if (len == 4) {
- outputBuffer[0] = (accum >> 16) & 0xFF;
- outputBuffer[1] = (accum >> 8) & 0xFF;
- outputBuffer[2] = (accum) & 0xFF;
- outCount = 3;
- return;
- } else if (len == 3) {
- outputBuffer[0] = (accum >> 16) & 0xFF;
- outputBuffer[1] = (accum >> 8) & 0xFF;
- outCount = 2;
- return;
- } else { // len == 2
- outputBuffer[0] = (accum >> 16) & 0xFF;
- outCount = 1;
- return;
- }
- }
-
- private static byte[] TRANSLATION = {
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x00 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x10 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, /* 0x20 */
- 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, /* 0x30 */
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, /* 0x40 */
- 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, /* 0x50 */
- -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, /* 0x60 */
- 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1, /* 0x70 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x80 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0x90 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xA0 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xB0 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xC0 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xD0 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, /* 0xE0 */
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 /* 0xF0 */
- };
-
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/decoder/ByteQueue.java b/emailcommon/src/org/apache/james/mime4j/decoder/ByteQueue.java
deleted file mode 100644
index 68e7d3380..000000000
--- a/emailcommon/src/org/apache/james/mime4j/decoder/ByteQueue.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.decoder;
-
-import java.util.Iterator;
-
-public class ByteQueue {
-
- private UnboundedFifoByteBuffer buf;
- private int initialCapacity = -1;
-
- public ByteQueue() {
- buf = new UnboundedFifoByteBuffer();
- }
-
- public ByteQueue(int initialCapacity) {
- buf = new UnboundedFifoByteBuffer(initialCapacity);
- this.initialCapacity = initialCapacity;
- }
-
- public void enqueue(byte b) {
- buf.add(b);
- }
-
- public byte dequeue() {
- return buf.remove();
- }
-
- public int count() {
- return buf.size();
- }
-
- public void clear() {
- if (initialCapacity != -1)
- buf = new UnboundedFifoByteBuffer(initialCapacity);
- else
- buf = new UnboundedFifoByteBuffer();
- }
-
- public Iterator iterator() {
- return buf.iterator();
- }
-
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/decoder/DecoderUtil.java b/emailcommon/src/org/apache/james/mime4j/decoder/DecoderUtil.java
deleted file mode 100644
index 551be0f57..000000000
--- a/emailcommon/src/org/apache/james/mime4j/decoder/DecoderUtil.java
+++ /dev/null
@@ -1,279 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.decoder;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.util.CharsetUtil;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.UnsupportedEncodingException;
-
-/**
- * Static methods for decoding strings, byte arrays and encoded words.
- *
- *
- * @version $Id: DecoderUtil.java,v 1.3 2005/02/07 15:33:59 ntherning Exp $
- */
-public class DecoderUtil {
- private static Log log = LogFactory.getLog(DecoderUtil.class);
-
- /**
- * Decodes a string containing quoted-printable encoded data.
- *
- * @param s the string to decode.
- * @return the decoded bytes.
- */
- public static byte[] decodeBaseQuotedPrintable(String s) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- try {
- byte[] bytes = s.getBytes("US-ASCII");
-
- QuotedPrintableInputStream is = new QuotedPrintableInputStream(
- new ByteArrayInputStream(bytes));
-
- int b = 0;
- while ((b = is.read()) != -1) {
- baos.write(b);
- }
- } catch (IOException e) {
- /*
- * This should never happen!
- */
- log.error(e);
- }
-
- return baos.toByteArray();
- }
-
- /**
- * Decodes a string containing base64 encoded data.
- *
- * @param s the string to decode.
- * @return the decoded bytes.
- */
- public static byte[] decodeBase64(String s) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- try {
- byte[] bytes = s.getBytes("US-ASCII");
-
- Base64InputStream is = new Base64InputStream(
- new ByteArrayInputStream(bytes));
-
- int b = 0;
- while ((b = is.read()) != -1) {
- baos.write(b);
- }
- } catch (IOException e) {
- /*
- * This should never happen!
- */
- log.error(e);
- }
-
- return baos.toByteArray();
- }
-
- /**
- * Decodes an encoded word encoded with the 'B' encoding (described in
- * RFC 2047) found in a header field body.
- *
- * @param encodedWord the encoded word to decode.
- * @param charset the Java charset to use.
- * @return the decoded string.
- * @throws UnsupportedEncodingException if the given Java charset isn't
- * supported.
- */
- public static String decodeB(String encodedWord, String charset)
- throws UnsupportedEncodingException {
-
- return new String(decodeBase64(encodedWord), charset);
- }
-
- /**
- * Decodes an encoded word encoded with the 'Q' encoding (described in
- * RFC 2047) found in a header field body.
- *
- * @param encodedWord the encoded word to decode.
- * @param charset the Java charset to use.
- * @return the decoded string.
- * @throws UnsupportedEncodingException if the given Java charset isn't
- * supported.
- */
- public static String decodeQ(String encodedWord, String charset)
- throws UnsupportedEncodingException {
-
- /*
- * Replace _ with =20
- */
- StringBuffer sb = new StringBuffer();
- for (int i = 0; i < encodedWord.length(); i++) {
- char c = encodedWord.charAt(i);
- if (c == '_') {
- sb.append("=20");
- } else {
- sb.append(c);
- }
- }
-
- return new String(decodeBaseQuotedPrintable(sb.toString()), charset);
- }
-
- /**
- * Decodes a string containing encoded words as defined by RFC 2047.
- * Encoded words in have the form
- * =?charset?enc?Encoded word?= where enc is either 'Q' or 'q' for
- * quoted-printable and 'B' or 'b' for Base64.
- *
- * ANDROID: COPIED FROM A NEWER VERSION OF MIME4J
- *
- * @param body the string to decode.
- * @return the decoded string.
- */
- public static String decodeEncodedWords(String body) {
-
- // ANDROID: Most strings will not include "=?" so a quick test can prevent unneeded
- // object creation. This could also be handled via lazy creation of the StringBuilder.
- if (body.indexOf("=?") == -1) {
- return body;
- }
-
- int previousEnd = 0;
- boolean previousWasEncoded = false;
-
- StringBuilder sb = new StringBuilder();
-
- while (true) {
- int begin = body.indexOf("=?", previousEnd);
-
- // ANDROID: The mime4j original version has an error here. It gets confused if
- // the encoded string begins with an '=' (just after "?Q?"). This patch seeks forward
- // to find the two '?' in the "header", before looking for the final "?=".
- int endScan = begin + 2;
- if (begin != -1) {
- int qm1 = body.indexOf('?', endScan + 2);
- int qm2 = body.indexOf('?', qm1 + 1);
- if (qm2 != -1) {
- endScan = qm2 + 1;
- }
- }
-
- int end = begin == -1 ? -1 : body.indexOf("?=", endScan);
- if (end == -1) {
- if (previousEnd == 0)
- return body;
-
- sb.append(body.substring(previousEnd));
- return sb.toString();
- }
- end += 2;
-
- String sep = body.substring(previousEnd, begin);
-
- String decoded = decodeEncodedWord(body, begin, end);
- if (decoded == null) {
- sb.append(sep);
- sb.append(body.substring(begin, end));
- } else {
- if (!previousWasEncoded || !CharsetUtil.isWhitespace(sep)) {
- sb.append(sep);
- }
- sb.append(decoded);
- }
-
- previousEnd = end;
- previousWasEncoded = decoded != null;
- }
- }
-
- // return null on error
- private static String decodeEncodedWord(String body, int begin, int end) {
- int qm1 = body.indexOf('?', begin + 2);
- if (qm1 == end - 2)
- return null;
-
- int qm2 = body.indexOf('?', qm1 + 1);
- if (qm2 == end - 2)
- return null;
-
- String mimeCharset = body.substring(begin + 2, qm1);
- String encoding = body.substring(qm1 + 1, qm2);
- String encodedText = body.substring(qm2 + 1, end - 2);
-
- String charset = CharsetUtil.toJavaCharset(mimeCharset);
- if (charset == null) {
- if (log.isWarnEnabled()) {
- log.warn("MIME charset '" + mimeCharset + "' in encoded word '"
- + body.substring(begin, end) + "' doesn't have a "
- + "corresponding Java charset");
- }
- return null;
- } else if (!CharsetUtil.isDecodingSupported(charset)) {
- if (log.isWarnEnabled()) {
- log.warn("Current JDK doesn't support decoding of charset '"
- + charset + "' (MIME charset '" + mimeCharset
- + "' in encoded word '" + body.substring(begin, end)
- + "')");
- }
- return null;
- }
-
- if (encodedText.length() == 0) {
- if (log.isWarnEnabled()) {
- log.warn("Missing encoded text in encoded word: '"
- + body.substring(begin, end) + "'");
- }
- return null;
- }
-
- try {
- if (encoding.equalsIgnoreCase("Q")) {
- return DecoderUtil.decodeQ(encodedText, charset);
- } else if (encoding.equalsIgnoreCase("B")) {
- return DecoderUtil.decodeB(encodedText, charset);
- } else {
- if (log.isWarnEnabled()) {
- log.warn("Warning: Unknown encoding in encoded word '"
- + body.substring(begin, end) + "'");
- }
- return null;
- }
- } catch (UnsupportedEncodingException e) {
- // should not happen because of isDecodingSupported check above
- if (log.isWarnEnabled()) {
- log.warn("Unsupported encoding in encoded word '"
- + body.substring(begin, end) + "'", e);
- }
- return null;
- } catch (RuntimeException e) {
- if (log.isWarnEnabled()) {
- log.warn("Could not decode encoded word '"
- + body.substring(begin, end) + "'", e);
- }
- return null;
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/decoder/QuotedPrintableInputStream.java b/emailcommon/src/org/apache/james/mime4j/decoder/QuotedPrintableInputStream.java
deleted file mode 100644
index cbcb22628..000000000
--- a/emailcommon/src/org/apache/james/mime4j/decoder/QuotedPrintableInputStream.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.decoder;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-
-/**
- * Performs Quoted-Printable decoding on an underlying stream.
- *
- *
- *
- * @version $Id: QuotedPrintableInputStream.java,v 1.3 2004/11/29 13:15:47 ntherning Exp $
- */
-public class QuotedPrintableInputStream extends InputStream {
- private static Log log = LogFactory.getLog(QuotedPrintableInputStream.class);
-
- private InputStream stream;
- ByteQueue byteq = new ByteQueue();
- ByteQueue pushbackq = new ByteQueue();
- private byte state = 0;
-
- public QuotedPrintableInputStream(InputStream stream) {
- this.stream = stream;
- }
-
- /**
- * Closes the underlying stream.
- *
- * @throws IOException on I/O errors.
- */
- public void close() throws IOException {
- stream.close();
- }
-
- public int read() throws IOException {
- fillBuffer();
- if (byteq.count() == 0)
- return -1;
- else {
- byte val = byteq.dequeue();
- if (val >= 0)
- return val;
- else
- return val & 0xFF;
- }
- }
-
- /**
- * Pulls bytes out of the underlying stream and places them in the
- * pushback queue. This is necessary (vs. reading from the
- * underlying stream directly) to detect and filter out "transport
- * padding" whitespace, i.e., all whitespace that appears immediately
- * before a CRLF.
- *
- * @throws IOException Underlying stream threw IOException.
- */
- private void populatePushbackQueue() throws IOException {
- //Debug.verify(pushbackq.count() == 0, "PopulatePushbackQueue called when pushback queue was not empty!");
-
- if (pushbackq.count() != 0)
- return;
-
- while (true) {
- int i = stream.read();
- switch (i) {
- case -1:
- // stream is done
- pushbackq.clear(); // discard any whitespace preceding EOF
- return;
- case ' ':
- case '\t':
- pushbackq.enqueue((byte)i);
- break;
- case '\r':
- case '\n':
- pushbackq.clear(); // discard any whitespace preceding EOL
- pushbackq.enqueue((byte)i);
- return;
- default:
- pushbackq.enqueue((byte)i);
- return;
- }
- }
- }
-
- /**
- * Causes the pushback queue to get populated if it is empty, then
- * consumes and decodes bytes out of it until one or more bytes are
- * in the byte queue. This decoding step performs the actual QP
- * decoding.
- *
- * @throws IOException Underlying stream threw IOException.
- */
- private void fillBuffer() throws IOException {
- byte msdChar = 0; // first digit of escaped num
- while (byteq.count() == 0) {
- if (pushbackq.count() == 0) {
- populatePushbackQueue();
- if (pushbackq.count() == 0)
- return;
- }
-
- byte b = (byte)pushbackq.dequeue();
-
- switch (state) {
- case 0: // start state, no bytes pending
- if (b != '=') {
- byteq.enqueue(b);
- break; // state remains 0
- } else {
- state = 1;
- break;
- }
- case 1: // encountered "=" so far
- if (b == '\r') {
- state = 2;
- break;
- } else if ((b >= '0' && b <= '9') || (b >= 'A' && b <= 'F') || (b >= 'a' && b <= 'f')) {
- state = 3;
- msdChar = b; // save until next digit encountered
- break;
- } else if (b == '=') {
- /*
- * Special case when == is encountered.
- * Emit one = and stay in this state.
- */
- if (log.isWarnEnabled()) {
- log.warn("Malformed MIME; got ==");
- }
- byteq.enqueue((byte)'=');
- break;
- } else {
- if (log.isWarnEnabled()) {
- log.warn("Malformed MIME; expected \\r or "
- + "[0-9A-Z], got " + b);
- }
- state = 0;
- byteq.enqueue((byte)'=');
- byteq.enqueue(b);
- break;
- }
- case 2: // encountered "=\r" so far
- if (b == '\n') {
- state = 0;
- break;
- } else {
- if (log.isWarnEnabled()) {
- log.warn("Malformed MIME; expected "
- + (int)'\n' + ", got " + b);
- }
- state = 0;
- byteq.enqueue((byte)'=');
- byteq.enqueue((byte)'\r');
- byteq.enqueue(b);
- break;
- }
- case 3: // encountered =<digit> so far; expecting another <digit> to complete the octet
- if ((b >= '0' && b <= '9') || (b >= 'A' && b <= 'F') || (b >= 'a' && b <= 'f')) {
- byte msd = asciiCharToNumericValue(msdChar);
- byte low = asciiCharToNumericValue(b);
- state = 0;
- byteq.enqueue((byte)((msd << 4) | low));
- break;
- } else {
- if (log.isWarnEnabled()) {
- log.warn("Malformed MIME; expected "
- + "[0-9A-Z], got " + b);
- }
- state = 0;
- byteq.enqueue((byte)'=');
- byteq.enqueue(msdChar);
- byteq.enqueue(b);
- break;
- }
- default: // should never happen
- log.error("Illegal state: " + state);
- state = 0;
- byteq.enqueue(b);
- break;
- }
- }
- }
-
- /**
- * Converts '0' => 0, 'A' => 10, etc.
- * @param c ASCII character value.
- * @return Numeric value of hexadecimal character.
- */
- private byte asciiCharToNumericValue(byte c) {
- if (c >= '0' && c <= '9') {
- return (byte)(c - '0');
- } else if (c >= 'A' && c <= 'Z') {
- return (byte)(0xA + (c - 'A'));
- } else if (c >= 'a' && c <= 'z') {
- return (byte)(0xA + (c - 'a'));
- } else {
- /*
- * This should never happen since all calls to this method
- * are preceded by a check that c is in [0-9A-Za-z]
- */
- throw new IllegalArgumentException((char) c
- + " is not a hexadecimal digit");
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/decoder/UnboundedFifoByteBuffer.java b/emailcommon/src/org/apache/james/mime4j/decoder/UnboundedFifoByteBuffer.java
deleted file mode 100644
index dc32caf36..000000000
--- a/emailcommon/src/org/apache/james/mime4j/decoder/UnboundedFifoByteBuffer.java
+++ /dev/null
@@ -1,272 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.decoder;
-
-import java.util.Iterator;
-import java.util.NoSuchElementException;
-
-/**
- * UnboundedFifoByteBuffer is a very efficient buffer implementation.
- * According to performance testing, it exhibits a constant access time, but it
- * also outperforms ArrayList when used for the same purpose.
- * <p>
- * The removal order of an <code>UnboundedFifoByteBuffer</code> is based on the insertion
- * order; elements are removed in the same order in which they were added.
- * The iteration order is the same as the removal order.
- * <p>
- * The {@link #remove()} and {@link #get()} operations perform in constant time.
- * The {@link #add(Object)} operation performs in amortized constant time. All
- * other operations perform in linear time or worse.
- * <p>
- * Note that this implementation is not synchronized. The following can be
- * used to provide synchronized access to your <code>UnboundedFifoByteBuffer</code>:
- * <pre>
- * Buffer fifo = BufferUtils.synchronizedBuffer(new UnboundedFifoByteBuffer());
- * </pre>
- * <p>
- * This buffer prevents null objects from being added.
- *
- * @since Commons Collections 3.0 (previously in main package v2.1)
- * @version $Revision: 1.1 $ $Date: 2004/08/24 06:52:02 $
- *
- *
- *
- *
- *
- *
- */
-class UnboundedFifoByteBuffer {
-
- protected byte[] buffer;
- protected int head;
- protected int tail;
-
- /**
- * Constructs an UnboundedFifoByteBuffer with the default number of elements.
- * It is exactly the same as performing the following:
- *
- * <pre>
- * new UnboundedFifoByteBuffer(32);
- * </pre>
- */
- public UnboundedFifoByteBuffer() {
- this(32);
- }
-
- /**
- * Constructs an UnboundedFifoByteBuffer with the specified number of elements.
- * The integer must be a positive integer.
- *
- * @param initialSize the initial size of the buffer
- * @throws IllegalArgumentException if the size is less than 1
- */
- public UnboundedFifoByteBuffer(int initialSize) {
- if (initialSize <= 0) {
- throw new IllegalArgumentException("The size must be greater than 0");
- }
- buffer = new byte[initialSize + 1];
- head = 0;
- tail = 0;
- }
-
- /**
- * Returns the number of elements stored in the buffer.
- *
- * @return this buffer's size
- */
- public int size() {
- int size = 0;
-
- if (tail < head) {
- size = buffer.length - head + tail;
- } else {
- size = tail - head;
- }
-
- return size;
- }
-
- /**
- * Returns true if this buffer is empty; false otherwise.
- *
- * @return true if this buffer is empty
- */
- public boolean isEmpty() {
- return (size() == 0);
- }
-
- /**
- * Adds the given element to this buffer.
- *
- * @param b the byte to add
- * @return true, always
- */
- public boolean add(final byte b) {
-
- if (size() + 1 >= buffer.length) {
- byte[] tmp = new byte[((buffer.length - 1) * 2) + 1];
-
- int j = 0;
- for (int i = head; i != tail;) {
- tmp[j] = buffer[i];
- buffer[i] = 0;
-
- j++;
- i++;
- if (i == buffer.length) {
- i = 0;
- }
- }
-
- buffer = tmp;
- head = 0;
- tail = j;
- }
-
- buffer[tail] = b;
- tail++;
- if (tail >= buffer.length) {
- tail = 0;
- }
- return true;
- }
-
- /**
- * Returns the next object in the buffer.
- *
- * @return the next object in the buffer
- * @throws BufferUnderflowException if this buffer is empty
- */
- public byte get() {
- if (isEmpty()) {
- throw new IllegalStateException("The buffer is already empty");
- }
-
- return buffer[head];
- }
-
- /**
- * Removes the next object from the buffer
- *
- * @return the removed object
- * @throws BufferUnderflowException if this buffer is empty
- */
- public byte remove() {
- if (isEmpty()) {
- throw new IllegalStateException("The buffer is already empty");
- }
-
- byte element = buffer[head];
-
- head++;
- if (head >= buffer.length) {
- head = 0;
- }
-
- return element;
- }
-
- /**
- * Increments the internal index.
- *
- * @param index the index to increment
- * @return the updated index
- */
- private int increment(int index) {
- index++;
- if (index >= buffer.length) {
- index = 0;
- }
- return index;
- }
-
- /**
- * Decrements the internal index.
- *
- * @param index the index to decrement
- * @return the updated index
- */
- private int decrement(int index) {
- index--;
- if (index < 0) {
- index = buffer.length - 1;
- }
- return index;
- }
-
- /**
- * Returns an iterator over this buffer's elements.
- *
- * @return an iterator over this buffer's elements
- */
- public Iterator iterator() {
- return new Iterator() {
-
- private int index = head;
- private int lastReturnedIndex = -1;
-
- public boolean hasNext() {
- return index != tail;
-
- }
-
- public Object next() {
- if (!hasNext()) {
- throw new NoSuchElementException();
- }
- lastReturnedIndex = index;
- index = increment(index);
- return new Byte(buffer[lastReturnedIndex]);
- }
-
- public void remove() {
- if (lastReturnedIndex == -1) {
- throw new IllegalStateException();
- }
-
- // First element can be removed quickly
- if (lastReturnedIndex == head) {
- UnboundedFifoByteBuffer.this.remove();
- lastReturnedIndex = -1;
- return;
- }
-
- // Other elements require us to shift the subsequent elements
- int i = lastReturnedIndex + 1;
- while (i != tail) {
- if (i >= buffer.length) {
- buffer[i - 1] = buffer[0];
- i = 0;
- } else {
- buffer[i - 1] = buffer[i];
- i++;
- }
- }
-
- lastReturnedIndex = -1;
- tail = decrement(tail);
- buffer[tail] = 0;
- index = decrement(index);
- }
-
- };
- }
-
-} \ No newline at end of file
diff --git a/emailcommon/src/org/apache/james/mime4j/field/AddressListField.java b/emailcommon/src/org/apache/james/mime4j/field/AddressListField.java
deleted file mode 100644
index b37abbb11..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/AddressListField.java
+++ /dev/null
@@ -1,65 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.field.address.AddressList;
-import org.apache.james.mime4j.field.address.parser.ParseException;
-
-public class AddressListField extends Field {
- private AddressList addressList;
- private ParseException parseException;
-
- protected AddressListField(String name, String body, String raw, AddressList addressList, ParseException parseException) {
- super(name, body, raw);
- this.addressList = addressList;
- this.parseException = parseException;
- }
-
- public AddressList getAddressList() {
- return addressList;
- }
-
- public ParseException getParseException() {
- return parseException;
- }
-
- public static class Parser implements FieldParser {
- private static Log log = LogFactory.getLog(Parser.class);
-
- public Field parse(final String name, final String body, final String raw) {
- AddressList addressList = null;
- ParseException parseException = null;
- try {
- addressList = AddressList.parse(body);
- }
- catch (ParseException e) {
- if (log.isDebugEnabled()) {
- log.debug("Parsing value '" + body + "': "+ e.getMessage());
- }
- parseException = e;
- }
- return new AddressListField(name, body, raw, addressList, parseException);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/ContentTransferEncodingField.java b/emailcommon/src/org/apache/james/mime4j/field/ContentTransferEncodingField.java
deleted file mode 100644
index eb6151377..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/ContentTransferEncodingField.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-
-
-/**
- * Represents a <code>Content-Transfer-Encoding</code> field.
- *
- *
- * @version $Id: ContentTransferEncodingField.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
- */
-public class ContentTransferEncodingField extends Field {
- /**
- * The <code>7bit</code> encoding.
- */
- public static final String ENC_7BIT = "7bit";
- /**
- * The <code>8bit</code> encoding.
- */
- public static final String ENC_8BIT = "8bit";
- /**
- * The <code>binary</code> encoding.
- */
- public static final String ENC_BINARY = "binary";
- /**
- * The <code>quoted-printable</code> encoding.
- */
- public static final String ENC_QUOTED_PRINTABLE = "quoted-printable";
- /**
- * The <code>base64</code> encoding.
- */
- public static final String ENC_BASE64 = "base64";
-
- private String encoding;
-
- protected ContentTransferEncodingField(String name, String body, String raw, String encoding) {
- super(name, body, raw);
- this.encoding = encoding;
- }
-
- /**
- * Gets the encoding defined in this field.
- *
- * @return the encoding or an empty string if not set.
- */
- public String getEncoding() {
- return encoding;
- }
-
- /**
- * Gets the encoding of the given field if. Returns the default
- * <code>7bit</code> if not set or if
- * <code>f</code> is <code>null</code>.
- *
- * @return the encoding.
- */
- public static String getEncoding(ContentTransferEncodingField f) {
- if (f != null && f.getEncoding().length() != 0) {
- return f.getEncoding();
- }
- return ENC_7BIT;
- }
-
- public static class Parser implements FieldParser {
- public Field parse(final String name, final String body, final String raw) {
- final String encoding = body.trim().toLowerCase();
- return new ContentTransferEncodingField(name, body, raw, encoding);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/ContentTypeField.java b/emailcommon/src/org/apache/james/mime4j/field/ContentTypeField.java
deleted file mode 100644
index 646cf141a..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/ContentTypeField.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-import java.io.StringReader;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.field.contenttype.parser.ContentTypeParser;
-import org.apache.james.mime4j.field.contenttype.parser.ParseException;
-import org.apache.james.mime4j.field.contenttype.parser.TokenMgrError;
-
-/**
- * Represents a <code>Content-Type</code> field.
- *
- * <p>TODO: Remove dependency on Java 1.4 regexps</p>
- *
- *
- * @version $Id: ContentTypeField.java,v 1.6 2005/01/27 14:16:31 ntherning Exp $
- */
-public class ContentTypeField extends Field {
-
- /**
- * The prefix of all <code>multipart</code> MIME types.
- */
- public static final String TYPE_MULTIPART_PREFIX = "multipart/";
- /**
- * The <code>multipart/digest</code> MIME type.
- */
- public static final String TYPE_MULTIPART_DIGEST = "multipart/digest";
- /**
- * The <code>text/plain</code> MIME type.
- */
- public static final String TYPE_TEXT_PLAIN = "text/plain";
- /**
- * The <code>message/rfc822</code> MIME type.
- */
- public static final String TYPE_MESSAGE_RFC822 = "message/rfc822";
- /**
- * The name of the <code>boundary</code> parameter.
- */
- public static final String PARAM_BOUNDARY = "boundary";
- /**
- * The name of the <code>charset</code> parameter.
- */
- public static final String PARAM_CHARSET = "charset";
-
- private String mimeType = "";
- private Map<String, String> parameters = null;
- private ParseException parseException;
-
- protected ContentTypeField(String name, String body, String raw, String mimeType, Map<String, String> parameters, ParseException parseException) {
- super(name, body, raw);
- this.mimeType = mimeType;
- this.parameters = parameters;
- this.parseException = parseException;
- }
-
- /**
- * Gets the exception that was raised during parsing of
- * the field value, if any; otherwise, null.
- */
- public ParseException getParseException() {
- return parseException;
- }
-
- /**
- * Gets the MIME type defined in this Content-Type field.
- *
- * @return the MIME type or an empty string if not set.
- */
- public String getMimeType() {
- return mimeType;
- }
-
- /**
- * Gets the MIME type defined in the child's
- * Content-Type field or derives a MIME type from the parent
- * if child is <code>null</code> or hasn't got a MIME type value set.
- * If child's MIME type is multipart but no boundary
- * has been set the MIME type of child will be derived from
- * the parent.
- *
- * @param child the child.
- * @param parent the parent.
- * @return the MIME type.
- */
- public static String getMimeType(ContentTypeField child,
- ContentTypeField parent) {
-
- if (child == null || child.getMimeType().length() == 0
- || child.isMultipart() && child.getBoundary() == null) {
-
- if (parent != null && parent.isMimeType(TYPE_MULTIPART_DIGEST)) {
- return TYPE_MESSAGE_RFC822;
- } else {
- return TYPE_TEXT_PLAIN;
- }
- }
-
- return child.getMimeType();
- }
-
- /**
- * Gets the value of a parameter. Parameter names are case-insensitive.
- *
- * @param name the name of the parameter to get.
- * @return the parameter value or <code>null</code> if not set.
- */
- public String getParameter(String name) {
- return parameters != null
- ? parameters.get(name.toLowerCase())
- : null;
- }
-
- /**
- * Gets all parameters.
- *
- * @return the parameters.
- */
- public Map<String, String> getParameters() {
- if (parameters != null) {
- return Collections.unmodifiableMap(parameters);
- }
- return Collections.emptyMap();
- }
-
- /**
- * Gets the value of the <code>boundary</code> parameter if set.
- *
- * @return the <code>boundary</code> parameter value or <code>null</code>
- * if not set.
- */
- public String getBoundary() {
- return getParameter(PARAM_BOUNDARY);
- }
-
- /**
- * Gets the value of the <code>charset</code> parameter if set.
- *
- * @return the <code>charset</code> parameter value or <code>null</code>
- * if not set.
- */
- public String getCharset() {
- return getParameter(PARAM_CHARSET);
- }
-
- /**
- * Gets the value of the <code>charset</code> parameter if set for the
- * given field. Returns the default <code>us-ascii</code> if not set or if
- * <code>f</code> is <code>null</code>.
- *
- * @return the <code>charset</code> parameter value.
- */
- public static String getCharset(ContentTypeField f) {
- if (f != null) {
- if (f.getCharset() != null && f.getCharset().length() > 0) {
- return f.getCharset();
- }
- }
- return "us-ascii";
- }
-
- /**
- * Determines if the MIME type of this field matches the given one.
- *
- * @param mimeType the MIME type to match against.
- * @return <code>true</code> if the MIME type of this field matches,
- * <code>false</code> otherwise.
- */
- public boolean isMimeType(String mimeType) {
- return this.mimeType.equalsIgnoreCase(mimeType);
- }
-
- /**
- * Determines if the MIME type of this field is <code>multipart/*</code>.
- *
- * @return <code>true</code> if this field is has a <code>multipart/*</code>
- * MIME type, <code>false</code> otherwise.
- */
- public boolean isMultipart() {
- return mimeType.startsWith(TYPE_MULTIPART_PREFIX);
- }
-
- public static class Parser implements FieldParser {
- private static Log log = LogFactory.getLog(Parser.class);
-
- public Field parse(final String name, final String body, final String raw) {
- ParseException parseException = null;
- String mimeType = "";
- Map<String, String> parameters = null;
-
- ContentTypeParser parser = new ContentTypeParser(new StringReader(body));
- try {
- parser.parseAll();
- }
- catch (ParseException e) {
- if (log.isDebugEnabled()) {
- log.debug("Parsing value '" + body + "': "+ e.getMessage());
- }
- parseException = e;
- }
- catch (TokenMgrError e) {
- if (log.isDebugEnabled()) {
- log.debug("Parsing value '" + body + "': "+ e.getMessage());
- }
- parseException = new ParseException(e.getMessage());
- }
-
- try {
- final String type = parser.getType();
- final String subType = parser.getSubType();
-
- if (type != null && subType != null) {
- mimeType = (type + "/" + parser.getSubType()).toLowerCase();
-
- ArrayList<String> paramNames = parser.getParamNames();
- ArrayList<String> paramValues = parser.getParamValues();
-
- if (paramNames != null && paramValues != null) {
- for (int i = 0; i < paramNames.size() && i < paramValues.size(); i++) {
- if (parameters == null)
- parameters = new HashMap<String, String>((int)(paramNames.size() * 1.3 + 1));
- String paramName = paramNames.get(i).toLowerCase();
- String paramValue = paramValues.get(i);
- parameters.put(paramName, paramValue);
- }
- }
- }
- }
- catch (NullPointerException npe) {
- }
- return new ContentTypeField(name, body, raw, mimeType, parameters, parseException);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/DateTimeField.java b/emailcommon/src/org/apache/james/mime4j/field/DateTimeField.java
deleted file mode 100644
index e65551fcd..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/DateTimeField.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-//BEGIN android-changed: Stubbing out logging
-import com.android.emailcommon.utility.Utility;
-
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END
-import org.apache.james.mime4j.field.datetime.DateTime;
-import org.apache.james.mime4j.field.datetime.parser.ParseException;
-
-import java.util.Date;
-
-public class DateTimeField extends Field {
- private Date date;
- private ParseException parseException;
-
- protected DateTimeField(String name, String body, String raw, Date date, ParseException parseException) {
- super(name, body, raw);
- this.date = date;
- this.parseException = parseException;
- }
-
- public Date getDate() {
- return date;
- }
-
- public ParseException getParseException() {
- return parseException;
- }
-
- public static class Parser implements FieldParser {
- private static Log log = LogFactory.getLog(Parser.class);
-
- public Field parse(final String name, String body, final String raw) {
- Date date = null;
- ParseException parseException = null;
- //BEGIN android-changed
- body = Utility.cleanUpMimeDate(body);
- //END android-changed
- try {
- date = DateTime.parse(body).getDate();
- }
- catch (ParseException e) {
- if (log.isDebugEnabled()) {
- log.debug("Parsing value '" + body + "': "+ e.getMessage());
- }
- parseException = e;
- }
- return new DateTimeField(name, body, raw, date, parseException);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/DefaultFieldParser.java b/emailcommon/src/org/apache/james/mime4j/field/DefaultFieldParser.java
deleted file mode 100644
index 84fcdcb2d..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/DefaultFieldParser.java
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * Copyright 2006 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field;
-
-public class DefaultFieldParser extends DelegatingFieldParser {
-
- public DefaultFieldParser() {
- setFieldParser(Field.CONTENT_TRANSFER_ENCODING, new ContentTransferEncodingField.Parser());
- setFieldParser(Field.CONTENT_TYPE, new ContentTypeField.Parser());
-
- final DateTimeField.Parser dateTimeParser = new DateTimeField.Parser();
- setFieldParser(Field.DATE, dateTimeParser);
- setFieldParser(Field.RESENT_DATE, dateTimeParser);
-
- final MailboxListField.Parser mailboxListParser = new MailboxListField.Parser();
- setFieldParser(Field.FROM, mailboxListParser);
- setFieldParser(Field.RESENT_FROM, mailboxListParser);
-
- final MailboxField.Parser mailboxParser = new MailboxField.Parser();
- setFieldParser(Field.SENDER, mailboxParser);
- setFieldParser(Field.RESENT_SENDER, mailboxParser);
-
- final AddressListField.Parser addressListParser = new AddressListField.Parser();
- setFieldParser(Field.TO, addressListParser);
- setFieldParser(Field.RESENT_TO, addressListParser);
- setFieldParser(Field.CC, addressListParser);
- setFieldParser(Field.RESENT_CC, addressListParser);
- setFieldParser(Field.BCC, addressListParser);
- setFieldParser(Field.RESENT_BCC, addressListParser);
- setFieldParser(Field.REPLY_TO, addressListParser);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/DelegatingFieldParser.java b/emailcommon/src/org/apache/james/mime4j/field/DelegatingFieldParser.java
deleted file mode 100644
index 2a2866f57..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/DelegatingFieldParser.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright 2006 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field;
-
-import java.util.HashMap;
-import java.util.Map;
-
-public class DelegatingFieldParser implements FieldParser {
-
- private Map<String, FieldParser> parsers = new HashMap<String, FieldParser>();
- private FieldParser defaultParser = new UnstructuredField.Parser();
-
- /**
- * Sets the parser used for the field named <code>name</code>.
- * @param name the name of the field
- * @param parser the parser for fields named <code>name</code>
- */
- public void setFieldParser(final String name, final FieldParser parser) {
- parsers.put(name.toLowerCase(), parser);
- }
-
- public FieldParser getParser(final String name) {
- final FieldParser field = parsers.get(name.toLowerCase());
- if(field==null) {
- return defaultParser;
- }
- return field;
- }
-
- public Field parse(final String name, final String body, final String raw) {
- final FieldParser parser = getParser(name);
- return parser.parse(name, body, raw);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/Field.java b/emailcommon/src/org/apache/james/mime4j/field/Field.java
deleted file mode 100644
index 7c2a20dc8..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/Field.java
+++ /dev/null
@@ -1,192 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * The base class of all field classes.
- *
- *
- * @version $Id: Field.java,v 1.6 2004/10/25 07:26:46 ntherning Exp $
- */
-public abstract class Field {
- public static final String SENDER = "Sender";
- public static final String FROM = "From";
- public static final String TO = "To";
- public static final String CC = "Cc";
- public static final String BCC = "Bcc";
- public static final String REPLY_TO = "Reply-To";
- public static final String RESENT_SENDER = "Resent-Sender";
- public static final String RESENT_FROM = "Resent-From";
- public static final String RESENT_TO = "Resent-To";
- public static final String RESENT_CC = "Resent-Cc";
- public static final String RESENT_BCC = "Resent-Bcc";
-
- public static final String DATE = "Date";
- public static final String RESENT_DATE = "Resent-Date";
-
- public static final String SUBJECT = "Subject";
- public static final String CONTENT_TYPE = "Content-Type";
- public static final String CONTENT_TRANSFER_ENCODING =
- "Content-Transfer-Encoding";
-
- private static final String FIELD_NAME_PATTERN =
- "^([\\x21-\\x39\\x3b-\\x7e]+)[ \t]*:";
- private static final Pattern fieldNamePattern =
- Pattern.compile(FIELD_NAME_PATTERN);
-
- private static final DefaultFieldParser parser = new DefaultFieldParser();
-
- private final String name;
- private final String body;
- private final String raw;
-
- protected Field(final String name, final String body, final String raw) {
- this.name = name;
- this.body = body;
- this.raw = raw;
- }
-
- /**
- * Parses the given string and returns an instance of the
- * <code>Field</code> class. The type of the class returned depends on
- * the field name:
- * <table>
- * <tr>
- * <td><em>Field name</em></td><td><em>Class returned</em></td>
- * <td>Content-Type</td><td>org.apache.james.mime4j.field.ContentTypeField</td>
- * <td>other</td><td>org.apache.james.mime4j.field.UnstructuredField</td>
- * </tr>
- * </table>
- *
- * @param s the string to parse.
- * @return a <code>Field</code> instance.
- * @throws IllegalArgumentException on parse errors.
- */
- public static Field parse(final String raw) {
-
- /*
- * Unfold the field.
- */
- final String unfolded = raw.replaceAll("\r|\n", "");
-
- /*
- * Split into name and value.
- */
- final Matcher fieldMatcher = fieldNamePattern.matcher(unfolded);
- if (!fieldMatcher.find()) {
- throw new IllegalArgumentException("Invalid field in string");
- }
- final String name = fieldMatcher.group(1);
-
- String body = unfolded.substring(fieldMatcher.end());
- if (body.length() > 0 && body.charAt(0) == ' ') {
- body = body.substring(1);
- }
-
- return parser.parse(name, body, raw);
- }
-
- /**
- * Gets the default parser used to parse fields.
- * @return the default field parser
- */
- public static DefaultFieldParser getParser() {
- return parser;
- }
-
- /**
- * Gets the name of the field (<code>Subject</code>,
- * <code>From</code>, etc).
- *
- * @return the field name.
- */
- public String getName() {
- return name;
- }
-
- /**
- * Gets the original raw field string.
- *
- * @return the original raw field string.
- */
- public String getRaw() {
- return raw;
- }
-
- /**
- * Gets the unfolded, unparsed and possibly encoded (see RFC 2047) field
- * body string.
- *
- * @return the unfolded unparsed field body string.
- */
- public String getBody() {
- return body;
- }
-
- /**
- * Determines if this is a <code>Content-Type</code> field.
- *
- * @return <code>true</code> if this is a <code>Content-Type</code> field,
- * <code>false</code> otherwise.
- */
- public boolean isContentType() {
- return CONTENT_TYPE.equalsIgnoreCase(name);
- }
-
- /**
- * Determines if this is a <code>Subject</code> field.
- *
- * @return <code>true</code> if this is a <code>Subject</code> field,
- * <code>false</code> otherwise.
- */
- public boolean isSubject() {
- return SUBJECT.equalsIgnoreCase(name);
- }
-
- /**
- * Determines if this is a <code>From</code> field.
- *
- * @return <code>true</code> if this is a <code>From</code> field,
- * <code>false</code> otherwise.
- */
- public boolean isFrom() {
- return FROM.equalsIgnoreCase(name);
- }
-
- /**
- * Determines if this is a <code>To</code> field.
- *
- * @return <code>true</code> if this is a <code>To</code> field,
- * <code>false</code> otherwise.
- */
- public boolean isTo() {
- return TO.equalsIgnoreCase(name);
- }
-
- /**
- * @see #getRaw()
- */
- public String toString() {
- return raw;
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/FieldParser.java b/emailcommon/src/org/apache/james/mime4j/field/FieldParser.java
deleted file mode 100644
index 4f33c9e26..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/FieldParser.java
+++ /dev/null
@@ -1,21 +0,0 @@
-/*
- * Copyright 2006 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field;
-
-public interface FieldParser {
-
- Field parse(final String name, final String body, final String raw);
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/MailboxField.java b/emailcommon/src/org/apache/james/mime4j/field/MailboxField.java
deleted file mode 100644
index 9404fd621..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/MailboxField.java
+++ /dev/null
@@ -1,70 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.field.address.AddressList;
-import org.apache.james.mime4j.field.address.Mailbox;
-import org.apache.james.mime4j.field.address.MailboxList;
-import org.apache.james.mime4j.field.address.parser.ParseException;
-
-public class MailboxField extends Field {
- private final Mailbox mailbox;
- private final ParseException parseException;
-
- protected MailboxField(final String name, final String body, final String raw, final Mailbox mailbox, final ParseException parseException) {
- super(name, body, raw);
- this.mailbox = mailbox;
- this.parseException = parseException;
- }
-
- public Mailbox getMailbox() {
- return mailbox;
- }
-
- public ParseException getParseException() {
- return parseException;
- }
-
- public static class Parser implements FieldParser {
- private static Log log = LogFactory.getLog(Parser.class);
-
- public Field parse(final String name, final String body, final String raw) {
- Mailbox mailbox = null;
- ParseException parseException = null;
- try {
- MailboxList mailboxList = AddressList.parse(body).flatten();
- if (mailboxList.size() > 0) {
- mailbox = mailboxList.get(0);
- }
- }
- catch (ParseException e) {
- if (log.isDebugEnabled()) {
- log.debug("Parsing value '" + body + "': "+ e.getMessage());
- }
- parseException = e;
- }
- return new MailboxField(name, body, raw, mailbox, parseException);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/MailboxListField.java b/emailcommon/src/org/apache/james/mime4j/field/MailboxListField.java
deleted file mode 100644
index 6364fc88c..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/MailboxListField.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.field.address.AddressList;
-import org.apache.james.mime4j.field.address.MailboxList;
-import org.apache.james.mime4j.field.address.parser.ParseException;
-
-public class MailboxListField extends Field {
-
- private MailboxList mailboxList;
- private ParseException parseException;
-
- protected MailboxListField(final String name, final String body, final String raw, final MailboxList mailboxList, final ParseException parseException) {
- super(name, body, raw);
- this.mailboxList = mailboxList;
- this.parseException = parseException;
- }
-
- public MailboxList getMailboxList() {
- return mailboxList;
- }
-
- public ParseException getParseException() {
- return parseException;
- }
-
- public static class Parser implements FieldParser {
- private static Log log = LogFactory.getLog(Parser.class);
-
- public Field parse(final String name, final String body, final String raw) {
- MailboxList mailboxList = null;
- ParseException parseException = null;
- try {
- mailboxList = AddressList.parse(body).flatten();
- }
- catch (ParseException e) {
- if (log.isDebugEnabled()) {
- log.debug("Parsing value '" + body + "': "+ e.getMessage());
- }
- parseException = e;
- }
- return new MailboxListField(name, body, raw, mailboxList, parseException);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/UnstructuredField.java b/emailcommon/src/org/apache/james/mime4j/field/UnstructuredField.java
deleted file mode 100644
index 5e2adf9f2..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/UnstructuredField.java
+++ /dev/null
@@ -1,49 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field;
-
-import org.apache.james.mime4j.decoder.DecoderUtil;
-
-
-/**
- * Simple unstructured field such as <code>Subject</code>.
- *
- *
- * @version $Id: UnstructuredField.java,v 1.3 2004/10/25 07:26:46 ntherning Exp $
- */
-public class UnstructuredField extends Field {
- private String value;
-
- protected UnstructuredField(String name, String body, String raw, String value) {
- super(name, body, raw);
- this.value = value;
- }
-
- public String getValue() {
- return value;
- }
-
- public static class Parser implements FieldParser {
- public Field parse(final String name, final String body, final String raw) {
- final String value = DecoderUtil.decodeEncodedWords(body);
- return new UnstructuredField(name, body, raw, value);
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/Address.java b/emailcommon/src/org/apache/james/mime4j/field/address/Address.java
deleted file mode 100644
index 2a5d61e36..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/Address.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-import java.util.ArrayList;
-
-/**
- * The abstract base for classes that represent RFC2822 addresses.
- * This includes groups and mailboxes.
- *
- * Currently, no public methods are introduced on this class.
- *
- *
- */
-public abstract class Address {
-
- /**
- * Adds any mailboxes represented by this address
- * into the given ArrayList. Note that this method
- * has default (package) access, so a doAddMailboxesTo
- * method is needed to allow the behavior to be
- * overridden by subclasses.
- */
- final void addMailboxesTo(ArrayList<Address> results) {
- doAddMailboxesTo(results);
- }
-
- /**
- * Adds any mailboxes represented by this address
- * into the given ArrayList. Must be overridden by
- * concrete subclasses.
- */
- protected abstract void doAddMailboxesTo(ArrayList<Address> results);
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/AddressList.java b/emailcommon/src/org/apache/james/mime4j/field/address/AddressList.java
deleted file mode 100644
index fa4d02c23..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/AddressList.java
+++ /dev/null
@@ -1,138 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-import org.apache.james.mime4j.field.address.parser.AddressListParser;
-import org.apache.james.mime4j.field.address.parser.ParseException;
-
-import java.io.StringReader;
-import java.util.ArrayList;
-
-/**
- * An immutable, random-access list of Address objects.
- *
- *
- */
-public class AddressList {
-
- private ArrayList<Address> addresses;
-
- /**
- * @param addresses An ArrayList that contains only Address objects.
- * @param dontCopy true iff it is not possible for the addresses ArrayList to be modified by someone else.
- */
- public AddressList(ArrayList<Address> addresses, boolean dontCopy) {
- if (addresses != null)
- this.addresses = (dontCopy ? addresses : new ArrayList<Address>(addresses));
- else
- this.addresses = new ArrayList<Address>(0);
- }
-
- /**
- * The number of elements in this list.
- */
- public int size() {
- return addresses.size();
- }
-
- /**
- * Gets an address.
- */
- public Address get(int index) {
- if (0 > index || size() <= index)
- throw new IndexOutOfBoundsException();
- return addresses.get(index);
- }
-
- /**
- * Returns a flat list of all mailboxes represented
- * in this address list. Use this if you don't care
- * about grouping.
- */
- public MailboxList flatten() {
- // in the common case, all addresses are mailboxes
- boolean groupDetected = false;
- for (int i = 0; i < size(); i++) {
- if (!(get(i) instanceof Mailbox)) {
- groupDetected = true;
- break;
- }
- }
-
- if (!groupDetected)
- return new MailboxList(addresses, true);
-
- ArrayList<Address> results = new ArrayList<Address>();
- for (int i = 0; i < size(); i++) {
- Address addr = get(i);
- addr.addMailboxesTo(results);
- }
-
- // copy-on-construct this time, because subclasses
- // could have held onto a reference to the results
- return new MailboxList(results, false);
- }
-
- /**
- * Dumps a representation of this address list to
- * stdout, for debugging purposes.
- */
- public void print() {
- for (int i = 0; i < size(); i++) {
- Address addr = get(i);
- System.out.println(addr.toString());
- }
- }
-
- /**
- * Parse the address list string, such as the value
- * of a From, To, Cc, Bcc, Sender, or Reply-To
- * header.
- *
- * The string MUST be unfolded already.
- */
- public static AddressList parse(String rawAddressList) throws ParseException {
- AddressListParser parser = new AddressListParser(new StringReader(rawAddressList));
- return Builder.getInstance().buildAddressList(parser.parse());
- }
-
- /**
- * Test console.
- */
- public static void main(String[] args) throws Exception {
- java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
- while (true) {
- try {
- System.out.print("> ");
- String line = reader.readLine();
- if (line.length() == 0 || line.toLowerCase().equals("exit") || line.toLowerCase().equals("quit")) {
- System.out.println("Goodbye.");
- return;
- }
- AddressList list = parse(line);
- list.print();
- }
- catch(Exception e) {
- e.printStackTrace();
- Thread.sleep(300);
- }
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/Builder.java b/emailcommon/src/org/apache/james/mime4j/field/address/Builder.java
deleted file mode 100644
index a2bd3f0c6..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/Builder.java
+++ /dev/null
@@ -1,243 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-
-import org.apache.james.mime4j.decoder.DecoderUtil;
-import org.apache.james.mime4j.field.address.parser.ASTaddr_spec;
-import org.apache.james.mime4j.field.address.parser.ASTaddress;
-import org.apache.james.mime4j.field.address.parser.ASTaddress_list;
-import org.apache.james.mime4j.field.address.parser.ASTangle_addr;
-import org.apache.james.mime4j.field.address.parser.ASTdomain;
-import org.apache.james.mime4j.field.address.parser.ASTgroup_body;
-import org.apache.james.mime4j.field.address.parser.ASTlocal_part;
-import org.apache.james.mime4j.field.address.parser.ASTmailbox;
-import org.apache.james.mime4j.field.address.parser.ASTname_addr;
-import org.apache.james.mime4j.field.address.parser.ASTphrase;
-import org.apache.james.mime4j.field.address.parser.ASTroute;
-import org.apache.james.mime4j.field.address.parser.Node;
-import org.apache.james.mime4j.field.address.parser.SimpleNode;
-import org.apache.james.mime4j.field.address.parser.Token;
-
-/**
- * Transforms the JJTree-generated abstract syntax tree
- * into a graph of org.apache.james.mime4j.field.address objects.
- *
- *
- */
-class Builder {
-
- private static Builder singleton = new Builder();
-
- public static Builder getInstance() {
- return singleton;
- }
-
-
-
- public AddressList buildAddressList(ASTaddress_list node) {
- ArrayList<Address> list = new ArrayList<Address>();
- for (int i = 0; i < node.jjtGetNumChildren(); i++) {
- ASTaddress childNode = (ASTaddress) node.jjtGetChild(i);
- Address address = buildAddress(childNode);
- list.add(address);
- }
- return new AddressList(list, true);
- }
-
- private Address buildAddress(ASTaddress node) {
- ChildNodeIterator it = new ChildNodeIterator(node);
- Node n = it.nextNode();
- if (n instanceof ASTaddr_spec) {
- return buildAddrSpec((ASTaddr_spec)n);
- }
- else if (n instanceof ASTangle_addr) {
- return buildAngleAddr((ASTangle_addr)n);
- }
- else if (n instanceof ASTphrase) {
- String name = buildString((ASTphrase)n, false);
- Node n2 = it.nextNode();
- if (n2 instanceof ASTgroup_body) {
- return new Group(name, buildGroupBody((ASTgroup_body)n2));
- }
- else if (n2 instanceof ASTangle_addr) {
- name = DecoderUtil.decodeEncodedWords(name);
- return new NamedMailbox(name, buildAngleAddr((ASTangle_addr)n2));
- }
- else {
- throw new IllegalStateException();
- }
- }
- else {
- throw new IllegalStateException();
- }
- }
-
-
-
- private MailboxList buildGroupBody(ASTgroup_body node) {
- ArrayList<Address> results = new ArrayList<Address>();
- ChildNodeIterator it = new ChildNodeIterator(node);
- while (it.hasNext()) {
- Node n = it.nextNode();
- if (n instanceof ASTmailbox)
- results.add(buildMailbox((ASTmailbox)n));
- else
- throw new IllegalStateException();
- }
- return new MailboxList(results, true);
- }
-
- private Mailbox buildMailbox(ASTmailbox node) {
- ChildNodeIterator it = new ChildNodeIterator(node);
- Node n = it.nextNode();
- if (n instanceof ASTaddr_spec) {
- return buildAddrSpec((ASTaddr_spec)n);
- }
- else if (n instanceof ASTangle_addr) {
- return buildAngleAddr((ASTangle_addr)n);
- }
- else if (n instanceof ASTname_addr) {
- return buildNameAddr((ASTname_addr)n);
- }
- else {
- throw new IllegalStateException();
- }
- }
-
- private NamedMailbox buildNameAddr(ASTname_addr node) {
- ChildNodeIterator it = new ChildNodeIterator(node);
- Node n = it.nextNode();
- String name;
- if (n instanceof ASTphrase) {
- name = buildString((ASTphrase)n, false);
- }
- else {
- throw new IllegalStateException();
- }
-
- n = it.nextNode();
- if (n instanceof ASTangle_addr) {
- name = DecoderUtil.decodeEncodedWords(name);
- return new NamedMailbox(name, buildAngleAddr((ASTangle_addr) n));
- }
- else {
- throw new IllegalStateException();
- }
- }
-
- private Mailbox buildAngleAddr(ASTangle_addr node) {
- ChildNodeIterator it = new ChildNodeIterator(node);
- DomainList route = null;
- Node n = it.nextNode();
- if (n instanceof ASTroute) {
- route = buildRoute((ASTroute)n);
- n = it.nextNode();
- }
- else if (n instanceof ASTaddr_spec)
- ; // do nothing
- else
- throw new IllegalStateException();
-
- if (n instanceof ASTaddr_spec)
- return buildAddrSpec(route, (ASTaddr_spec)n);
- else
- throw new IllegalStateException();
- }
-
- private DomainList buildRoute(ASTroute node) {
- ArrayList<String> results = new ArrayList<String>(node.jjtGetNumChildren());
- ChildNodeIterator it = new ChildNodeIterator(node);
- while (it.hasNext()) {
- Node n = it.nextNode();
- if (n instanceof ASTdomain)
- results.add(buildString((ASTdomain)n, true));
- else
- throw new IllegalStateException();
- }
- return new DomainList(results, true);
- }
-
- private Mailbox buildAddrSpec(ASTaddr_spec node) {
- return buildAddrSpec(null, node);
- }
- private Mailbox buildAddrSpec(DomainList route, ASTaddr_spec node) {
- ChildNodeIterator it = new ChildNodeIterator(node);
- String localPart = buildString((ASTlocal_part)it.nextNode(), true);
- String domain = buildString((ASTdomain)it.nextNode(), true);
- return new Mailbox(route, localPart, domain);
- }
-
-
- private String buildString(SimpleNode node, boolean stripSpaces) {
- Token head = node.firstToken;
- Token tail = node.lastToken;
- StringBuffer out = new StringBuffer();
-
- while (head != tail) {
- out.append(head.image);
- head = head.next;
- if (!stripSpaces)
- addSpecials(out, head.specialToken);
- }
- out.append(tail.image);
-
- return out.toString();
- }
-
- private void addSpecials(StringBuffer out, Token specialToken) {
- if (specialToken != null) {
- addSpecials(out, specialToken.specialToken);
- out.append(specialToken.image);
- }
- }
-
- private static class ChildNodeIterator implements Iterator<Node> {
-
- private SimpleNode simpleNode;
- private int index;
- private int len;
-
- public ChildNodeIterator(SimpleNode simpleNode) {
- this.simpleNode = simpleNode;
- this.len = simpleNode.jjtGetNumChildren();
- this.index = 0;
- }
-
- public void remove() {
- throw new UnsupportedOperationException();
- }
-
- public boolean hasNext() {
- return index < len;
- }
-
- public Node next() {
- return nextNode();
- }
-
- public Node nextNode() {
- return simpleNode.jjtGetChild(index++);
- }
-
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/DomainList.java b/emailcommon/src/org/apache/james/mime4j/field/address/DomainList.java
deleted file mode 100644
index df5b4de27..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/DomainList.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-import java.util.ArrayList;
-
-/**
- * An immutable, random-access list of Strings (that
- * are supposedly domain names or domain literals).
- *
- *
- */
-public class DomainList {
- private ArrayList<String> domains;
-
- /**
- * @param domains An ArrayList that contains only String objects.
- * @param dontCopy true iff it is not possible for the domains ArrayList to be modified by someone else.
- */
- public DomainList(ArrayList<String> domains, boolean dontCopy) {
- if (domains != null)
- this.domains = (dontCopy ? domains : new ArrayList<String>(domains));
- else
- this.domains = new ArrayList<String>(0);
- }
-
- /**
- * The number of elements in this list.
- */
- public int size() {
- return domains.size();
- }
-
- /**
- * Gets the domain name or domain literal at the
- * specified index.
- * @throws IndexOutOfBoundsException If index is &lt; 0 or &gt;= size().
- */
- public String get(int index) {
- if (0 > index || size() <= index)
- throw new IndexOutOfBoundsException();
- return domains.get(index);
- }
-
- /**
- * Returns the list of domains formatted as a route
- * string (not including the trailing ':').
- */
- public String toRouteString() {
- StringBuffer out = new StringBuffer();
- for (int i = 0; i < domains.size(); i++) {
- out.append("@");
- out.append(get(i));
- if (i + 1 < domains.size())
- out.append(",");
- }
- return out.toString();
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/Group.java b/emailcommon/src/org/apache/james/mime4j/field/address/Group.java
deleted file mode 100644
index cca2b40b5..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/Group.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-import java.util.ArrayList;
-
-/**
- * A named group of zero or more mailboxes.
- *
- *
- */
-public class Group extends Address {
- private String name;
- private MailboxList mailboxList;
-
- /**
- * @param name The group name.
- * @param mailboxes The mailboxes in this group.
- */
- public Group(String name, MailboxList mailboxes) {
- this.name = name;
- this.mailboxList = mailboxes;
- }
-
- /**
- * Returns the group name.
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns the mailboxes in this group.
- */
- public MailboxList getMailboxes() {
- return mailboxList;
- }
-
- @Override
- public String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append(name);
- buf.append(":");
- for (int i = 0; i < mailboxList.size(); i++) {
- buf.append(mailboxList.get(i).toString());
- if (i + 1 < mailboxList.size())
- buf.append(",");
- }
- buf.append(";");
- return buf.toString();
- }
-
- @Override
- protected void doAddMailboxesTo(ArrayList<Address> results) {
- for (int i = 0; i < mailboxList.size(); i++)
- results.add(mailboxList.get(i));
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/Mailbox.java b/emailcommon/src/org/apache/james/mime4j/field/address/Mailbox.java
deleted file mode 100644
index c05a57f8e..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/Mailbox.java
+++ /dev/null
@@ -1,121 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-import java.util.ArrayList;
-
-/**
- * Represents a single e-mail address.
- *
- *
- */
-public class Mailbox extends Address {
- private DomainList route;
- private String localPart;
- private String domain;
-
- /**
- * Creates a mailbox without a route. Routes are obsolete.
- * @param localPart The part of the e-mail address to the left of the "@".
- * @param domain The part of the e-mail address to the right of the "@".
- */
- public Mailbox(String localPart, String domain) {
- this(null, localPart, domain);
- }
-
- /**
- * Creates a mailbox with a route. Routes are obsolete.
- * @param route The zero or more domains that make up the route. Can be null.
- * @param localPart The part of the e-mail address to the left of the "@".
- * @param domain The part of the e-mail address to the right of the "@".
- */
- public Mailbox(DomainList route, String localPart, String domain) {
- this.route = route;
- this.localPart = localPart;
- this.domain = domain;
- }
-
- /**
- * Returns the route list.
- */
- public DomainList getRoute() {
- return route;
- }
-
- /**
- * Returns the left part of the e-mail address
- * (before "@").
- */
- public String getLocalPart() {
- return localPart;
- }
-
- /**
- * Returns the right part of the e-mail address
- * (after "@").
- */
- public String getDomain() {
- return domain;
- }
-
- /**
- * Formats the address as a string, not including
- * the route.
- *
- * @see #getAddressString(boolean)
- */
- public String getAddressString() {
- return getAddressString(false);
- }
-
- /**
- * Note that this value may not be usable
- * for transport purposes, only display purposes.
- *
- * For example, if the unparsed address was
- *
- * <"Joe Cheng"@joecheng.com>
- *
- * this method would return
- *
- * <Joe Cheng@joecheng.com>
- *
- * which is not valid for transport; the local part
- * would need to be re-quoted.
- *
- * @param includeRoute true if the route should be included if it exists.
- */
- public String getAddressString(boolean includeRoute) {
- return "<" + (!includeRoute || route == null ? "" : route.toRouteString() + ":")
- + localPart
- + (domain == null ? "" : "@")
- + domain + ">";
- }
-
- @Override
- protected final void doAddMailboxesTo(ArrayList<Address> results) {
- results.add(this);
- }
-
- @Override
- public String toString() {
- return getAddressString();
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/MailboxList.java b/emailcommon/src/org/apache/james/mime4j/field/address/MailboxList.java
deleted file mode 100644
index 25337de9e..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/MailboxList.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-import java.util.ArrayList;
-
-/**
- * An immutable, random-access list of Mailbox objects.
- *
- *
- */
-public class MailboxList {
-
- private ArrayList<Address> mailboxes;
-
- /**
- * @param mailboxes An ArrayList that contains only Mailbox objects.
- * @param dontCopy true iff it is not possible for the mailboxes ArrayList to be modified by someone else.
- */
- public MailboxList(ArrayList<Address> mailboxes, boolean dontCopy) {
- if (mailboxes != null)
- this.mailboxes = (dontCopy ? mailboxes : new ArrayList<Address>(mailboxes));
- else
- this.mailboxes = new ArrayList<Address>(0);
- }
-
- /**
- * The number of elements in this list.
- */
- public int size() {
- return mailboxes.size();
- }
-
- /**
- * Gets an address.
- */
- public Mailbox get(int index) {
- if (0 > index || size() <= index)
- throw new IndexOutOfBoundsException();
- return (Mailbox)mailboxes.get(index);
- }
-
- /**
- * Dumps a representation of this mailbox list to
- * stdout, for debugging purposes.
- */
- public void print() {
- for (int i = 0; i < size(); i++) {
- Mailbox mailbox = get(i);
- System.out.println(mailbox.toString());
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/NamedMailbox.java b/emailcommon/src/org/apache/james/mime4j/field/address/NamedMailbox.java
deleted file mode 100644
index a54bd1dad..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/NamedMailbox.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address;
-
-/**
- * A Mailbox that has a name/description.
- *
- *
- */
-public class NamedMailbox extends Mailbox {
- private String name;
-
- /**
- * @see Mailbox#Mailbox(String, String)
- */
- public NamedMailbox(String name, String localPart, String domain) {
- super(localPart, domain);
- this.name = name;
- }
-
- /**
- * @see Mailbox#Mailbox(DomainList, String, String)
- */
- public NamedMailbox(String name, DomainList route, String localPart, String domain) {
- super(route, localPart, domain);
- this.name = name;
- }
-
- /**
- * Creates a named mailbox based on an unnamed mailbox.
- */
- public NamedMailbox(String name, Mailbox baseMailbox) {
- super(baseMailbox.getRoute(), baseMailbox.getLocalPart(), baseMailbox.getDomain());
- this.name = name;
- }
-
- /**
- * Returns the name of the mailbox.
- */
- public String getName() {
- return this.name;
- }
-
- /**
- * Same features (or problems) as Mailbox.getAddressString(boolean),
- * only more so.
- *
- * @see Mailbox#getAddressString(boolean)
- */
- @Override
- public String getAddressString(boolean includeRoute) {
- return (name == null ? "" : name + " ") + super.getAddressString(includeRoute);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddr_spec.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddr_spec.java
deleted file mode 100644
index 4d56d000b..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddr_spec.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTaddr_spec.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTaddr_spec extends SimpleNode {
- public ASTaddr_spec(int id) {
- super(id);
- }
-
- public ASTaddr_spec(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress.java
deleted file mode 100644
index 47bdeda8e..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTaddress.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTaddress extends SimpleNode {
- public ASTaddress(int id) {
- super(id);
- }
-
- public ASTaddress(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress_list.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress_list.java
deleted file mode 100644
index 737840e38..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTaddress_list.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTaddress_list.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTaddress_list extends SimpleNode {
- public ASTaddress_list(int id) {
- super(id);
- }
-
- public ASTaddress_list(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTangle_addr.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTangle_addr.java
deleted file mode 100644
index 8cb8f421f..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTangle_addr.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTangle_addr.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTangle_addr extends SimpleNode {
- public ASTangle_addr(int id) {
- super(id);
- }
-
- public ASTangle_addr(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTdomain.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTdomain.java
deleted file mode 100644
index b52664386..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTdomain.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTdomain.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTdomain extends SimpleNode {
- public ASTdomain(int id) {
- super(id);
- }
-
- public ASTdomain(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTgroup_body.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTgroup_body.java
deleted file mode 100644
index f6017b9fc..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTgroup_body.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTgroup_body.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTgroup_body extends SimpleNode {
- public ASTgroup_body(int id) {
- super(id);
- }
-
- public ASTgroup_body(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTlocal_part.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTlocal_part.java
deleted file mode 100644
index 5c244fa3e..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTlocal_part.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTlocal_part.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTlocal_part extends SimpleNode {
- public ASTlocal_part(int id) {
- super(id);
- }
-
- public ASTlocal_part(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTmailbox.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTmailbox.java
deleted file mode 100644
index aeb469da1..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTmailbox.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTmailbox.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTmailbox extends SimpleNode {
- public ASTmailbox(int id) {
- super(id);
- }
-
- public ASTmailbox(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTname_addr.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTname_addr.java
deleted file mode 100644
index 846c73167..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTname_addr.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTname_addr.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTname_addr extends SimpleNode {
- public ASTname_addr(int id) {
- super(id);
- }
-
- public ASTname_addr(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTphrase.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTphrase.java
deleted file mode 100644
index 7d711c529..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTphrase.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTphrase.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTphrase extends SimpleNode {
- public ASTphrase(int id) {
- super(id);
- }
-
- public ASTphrase(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTroute.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTroute.java
deleted file mode 100644
index 54ea11523..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ASTroute.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. ASTroute.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class ASTroute extends SimpleNode {
- public ASTroute(int id) {
- super(id);
- }
-
- public ASTroute(AddressListParser p, int id) {
- super(p, id);
- }
-
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.java
deleted file mode 100644
index dde2a0892..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.java
+++ /dev/null
@@ -1,977 +0,0 @@
-/* Generated By:JJTree&JavaCC: Do not edit this line. AddressListParser.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-public class AddressListParser/*@bgen(jjtree)*/implements AddressListParserTreeConstants, AddressListParserConstants {/*@bgen(jjtree)*/
- protected JJTAddressListParserState jjtree = new JJTAddressListParserState();public static void main(String args[]) throws ParseException {
- while (true) {
- try {
- AddressListParser parser = new AddressListParser(System.in);
- parser.parseLine();
- ((SimpleNode)parser.jjtree.rootNode()).dump("> ");
- } catch (Exception x) {
- x.printStackTrace();
- return;
- }
- }
- }
-
- private static void log(String msg) {
- System.out.print(msg);
- }
-
- public ASTaddress_list parse() throws ParseException {
- try {
- parseAll();
- return (ASTaddress_list)jjtree.rootNode();
- } catch (TokenMgrError tme) {
- throw new ParseException(tme.getMessage());
- }
- }
-
-
- void jjtreeOpenNodeScope(Node n) {
- ((SimpleNode)n).firstToken = getToken(1);
- }
-
- void jjtreeCloseNodeScope(Node n) {
- ((SimpleNode)n).lastToken = getToken(0);
- }
-
- final public void parseLine() throws ParseException {
- address_list();
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 1:
- jj_consume_token(1);
- break;
- default:
- jj_la1[0] = jj_gen;
- ;
- }
- jj_consume_token(2);
- }
-
- final public void parseAll() throws ParseException {
- address_list();
- jj_consume_token(0);
- }
-
- final public void address_list() throws ParseException {
- /*@bgen(jjtree) address_list */
- ASTaddress_list jjtn000 = new ASTaddress_list(JJTADDRESS_LIST);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 6:
- case DOTATOM:
- case QUOTEDSTRING:
- address();
- break;
- default:
- jj_la1[1] = jj_gen;
- ;
- }
- label_1:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 3:
- ;
- break;
- default:
- jj_la1[2] = jj_gen;
- break label_1;
- }
- jj_consume_token(3);
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 6:
- case DOTATOM:
- case QUOTEDSTRING:
- address();
- break;
- default:
- jj_la1[3] = jj_gen;
- ;
- }
- }
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void address() throws ParseException {
- /*@bgen(jjtree) address */
- ASTaddress jjtn000 = new ASTaddress(JJTADDRESS);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- if (jj_2_1(2147483647)) {
- addr_spec();
- } else {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 6:
- angle_addr();
- break;
- case DOTATOM:
- case QUOTEDSTRING:
- phrase();
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 4:
- group_body();
- break;
- case 6:
- angle_addr();
- break;
- default:
- jj_la1[4] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- break;
- default:
- jj_la1[5] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- }
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void mailbox() throws ParseException {
- /*@bgen(jjtree) mailbox */
- ASTmailbox jjtn000 = new ASTmailbox(JJTMAILBOX);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- if (jj_2_2(2147483647)) {
- addr_spec();
- } else {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 6:
- angle_addr();
- break;
- case DOTATOM:
- case QUOTEDSTRING:
- name_addr();
- break;
- default:
- jj_la1[6] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- }
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void name_addr() throws ParseException {
- /*@bgen(jjtree) name_addr */
- ASTname_addr jjtn000 = new ASTname_addr(JJTNAME_ADDR);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- phrase();
- angle_addr();
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void group_body() throws ParseException {
- /*@bgen(jjtree) group_body */
- ASTgroup_body jjtn000 = new ASTgroup_body(JJTGROUP_BODY);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- jj_consume_token(4);
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 6:
- case DOTATOM:
- case QUOTEDSTRING:
- mailbox();
- break;
- default:
- jj_la1[7] = jj_gen;
- ;
- }
- label_2:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 3:
- ;
- break;
- default:
- jj_la1[8] = jj_gen;
- break label_2;
- }
- jj_consume_token(3);
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 6:
- case DOTATOM:
- case QUOTEDSTRING:
- mailbox();
- break;
- default:
- jj_la1[9] = jj_gen;
- ;
- }
- }
- jj_consume_token(5);
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void angle_addr() throws ParseException {
- /*@bgen(jjtree) angle_addr */
- ASTangle_addr jjtn000 = new ASTangle_addr(JJTANGLE_ADDR);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- jj_consume_token(6);
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 8:
- route();
- break;
- default:
- jj_la1[10] = jj_gen;
- ;
- }
- addr_spec();
- jj_consume_token(7);
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void route() throws ParseException {
- /*@bgen(jjtree) route */
- ASTroute jjtn000 = new ASTroute(JJTROUTE);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- jj_consume_token(8);
- domain();
- label_3:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 3:
- case 8:
- ;
- break;
- default:
- jj_la1[11] = jj_gen;
- break label_3;
- }
- label_4:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 3:
- ;
- break;
- default:
- jj_la1[12] = jj_gen;
- break label_4;
- }
- jj_consume_token(3);
- }
- jj_consume_token(8);
- domain();
- }
- jj_consume_token(4);
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void phrase() throws ParseException {
- /*@bgen(jjtree) phrase */
- ASTphrase jjtn000 = new ASTphrase(JJTPHRASE);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- label_5:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case DOTATOM:
- jj_consume_token(DOTATOM);
- break;
- case QUOTEDSTRING:
- jj_consume_token(QUOTEDSTRING);
- break;
- default:
- jj_la1[13] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case DOTATOM:
- case QUOTEDSTRING:
- ;
- break;
- default:
- jj_la1[14] = jj_gen;
- break label_5;
- }
- }
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void addr_spec() throws ParseException {
- /*@bgen(jjtree) addr_spec */
- ASTaddr_spec jjtn000 = new ASTaddr_spec(JJTADDR_SPEC);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
- try {
- local_part();
- jj_consume_token(8);
- domain();
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- {if (true) throw (RuntimeException)jjte000;}
- }
- if (jjte000 instanceof ParseException) {
- {if (true) throw (ParseException)jjte000;}
- }
- {if (true) throw (Error)jjte000;}
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void local_part() throws ParseException {
- /*@bgen(jjtree) local_part */
- ASTlocal_part jjtn000 = new ASTlocal_part(JJTLOCAL_PART);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);Token t;
- try {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case DOTATOM:
- t = jj_consume_token(DOTATOM);
- break;
- case QUOTEDSTRING:
- t = jj_consume_token(QUOTEDSTRING);
- break;
- default:
- jj_la1[15] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- label_6:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 9:
- case DOTATOM:
- case QUOTEDSTRING:
- ;
- break;
- default:
- jj_la1[16] = jj_gen;
- break label_6;
- }
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 9:
- t = jj_consume_token(9);
- break;
- default:
- jj_la1[17] = jj_gen;
- ;
- }
- if (t.image.charAt(t.image.length() - 1) != '.' || t.kind == AddressListParserConstants.QUOTEDSTRING)
- {if (true) throw new ParseException("Words in local part must be separated by '.'");}
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case DOTATOM:
- t = jj_consume_token(DOTATOM);
- break;
- case QUOTEDSTRING:
- t = jj_consume_token(QUOTEDSTRING);
- break;
- default:
- jj_la1[18] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- }
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final public void domain() throws ParseException {
- /*@bgen(jjtree) domain */
- ASTdomain jjtn000 = new ASTdomain(JJTDOMAIN);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);Token t;
- try {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case DOTATOM:
- t = jj_consume_token(DOTATOM);
- label_7:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 9:
- case DOTATOM:
- ;
- break;
- default:
- jj_la1[19] = jj_gen;
- break label_7;
- }
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 9:
- t = jj_consume_token(9);
- break;
- default:
- jj_la1[20] = jj_gen;
- ;
- }
- if (t.image.charAt(t.image.length() - 1) != '.')
- {if (true) throw new ParseException("Atoms in domain names must be separated by '.'");}
- t = jj_consume_token(DOTATOM);
- }
- break;
- case DOMAINLITERAL:
- jj_consume_token(DOMAINLITERAL);
- break;
- default:
- jj_la1[21] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
- }
-
- final private boolean jj_2_1(int xla) {
- jj_la = xla; jj_lastpos = jj_scanpos = token;
- try { return !jj_3_1(); }
- catch(LookaheadSuccess ls) { return true; }
- finally { jj_save(0, xla); }
- }
-
- final private boolean jj_2_2(int xla) {
- jj_la = xla; jj_lastpos = jj_scanpos = token;
- try { return !jj_3_2(); }
- catch(LookaheadSuccess ls) { return true; }
- finally { jj_save(1, xla); }
- }
-
- final private boolean jj_3R_11() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_scan_token(9)) jj_scanpos = xsp;
- xsp = jj_scanpos;
- if (jj_scan_token(14)) {
- jj_scanpos = xsp;
- if (jj_scan_token(31)) return true;
- }
- return false;
- }
-
- final private boolean jj_3R_13() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_scan_token(9)) jj_scanpos = xsp;
- if (jj_scan_token(DOTATOM)) return true;
- return false;
- }
-
- final private boolean jj_3R_8() {
- if (jj_3R_9()) return true;
- if (jj_scan_token(8)) return true;
- if (jj_3R_10()) return true;
- return false;
- }
-
- final private boolean jj_3_1() {
- if (jj_3R_8()) return true;
- return false;
- }
-
- final private boolean jj_3R_12() {
- if (jj_scan_token(DOTATOM)) return true;
- Token xsp;
- while (true) {
- xsp = jj_scanpos;
- if (jj_3R_13()) { jj_scanpos = xsp; break; }
- }
- return false;
- }
-
- final private boolean jj_3R_10() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_3R_12()) {
- jj_scanpos = xsp;
- if (jj_scan_token(18)) return true;
- }
- return false;
- }
-
- final private boolean jj_3_2() {
- if (jj_3R_8()) return true;
- return false;
- }
-
- final private boolean jj_3R_9() {
- Token xsp;
- xsp = jj_scanpos;
- if (jj_scan_token(14)) {
- jj_scanpos = xsp;
- if (jj_scan_token(31)) return true;
- }
- while (true) {
- xsp = jj_scanpos;
- if (jj_3R_11()) { jj_scanpos = xsp; break; }
- }
- return false;
- }
-
- public AddressListParserTokenManager token_source;
- SimpleCharStream jj_input_stream;
- public Token token, jj_nt;
- private int jj_ntk;
- private Token jj_scanpos, jj_lastpos;
- private int jj_la;
- public boolean lookingAhead = false;
- private boolean jj_semLA;
- private int jj_gen;
- final private int[] jj_la1 = new int[22];
- static private int[] jj_la1_0;
- static private int[] jj_la1_1;
- static {
- jj_la1_0();
- jj_la1_1();
- }
- private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x2,0x80004040,0x8,0x80004040,0x50,0x80004040,0x80004040,0x80004040,0x8,0x80004040,0x100,0x108,0x8,0x80004000,0x80004000,0x80004000,0x80004200,0x200,0x80004000,0x4200,0x200,0x44000,};
- }
- private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,};
- }
- final private JJCalls[] jj_2_rtns = new JJCalls[2];
- private boolean jj_rescan = false;
- private int jj_gc = 0;
-
- public AddressListParser(java.io.InputStream stream) {
- this(stream, null);
- }
- public AddressListParser(java.io.InputStream stream, String encoding) {
- try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
- token_source = new AddressListParserTokenManager(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 22; i++) jj_la1[i] = -1;
- for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
- }
-
- public void ReInit(java.io.InputStream stream) {
- ReInit(stream, null);
- }
- public void ReInit(java.io.InputStream stream, String encoding) {
- try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
- token_source.ReInit(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jjtree.reset();
- jj_gen = 0;
- for (int i = 0; i < 22; i++) jj_la1[i] = -1;
- for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
- }
-
- public AddressListParser(java.io.Reader stream) {
- jj_input_stream = new SimpleCharStream(stream, 1, 1);
- token_source = new AddressListParserTokenManager(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 22; i++) jj_la1[i] = -1;
- for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
- }
-
- public void ReInit(java.io.Reader stream) {
- jj_input_stream.ReInit(stream, 1, 1);
- token_source.ReInit(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jjtree.reset();
- jj_gen = 0;
- for (int i = 0; i < 22; i++) jj_la1[i] = -1;
- for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
- }
-
- public AddressListParser(AddressListParserTokenManager tm) {
- token_source = tm;
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 22; i++) jj_la1[i] = -1;
- for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
- }
-
- public void ReInit(AddressListParserTokenManager tm) {
- token_source = tm;
- token = new Token();
- jj_ntk = -1;
- jjtree.reset();
- jj_gen = 0;
- for (int i = 0; i < 22; i++) jj_la1[i] = -1;
- for (int i = 0; i < jj_2_rtns.length; i++) jj_2_rtns[i] = new JJCalls();
- }
-
- final private Token jj_consume_token(int kind) throws ParseException {
- Token oldToken;
- if ((oldToken = token).next != null) token = token.next;
- else token = token.next = token_source.getNextToken();
- jj_ntk = -1;
- if (token.kind == kind) {
- jj_gen++;
- if (++jj_gc > 100) {
- jj_gc = 0;
- for (int i = 0; i < jj_2_rtns.length; i++) {
- JJCalls c = jj_2_rtns[i];
- while (c != null) {
- if (c.gen < jj_gen) c.first = null;
- c = c.next;
- }
- }
- }
- return token;
- }
- token = oldToken;
- jj_kind = kind;
- throw generateParseException();
- }
-
- static private final class LookaheadSuccess extends java.lang.Error { }
- final private LookaheadSuccess jj_ls = new LookaheadSuccess();
- final private boolean jj_scan_token(int kind) {
- if (jj_scanpos == jj_lastpos) {
- jj_la--;
- if (jj_scanpos.next == null) {
- jj_lastpos = jj_scanpos = jj_scanpos.next = token_source.getNextToken();
- } else {
- jj_lastpos = jj_scanpos = jj_scanpos.next;
- }
- } else {
- jj_scanpos = jj_scanpos.next;
- }
- if (jj_rescan) {
- int i = 0; Token tok = token;
- while (tok != null && tok != jj_scanpos) { i++; tok = tok.next; }
- if (tok != null) jj_add_error_token(kind, i);
- }
- if (jj_scanpos.kind != kind) return true;
- if (jj_la == 0 && jj_scanpos == jj_lastpos) throw jj_ls;
- return false;
- }
-
- final public Token getNextToken() {
- if (token.next != null) token = token.next;
- else token = token.next = token_source.getNextToken();
- jj_ntk = -1;
- jj_gen++;
- return token;
- }
-
- final public Token getToken(int index) {
- Token t = lookingAhead ? jj_scanpos : token;
- for (int i = 0; i < index; i++) {
- if (t.next != null) t = t.next;
- else t = t.next = token_source.getNextToken();
- }
- return t;
- }
-
- final private int jj_ntk() {
- if ((jj_nt=token.next) == null)
- return (jj_ntk = (token.next=token_source.getNextToken()).kind);
- else
- return (jj_ntk = jj_nt.kind);
- }
-
- private java.util.Vector<int[]> jj_expentries = new java.util.Vector<int[]>();
- private int[] jj_expentry;
- private int jj_kind = -1;
- private int[] jj_lasttokens = new int[100];
- private int jj_endpos;
-
- private void jj_add_error_token(int kind, int pos) {
- if (pos >= 100) return;
- if (pos == jj_endpos + 1) {
- jj_lasttokens[jj_endpos++] = kind;
- } else if (jj_endpos != 0) {
- jj_expentry = new int[jj_endpos];
- for (int i = 0; i < jj_endpos; i++) {
- jj_expentry[i] = jj_lasttokens[i];
- }
- boolean exists = false;
- for (java.util.Enumeration<int[]> e = jj_expentries.elements(); e.hasMoreElements();) {
- int[] oldentry = e.nextElement();
- if (oldentry.length == jj_expentry.length) {
- exists = true;
- for (int i = 0; i < jj_expentry.length; i++) {
- if (oldentry[i] != jj_expentry[i]) {
- exists = false;
- break;
- }
- }
- if (exists) break;
- }
- }
- if (!exists) jj_expentries.addElement(jj_expentry);
- if (pos != 0) jj_lasttokens[(jj_endpos = pos) - 1] = kind;
- }
- }
-
- public ParseException generateParseException() {
- jj_expentries.removeAllElements();
- boolean[] la1tokens = new boolean[34];
- for (int i = 0; i < 34; i++) {
- la1tokens[i] = false;
- }
- if (jj_kind >= 0) {
- la1tokens[jj_kind] = true;
- jj_kind = -1;
- }
- for (int i = 0; i < 22; i++) {
- if (jj_la1[i] == jj_gen) {
- for (int j = 0; j < 32; j++) {
- if ((jj_la1_0[i] & (1<<j)) != 0) {
- la1tokens[j] = true;
- }
- if ((jj_la1_1[i] & (1<<j)) != 0) {
- la1tokens[32+j] = true;
- }
- }
- }
- }
- for (int i = 0; i < 34; i++) {
- if (la1tokens[i]) {
- jj_expentry = new int[1];
- jj_expentry[0] = i;
- jj_expentries.addElement(jj_expentry);
- }
- }
- jj_endpos = 0;
- jj_rescan_token();
- jj_add_error_token(0, 0);
- int[][] exptokseq = new int[jj_expentries.size()][];
- for (int i = 0; i < jj_expentries.size(); i++) {
- exptokseq[i] = jj_expentries.elementAt(i);
- }
- return new ParseException(token, exptokseq, tokenImage);
- }
-
- final public void enable_tracing() {
- }
-
- final public void disable_tracing() {
- }
-
- final private void jj_rescan_token() {
- jj_rescan = true;
- for (int i = 0; i < 2; i++) {
- try {
- JJCalls p = jj_2_rtns[i];
- do {
- if (p.gen > jj_gen) {
- jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
- switch (i) {
- case 0: jj_3_1(); break;
- case 1: jj_3_2(); break;
- }
- }
- p = p.next;
- } while (p != null);
- } catch(LookaheadSuccess ls) { }
- }
- jj_rescan = false;
- }
-
- final private void jj_save(int index, int xla) {
- JJCalls p = jj_2_rtns[index];
- while (p.gen > jj_gen) {
- if (p.next == null) { p = p.next = new JJCalls(); break; }
- p = p.next;
- }
- p.gen = jj_gen + xla - jj_la; p.first = token; p.arg = xla;
- }
-
- static final class JJCalls {
- int gen;
- Token first;
- int arg;
- JJCalls next;
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.jj b/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.jj
deleted file mode 100644
index 685988634..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParser.jj
+++ /dev/null
@@ -1,595 +0,0 @@
-/*@bgen(jjtree) Generated By:JJTree: Do not edit this line. /Users/jason/Projects/apache-mime4j-0.3/target/generated-sources/jjtree/org/apache/james/mime4j/field/address/parser/AddressListParser.jj */
-/*@egen*//****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-
-/**
- * RFC2822 address list parser.
- *
- * Created 9/17/2004
- * by Joe Cheng <code@joecheng.com>
- */
-
-options {
- STATIC=false;
- LOOKAHEAD=1;
- //DEBUG_PARSER=true;
- //DEBUG_TOKEN_MANAGER=true;
-}
-
-PARSER_BEGIN(AddressListParser)
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-public class AddressListParser/*@bgen(jjtree)*/implements AddressListParserTreeConstants/*@egen*/ {/*@bgen(jjtree)*/
- protected JJTAddressListParserState jjtree = new JJTAddressListParserState();
-
-/*@egen*/
- public static void main(String args[]) throws ParseException {
- while (true) {
- try {
- AddressListParser parser = new AddressListParser(System.in);
- parser.parseLine();
- ((SimpleNode)parser.jjtree.rootNode()).dump("> ");
- } catch (Exception x) {
- x.printStackTrace();
- return;
- }
- }
- }
-
- private static void log(String msg) {
- System.out.print(msg);
- }
-
- public ASTaddress_list parse() throws ParseException {
- try {
- parseAll();
- return (ASTaddress_list)jjtree.rootNode();
- } catch (TokenMgrError tme) {
- throw new ParseException(tme.getMessage());
- }
- }
-
-
- void jjtreeOpenNodeScope(Node n) {
- ((SimpleNode)n).firstToken = getToken(1);
- }
-
- void jjtreeCloseNodeScope(Node n) {
- ((SimpleNode)n).lastToken = getToken(0);
- }
-}
-
-PARSER_END(AddressListParser)
-
-void parseLine() :
-{}
-{
- address_list() ["\r"] "\n"
-}
-
-void parseAll() :
-{}
-{
- address_list() <EOF>
-}
-
-void address_list() :
-{/*@bgen(jjtree) address_list */
- ASTaddress_list jjtn000 = new ASTaddress_list(JJTADDRESS_LIST);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) address_list */
- try {
-/*@egen*/
- [ address() ]
- (
- ","
- [ address() ]
- )*/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void address() :
-{/*@bgen(jjtree) address */
- ASTaddress jjtn000 = new ASTaddress(JJTADDRESS);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) address */
- try {
-/*@egen*/
- LOOKAHEAD(2147483647)
- addr_spec()
-| angle_addr()
-| ( phrase() (group_body() | angle_addr()) )/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void mailbox() :
-{/*@bgen(jjtree) mailbox */
- ASTmailbox jjtn000 = new ASTmailbox(JJTMAILBOX);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) mailbox */
- try {
-/*@egen*/
- LOOKAHEAD(2147483647)
- addr_spec()
-| angle_addr()
-| name_addr()/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void name_addr() :
-{/*@bgen(jjtree) name_addr */
- ASTname_addr jjtn000 = new ASTname_addr(JJTNAME_ADDR);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) name_addr */
- try {
-/*@egen*/
- phrase() angle_addr()/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void group_body() :
-{/*@bgen(jjtree) group_body */
- ASTgroup_body jjtn000 = new ASTgroup_body(JJTGROUP_BODY);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) group_body */
- try {
-/*@egen*/
- ":"
- [ mailbox() ]
- (
- ","
- [ mailbox() ]
- )*
- ";"/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void angle_addr() :
-{/*@bgen(jjtree) angle_addr */
- ASTangle_addr jjtn000 = new ASTangle_addr(JJTANGLE_ADDR);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) angle_addr */
- try {
-/*@egen*/
- "<" [ route() ] addr_spec() ">"/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void route() :
-{/*@bgen(jjtree) route */
- ASTroute jjtn000 = new ASTroute(JJTROUTE);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) route */
- try {
-/*@egen*/
- "@" domain() ( (",")* "@" domain() )* ":"/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void phrase() :
-{/*@bgen(jjtree) phrase */
- ASTphrase jjtn000 = new ASTphrase(JJTPHRASE);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) phrase */
-try {
-/*@egen*/
-( <DOTATOM>
-| <QUOTEDSTRING>
-)+/*@bgen(jjtree)*/
-} finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
-}
-/*@egen*/
-}
-
-void addr_spec() :
-{/*@bgen(jjtree) addr_spec */
- ASTaddr_spec jjtn000 = new ASTaddr_spec(JJTADDR_SPEC);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/}
-{/*@bgen(jjtree) addr_spec */
- try {
-/*@egen*/
- ( local_part() "@" domain() )/*@bgen(jjtree)*/
- } catch (Throwable jjte000) {
- if (jjtc000) {
- jjtree.clearNodeScope(jjtn000);
- jjtc000 = false;
- } else {
- jjtree.popNode();
- }
- if (jjte000 instanceof RuntimeException) {
- throw (RuntimeException)jjte000;
- }
- if (jjte000 instanceof ParseException) {
- throw (ParseException)jjte000;
- }
- throw (Error)jjte000;
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void local_part() :
-{/*@bgen(jjtree) local_part */
- ASTlocal_part jjtn000 = new ASTlocal_part(JJTLOCAL_PART);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/ Token t; }
-{/*@bgen(jjtree) local_part */
- try {
-/*@egen*/
- ( t=<DOTATOM> | t=<QUOTEDSTRING> )
- ( [t="."]
- {
- if (t.image.charAt(t.image.length() - 1) != '.' || t.kind == AddressListParserConstants.QUOTEDSTRING)
- throw new ParseException("Words in local part must be separated by '.'");
- }
- ( t=<DOTATOM> | t=<QUOTEDSTRING> )
- )*/*@bgen(jjtree)*/
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-void domain() :
-{/*@bgen(jjtree) domain */
- ASTdomain jjtn000 = new ASTdomain(JJTDOMAIN);
- boolean jjtc000 = true;
- jjtree.openNodeScope(jjtn000);
- jjtreeOpenNodeScope(jjtn000);
-/*@egen*/ Token t; }
-{/*@bgen(jjtree) domain */
- try {
-/*@egen*/
- ( t=<DOTATOM>
- ( [t="."]
- {
- if (t.image.charAt(t.image.length() - 1) != '.')
- throw new ParseException("Atoms in domain names must be separated by '.'");
- }
- t=<DOTATOM>
- )*
- )
-| <DOMAINLITERAL>/*@bgen(jjtree)*/
- } finally {
- if (jjtc000) {
- jjtree.closeNodeScope(jjtn000, true);
- jjtreeCloseNodeScope(jjtn000);
- }
- }
-/*@egen*/
-}
-
-SPECIAL_TOKEN :
-{
- < WS: ( [" ", "\t"] )+ >
-}
-
-TOKEN :
-{
- < #ALPHA: ["a" - "z", "A" - "Z"] >
-| < #DIGIT: ["0" - "9"] >
-| < #ATEXT: ( <ALPHA> | <DIGIT>
- | "!" | "#" | "$" | "%"
- | "&" | "'" | "*" | "+"
- | "-" | "/" | "=" | "?"
- | "^" | "_" | "`" | "{"
- | "|" | "}" | "~"
- )>
-| < DOTATOM: <ATEXT> ( <ATEXT> | "." )* >
-}
-
-TOKEN_MGR_DECLS :
-{
- // Keeps track of how many levels of comment nesting
- // we've encountered. This is only used when the 2nd
- // level is reached, for example ((this)), not (this).
- // This is because the outermost level must be treated
- // specially anyway, because the outermost ")" has a
- // different token type than inner ")" instances.
- static int commentNest;
-}
-
-MORE :
-{
- // domain literal
- "[" : INDOMAINLITERAL
-}
-
-<INDOMAINLITERAL>
-MORE :
-{
- < <QUOTEDPAIR>> { image.deleteCharAt(image.length() - 2); }
-| < ~["[", "]", "\\"] >
-}
-
-<INDOMAINLITERAL>
-TOKEN :
-{
- < DOMAINLITERAL: "]" > { matchedToken.image = image.toString(); }: DEFAULT
-}
-
-MORE :
-{
- // starts a comment
- "(" : INCOMMENT
-}
-
-<INCOMMENT>
-SKIP :
-{
- // ends a comment
- < COMMENT: ")" > : DEFAULT
- // if this is ever changed to not be a SKIP, need
- // to make sure matchedToken.token = token.toString()
- // is called.
-}
-
-<INCOMMENT>
-MORE :
-{
- < <QUOTEDPAIR>> { image.deleteCharAt(image.length() - 2); }
-| "(" { commentNest = 1; } : NESTED_COMMENT
-| < <ANY>>
-}
-
-<NESTED_COMMENT>
-MORE :
-{
- < <QUOTEDPAIR>> { image.deleteCharAt(image.length() - 2); }
-| "(" { ++commentNest; }
-| ")" { --commentNest; if (commentNest == 0) SwitchTo(INCOMMENT); }
-| < <ANY>>
-}
-
-
-// QUOTED STRINGS
-
-MORE :
-{
- "\"" { image.deleteCharAt(image.length() - 1); } : INQUOTEDSTRING
-}
-
-<INQUOTEDSTRING>
-MORE :
-{
- < <QUOTEDPAIR>> { image.deleteCharAt(image.length() - 2); }
-| < (~["\"", "\\"])+ >
-}
-
-<INQUOTEDSTRING>
-TOKEN :
-{
- < QUOTEDSTRING: "\"" > { matchedToken.image = image.substring(0, image.length() - 1); } : DEFAULT
-}
-
-// GLOBALS
-
-<*>
-TOKEN :
-{
- < #QUOTEDPAIR: "\\" <ANY> >
-| < #ANY: ~[] >
-}
-
-// ERROR!
-/*
-
-<*>
-TOKEN :
-{
- < UNEXPECTED_CHAR: <ANY> >
-}
-
-*/ \ No newline at end of file
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserConstants.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserConstants.java
deleted file mode 100644
index a21ad35db..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserConstants.java
+++ /dev/null
@@ -1,76 +0,0 @@
-/* Generated By:JJTree&JavaCC: Do not edit this line. AddressListParserConstants.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-public interface AddressListParserConstants {
-
- int EOF = 0;
- int WS = 10;
- int ALPHA = 11;
- int DIGIT = 12;
- int ATEXT = 13;
- int DOTATOM = 14;
- int DOMAINLITERAL = 18;
- int COMMENT = 20;
- int QUOTEDSTRING = 31;
- int QUOTEDPAIR = 32;
- int ANY = 33;
-
- int DEFAULT = 0;
- int INDOMAINLITERAL = 1;
- int INCOMMENT = 2;
- int NESTED_COMMENT = 3;
- int INQUOTEDSTRING = 4;
-
- String[] tokenImage = {
- "<EOF>",
- "\"\\r\"",
- "\"\\n\"",
- "\",\"",
- "\":\"",
- "\";\"",
- "\"<\"",
- "\">\"",
- "\"@\"",
- "\".\"",
- "<WS>",
- "<ALPHA>",
- "<DIGIT>",
- "<ATEXT>",
- "<DOTATOM>",
- "\"[\"",
- "<token of kind 16>",
- "<token of kind 17>",
- "\"]\"",
- "\"(\"",
- "\")\"",
- "<token of kind 21>",
- "\"(\"",
- "<token of kind 23>",
- "<token of kind 24>",
- "\"(\"",
- "\")\"",
- "<token of kind 27>",
- "\"\\\"\"",
- "<token of kind 29>",
- "<token of kind 30>",
- "\"\\\"\"",
- "<QUOTEDPAIR>",
- "<ANY>",
- };
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTokenManager.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTokenManager.java
deleted file mode 100644
index df8974a3b..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTokenManager.java
+++ /dev/null
@@ -1,1009 +0,0 @@
-/* Generated By:JJTree&JavaCC: Do not edit this line. AddressListParserTokenManager.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-public class AddressListParserTokenManager implements AddressListParserConstants
-{
- // Keeps track of how many levels of comment nesting
- // we've encountered. This is only used when the 2nd
- // level is reached, for example ((this)), not (this).
- // This is because the outermost level must be treated
- // specially anyway, because the outermost ")" has a
- // different token type than inner ")" instances.
- static int commentNest;
- public java.io.PrintStream debugStream = System.out;
- public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }
-private final int jjStopStringLiteralDfa_0(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_0(int pos, long active0)
-{
- return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1);
-}
-private final int jjStopAtPos(int pos, int kind)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- return pos + 1;
-}
-private final int jjStartNfaWithStates_0(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_0(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_0()
-{
- switch(curChar)
- {
- case 10:
- return jjStopAtPos(0, 2);
- case 13:
- return jjStopAtPos(0, 1);
- case 34:
- return jjStopAtPos(0, 28);
- case 40:
- return jjStopAtPos(0, 19);
- case 44:
- return jjStopAtPos(0, 3);
- case 46:
- return jjStopAtPos(0, 9);
- case 58:
- return jjStopAtPos(0, 4);
- case 59:
- return jjStopAtPos(0, 5);
- case 60:
- return jjStopAtPos(0, 6);
- case 62:
- return jjStopAtPos(0, 7);
- case 64:
- return jjStopAtPos(0, 8);
- case 91:
- return jjStopAtPos(0, 15);
- default :
- return jjMoveNfa_0(1, 0);
- }
-}
-private final void jjCheckNAdd(int state)
-{
- if (jjrounds[state] != jjround)
- {
- jjstateSet[jjnewStateCnt++] = state;
- jjrounds[state] = jjround;
- }
-}
-private final void jjAddStates(int start, int end)
-{
- do {
- jjstateSet[jjnewStateCnt++] = jjnextStates[start];
- } while (start++ != end);
-}
-private final void jjCheckNAddTwoStates(int state1, int state2)
-{
- jjCheckNAdd(state1);
- jjCheckNAdd(state2);
-}
-private final void jjCheckNAddStates(int start, int end)
-{
- do {
- jjCheckNAdd(jjnextStates[start]);
- } while (start++ != end);
-}
-private final void jjCheckNAddStates(int start)
-{
- jjCheckNAdd(jjnextStates[start]);
- jjCheckNAdd(jjnextStates[start + 1]);
-}
-private final int jjMoveNfa_0(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 1:
- if ((0xa3ffacfa00000000L & l) != 0L)
- {
- if (kind > 14)
- kind = 14;
- jjCheckNAdd(2);
- }
- else if ((0x100000200L & l) != 0L)
- {
- if (kind > 10)
- kind = 10;
- jjCheckNAdd(0);
- }
- break;
- case 0:
- if ((0x100000200L & l) == 0L)
- break;
- kind = 10;
- jjCheckNAdd(0);
- break;
- case 2:
- if ((0xa3ffecfa00000000L & l) == 0L)
- break;
- if (kind > 14)
- kind = 14;
- jjCheckNAdd(2);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 1:
- case 2:
- if ((0x7fffffffc7fffffeL & l) == 0L)
- break;
- if (kind > 14)
- kind = 14;
- jjCheckNAdd(2);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_2(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_2(int pos, long active0)
-{
- return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_2(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_2(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_2()
-{
- switch(curChar)
- {
- case 40:
- return jjStopAtPos(0, 22);
- case 41:
- return jjStopAtPos(0, 20);
- default :
- return jjMoveNfa_2(0, 0);
- }
-}
-static final long[] jjbitVec0 = {
- 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
-};
-private final int jjMoveNfa_2(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 23)
- kind = 23;
- break;
- case 1:
- if (kind > 21)
- kind = 21;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 23)
- kind = 23;
- if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 21)
- kind = 21;
- break;
- case 2:
- if (kind > 23)
- kind = 23;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 23)
- kind = 23;
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 21)
- kind = 21;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_4(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_4(int pos, long active0)
-{
- return jjMoveNfa_4(jjStopStringLiteralDfa_4(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_4(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_4(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_4()
-{
- switch(curChar)
- {
- case 34:
- return jjStopAtPos(0, 31);
- default :
- return jjMoveNfa_4(0, 0);
- }
-}
-private final int jjMoveNfa_4(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- case 2:
- if ((0xfffffffbffffffffL & l) == 0L)
- break;
- if (kind > 30)
- kind = 30;
- jjCheckNAdd(2);
- break;
- case 1:
- if (kind > 29)
- kind = 29;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((0xffffffffefffffffL & l) != 0L)
- {
- if (kind > 30)
- kind = 30;
- jjCheckNAdd(2);
- }
- else if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 29)
- kind = 29;
- break;
- case 2:
- if ((0xffffffffefffffffL & l) == 0L)
- break;
- if (kind > 30)
- kind = 30;
- jjCheckNAdd(2);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- case 2:
- if ((jjbitVec0[i2] & l2) == 0L)
- break;
- if (kind > 30)
- kind = 30;
- jjCheckNAdd(2);
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 29)
- kind = 29;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_3(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_3(int pos, long active0)
-{
- return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_3(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_3(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_3()
-{
- switch(curChar)
- {
- case 40:
- return jjStopAtPos(0, 25);
- case 41:
- return jjStopAtPos(0, 26);
- default :
- return jjMoveNfa_3(0, 0);
- }
-}
-private final int jjMoveNfa_3(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 27)
- kind = 27;
- break;
- case 1:
- if (kind > 24)
- kind = 24;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 27)
- kind = 27;
- if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 24)
- kind = 24;
- break;
- case 2:
- if (kind > 27)
- kind = 27;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 27)
- kind = 27;
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 24)
- kind = 24;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_1(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_1(int pos, long active0)
-{
- return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_1(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_1(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_1()
-{
- switch(curChar)
- {
- case 93:
- return jjStopAtPos(0, 18);
- default :
- return jjMoveNfa_1(0, 0);
- }
-}
-private final int jjMoveNfa_1(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 17)
- kind = 17;
- break;
- case 1:
- if (kind > 16)
- kind = 16;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((0xffffffffc7ffffffL & l) != 0L)
- {
- if (kind > 17)
- kind = 17;
- }
- else if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 16)
- kind = 16;
- break;
- case 2:
- if ((0xffffffffc7ffffffL & l) != 0L && kind > 17)
- kind = 17;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 17)
- kind = 17;
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 16)
- kind = 16;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-static final int[] jjnextStates = {
-};
-public static final String[] jjstrLiteralImages = {
-"", "\15", "\12", "\54", "\72", "\73", "\74", "\76", "\100", "\56", null, null,
-null, null, null, null, null, null, null, null, null, null, null, null, null, null,
-null, null, null, null, null, null, null, null, };
-public static final String[] lexStateNames = {
- "DEFAULT",
- "INDOMAINLITERAL",
- "INCOMMENT",
- "NESTED_COMMENT",
- "INQUOTEDSTRING",
-};
-public static final int[] jjnewLexState = {
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, 0, 2, 0, -1, 3, -1, -1,
- -1, -1, -1, 4, -1, -1, 0, -1, -1,
-};
-static final long[] jjtoToken = {
- 0x800443ffL,
-};
-static final long[] jjtoSkip = {
- 0x100400L,
-};
-static final long[] jjtoSpecial = {
- 0x400L,
-};
-static final long[] jjtoMore = {
- 0x7feb8000L,
-};
-protected SimpleCharStream input_stream;
-private final int[] jjrounds = new int[3];
-private final int[] jjstateSet = new int[6];
-StringBuffer image;
-int jjimageLen;
-int lengthOfMatch;
-protected char curChar;
-public AddressListParserTokenManager(SimpleCharStream stream){
- if (SimpleCharStream.staticFlag)
- throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
- input_stream = stream;
-}
-public AddressListParserTokenManager(SimpleCharStream stream, int lexState){
- this(stream);
- SwitchTo(lexState);
-}
-public void ReInit(SimpleCharStream stream)
-{
- jjmatchedPos = jjnewStateCnt = 0;
- curLexState = defaultLexState;
- input_stream = stream;
- ReInitRounds();
-}
-private final void ReInitRounds()
-{
- int i;
- jjround = 0x80000001;
- for (i = 3; i-- > 0;)
- jjrounds[i] = 0x80000000;
-}
-public void ReInit(SimpleCharStream stream, int lexState)
-{
- ReInit(stream);
- SwitchTo(lexState);
-}
-public void SwitchTo(int lexState)
-{
- if (lexState >= 5 || lexState < 0)
- throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
- else
- curLexState = lexState;
-}
-
-protected Token jjFillToken()
-{
- Token t = Token.newToken(jjmatchedKind);
- t.kind = jjmatchedKind;
- String im = jjstrLiteralImages[jjmatchedKind];
- t.image = (im == null) ? input_stream.GetImage() : im;
- t.beginLine = input_stream.getBeginLine();
- t.beginColumn = input_stream.getBeginColumn();
- t.endLine = input_stream.getEndLine();
- t.endColumn = input_stream.getEndColumn();
- return t;
-}
-
-int curLexState = 0;
-int defaultLexState = 0;
-int jjnewStateCnt;
-int jjround;
-int jjmatchedPos;
-int jjmatchedKind;
-
-public Token getNextToken()
-{
- int kind;
- Token specialToken = null;
- Token matchedToken;
- int curPos = 0;
-
- EOFLoop :
- for (;;)
- {
- try
- {
- curChar = input_stream.BeginToken();
- }
- catch(java.io.IOException e)
- {
- jjmatchedKind = 0;
- matchedToken = jjFillToken();
- matchedToken.specialToken = specialToken;
- return matchedToken;
- }
- image = null;
- jjimageLen = 0;
-
- for (;;)
- {
- switch(curLexState)
- {
- case 0:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_0();
- break;
- case 1:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_1();
- break;
- case 2:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_2();
- break;
- case 3:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_3();
- break;
- case 4:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_4();
- break;
- }
- if (jjmatchedKind != 0x7fffffff)
- {
- if (jjmatchedPos + 1 < curPos)
- input_stream.backup(curPos - jjmatchedPos - 1);
- if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- matchedToken = jjFillToken();
- matchedToken.specialToken = specialToken;
- TokenLexicalActions(matchedToken);
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- return matchedToken;
- }
- else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- matchedToken = jjFillToken();
- if (specialToken == null)
- specialToken = matchedToken;
- else
- {
- matchedToken.specialToken = specialToken;
- specialToken = (specialToken.next = matchedToken);
- }
- }
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- continue EOFLoop;
- }
- MoreLexicalActions();
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- curPos = 0;
- jjmatchedKind = 0x7fffffff;
- try {
- curChar = input_stream.readChar();
- continue;
- }
- catch (java.io.IOException e1) { }
- }
- int error_line = input_stream.getEndLine();
- int error_column = input_stream.getEndColumn();
- String error_after = null;
- boolean EOFSeen = false;
- try { input_stream.readChar(); input_stream.backup(1); }
- catch (java.io.IOException e1) {
- EOFSeen = true;
- error_after = curPos <= 1 ? "" : input_stream.GetImage();
- if (curChar == '\n' || curChar == '\r') {
- error_line++;
- error_column = 0;
- }
- else
- error_column++;
- }
- if (!EOFSeen) {
- input_stream.backup(1);
- error_after = curPos <= 1 ? "" : input_stream.GetImage();
- }
- throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
- }
- }
-}
-
-void MoreLexicalActions()
-{
- jjimageLen += (lengthOfMatch = jjmatchedPos + 1);
- switch(jjmatchedKind)
- {
- case 16 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- case 21 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- case 22 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- commentNest = 1;
- break;
- case 24 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- case 25 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- ++commentNest;
- break;
- case 26 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- --commentNest; if (commentNest == 0) SwitchTo(INCOMMENT);
- break;
- case 28 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 1);
- break;
- case 29 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- default :
- break;
- }
-}
-void TokenLexicalActions(Token matchedToken)
-{
- switch(jjmatchedKind)
- {
- case 18 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));
- matchedToken.image = image.toString();
- break;
- case 31 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));
- matchedToken.image = image.substring(0, image.length() - 1);
- break;
- default :
- break;
- }
-}
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTreeConstants.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTreeConstants.java
deleted file mode 100644
index 5987f19d8..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserTreeConstants.java
+++ /dev/null
@@ -1,35 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. /Users/jason/Projects/apache-mime4j-0.3/target/generated-sources/jjtree/org/apache/james/mime4j/field/address/parser/AddressListParserTreeConstants.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public interface AddressListParserTreeConstants
-{
- public int JJTVOID = 0;
- public int JJTADDRESS_LIST = 1;
- public int JJTADDRESS = 2;
- public int JJTMAILBOX = 3;
- public int JJTNAME_ADDR = 4;
- public int JJTGROUP_BODY = 5;
- public int JJTANGLE_ADDR = 6;
- public int JJTROUTE = 7;
- public int JJTPHRASE = 8;
- public int JJTADDR_SPEC = 9;
- public int JJTLOCAL_PART = 10;
- public int JJTDOMAIN = 11;
-
-
- public String[] jjtNodeName = {
- "void",
- "address_list",
- "address",
- "mailbox",
- "name_addr",
- "group_body",
- "angle_addr",
- "route",
- "phrase",
- "addr_spec",
- "local_part",
- "domain",
- };
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserVisitor.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserVisitor.java
deleted file mode 100644
index 8ec2fe7d2..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/AddressListParserVisitor.java
+++ /dev/null
@@ -1,19 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. /Users/jason/Projects/apache-mime4j-0.3/target/generated-sources/jjtree/org/apache/james/mime4j/field/address/parser/AddressListParserVisitor.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public interface AddressListParserVisitor
-{
- public Object visit(SimpleNode node, Object data);
- public Object visit(ASTaddress_list node, Object data);
- public Object visit(ASTaddress node, Object data);
- public Object visit(ASTmailbox node, Object data);
- public Object visit(ASTname_addr node, Object data);
- public Object visit(ASTgroup_body node, Object data);
- public Object visit(ASTangle_addr node, Object data);
- public Object visit(ASTroute node, Object data);
- public Object visit(ASTphrase node, Object data);
- public Object visit(ASTaddr_spec node, Object data);
- public Object visit(ASTlocal_part node, Object data);
- public Object visit(ASTdomain node, Object data);
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/BaseNode.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/BaseNode.java
deleted file mode 100644
index 42fe3db0c..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/BaseNode.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.address.parser;
-
-import org.apache.james.mime4j.field.address.parser.Node;
-import org.apache.james.mime4j.field.address.parser.Token;
-
-public abstract class BaseNode implements Node {
-
- public Token firstToken;
- public Token lastToken;
-
-} \ No newline at end of file
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/JJTAddressListParserState.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/JJTAddressListParserState.java
deleted file mode 100644
index 08b5c5bef..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/JJTAddressListParserState.java
+++ /dev/null
@@ -1,123 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. /Users/jason/Projects/apache-mime4j-0.3/target/generated-sources/jjtree/org/apache/james/mime4j/field/address/parser/JJTAddressListParserState.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-class JJTAddressListParserState {
- private java.util.Stack<Node> nodes;
- private java.util.Stack<Integer> marks;
-
- private int sp; // number of nodes on stack
- private int mk; // current mark
- private boolean node_created;
-
- JJTAddressListParserState() {
- nodes = new java.util.Stack<Node>();
- marks = new java.util.Stack<Integer>();
- sp = 0;
- mk = 0;
- }
-
- /* Determines whether the current node was actually closed and
- pushed. This should only be called in the final user action of a
- node scope. */
- boolean nodeCreated() {
- return node_created;
- }
-
- /* Call this to reinitialize the node stack. It is called
- automatically by the parser's ReInit() method. */
- void reset() {
- nodes.removeAllElements();
- marks.removeAllElements();
- sp = 0;
- mk = 0;
- }
-
- /* Returns the root node of the AST. It only makes sense to call
- this after a successful parse. */
- Node rootNode() {
- return nodes.elementAt(0);
- }
-
- /* Pushes a node on to the stack. */
- void pushNode(Node n) {
- nodes.push(n);
- ++sp;
- }
-
- /* Returns the node on the top of the stack, and remove it from the
- stack. */
- Node popNode() {
- if (--sp < mk) {
- mk = marks.pop().intValue();
- }
- return nodes.pop();
- }
-
- /* Returns the node currently on the top of the stack. */
- Node peekNode() {
- return nodes.peek();
- }
-
- /* Returns the number of children on the stack in the current node
- scope. */
- int nodeArity() {
- return sp - mk;
- }
-
-
- void clearNodeScope(Node n) {
- while (sp > mk) {
- popNode();
- }
- mk = marks.pop().intValue();
- }
-
-
- void openNodeScope(Node n) {
- marks.push(new Integer(mk));
- mk = sp;
- n.jjtOpen();
- }
-
-
- /* A definite node is constructed from a specified number of
- children. That number of nodes are popped from the stack and
- made the children of the definite node. Then the definite node
- is pushed on to the stack. */
- void closeNodeScope(Node n, int num) {
- mk = marks.pop().intValue();
- while (num-- > 0) {
- Node c = popNode();
- c.jjtSetParent(n);
- n.jjtAddChild(c, num);
- }
- n.jjtClose();
- pushNode(n);
- node_created = true;
- }
-
-
- /* A conditional node is constructed if its condition is true. All
- the nodes that have been pushed since the node was opened are
- made children of the the conditional node, which is then pushed
- on to the stack. If the condition is false the node is not
- constructed and they are left on the stack. */
- void closeNodeScope(Node n, boolean condition) {
- if (condition) {
- int a = nodeArity();
- mk = marks.pop().intValue();
- while (a-- > 0) {
- Node c = popNode();
- c.jjtSetParent(n);
- n.jjtAddChild(c, a);
- }
- n.jjtClose();
- pushNode(n);
- node_created = true;
- } else {
- mk = marks.pop().intValue();
- node_created = false;
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/Node.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/Node.java
deleted file mode 100644
index 158892016..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/Node.java
+++ /dev/null
@@ -1,37 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. Node.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-/* All AST nodes must implement this interface. It provides basic
- machinery for constructing the parent and child relationships
- between nodes. */
-
-public interface Node {
-
- /** This method is called after the node has been made the current
- node. It indicates that child nodes can now be added to it. */
- public void jjtOpen();
-
- /** This method is called after all the child nodes have been
- added. */
- public void jjtClose();
-
- /** This pair of methods are used to inform the node of its
- parent. */
- public void jjtSetParent(Node n);
- public Node jjtGetParent();
-
- /** This method tells the node to add its argument to the node's
- list of children. */
- public void jjtAddChild(Node n, int i);
-
- /** This method returns a child node. The children are numbered
- from zero, left to right. */
- public Node jjtGetChild(int i);
-
- /** Return the number of children the node has. */
- public int jjtGetNumChildren();
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data);
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ParseException.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/ParseException.java
deleted file mode 100644
index 939c6cfed..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/ParseException.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-/**
- * This exception is thrown when parse errors are encountered.
- * You can explicitly create objects of this exception type by
- * calling the method generateParseException in the generated
- * parser.
- *
- * You can modify this class to customize your error reporting
- * mechanisms so long as you retain the public fields.
- */
-public class ParseException extends Exception {
-
- /**
- * This constructor is used by the method "generateParseException"
- * in the generated parser. Calling this constructor generates
- * a new object of this type with the fields "currentToken",
- * "expectedTokenSequences", and "tokenImage" set. The boolean
- * flag "specialConstructor" is also set to true to indicate that
- * this constructor was used to create this object.
- * This constructor calls its super class with the empty string
- * to force the "toString" method of parent class "Throwable" to
- * print the error message in the form:
- * ParseException: <result of getMessage>
- */
- public ParseException(Token currentTokenVal,
- int[][] expectedTokenSequencesVal,
- String[] tokenImageVal
- )
- {
- super("");
- specialConstructor = true;
- currentToken = currentTokenVal;
- expectedTokenSequences = expectedTokenSequencesVal;
- tokenImage = tokenImageVal;
- }
-
- /**
- * The following constructors are for use by you for whatever
- * purpose you can think of. Constructing the exception in this
- * manner makes the exception behave in the normal way - i.e., as
- * documented in the class "Throwable". The fields "errorToken",
- * "expectedTokenSequences", and "tokenImage" do not contain
- * relevant information. The JavaCC generated code does not use
- * these constructors.
- */
-
- public ParseException() {
- super();
- specialConstructor = false;
- }
-
- public ParseException(String message) {
- super(message);
- specialConstructor = false;
- }
-
- /**
- * This variable determines which constructor was used to create
- * this object and thereby affects the semantics of the
- * "getMessage" method (see below).
- */
- protected boolean specialConstructor;
-
- /**
- * This is the last token that has been consumed successfully. If
- * this object has been created due to a parse error, the token
- * followng this token will (therefore) be the first error token.
- */
- public Token currentToken;
-
- /**
- * Each entry in this array is an array of integers. Each array
- * of integers represents a sequence of tokens (by their ordinal
- * values) that is expected at this point of the parse.
- */
- public int[][] expectedTokenSequences;
-
- /**
- * This is a reference to the "tokenImage" array of the generated
- * parser within which the parse error occurred. This array is
- * defined in the generated ...Constants interface.
- */
- public String[] tokenImage;
-
- /**
- * This method has the standard behavior when this object has been
- * created using the standard constructors. Otherwise, it uses
- * "currentToken" and "expectedTokenSequences" to generate a parse
- * error message and returns it. If this object has been created
- * due to a parse error, and you do not catch it (it gets thrown
- * from the parser), then this method is called during the printing
- * of the final stack trace, and hence the correct error message
- * gets displayed.
- */
- public String getMessage() {
- if (!specialConstructor) {
- return super.getMessage();
- }
- StringBuffer expected = new StringBuffer();
- int maxSize = 0;
- for (int i = 0; i < expectedTokenSequences.length; i++) {
- if (maxSize < expectedTokenSequences[i].length) {
- maxSize = expectedTokenSequences[i].length;
- }
- for (int j = 0; j < expectedTokenSequences[i].length; j++) {
- expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" ");
- }
- if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
- expected.append("...");
- }
- expected.append(eol).append(" ");
- }
- String retval = "Encountered \"";
- Token tok = currentToken.next;
- for (int i = 0; i < maxSize; i++) {
- if (i != 0) retval += " ";
- if (tok.kind == 0) {
- retval += tokenImage[0];
- break;
- }
- retval += add_escapes(tok.image);
- tok = tok.next;
- }
- retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
- retval += "." + eol;
- if (expectedTokenSequences.length == 1) {
- retval += "Was expecting:" + eol + " ";
- } else {
- retval += "Was expecting one of:" + eol + " ";
- }
- retval += expected.toString();
- return retval;
- }
-
- /**
- * The end of line string for this machine.
- */
- protected String eol = System.getProperty("line.separator", "\n");
-
- /**
- * Used to convert raw characters to their escaped version
- * when these raw version cannot be used as part of an ASCII
- * string literal.
- */
- protected String add_escapes(String str) {
- StringBuffer retval = new StringBuffer();
- char ch;
- for (int i = 0; i < str.length(); i++) {
- switch (str.charAt(i))
- {
- case 0 :
- continue;
- case '\b':
- retval.append("\\b");
- continue;
- case '\t':
- retval.append("\\t");
- continue;
- case '\n':
- retval.append("\\n");
- continue;
- case '\f':
- retval.append("\\f");
- continue;
- case '\r':
- retval.append("\\r");
- continue;
- case '\"':
- retval.append("\\\"");
- continue;
- case '\'':
- retval.append("\\\'");
- continue;
- case '\\':
- retval.append("\\\\");
- continue;
- default:
- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
- String s = "0000" + Integer.toString(ch, 16);
- retval.append("\\u" + s.substring(s.length() - 4, s.length()));
- } else {
- retval.append(ch);
- }
- continue;
- }
- }
- return retval.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleCharStream.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleCharStream.java
deleted file mode 100644
index 957bbeabc..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleCharStream.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-/**
- * An implementation of interface CharStream, where the stream is assumed to
- * contain only ASCII characters (without unicode processing).
- */
-
-public class SimpleCharStream
-{
- public static final boolean staticFlag = false;
- int bufsize;
- int available;
- int tokenBegin;
- public int bufpos = -1;
- protected int bufline[];
- protected int bufcolumn[];
-
- protected int column = 0;
- protected int line = 1;
-
- protected boolean prevCharIsCR = false;
- protected boolean prevCharIsLF = false;
-
- protected java.io.Reader inputStream;
-
- protected char[] buffer;
- protected int maxNextCharInd = 0;
- protected int inBuf = 0;
- protected int tabSize = 8;
-
- protected void setTabSize(int i) { tabSize = i; }
- protected int getTabSize(int i) { return tabSize; }
-
-
- protected void ExpandBuff(boolean wrapAround)
- {
- char[] newbuffer = new char[bufsize + 2048];
- int newbufline[] = new int[bufsize + 2048];
- int newbufcolumn[] = new int[bufsize + 2048];
-
- try
- {
- if (wrapAround)
- {
- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
- System.arraycopy(buffer, 0, newbuffer,
- bufsize - tokenBegin, bufpos);
- buffer = newbuffer;
-
- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
- System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
- bufline = newbufline;
-
- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
- System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
- bufcolumn = newbufcolumn;
-
- maxNextCharInd = (bufpos += (bufsize - tokenBegin));
- }
- else
- {
- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
- buffer = newbuffer;
-
- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
- bufline = newbufline;
-
- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
- bufcolumn = newbufcolumn;
-
- maxNextCharInd = (bufpos -= tokenBegin);
- }
- }
- catch (Throwable t)
- {
- throw new Error(t.getMessage());
- }
-
-
- bufsize += 2048;
- available = bufsize;
- tokenBegin = 0;
- }
-
- protected void FillBuff() throws java.io.IOException
- {
- if (maxNextCharInd == available)
- {
- if (available == bufsize)
- {
- if (tokenBegin > 2048)
- {
- bufpos = maxNextCharInd = 0;
- available = tokenBegin;
- }
- else if (tokenBegin < 0)
- bufpos = maxNextCharInd = 0;
- else
- ExpandBuff(false);
- }
- else if (available > tokenBegin)
- available = bufsize;
- else if ((tokenBegin - available) < 2048)
- ExpandBuff(true);
- else
- available = tokenBegin;
- }
-
- int i;
- try {
- if ((i = inputStream.read(buffer, maxNextCharInd,
- available - maxNextCharInd)) == -1)
- {
- inputStream.close();
- throw new java.io.IOException();
- }
- else
- maxNextCharInd += i;
- return;
- }
- catch(java.io.IOException e) {
- --bufpos;
- backup(0);
- if (tokenBegin == -1)
- tokenBegin = bufpos;
- throw e;
- }
- }
-
- public char BeginToken() throws java.io.IOException
- {
- tokenBegin = -1;
- char c = readChar();
- tokenBegin = bufpos;
-
- return c;
- }
-
- protected void UpdateLineColumn(char c)
- {
- column++;
-
- if (prevCharIsLF)
- {
- prevCharIsLF = false;
- line += (column = 1);
- }
- else if (prevCharIsCR)
- {
- prevCharIsCR = false;
- if (c == '\n')
- {
- prevCharIsLF = true;
- }
- else
- line += (column = 1);
- }
-
- switch (c)
- {
- case '\r' :
- prevCharIsCR = true;
- break;
- case '\n' :
- prevCharIsLF = true;
- break;
- case '\t' :
- column--;
- column += (tabSize - (column % tabSize));
- break;
- default :
- break;
- }
-
- bufline[bufpos] = line;
- bufcolumn[bufpos] = column;
- }
-
- public char readChar() throws java.io.IOException
- {
- if (inBuf > 0)
- {
- --inBuf;
-
- if (++bufpos == bufsize)
- bufpos = 0;
-
- return buffer[bufpos];
- }
-
- if (++bufpos >= maxNextCharInd)
- FillBuff();
-
- char c = buffer[bufpos];
-
- UpdateLineColumn(c);
- return (c);
- }
-
- /**
- * @deprecated
- * @see #getEndColumn
- */
-
- public int getColumn() {
- return bufcolumn[bufpos];
- }
-
- /**
- * @deprecated
- * @see #getEndLine
- */
-
- public int getLine() {
- return bufline[bufpos];
- }
-
- public int getEndColumn() {
- return bufcolumn[bufpos];
- }
-
- public int getEndLine() {
- return bufline[bufpos];
- }
-
- public int getBeginColumn() {
- return bufcolumn[tokenBegin];
- }
-
- public int getBeginLine() {
- return bufline[tokenBegin];
- }
-
- public void backup(int amount) {
-
- inBuf += amount;
- if ((bufpos -= amount) < 0)
- bufpos += bufsize;
- }
-
- public SimpleCharStream(java.io.Reader dstream, int startline,
- int startcolumn, int buffersize)
- {
- inputStream = dstream;
- line = startline;
- column = startcolumn - 1;
-
- available = bufsize = buffersize;
- buffer = new char[buffersize];
- bufline = new int[buffersize];
- bufcolumn = new int[buffersize];
- }
-
- public SimpleCharStream(java.io.Reader dstream, int startline,
- int startcolumn)
- {
- this(dstream, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.Reader dstream)
- {
- this(dstream, 1, 1, 4096);
- }
- public void ReInit(java.io.Reader dstream, int startline,
- int startcolumn, int buffersize)
- {
- inputStream = dstream;
- line = startline;
- column = startcolumn - 1;
-
- if (buffer == null || buffersize != buffer.length)
- {
- available = bufsize = buffersize;
- buffer = new char[buffersize];
- bufline = new int[buffersize];
- bufcolumn = new int[buffersize];
- }
- prevCharIsLF = prevCharIsCR = false;
- tokenBegin = inBuf = maxNextCharInd = 0;
- bufpos = -1;
- }
-
- public void ReInit(java.io.Reader dstream, int startline,
- int startcolumn)
- {
- ReInit(dstream, startline, startcolumn, 4096);
- }
-
- public void ReInit(java.io.Reader dstream)
- {
- ReInit(dstream, 1, 1, 4096);
- }
- public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
- {
- this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, int startline,
- int startcolumn, int buffersize)
- {
- this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn) throws java.io.UnsupportedEncodingException
- {
- this(dstream, encoding, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, int startline,
- int startcolumn)
- {
- this(dstream, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
- {
- this(dstream, encoding, 1, 1, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream)
- {
- this(dstream, 1, 1, 4096);
- }
-
- public void ReInit(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
- {
- ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
- }
-
- public void ReInit(java.io.InputStream dstream, int startline,
- int startcolumn, int buffersize)
- {
- ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
- }
-
- public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
- {
- ReInit(dstream, encoding, 1, 1, 4096);
- }
-
- public void ReInit(java.io.InputStream dstream)
- {
- ReInit(dstream, 1, 1, 4096);
- }
- public void ReInit(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn) throws java.io.UnsupportedEncodingException
- {
- ReInit(dstream, encoding, startline, startcolumn, 4096);
- }
- public void ReInit(java.io.InputStream dstream, int startline,
- int startcolumn)
- {
- ReInit(dstream, startline, startcolumn, 4096);
- }
- public String GetImage()
- {
- if (bufpos >= tokenBegin)
- return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
- else
- return new String(buffer, tokenBegin, bufsize - tokenBegin) +
- new String(buffer, 0, bufpos + 1);
- }
-
- public char[] GetSuffix(int len)
- {
- char[] ret = new char[len];
-
- if ((bufpos + 1) >= len)
- System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
- else
- {
- System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
- len - bufpos - 1);
- System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
- }
-
- return ret;
- }
-
- public void Done()
- {
- buffer = null;
- bufline = null;
- bufcolumn = null;
- }
-
- /**
- * Method to adjust line and column numbers for the start of a token.
- */
- public void adjustBeginLineColumn(int newLine, int newCol)
- {
- int start = tokenBegin;
- int len;
-
- if (bufpos >= tokenBegin)
- {
- len = bufpos - tokenBegin + inBuf + 1;
- }
- else
- {
- len = bufsize - tokenBegin + bufpos + 1 + inBuf;
- }
-
- int i = 0, j = 0, k = 0;
- int nextColDiff = 0, columnDiff = 0;
-
- while (i < len &&
- bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
- {
- bufline[j] = newLine;
- nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
- bufcolumn[j] = newCol + columnDiff;
- columnDiff = nextColDiff;
- i++;
- }
-
- if (i < len)
- {
- bufline[j] = newLine++;
- bufcolumn[j] = newCol + columnDiff;
-
- while (i++ < len)
- {
- if (bufline[j = start % bufsize] != bufline[++start % bufsize])
- bufline[j] = newLine++;
- else
- bufline[j] = newLine;
- }
- }
-
- line = bufline[j];
- column = bufcolumn[j];
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleNode.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleNode.java
deleted file mode 100644
index 9bf537e60..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/SimpleNode.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/* Generated By:JJTree: Do not edit this line. SimpleNode.java */
-
-package org.apache.james.mime4j.field.address.parser;
-
-public class SimpleNode extends org.apache.james.mime4j.field.address.parser.BaseNode implements Node {
- protected Node parent;
- protected Node[] children;
- protected int id;
- protected AddressListParser parser;
-
- public SimpleNode(int i) {
- id = i;
- }
-
- public SimpleNode(AddressListParser p, int i) {
- this(i);
- parser = p;
- }
-
- public void jjtOpen() {
- }
-
- public void jjtClose() {
- }
-
- public void jjtSetParent(Node n) { parent = n; }
- public Node jjtGetParent() { return parent; }
-
- public void jjtAddChild(Node n, int i) {
- if (children == null) {
- children = new Node[i + 1];
- } else if (i >= children.length) {
- Node c[] = new Node[i + 1];
- System.arraycopy(children, 0, c, 0, children.length);
- children = c;
- }
- children[i] = n;
- }
-
- public Node jjtGetChild(int i) {
- return children[i];
- }
-
- public int jjtGetNumChildren() {
- return (children == null) ? 0 : children.length;
- }
-
- /** Accept the visitor. **/
- public Object jjtAccept(AddressListParserVisitor visitor, Object data) {
- return visitor.visit(this, data);
- }
-
- /** Accept the visitor. **/
- public Object childrenAccept(AddressListParserVisitor visitor, Object data) {
- if (children != null) {
- for (int i = 0; i < children.length; ++i) {
- children[i].jjtAccept(visitor, data);
- }
- }
- return data;
- }
-
- /* You can override these two methods in subclasses of SimpleNode to
- customize the way the node appears when the tree is dumped. If
- your output uses more than one line you should override
- toString(String), otherwise overriding toString() is probably all
- you need to do. */
-
- public String toString() { return AddressListParserTreeConstants.jjtNodeName[id]; }
- public String toString(String prefix) { return prefix + toString(); }
-
- /* Override this method if you want to customize how the node dumps
- out its children. */
-
- public void dump(String prefix) {
- System.out.println(toString(prefix));
- if (children != null) {
- for (int i = 0; i < children.length; ++i) {
- SimpleNode n = (SimpleNode)children[i];
- if (n != null) {
- n.dump(prefix + " ");
- }
- }
- }
- }
-}
-
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/Token.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/Token.java
deleted file mode 100644
index 0228aac3e..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/Token.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-/**
- * Describes the input token stream.
- */
-
-public class Token {
-
- /**
- * An integer that describes the kind of this token. This numbering
- * system is determined by JavaCCParser, and a table of these numbers is
- * stored in the file ...Constants.java.
- */
- public int kind;
-
- /**
- * beginLine and beginColumn describe the position of the first character
- * of this token; endLine and endColumn describe the position of the
- * last character of this token.
- */
- public int beginLine, beginColumn, endLine, endColumn;
-
- /**
- * The string image of the token.
- */
- public String image;
-
- /**
- * A reference to the next regular (non-special) token from the input
- * stream. If this is the last token from the input stream, or if the
- * token manager has not read tokens beyond this one, this field is
- * set to null. This is true only if this token is also a regular
- * token. Otherwise, see below for a description of the contents of
- * this field.
- */
- public Token next;
-
- /**
- * This field is used to access special tokens that occur prior to this
- * token, but after the immediately preceding regular (non-special) token.
- * If there are no such special tokens, this field is set to null.
- * When there are more than one such special token, this field refers
- * to the last of these special tokens, which in turn refers to the next
- * previous special token through its specialToken field, and so on
- * until the first special token (whose specialToken field is null).
- * The next fields of special tokens refer to other special tokens that
- * immediately follow it (without an intervening regular token). If there
- * is no such token, this field is null.
- */
- public Token specialToken;
-
- /**
- * Returns the image.
- */
- public String toString()
- {
- return image;
- }
-
- /**
- * Returns a new Token object, by default. However, if you want, you
- * can create and return subclass objects based on the value of ofKind.
- * Simply add the cases to the switch for all those special cases.
- * For example, if you have a subclass of Token called IDToken that
- * you want to create if ofKind is ID, simlpy add something like :
- *
- * case MyParserConstants.ID : return new IDToken();
- *
- * to the following switch statement. Then you can cast matchedToken
- * variable to the appropriate type and use it in your lexical actions.
- */
- public static final Token newToken(int ofKind)
- {
- switch(ofKind)
- {
- default : return new Token();
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/address/parser/TokenMgrError.java b/emailcommon/src/org/apache/james/mime4j/field/address/parser/TokenMgrError.java
deleted file mode 100644
index c06a44cf3..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/address/parser/TokenMgrError.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.address.parser;
-
-public class TokenMgrError extends Error
-{
- /*
- * Ordinals for various reasons why an Error of this type can be thrown.
- */
-
- /**
- * Lexical error occured.
- */
- static final int LEXICAL_ERROR = 0;
-
- /**
- * An attempt wass made to create a second instance of a static token manager.
- */
- static final int STATIC_LEXER_ERROR = 1;
-
- /**
- * Tried to change to an invalid lexical state.
- */
- static final int INVALID_LEXICAL_STATE = 2;
-
- /**
- * Detected (and bailed out of) an infinite loop in the token manager.
- */
- static final int LOOP_DETECTED = 3;
-
- /**
- * Indicates the reason why the exception is thrown. It will have
- * one of the above 4 values.
- */
- int errorCode;
-
- /**
- * Replaces unprintable characters by their espaced (or unicode escaped)
- * equivalents in the given string
- */
- protected static final String addEscapes(String str) {
- StringBuffer retval = new StringBuffer();
- char ch;
- for (int i = 0; i < str.length(); i++) {
- switch (str.charAt(i))
- {
- case 0 :
- continue;
- case '\b':
- retval.append("\\b");
- continue;
- case '\t':
- retval.append("\\t");
- continue;
- case '\n':
- retval.append("\\n");
- continue;
- case '\f':
- retval.append("\\f");
- continue;
- case '\r':
- retval.append("\\r");
- continue;
- case '\"':
- retval.append("\\\"");
- continue;
- case '\'':
- retval.append("\\\'");
- continue;
- case '\\':
- retval.append("\\\\");
- continue;
- default:
- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
- String s = "0000" + Integer.toString(ch, 16);
- retval.append("\\u" + s.substring(s.length() - 4, s.length()));
- } else {
- retval.append(ch);
- }
- continue;
- }
- }
- return retval.toString();
- }
-
- /**
- * Returns a detailed message for the Error when it is thrown by the
- * token manager to indicate a lexical error.
- * Parameters :
- * EOFSeen : indicates if EOF caused the lexicl error
- * curLexState : lexical state in which this error occured
- * errorLine : line number when the error occured
- * errorColumn : column number when the error occured
- * errorAfter : prefix that was seen before this error occured
- * curchar : the offending character
- * Note: You can customize the lexical error message by modifying this method.
- */
- protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
- return("Lexical error at line " +
- errorLine + ", column " +
- errorColumn + ". Encountered: " +
- (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
- "after : \"" + addEscapes(errorAfter) + "\"");
- }
-
- /**
- * You can also modify the body of this method to customize your error messages.
- * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
- * of end-users concern, so you can return something like :
- *
- * "Internal Error : Please file a bug report .... "
- *
- * from this method for such cases in the release version of your parser.
- */
- public String getMessage() {
- return super.getMessage();
- }
-
- /*
- * Constructors of various flavors follow.
- */
-
- public TokenMgrError() {
- }
-
- public TokenMgrError(String message, int reason) {
- super(message);
- errorCode = reason;
- }
-
- public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
- this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParser.java b/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParser.java
deleted file mode 100644
index 9d4a0f564..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParser.java
+++ /dev/null
@@ -1,268 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. ContentTypeParser.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.contenttype.parser;
-
-import java.util.ArrayList;
-import java.util.Vector;
-
-public class ContentTypeParser implements ContentTypeParserConstants {
-
- private String type;
- private String subtype;
- private ArrayList<String> paramNames = new ArrayList<String>();
- private ArrayList<String> paramValues = new ArrayList<String>();
-
- public String getType() { return type; }
- public String getSubType() { return subtype; }
- public ArrayList<String> getParamNames() { return paramNames; }
- public ArrayList<String> getParamValues() { return paramValues; }
-
- public static void main(String args[]) throws ParseException {
- while (true) {
- try {
- ContentTypeParser parser = new ContentTypeParser(System.in);
- parser.parseLine();
- } catch (Exception x) {
- x.printStackTrace();
- return;
- }
- }
- }
-
- final public void parseLine() throws ParseException {
- parse();
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 1:
- jj_consume_token(1);
- break;
- default:
- jj_la1[0] = jj_gen;
- ;
- }
- jj_consume_token(2);
- }
-
- final public void parseAll() throws ParseException {
- parse();
- jj_consume_token(0);
- }
-
- final public void parse() throws ParseException {
- Token type;
- Token subtype;
- type = jj_consume_token(ATOKEN);
- jj_consume_token(3);
- subtype = jj_consume_token(ATOKEN);
- this.type = type.image;
- this.subtype = subtype.image;
- label_1:
- while (true) {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 4:
- ;
- break;
- default:
- jj_la1[1] = jj_gen;
- break label_1;
- }
- jj_consume_token(4);
- parameter();
- }
- }
-
- final public void parameter() throws ParseException {
- Token attrib;
- String val;
- attrib = jj_consume_token(ATOKEN);
- jj_consume_token(5);
- val = value();
- paramNames.add(attrib.image);
- paramValues.add(val);
- }
-
- final public String value() throws ParseException {
- Token t;
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case ATOKEN:
- t = jj_consume_token(ATOKEN);
- break;
- case QUOTEDSTRING:
- t = jj_consume_token(QUOTEDSTRING);
- break;
- default:
- jj_la1[2] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- {if (true) return t.image;}
- throw new Error("Missing return statement in function");
- }
-
- public ContentTypeParserTokenManager token_source;
- SimpleCharStream jj_input_stream;
- public Token token, jj_nt;
- private int jj_ntk;
- private int jj_gen;
- final private int[] jj_la1 = new int[3];
- static private int[] jj_la1_0;
- static {
- jj_la1_0();
- }
- private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x2,0x10,0x280000,};
- }
-
- public ContentTypeParser(java.io.InputStream stream) {
- this(stream, null);
- }
- public ContentTypeParser(java.io.InputStream stream, String encoding) {
- try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
- token_source = new ContentTypeParserTokenManager(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 3; i++) jj_la1[i] = -1;
- }
-
- public void ReInit(java.io.InputStream stream) {
- ReInit(stream, null);
- }
- public void ReInit(java.io.InputStream stream, String encoding) {
- try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
- token_source.ReInit(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 3; i++) jj_la1[i] = -1;
- }
-
- public ContentTypeParser(java.io.Reader stream) {
- jj_input_stream = new SimpleCharStream(stream, 1, 1);
- token_source = new ContentTypeParserTokenManager(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 3; i++) jj_la1[i] = -1;
- }
-
- public void ReInit(java.io.Reader stream) {
- jj_input_stream.ReInit(stream, 1, 1);
- token_source.ReInit(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 3; i++) jj_la1[i] = -1;
- }
-
- public ContentTypeParser(ContentTypeParserTokenManager tm) {
- token_source = tm;
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 3; i++) jj_la1[i] = -1;
- }
-
- public void ReInit(ContentTypeParserTokenManager tm) {
- token_source = tm;
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 3; i++) jj_la1[i] = -1;
- }
-
- final private Token jj_consume_token(int kind) throws ParseException {
- Token oldToken;
- if ((oldToken = token).next != null) token = token.next;
- else token = token.next = token_source.getNextToken();
- jj_ntk = -1;
- if (token.kind == kind) {
- jj_gen++;
- return token;
- }
- token = oldToken;
- jj_kind = kind;
- throw generateParseException();
- }
-
- final public Token getNextToken() {
- if (token.next != null) token = token.next;
- else token = token.next = token_source.getNextToken();
- jj_ntk = -1;
- jj_gen++;
- return token;
- }
-
- final public Token getToken(int index) {
- Token t = token;
- for (int i = 0; i < index; i++) {
- if (t.next != null) t = t.next;
- else t = t.next = token_source.getNextToken();
- }
- return t;
- }
-
- final private int jj_ntk() {
- if ((jj_nt=token.next) == null)
- return (jj_ntk = (token.next=token_source.getNextToken()).kind);
- else
- return (jj_ntk = jj_nt.kind);
- }
-
- private Vector<int[]> jj_expentries = new Vector<int[]>();
- private int[] jj_expentry;
- private int jj_kind = -1;
-
- public ParseException generateParseException() {
- jj_expentries.removeAllElements();
- boolean[] la1tokens = new boolean[24];
- for (int i = 0; i < 24; i++) {
- la1tokens[i] = false;
- }
- if (jj_kind >= 0) {
- la1tokens[jj_kind] = true;
- jj_kind = -1;
- }
- for (int i = 0; i < 3; i++) {
- if (jj_la1[i] == jj_gen) {
- for (int j = 0; j < 32; j++) {
- if ((jj_la1_0[i] & (1<<j)) != 0) {
- la1tokens[j] = true;
- }
- }
- }
- }
- for (int i = 0; i < 24; i++) {
- if (la1tokens[i]) {
- jj_expentry = new int[1];
- jj_expentry[0] = i;
- jj_expentries.addElement(jj_expentry);
- }
- }
- int[][] exptokseq = new int[jj_expentries.size()][];
- for (int i = 0; i < jj_expentries.size(); i++) {
- exptokseq[i] = jj_expentries.elementAt(i);
- }
- return new ParseException(token, exptokseq, tokenImage);
- }
-
- final public void enable_tracing() {
- }
-
- final public void disable_tracing() {
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserConstants.java b/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserConstants.java
deleted file mode 100644
index 8a763287d..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserConstants.java
+++ /dev/null
@@ -1,62 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. ContentTypeParserConstants.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.contenttype.parser;
-
-public interface ContentTypeParserConstants {
-
- int EOF = 0;
- int WS = 6;
- int COMMENT = 8;
- int QUOTEDSTRING = 19;
- int DIGITS = 20;
- int ATOKEN = 21;
- int QUOTEDPAIR = 22;
- int ANY = 23;
-
- int DEFAULT = 0;
- int INCOMMENT = 1;
- int NESTED_COMMENT = 2;
- int INQUOTEDSTRING = 3;
-
- String[] tokenImage = {
- "<EOF>",
- "\"\\r\"",
- "\"\\n\"",
- "\"/\"",
- "\";\"",
- "\"=\"",
- "<WS>",
- "\"(\"",
- "\")\"",
- "<token of kind 9>",
- "\"(\"",
- "<token of kind 11>",
- "<token of kind 12>",
- "\"(\"",
- "\")\"",
- "<token of kind 15>",
- "\"\\\"\"",
- "<token of kind 17>",
- "<token of kind 18>",
- "\"\\\"\"",
- "<DIGITS>",
- "<ATOKEN>",
- "<QUOTEDPAIR>",
- "<ANY>",
- };
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserTokenManager.java b/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserTokenManager.java
deleted file mode 100644
index 05d940db5..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ContentTypeParserTokenManager.java
+++ /dev/null
@@ -1,877 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. ContentTypeParserTokenManager.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.contenttype.parser;
-import java.util.ArrayList;
-
-public class ContentTypeParserTokenManager implements ContentTypeParserConstants
-{
- // Keeps track of how many levels of comment nesting
- // we've encountered. This is only used when the 2nd
- // level is reached, for example ((this)), not (this).
- // This is because the outermost level must be treated
- // specially anyway, because the outermost ")" has a
- // different token type than inner ")" instances.
- static int commentNest;
- public java.io.PrintStream debugStream = System.out;
- public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }
-private final int jjStopStringLiteralDfa_0(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_0(int pos, long active0)
-{
- return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1);
-}
-private final int jjStopAtPos(int pos, int kind)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- return pos + 1;
-}
-private final int jjStartNfaWithStates_0(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_0(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_0()
-{
- switch(curChar)
- {
- case 10:
- return jjStartNfaWithStates_0(0, 2, 2);
- case 13:
- return jjStartNfaWithStates_0(0, 1, 2);
- case 34:
- return jjStopAtPos(0, 16);
- case 40:
- return jjStopAtPos(0, 7);
- case 47:
- return jjStopAtPos(0, 3);
- case 59:
- return jjStopAtPos(0, 4);
- case 61:
- return jjStopAtPos(0, 5);
- default :
- return jjMoveNfa_0(3, 0);
- }
-}
-private final void jjCheckNAdd(int state)
-{
- if (jjrounds[state] != jjround)
- {
- jjstateSet[jjnewStateCnt++] = state;
- jjrounds[state] = jjround;
- }
-}
-private final void jjAddStates(int start, int end)
-{
- do {
- jjstateSet[jjnewStateCnt++] = jjnextStates[start];
- } while (start++ != end);
-}
-private final void jjCheckNAddTwoStates(int state1, int state2)
-{
- jjCheckNAdd(state1);
- jjCheckNAdd(state2);
-}
-private final void jjCheckNAddStates(int start, int end)
-{
- do {
- jjCheckNAdd(jjnextStates[start]);
- } while (start++ != end);
-}
-private final void jjCheckNAddStates(int start)
-{
- jjCheckNAdd(jjnextStates[start]);
- jjCheckNAdd(jjnextStates[start + 1]);
-}
-static final long[] jjbitVec0 = {
- 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
-};
-private final int jjMoveNfa_0(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 3:
- if ((0x3ff6cfafffffdffL & l) != 0L)
- {
- if (kind > 21)
- kind = 21;
- jjCheckNAdd(2);
- }
- else if ((0x100000200L & l) != 0L)
- {
- if (kind > 6)
- kind = 6;
- jjCheckNAdd(0);
- }
- if ((0x3ff000000000000L & l) != 0L)
- {
- if (kind > 20)
- kind = 20;
- jjCheckNAdd(1);
- }
- break;
- case 0:
- if ((0x100000200L & l) == 0L)
- break;
- kind = 6;
- jjCheckNAdd(0);
- break;
- case 1:
- if ((0x3ff000000000000L & l) == 0L)
- break;
- if (kind > 20)
- kind = 20;
- jjCheckNAdd(1);
- break;
- case 2:
- if ((0x3ff6cfafffffdffL & l) == 0L)
- break;
- if (kind > 21)
- kind = 21;
- jjCheckNAdd(2);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 3:
- case 2:
- if ((0xffffffffc7fffffeL & l) == 0L)
- break;
- kind = 21;
- jjCheckNAdd(2);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 3:
- case 2:
- if ((jjbitVec0[i2] & l2) == 0L)
- break;
- if (kind > 21)
- kind = 21;
- jjCheckNAdd(2);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_1(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_1(int pos, long active0)
-{
- return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_1(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_1(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_1()
-{
- switch(curChar)
- {
- case 40:
- return jjStopAtPos(0, 10);
- case 41:
- return jjStopAtPos(0, 8);
- default :
- return jjMoveNfa_1(0, 0);
- }
-}
-private final int jjMoveNfa_1(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 11)
- kind = 11;
- break;
- case 1:
- if (kind > 9)
- kind = 9;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 11)
- kind = 11;
- if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 9)
- kind = 9;
- break;
- case 2:
- if (kind > 11)
- kind = 11;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 11)
- kind = 11;
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 9)
- kind = 9;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_3(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_3(int pos, long active0)
-{
- return jjMoveNfa_3(jjStopStringLiteralDfa_3(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_3(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_3(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_3()
-{
- switch(curChar)
- {
- case 34:
- return jjStopAtPos(0, 19);
- default :
- return jjMoveNfa_3(0, 0);
- }
-}
-private final int jjMoveNfa_3(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- case 2:
- if ((0xfffffffbffffffffL & l) == 0L)
- break;
- if (kind > 18)
- kind = 18;
- jjCheckNAdd(2);
- break;
- case 1:
- if (kind > 17)
- kind = 17;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((0xffffffffefffffffL & l) != 0L)
- {
- if (kind > 18)
- kind = 18;
- jjCheckNAdd(2);
- }
- else if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 17)
- kind = 17;
- break;
- case 2:
- if ((0xffffffffefffffffL & l) == 0L)
- break;
- if (kind > 18)
- kind = 18;
- jjCheckNAdd(2);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- case 2:
- if ((jjbitVec0[i2] & l2) == 0L)
- break;
- if (kind > 18)
- kind = 18;
- jjCheckNAdd(2);
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 17)
- kind = 17;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_2(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_2(int pos, long active0)
-{
- return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_2(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_2(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_2()
-{
- switch(curChar)
- {
- case 40:
- return jjStopAtPos(0, 13);
- case 41:
- return jjStopAtPos(0, 14);
- default :
- return jjMoveNfa_2(0, 0);
- }
-}
-private final int jjMoveNfa_2(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 15)
- kind = 15;
- break;
- case 1:
- if (kind > 12)
- kind = 12;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 15)
- kind = 15;
- if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 12)
- kind = 12;
- break;
- case 2:
- if (kind > 15)
- kind = 15;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 15)
- kind = 15;
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 12)
- kind = 12;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-static final int[] jjnextStates = {
-};
-public static final String[] jjstrLiteralImages = {
-"", "\15", "\12", "\57", "\73", "\75", null, null, null, null, null, null,
-null, null, null, null, null, null, null, null, null, null, null, null, };
-public static final String[] lexStateNames = {
- "DEFAULT",
- "INCOMMENT",
- "NESTED_COMMENT",
- "INQUOTEDSTRING",
-};
-public static final int[] jjnewLexState = {
- -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, 2, -1, -1, -1, -1, -1, 3, -1, -1, 0, -1, -1, -1, -1,
-};
-static final long[] jjtoToken = {
- 0x38003fL,
-};
-static final long[] jjtoSkip = {
- 0x140L,
-};
-static final long[] jjtoSpecial = {
- 0x40L,
-};
-static final long[] jjtoMore = {
- 0x7fe80L,
-};
-protected SimpleCharStream input_stream;
-private final int[] jjrounds = new int[3];
-private final int[] jjstateSet = new int[6];
-StringBuffer image;
-int jjimageLen;
-int lengthOfMatch;
-protected char curChar;
-public ContentTypeParserTokenManager(SimpleCharStream stream){
- if (SimpleCharStream.staticFlag)
- throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
- input_stream = stream;
-}
-public ContentTypeParserTokenManager(SimpleCharStream stream, int lexState){
- this(stream);
- SwitchTo(lexState);
-}
-public void ReInit(SimpleCharStream stream)
-{
- jjmatchedPos = jjnewStateCnt = 0;
- curLexState = defaultLexState;
- input_stream = stream;
- ReInitRounds();
-}
-private final void ReInitRounds()
-{
- int i;
- jjround = 0x80000001;
- for (i = 3; i-- > 0;)
- jjrounds[i] = 0x80000000;
-}
-public void ReInit(SimpleCharStream stream, int lexState)
-{
- ReInit(stream);
- SwitchTo(lexState);
-}
-public void SwitchTo(int lexState)
-{
- if (lexState >= 4 || lexState < 0)
- throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
- else
- curLexState = lexState;
-}
-
-protected Token jjFillToken()
-{
- Token t = Token.newToken(jjmatchedKind);
- t.kind = jjmatchedKind;
- String im = jjstrLiteralImages[jjmatchedKind];
- t.image = (im == null) ? input_stream.GetImage() : im;
- t.beginLine = input_stream.getBeginLine();
- t.beginColumn = input_stream.getBeginColumn();
- t.endLine = input_stream.getEndLine();
- t.endColumn = input_stream.getEndColumn();
- return t;
-}
-
-int curLexState = 0;
-int defaultLexState = 0;
-int jjnewStateCnt;
-int jjround;
-int jjmatchedPos;
-int jjmatchedKind;
-
-public Token getNextToken()
-{
- int kind;
- Token specialToken = null;
- Token matchedToken;
- int curPos = 0;
-
- EOFLoop :
- for (;;)
- {
- try
- {
- curChar = input_stream.BeginToken();
- }
- catch(java.io.IOException e)
- {
- jjmatchedKind = 0;
- matchedToken = jjFillToken();
- matchedToken.specialToken = specialToken;
- return matchedToken;
- }
- image = null;
- jjimageLen = 0;
-
- for (;;)
- {
- switch(curLexState)
- {
- case 0:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_0();
- break;
- case 1:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_1();
- break;
- case 2:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_2();
- break;
- case 3:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_3();
- break;
- }
- if (jjmatchedKind != 0x7fffffff)
- {
- if (jjmatchedPos + 1 < curPos)
- input_stream.backup(curPos - jjmatchedPos - 1);
- if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- matchedToken = jjFillToken();
- matchedToken.specialToken = specialToken;
- TokenLexicalActions(matchedToken);
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- return matchedToken;
- }
- else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- matchedToken = jjFillToken();
- if (specialToken == null)
- specialToken = matchedToken;
- else
- {
- matchedToken.specialToken = specialToken;
- specialToken = (specialToken.next = matchedToken);
- }
- }
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- continue EOFLoop;
- }
- MoreLexicalActions();
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- curPos = 0;
- jjmatchedKind = 0x7fffffff;
- try {
- curChar = input_stream.readChar();
- continue;
- }
- catch (java.io.IOException e1) { }
- }
- int error_line = input_stream.getEndLine();
- int error_column = input_stream.getEndColumn();
- String error_after = null;
- boolean EOFSeen = false;
- try { input_stream.readChar(); input_stream.backup(1); }
- catch (java.io.IOException e1) {
- EOFSeen = true;
- error_after = curPos <= 1 ? "" : input_stream.GetImage();
- if (curChar == '\n' || curChar == '\r') {
- error_line++;
- error_column = 0;
- }
- else
- error_column++;
- }
- if (!EOFSeen) {
- input_stream.backup(1);
- error_after = curPos <= 1 ? "" : input_stream.GetImage();
- }
- throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
- }
- }
-}
-
-void MoreLexicalActions()
-{
- jjimageLen += (lengthOfMatch = jjmatchedPos + 1);
- switch(jjmatchedKind)
- {
- case 9 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- case 10 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- commentNest = 1;
- break;
- case 12 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- case 13 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- ++commentNest;
- break;
- case 14 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- --commentNest; if (commentNest == 0) SwitchTo(INCOMMENT);
- break;
- case 16 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 1);
- break;
- case 17 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- default :
- break;
- }
-}
-void TokenLexicalActions(Token matchedToken)
-{
- switch(jjmatchedKind)
- {
- case 19 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen + (lengthOfMatch = jjmatchedPos + 1)));
- matchedToken.image = image.substring(0, image.length() - 1);
- break;
- default :
- break;
- }
-}
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ParseException.java b/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ParseException.java
deleted file mode 100644
index 2c5dc8275..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/ParseException.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.contenttype.parser;
-
-/**
- * This exception is thrown when parse errors are encountered.
- * You can explicitly create objects of this exception type by
- * calling the method generateParseException in the generated
- * parser.
- *
- * You can modify this class to customize your error reporting
- * mechanisms so long as you retain the public fields.
- */
-public class ParseException extends Exception {
-
- /**
- * This constructor is used by the method "generateParseException"
- * in the generated parser. Calling this constructor generates
- * a new object of this type with the fields "currentToken",
- * "expectedTokenSequences", and "tokenImage" set. The boolean
- * flag "specialConstructor" is also set to true to indicate that
- * this constructor was used to create this object.
- * This constructor calls its super class with the empty string
- * to force the "toString" method of parent class "Throwable" to
- * print the error message in the form:
- * ParseException: <result of getMessage>
- */
- public ParseException(Token currentTokenVal,
- int[][] expectedTokenSequencesVal,
- String[] tokenImageVal
- )
- {
- super("");
- specialConstructor = true;
- currentToken = currentTokenVal;
- expectedTokenSequences = expectedTokenSequencesVal;
- tokenImage = tokenImageVal;
- }
-
- /**
- * The following constructors are for use by you for whatever
- * purpose you can think of. Constructing the exception in this
- * manner makes the exception behave in the normal way - i.e., as
- * documented in the class "Throwable". The fields "errorToken",
- * "expectedTokenSequences", and "tokenImage" do not contain
- * relevant information. The JavaCC generated code does not use
- * these constructors.
- */
-
- public ParseException() {
- super();
- specialConstructor = false;
- }
-
- public ParseException(String message) {
- super(message);
- specialConstructor = false;
- }
-
- /**
- * This variable determines which constructor was used to create
- * this object and thereby affects the semantics of the
- * "getMessage" method (see below).
- */
- protected boolean specialConstructor;
-
- /**
- * This is the last token that has been consumed successfully. If
- * this object has been created due to a parse error, the token
- * followng this token will (therefore) be the first error token.
- */
- public Token currentToken;
-
- /**
- * Each entry in this array is an array of integers. Each array
- * of integers represents a sequence of tokens (by their ordinal
- * values) that is expected at this point of the parse.
- */
- public int[][] expectedTokenSequences;
-
- /**
- * This is a reference to the "tokenImage" array of the generated
- * parser within which the parse error occurred. This array is
- * defined in the generated ...Constants interface.
- */
- public String[] tokenImage;
-
- /**
- * This method has the standard behavior when this object has been
- * created using the standard constructors. Otherwise, it uses
- * "currentToken" and "expectedTokenSequences" to generate a parse
- * error message and returns it. If this object has been created
- * due to a parse error, and you do not catch it (it gets thrown
- * from the parser), then this method is called during the printing
- * of the final stack trace, and hence the correct error message
- * gets displayed.
- */
- public String getMessage() {
- if (!specialConstructor) {
- return super.getMessage();
- }
- StringBuffer expected = new StringBuffer();
- int maxSize = 0;
- for (int i = 0; i < expectedTokenSequences.length; i++) {
- if (maxSize < expectedTokenSequences[i].length) {
- maxSize = expectedTokenSequences[i].length;
- }
- for (int j = 0; j < expectedTokenSequences[i].length; j++) {
- expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" ");
- }
- if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
- expected.append("...");
- }
- expected.append(eol).append(" ");
- }
- String retval = "Encountered \"";
- Token tok = currentToken.next;
- for (int i = 0; i < maxSize; i++) {
- if (i != 0) retval += " ";
- if (tok.kind == 0) {
- retval += tokenImage[0];
- break;
- }
- retval += add_escapes(tok.image);
- tok = tok.next;
- }
- retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
- retval += "." + eol;
- if (expectedTokenSequences.length == 1) {
- retval += "Was expecting:" + eol + " ";
- } else {
- retval += "Was expecting one of:" + eol + " ";
- }
- retval += expected.toString();
- return retval;
- }
-
- /**
- * The end of line string for this machine.
- */
- protected String eol = System.getProperty("line.separator", "\n");
-
- /**
- * Used to convert raw characters to their escaped version
- * when these raw version cannot be used as part of an ASCII
- * string literal.
- */
- protected String add_escapes(String str) {
- StringBuffer retval = new StringBuffer();
- char ch;
- for (int i = 0; i < str.length(); i++) {
- switch (str.charAt(i))
- {
- case 0 :
- continue;
- case '\b':
- retval.append("\\b");
- continue;
- case '\t':
- retval.append("\\t");
- continue;
- case '\n':
- retval.append("\\n");
- continue;
- case '\f':
- retval.append("\\f");
- continue;
- case '\r':
- retval.append("\\r");
- continue;
- case '\"':
- retval.append("\\\"");
- continue;
- case '\'':
- retval.append("\\\'");
- continue;
- case '\\':
- retval.append("\\\\");
- continue;
- default:
- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
- String s = "0000" + Integer.toString(ch, 16);
- retval.append("\\u" + s.substring(s.length() - 4, s.length()));
- } else {
- retval.append(ch);
- }
- continue;
- }
- }
- return retval.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/SimpleCharStream.java b/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/SimpleCharStream.java
deleted file mode 100644
index c139e4f38..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/SimpleCharStream.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.contenttype.parser;
-
-/**
- * An implementation of interface CharStream, where the stream is assumed to
- * contain only ASCII characters (without unicode processing).
- */
-
-public class SimpleCharStream
-{
- public static final boolean staticFlag = false;
- int bufsize;
- int available;
- int tokenBegin;
- public int bufpos = -1;
- protected int bufline[];
- protected int bufcolumn[];
-
- protected int column = 0;
- protected int line = 1;
-
- protected boolean prevCharIsCR = false;
- protected boolean prevCharIsLF = false;
-
- protected java.io.Reader inputStream;
-
- protected char[] buffer;
- protected int maxNextCharInd = 0;
- protected int inBuf = 0;
- protected int tabSize = 8;
-
- protected void setTabSize(int i) { tabSize = i; }
- protected int getTabSize(int i) { return tabSize; }
-
-
- protected void ExpandBuff(boolean wrapAround)
- {
- char[] newbuffer = new char[bufsize + 2048];
- int newbufline[] = new int[bufsize + 2048];
- int newbufcolumn[] = new int[bufsize + 2048];
-
- try
- {
- if (wrapAround)
- {
- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
- System.arraycopy(buffer, 0, newbuffer,
- bufsize - tokenBegin, bufpos);
- buffer = newbuffer;
-
- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
- System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
- bufline = newbufline;
-
- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
- System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
- bufcolumn = newbufcolumn;
-
- maxNextCharInd = (bufpos += (bufsize - tokenBegin));
- }
- else
- {
- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
- buffer = newbuffer;
-
- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
- bufline = newbufline;
-
- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
- bufcolumn = newbufcolumn;
-
- maxNextCharInd = (bufpos -= tokenBegin);
- }
- }
- catch (Throwable t)
- {
- throw new Error(t.getMessage());
- }
-
-
- bufsize += 2048;
- available = bufsize;
- tokenBegin = 0;
- }
-
- protected void FillBuff() throws java.io.IOException
- {
- if (maxNextCharInd == available)
- {
- if (available == bufsize)
- {
- if (tokenBegin > 2048)
- {
- bufpos = maxNextCharInd = 0;
- available = tokenBegin;
- }
- else if (tokenBegin < 0)
- bufpos = maxNextCharInd = 0;
- else
- ExpandBuff(false);
- }
- else if (available > tokenBegin)
- available = bufsize;
- else if ((tokenBegin - available) < 2048)
- ExpandBuff(true);
- else
- available = tokenBegin;
- }
-
- int i;
- try {
- if ((i = inputStream.read(buffer, maxNextCharInd,
- available - maxNextCharInd)) == -1)
- {
- inputStream.close();
- throw new java.io.IOException();
- }
- else
- maxNextCharInd += i;
- return;
- }
- catch(java.io.IOException e) {
- --bufpos;
- backup(0);
- if (tokenBegin == -1)
- tokenBegin = bufpos;
- throw e;
- }
- }
-
- public char BeginToken() throws java.io.IOException
- {
- tokenBegin = -1;
- char c = readChar();
- tokenBegin = bufpos;
-
- return c;
- }
-
- protected void UpdateLineColumn(char c)
- {
- column++;
-
- if (prevCharIsLF)
- {
- prevCharIsLF = false;
- line += (column = 1);
- }
- else if (prevCharIsCR)
- {
- prevCharIsCR = false;
- if (c == '\n')
- {
- prevCharIsLF = true;
- }
- else
- line += (column = 1);
- }
-
- switch (c)
- {
- case '\r' :
- prevCharIsCR = true;
- break;
- case '\n' :
- prevCharIsLF = true;
- break;
- case '\t' :
- column--;
- column += (tabSize - (column % tabSize));
- break;
- default :
- break;
- }
-
- bufline[bufpos] = line;
- bufcolumn[bufpos] = column;
- }
-
- public char readChar() throws java.io.IOException
- {
- if (inBuf > 0)
- {
- --inBuf;
-
- if (++bufpos == bufsize)
- bufpos = 0;
-
- return buffer[bufpos];
- }
-
- if (++bufpos >= maxNextCharInd)
- FillBuff();
-
- char c = buffer[bufpos];
-
- UpdateLineColumn(c);
- return (c);
- }
-
- /**
- * @deprecated
- * @see #getEndColumn
- */
-
- public int getColumn() {
- return bufcolumn[bufpos];
- }
-
- /**
- * @deprecated
- * @see #getEndLine
- */
-
- public int getLine() {
- return bufline[bufpos];
- }
-
- public int getEndColumn() {
- return bufcolumn[bufpos];
- }
-
- public int getEndLine() {
- return bufline[bufpos];
- }
-
- public int getBeginColumn() {
- return bufcolumn[tokenBegin];
- }
-
- public int getBeginLine() {
- return bufline[tokenBegin];
- }
-
- public void backup(int amount) {
-
- inBuf += amount;
- if ((bufpos -= amount) < 0)
- bufpos += bufsize;
- }
-
- public SimpleCharStream(java.io.Reader dstream, int startline,
- int startcolumn, int buffersize)
- {
- inputStream = dstream;
- line = startline;
- column = startcolumn - 1;
-
- available = bufsize = buffersize;
- buffer = new char[buffersize];
- bufline = new int[buffersize];
- bufcolumn = new int[buffersize];
- }
-
- public SimpleCharStream(java.io.Reader dstream, int startline,
- int startcolumn)
- {
- this(dstream, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.Reader dstream)
- {
- this(dstream, 1, 1, 4096);
- }
- public void ReInit(java.io.Reader dstream, int startline,
- int startcolumn, int buffersize)
- {
- inputStream = dstream;
- line = startline;
- column = startcolumn - 1;
-
- if (buffer == null || buffersize != buffer.length)
- {
- available = bufsize = buffersize;
- buffer = new char[buffersize];
- bufline = new int[buffersize];
- bufcolumn = new int[buffersize];
- }
- prevCharIsLF = prevCharIsCR = false;
- tokenBegin = inBuf = maxNextCharInd = 0;
- bufpos = -1;
- }
-
- public void ReInit(java.io.Reader dstream, int startline,
- int startcolumn)
- {
- ReInit(dstream, startline, startcolumn, 4096);
- }
-
- public void ReInit(java.io.Reader dstream)
- {
- ReInit(dstream, 1, 1, 4096);
- }
- public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
- {
- this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, int startline,
- int startcolumn, int buffersize)
- {
- this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn) throws java.io.UnsupportedEncodingException
- {
- this(dstream, encoding, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, int startline,
- int startcolumn)
- {
- this(dstream, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
- {
- this(dstream, encoding, 1, 1, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream)
- {
- this(dstream, 1, 1, 4096);
- }
-
- public void ReInit(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
- {
- ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
- }
-
- public void ReInit(java.io.InputStream dstream, int startline,
- int startcolumn, int buffersize)
- {
- ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
- }
-
- public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
- {
- ReInit(dstream, encoding, 1, 1, 4096);
- }
-
- public void ReInit(java.io.InputStream dstream)
- {
- ReInit(dstream, 1, 1, 4096);
- }
- public void ReInit(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn) throws java.io.UnsupportedEncodingException
- {
- ReInit(dstream, encoding, startline, startcolumn, 4096);
- }
- public void ReInit(java.io.InputStream dstream, int startline,
- int startcolumn)
- {
- ReInit(dstream, startline, startcolumn, 4096);
- }
- public String GetImage()
- {
- if (bufpos >= tokenBegin)
- return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
- else
- return new String(buffer, tokenBegin, bufsize - tokenBegin) +
- new String(buffer, 0, bufpos + 1);
- }
-
- public char[] GetSuffix(int len)
- {
- char[] ret = new char[len];
-
- if ((bufpos + 1) >= len)
- System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
- else
- {
- System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
- len - bufpos - 1);
- System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
- }
-
- return ret;
- }
-
- public void Done()
- {
- buffer = null;
- bufline = null;
- bufcolumn = null;
- }
-
- /**
- * Method to adjust line and column numbers for the start of a token.
- */
- public void adjustBeginLineColumn(int newLine, int newCol)
- {
- int start = tokenBegin;
- int len;
-
- if (bufpos >= tokenBegin)
- {
- len = bufpos - tokenBegin + inBuf + 1;
- }
- else
- {
- len = bufsize - tokenBegin + bufpos + 1 + inBuf;
- }
-
- int i = 0, j = 0, k = 0;
- int nextColDiff = 0, columnDiff = 0;
-
- while (i < len &&
- bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
- {
- bufline[j] = newLine;
- nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
- bufcolumn[j] = newCol + columnDiff;
- columnDiff = nextColDiff;
- i++;
- }
-
- if (i < len)
- {
- bufline[j] = newLine++;
- bufcolumn[j] = newCol + columnDiff;
-
- while (i++ < len)
- {
- if (bufline[j = start % bufsize] != bufline[++start % bufsize])
- bufline[j] = newLine++;
- else
- bufline[j] = newLine;
- }
- }
-
- line = bufline[j];
- column = bufcolumn[j];
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/Token.java b/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/Token.java
deleted file mode 100644
index 5bef6cf02..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/Token.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.contenttype.parser;
-
-/**
- * Describes the input token stream.
- */
-
-public class Token {
-
- /**
- * An integer that describes the kind of this token. This numbering
- * system is determined by JavaCCParser, and a table of these numbers is
- * stored in the file ...Constants.java.
- */
- public int kind;
-
- /**
- * beginLine and beginColumn describe the position of the first character
- * of this token; endLine and endColumn describe the position of the
- * last character of this token.
- */
- public int beginLine, beginColumn, endLine, endColumn;
-
- /**
- * The string image of the token.
- */
- public String image;
-
- /**
- * A reference to the next regular (non-special) token from the input
- * stream. If this is the last token from the input stream, or if the
- * token manager has not read tokens beyond this one, this field is
- * set to null. This is true only if this token is also a regular
- * token. Otherwise, see below for a description of the contents of
- * this field.
- */
- public Token next;
-
- /**
- * This field is used to access special tokens that occur prior to this
- * token, but after the immediately preceding regular (non-special) token.
- * If there are no such special tokens, this field is set to null.
- * When there are more than one such special token, this field refers
- * to the last of these special tokens, which in turn refers to the next
- * previous special token through its specialToken field, and so on
- * until the first special token (whose specialToken field is null).
- * The next fields of special tokens refer to other special tokens that
- * immediately follow it (without an intervening regular token). If there
- * is no such token, this field is null.
- */
- public Token specialToken;
-
- /**
- * Returns the image.
- */
- public String toString()
- {
- return image;
- }
-
- /**
- * Returns a new Token object, by default. However, if you want, you
- * can create and return subclass objects based on the value of ofKind.
- * Simply add the cases to the switch for all those special cases.
- * For example, if you have a subclass of Token called IDToken that
- * you want to create if ofKind is ID, simlpy add something like :
- *
- * case MyParserConstants.ID : return new IDToken();
- *
- * to the following switch statement. Then you can cast matchedToken
- * variable to the appropriate type and use it in your lexical actions.
- */
- public static final Token newToken(int ofKind)
- {
- switch(ofKind)
- {
- default : return new Token();
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/TokenMgrError.java b/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/TokenMgrError.java
deleted file mode 100644
index 4a490efac..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/contenttype/parser/TokenMgrError.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.contenttype.parser;
-
-public class TokenMgrError extends Error
-{
- /*
- * Ordinals for various reasons why an Error of this type can be thrown.
- */
-
- /**
- * Lexical error occured.
- */
- static final int LEXICAL_ERROR = 0;
-
- /**
- * An attempt wass made to create a second instance of a static token manager.
- */
- static final int STATIC_LEXER_ERROR = 1;
-
- /**
- * Tried to change to an invalid lexical state.
- */
- static final int INVALID_LEXICAL_STATE = 2;
-
- /**
- * Detected (and bailed out of) an infinite loop in the token manager.
- */
- static final int LOOP_DETECTED = 3;
-
- /**
- * Indicates the reason why the exception is thrown. It will have
- * one of the above 4 values.
- */
- int errorCode;
-
- /**
- * Replaces unprintable characters by their espaced (or unicode escaped)
- * equivalents in the given string
- */
- protected static final String addEscapes(String str) {
- StringBuffer retval = new StringBuffer();
- char ch;
- for (int i = 0; i < str.length(); i++) {
- switch (str.charAt(i))
- {
- case 0 :
- continue;
- case '\b':
- retval.append("\\b");
- continue;
- case '\t':
- retval.append("\\t");
- continue;
- case '\n':
- retval.append("\\n");
- continue;
- case '\f':
- retval.append("\\f");
- continue;
- case '\r':
- retval.append("\\r");
- continue;
- case '\"':
- retval.append("\\\"");
- continue;
- case '\'':
- retval.append("\\\'");
- continue;
- case '\\':
- retval.append("\\\\");
- continue;
- default:
- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
- String s = "0000" + Integer.toString(ch, 16);
- retval.append("\\u" + s.substring(s.length() - 4, s.length()));
- } else {
- retval.append(ch);
- }
- continue;
- }
- }
- return retval.toString();
- }
-
- /**
- * Returns a detailed message for the Error when it is thrown by the
- * token manager to indicate a lexical error.
- * Parameters :
- * EOFSeen : indicates if EOF caused the lexicl error
- * curLexState : lexical state in which this error occured
- * errorLine : line number when the error occured
- * errorColumn : column number when the error occured
- * errorAfter : prefix that was seen before this error occured
- * curchar : the offending character
- * Note: You can customize the lexical error message by modifying this method.
- */
- protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
- return("Lexical error at line " +
- errorLine + ", column " +
- errorColumn + ". Encountered: " +
- (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
- "after : \"" + addEscapes(errorAfter) + "\"");
- }
-
- /**
- * You can also modify the body of this method to customize your error messages.
- * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
- * of end-users concern, so you can return something like :
- *
- * "Internal Error : Please file a bug report .... "
- *
- * from this method for such cases in the release version of your parser.
- */
- public String getMessage() {
- return super.getMessage();
- }
-
- /*
- * Constructors of various flavors follow.
- */
-
- public TokenMgrError() {
- }
-
- public TokenMgrError(String message, int reason) {
- super(message);
- errorCode = reason;
- }
-
- public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
- this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/DateTime.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/DateTime.java
deleted file mode 100644
index bf00ca753..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/DateTime.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.field.datetime;
-
-import org.apache.james.mime4j.field.datetime.parser.DateTimeParser;
-import org.apache.james.mime4j.field.datetime.parser.ParseException;
-import org.apache.james.mime4j.field.datetime.parser.TokenMgrError;
-
-import java.util.Date;
-import java.util.Calendar;
-import java.util.TimeZone;
-import java.util.GregorianCalendar;
-import java.io.StringReader;
-
-public class DateTime {
- private final Date date;
- private final int year;
- private final int month;
- private final int day;
- private final int hour;
- private final int minute;
- private final int second;
- private final int timeZone;
-
- public DateTime(String yearString, int month, int day, int hour, int minute, int second, int timeZone) {
- this.year = convertToYear(yearString);
- this.date = convertToDate(year, month, day, hour, minute, second, timeZone);
- this.month = month;
- this.day = day;
- this.hour = hour;
- this.minute = minute;
- this.second = second;
- this.timeZone = timeZone;
- }
-
- private int convertToYear(String yearString) {
- int year = Integer.parseInt(yearString);
- switch (yearString.length()) {
- case 1:
- case 2:
- if (year >= 0 && year < 50)
- return 2000 + year;
- else
- return 1900 + year;
- case 3:
- return 1900 + year;
- default:
- return year;
- }
- }
-
- public static Date convertToDate(int year, int month, int day, int hour, int minute, int second, int timeZone) {
- Calendar c = new GregorianCalendar(TimeZone.getTimeZone("GMT+0"));
- c.set(year, month - 1, day, hour, minute, second);
- c.set(Calendar.MILLISECOND, 0);
-
- if (timeZone != Integer.MIN_VALUE) {
- int minutes = ((timeZone / 100) * 60) + timeZone % 100;
- c.add(Calendar.MINUTE, -1 * minutes);
- }
-
- return c.getTime();
- }
-
- public Date getDate() {
- return date;
- }
-
- public int getYear() {
- return year;
- }
-
- public int getMonth() {
- return month;
- }
-
- public int getDay() {
- return day;
- }
-
- public int getHour() {
- return hour;
- }
-
- public int getMinute() {
- return minute;
- }
-
- public int getSecond() {
- return second;
- }
-
- public int getTimeZone() {
- return timeZone;
- }
-
- public void print() {
- System.out.println(getYear() + " " + getMonth() + " " + getDay() + "; " + getHour() + " " + getMinute() + " " + getSecond() + " " + getTimeZone());
- }
-
-
- public static DateTime parse(String dateString) throws ParseException {
- try {
- return new DateTimeParser(new StringReader(dateString)).parseAll();
- }
- catch (TokenMgrError err) {
- throw new ParseException(err.getMessage());
- }
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParser.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParser.java
deleted file mode 100644
index 04cb9520b..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParser.java
+++ /dev/null
@@ -1,570 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. DateTimeParser.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.datetime.parser;
-
-import org.apache.james.mime4j.field.datetime.DateTime;
-
-import java.util.Vector;
-
-public class DateTimeParser implements DateTimeParserConstants {
- private static final boolean ignoreMilitaryZoneOffset = true;
-
- public static void main(String args[]) throws ParseException {
- while (true) {
- try {
- DateTimeParser parser = new DateTimeParser(System.in);
- parser.parseLine();
- } catch (Exception x) {
- x.printStackTrace();
- return;
- }
- }
- }
-
- private static int parseDigits(Token token) {
- return Integer.parseInt(token.image, 10);
- }
-
- private static int getMilitaryZoneOffset(char c) {
- if (ignoreMilitaryZoneOffset)
- return 0;
-
- c = Character.toUpperCase(c);
-
- switch (c) {
- case 'A': return 1;
- case 'B': return 2;
- case 'C': return 3;
- case 'D': return 4;
- case 'E': return 5;
- case 'F': return 6;
- case 'G': return 7;
- case 'H': return 8;
- case 'I': return 9;
- case 'K': return 10;
- case 'L': return 11;
- case 'M': return 12;
-
- case 'N': return -1;
- case 'O': return -2;
- case 'P': return -3;
- case 'Q': return -4;
- case 'R': return -5;
- case 'S': return -6;
- case 'T': return -7;
- case 'U': return -8;
- case 'V': return -9;
- case 'W': return -10;
- case 'X': return -11;
- case 'Y': return -12;
-
- case 'Z': return 0;
- default: return 0;
- }
- }
-
- private static class Time {
- private int hour;
- private int minute;
- private int second;
- private int zone;
-
- public Time(int hour, int minute, int second, int zone) {
- this.hour = hour;
- this.minute = minute;
- this.second = second;
- this.zone = zone;
- }
-
- public int getHour() { return hour; }
- public int getMinute() { return minute; }
- public int getSecond() { return second; }
- public int getZone() { return zone; }
- }
-
- private static class Date {
- private String year;
- private int month;
- private int day;
-
- public Date(String year, int month, int day) {
- this.year = year;
- this.month = month;
- this.day = day;
- }
-
- public String getYear() { return year; }
- public int getMonth() { return month; }
- public int getDay() { return day; }
- }
-
- final public DateTime parseLine() throws ParseException {
- DateTime dt;
- dt = date_time();
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 1:
- jj_consume_token(1);
- break;
- default:
- jj_la1[0] = jj_gen;
- ;
- }
- jj_consume_token(2);
- {if (true) return dt;}
- throw new Error("Missing return statement in function");
- }
-
- final public DateTime parseAll() throws ParseException {
- DateTime dt;
- dt = date_time();
- jj_consume_token(0);
- {if (true) return dt;}
- throw new Error("Missing return statement in function");
- }
-
- final public DateTime date_time() throws ParseException {
- Date d; Time t;
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 4:
- case 5:
- case 6:
- case 7:
- case 8:
- case 9:
- case 10:
- day_of_week();
- jj_consume_token(3);
- break;
- default:
- jj_la1[1] = jj_gen;
- ;
- }
- d = date();
- t = time();
- {if (true) return new DateTime(
- d.getYear(),
- d.getMonth(),
- d.getDay(),
- t.getHour(),
- t.getMinute(),
- t.getSecond(),
- t.getZone());} // time zone offset
-
- throw new Error("Missing return statement in function");
- }
-
- final public String day_of_week() throws ParseException {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 4:
- jj_consume_token(4);
- break;
- case 5:
- jj_consume_token(5);
- break;
- case 6:
- jj_consume_token(6);
- break;
- case 7:
- jj_consume_token(7);
- break;
- case 8:
- jj_consume_token(8);
- break;
- case 9:
- jj_consume_token(9);
- break;
- case 10:
- jj_consume_token(10);
- break;
- default:
- jj_la1[2] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- {if (true) return token.image;}
- throw new Error("Missing return statement in function");
- }
-
- final public Date date() throws ParseException {
- int d, m; String y;
- d = day();
- m = month();
- y = year();
- {if (true) return new Date(y, m, d);}
- throw new Error("Missing return statement in function");
- }
-
- final public int day() throws ParseException {
- Token t;
- t = jj_consume_token(DIGITS);
- {if (true) return parseDigits(t);}
- throw new Error("Missing return statement in function");
- }
-
- final public int month() throws ParseException {
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 11:
- jj_consume_token(11);
- {if (true) return 1;}
- break;
- case 12:
- jj_consume_token(12);
- {if (true) return 2;}
- break;
- case 13:
- jj_consume_token(13);
- {if (true) return 3;}
- break;
- case 14:
- jj_consume_token(14);
- {if (true) return 4;}
- break;
- case 15:
- jj_consume_token(15);
- {if (true) return 5;}
- break;
- case 16:
- jj_consume_token(16);
- {if (true) return 6;}
- break;
- case 17:
- jj_consume_token(17);
- {if (true) return 7;}
- break;
- case 18:
- jj_consume_token(18);
- {if (true) return 8;}
- break;
- case 19:
- jj_consume_token(19);
- {if (true) return 9;}
- break;
- case 20:
- jj_consume_token(20);
- {if (true) return 10;}
- break;
- case 21:
- jj_consume_token(21);
- {if (true) return 11;}
- break;
- case 22:
- jj_consume_token(22);
- {if (true) return 12;}
- break;
- default:
- jj_la1[3] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- throw new Error("Missing return statement in function");
- }
-
- final public String year() throws ParseException {
- Token t;
- t = jj_consume_token(DIGITS);
- {if (true) return t.image;}
- throw new Error("Missing return statement in function");
- }
-
- final public Time time() throws ParseException {
- int h, m, s=0, z;
- h = hour();
- jj_consume_token(23);
- m = minute();
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 23:
- jj_consume_token(23);
- s = second();
- break;
- default:
- jj_la1[4] = jj_gen;
- ;
- }
- z = zone();
- {if (true) return new Time(h, m, s, z);}
- throw new Error("Missing return statement in function");
- }
-
- final public int hour() throws ParseException {
- Token t;
- t = jj_consume_token(DIGITS);
- {if (true) return parseDigits(t);}
- throw new Error("Missing return statement in function");
- }
-
- final public int minute() throws ParseException {
- Token t;
- t = jj_consume_token(DIGITS);
- {if (true) return parseDigits(t);}
- throw new Error("Missing return statement in function");
- }
-
- final public int second() throws ParseException {
- Token t;
- t = jj_consume_token(DIGITS);
- {if (true) return parseDigits(t);}
- throw new Error("Missing return statement in function");
- }
-
- final public int zone() throws ParseException {
- Token t, u; int z;
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case OFFSETDIR:
- t = jj_consume_token(OFFSETDIR);
- u = jj_consume_token(DIGITS);
- z=parseDigits(u)*(t.image.equals("-") ? -1 : 1);
- break;
- case 25:
- case 26:
- case 27:
- case 28:
- case 29:
- case 30:
- case 31:
- case 32:
- case 33:
- case 34:
- case MILITARY_ZONE:
- z = obs_zone();
- break;
- default:
- jj_la1[5] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- {if (true) return z;}
- throw new Error("Missing return statement in function");
- }
-
- final public int obs_zone() throws ParseException {
- Token t; int z;
- switch ((jj_ntk==-1)?jj_ntk():jj_ntk) {
- case 25:
- jj_consume_token(25);
- z=0;
- break;
- case 26:
- jj_consume_token(26);
- z=0;
- break;
- case 27:
- jj_consume_token(27);
- z=-5;
- break;
- case 28:
- jj_consume_token(28);
- z=-4;
- break;
- case 29:
- jj_consume_token(29);
- z=-6;
- break;
- case 30:
- jj_consume_token(30);
- z=-5;
- break;
- case 31:
- jj_consume_token(31);
- z=-7;
- break;
- case 32:
- jj_consume_token(32);
- z=-6;
- break;
- case 33:
- jj_consume_token(33);
- z=-8;
- break;
- case 34:
- jj_consume_token(34);
- z=-7;
- break;
- case MILITARY_ZONE:
- t = jj_consume_token(MILITARY_ZONE);
- z=getMilitaryZoneOffset(t.image.charAt(0));
- break;
- default:
- jj_la1[6] = jj_gen;
- jj_consume_token(-1);
- throw new ParseException();
- }
- {if (true) return z * 100;}
- throw new Error("Missing return statement in function");
- }
-
- public DateTimeParserTokenManager token_source;
- SimpleCharStream jj_input_stream;
- public Token token, jj_nt;
- private int jj_ntk;
- private int jj_gen;
- final private int[] jj_la1 = new int[7];
- static private int[] jj_la1_0;
- static private int[] jj_la1_1;
- static {
- jj_la1_0();
- jj_la1_1();
- }
- private static void jj_la1_0() {
- jj_la1_0 = new int[] {0x2,0x7f0,0x7f0,0x7ff800,0x800000,0xff000000,0xfe000000,};
- }
- private static void jj_la1_1() {
- jj_la1_1 = new int[] {0x0,0x0,0x0,0x0,0x0,0xf,0xf,};
- }
-
- public DateTimeParser(java.io.InputStream stream) {
- this(stream, null);
- }
- public DateTimeParser(java.io.InputStream stream, String encoding) {
- try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
- token_source = new DateTimeParserTokenManager(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 7; i++) jj_la1[i] = -1;
- }
-
- public void ReInit(java.io.InputStream stream) {
- ReInit(stream, null);
- }
- public void ReInit(java.io.InputStream stream, String encoding) {
- try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); }
- token_source.ReInit(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 7; i++) jj_la1[i] = -1;
- }
-
- public DateTimeParser(java.io.Reader stream) {
- jj_input_stream = new SimpleCharStream(stream, 1, 1);
- token_source = new DateTimeParserTokenManager(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 7; i++) jj_la1[i] = -1;
- }
-
- public void ReInit(java.io.Reader stream) {
- jj_input_stream.ReInit(stream, 1, 1);
- token_source.ReInit(jj_input_stream);
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 7; i++) jj_la1[i] = -1;
- }
-
- public DateTimeParser(DateTimeParserTokenManager tm) {
- token_source = tm;
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 7; i++) jj_la1[i] = -1;
- }
-
- public void ReInit(DateTimeParserTokenManager tm) {
- token_source = tm;
- token = new Token();
- jj_ntk = -1;
- jj_gen = 0;
- for (int i = 0; i < 7; i++) jj_la1[i] = -1;
- }
-
- final private Token jj_consume_token(int kind) throws ParseException {
- Token oldToken;
- if ((oldToken = token).next != null) token = token.next;
- else token = token.next = token_source.getNextToken();
- jj_ntk = -1;
- if (token.kind == kind) {
- jj_gen++;
- return token;
- }
- token = oldToken;
- jj_kind = kind;
- throw generateParseException();
- }
-
- final public Token getNextToken() {
- if (token.next != null) token = token.next;
- else token = token.next = token_source.getNextToken();
- jj_ntk = -1;
- jj_gen++;
- return token;
- }
-
- final public Token getToken(int index) {
- Token t = token;
- for (int i = 0; i < index; i++) {
- if (t.next != null) t = t.next;
- else t = t.next = token_source.getNextToken();
- }
- return t;
- }
-
- final private int jj_ntk() {
- if ((jj_nt=token.next) == null)
- return (jj_ntk = (token.next=token_source.getNextToken()).kind);
- else
- return (jj_ntk = jj_nt.kind);
- }
-
- private Vector<int[]> jj_expentries = new Vector<int[]>();
- private int[] jj_expentry;
- private int jj_kind = -1;
-
- public ParseException generateParseException() {
- jj_expentries.removeAllElements();
- boolean[] la1tokens = new boolean[49];
- for (int i = 0; i < 49; i++) {
- la1tokens[i] = false;
- }
- if (jj_kind >= 0) {
- la1tokens[jj_kind] = true;
- jj_kind = -1;
- }
- for (int i = 0; i < 7; i++) {
- if (jj_la1[i] == jj_gen) {
- for (int j = 0; j < 32; j++) {
- if ((jj_la1_0[i] & (1<<j)) != 0) {
- la1tokens[j] = true;
- }
- if ((jj_la1_1[i] & (1<<j)) != 0) {
- la1tokens[32+j] = true;
- }
- }
- }
- }
- for (int i = 0; i < 49; i++) {
- if (la1tokens[i]) {
- jj_expentry = new int[1];
- jj_expentry[0] = i;
- jj_expentries.addElement(jj_expentry);
- }
- }
- int[][] exptokseq = new int[jj_expentries.size()][];
- for (int i = 0; i < jj_expentries.size(); i++) {
- exptokseq[i] = jj_expentries.elementAt(i);
- }
- return new ParseException(token, exptokseq, tokenImage);
- }
-
- final public void enable_tracing() {
- }
-
- final public void disable_tracing() {
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserConstants.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserConstants.java
deleted file mode 100644
index 17389d816..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserConstants.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. DateTimeParserConstants.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.datetime.parser;
-
-public interface DateTimeParserConstants {
-
- int EOF = 0;
- int OFFSETDIR = 24;
- int MILITARY_ZONE = 35;
- int WS = 36;
- int COMMENT = 38;
- int DIGITS = 46;
- int QUOTEDPAIR = 47;
- int ANY = 48;
-
- int DEFAULT = 0;
- int INCOMMENT = 1;
- int NESTED_COMMENT = 2;
-
- String[] tokenImage = {
- "<EOF>",
- "\"\\r\"",
- "\"\\n\"",
- "\",\"",
- "\"Mon\"",
- "\"Tue\"",
- "\"Wed\"",
- "\"Thu\"",
- "\"Fri\"",
- "\"Sat\"",
- "\"Sun\"",
- "\"Jan\"",
- "\"Feb\"",
- "\"Mar\"",
- "\"Apr\"",
- "\"May\"",
- "\"Jun\"",
- "\"Jul\"",
- "\"Aug\"",
- "\"Sep\"",
- "\"Oct\"",
- "\"Nov\"",
- "\"Dec\"",
- "\":\"",
- "<OFFSETDIR>",
- "\"UT\"",
- "\"GMT\"",
- "\"EST\"",
- "\"EDT\"",
- "\"CST\"",
- "\"CDT\"",
- "\"MST\"",
- "\"MDT\"",
- "\"PST\"",
- "\"PDT\"",
- "<MILITARY_ZONE>",
- "<WS>",
- "\"(\"",
- "\")\"",
- "<token of kind 39>",
- "\"(\"",
- "<token of kind 41>",
- "<token of kind 42>",
- "\"(\"",
- "\")\"",
- "<token of kind 45>",
- "<DIGITS>",
- "<QUOTEDPAIR>",
- "<ANY>",
- };
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserTokenManager.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserTokenManager.java
deleted file mode 100644
index e75998cf2..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/DateTimeParserTokenManager.java
+++ /dev/null
@@ -1,882 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. DateTimeParserTokenManager.java */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.datetime.parser;
-import org.apache.james.mime4j.field.datetime.DateTime;
-import java.util.Calendar;
-
-public class DateTimeParserTokenManager implements DateTimeParserConstants
-{
- // Keeps track of how many levels of comment nesting
- // we've encountered. This is only used when the 2nd
- // level is reached, for example ((this)), not (this).
- // This is because the outermost level must be treated
- // specially anyway, because the outermost ")" has a
- // different token type than inner ")" instances.
- static int commentNest;
- public java.io.PrintStream debugStream = System.out;
- public void setDebugStream(java.io.PrintStream ds) { debugStream = ds; }
-private final int jjStopStringLiteralDfa_0(int pos, long active0)
-{
- switch (pos)
- {
- case 0:
- if ((active0 & 0x7fe7cf7f0L) != 0L)
- {
- jjmatchedKind = 35;
- return -1;
- }
- return -1;
- case 1:
- if ((active0 & 0x7fe7cf7f0L) != 0L)
- {
- if (jjmatchedPos == 0)
- {
- jjmatchedKind = 35;
- jjmatchedPos = 0;
- }
- return -1;
- }
- return -1;
- default :
- return -1;
- }
-}
-private final int jjStartNfa_0(int pos, long active0)
-{
- return jjMoveNfa_0(jjStopStringLiteralDfa_0(pos, active0), pos + 1);
-}
-private final int jjStopAtPos(int pos, int kind)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- return pos + 1;
-}
-private final int jjStartNfaWithStates_0(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_0(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_0()
-{
- switch(curChar)
- {
- case 10:
- return jjStopAtPos(0, 2);
- case 13:
- return jjStopAtPos(0, 1);
- case 40:
- return jjStopAtPos(0, 37);
- case 44:
- return jjStopAtPos(0, 3);
- case 58:
- return jjStopAtPos(0, 23);
- case 65:
- return jjMoveStringLiteralDfa1_0(0x44000L);
- case 67:
- return jjMoveStringLiteralDfa1_0(0x60000000L);
- case 68:
- return jjMoveStringLiteralDfa1_0(0x400000L);
- case 69:
- return jjMoveStringLiteralDfa1_0(0x18000000L);
- case 70:
- return jjMoveStringLiteralDfa1_0(0x1100L);
- case 71:
- return jjMoveStringLiteralDfa1_0(0x4000000L);
- case 74:
- return jjMoveStringLiteralDfa1_0(0x30800L);
- case 77:
- return jjMoveStringLiteralDfa1_0(0x18000a010L);
- case 78:
- return jjMoveStringLiteralDfa1_0(0x200000L);
- case 79:
- return jjMoveStringLiteralDfa1_0(0x100000L);
- case 80:
- return jjMoveStringLiteralDfa1_0(0x600000000L);
- case 83:
- return jjMoveStringLiteralDfa1_0(0x80600L);
- case 84:
- return jjMoveStringLiteralDfa1_0(0xa0L);
- case 85:
- return jjMoveStringLiteralDfa1_0(0x2000000L);
- case 87:
- return jjMoveStringLiteralDfa1_0(0x40L);
- default :
- return jjMoveNfa_0(0, 0);
- }
-}
-private final int jjMoveStringLiteralDfa1_0(long active0)
-{
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) {
- jjStopStringLiteralDfa_0(0, active0);
- return 1;
- }
- switch(curChar)
- {
- case 68:
- return jjMoveStringLiteralDfa2_0(active0, 0x550000000L);
- case 77:
- return jjMoveStringLiteralDfa2_0(active0, 0x4000000L);
- case 83:
- return jjMoveStringLiteralDfa2_0(active0, 0x2a8000000L);
- case 84:
- if ((active0 & 0x2000000L) != 0L)
- return jjStopAtPos(1, 25);
- break;
- case 97:
- return jjMoveStringLiteralDfa2_0(active0, 0xaa00L);
- case 99:
- return jjMoveStringLiteralDfa2_0(active0, 0x100000L);
- case 101:
- return jjMoveStringLiteralDfa2_0(active0, 0x481040L);
- case 104:
- return jjMoveStringLiteralDfa2_0(active0, 0x80L);
- case 111:
- return jjMoveStringLiteralDfa2_0(active0, 0x200010L);
- case 112:
- return jjMoveStringLiteralDfa2_0(active0, 0x4000L);
- case 114:
- return jjMoveStringLiteralDfa2_0(active0, 0x100L);
- case 117:
- return jjMoveStringLiteralDfa2_0(active0, 0x70420L);
- default :
- break;
- }
- return jjStartNfa_0(0, active0);
-}
-private final int jjMoveStringLiteralDfa2_0(long old0, long active0)
-{
- if (((active0 &= old0)) == 0L)
- return jjStartNfa_0(0, old0);
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) {
- jjStopStringLiteralDfa_0(1, active0);
- return 2;
- }
- switch(curChar)
- {
- case 84:
- if ((active0 & 0x4000000L) != 0L)
- return jjStopAtPos(2, 26);
- else if ((active0 & 0x8000000L) != 0L)
- return jjStopAtPos(2, 27);
- else if ((active0 & 0x10000000L) != 0L)
- return jjStopAtPos(2, 28);
- else if ((active0 & 0x20000000L) != 0L)
- return jjStopAtPos(2, 29);
- else if ((active0 & 0x40000000L) != 0L)
- return jjStopAtPos(2, 30);
- else if ((active0 & 0x80000000L) != 0L)
- return jjStopAtPos(2, 31);
- else if ((active0 & 0x100000000L) != 0L)
- return jjStopAtPos(2, 32);
- else if ((active0 & 0x200000000L) != 0L)
- return jjStopAtPos(2, 33);
- else if ((active0 & 0x400000000L) != 0L)
- return jjStopAtPos(2, 34);
- break;
- case 98:
- if ((active0 & 0x1000L) != 0L)
- return jjStopAtPos(2, 12);
- break;
- case 99:
- if ((active0 & 0x400000L) != 0L)
- return jjStopAtPos(2, 22);
- break;
- case 100:
- if ((active0 & 0x40L) != 0L)
- return jjStopAtPos(2, 6);
- break;
- case 101:
- if ((active0 & 0x20L) != 0L)
- return jjStopAtPos(2, 5);
- break;
- case 103:
- if ((active0 & 0x40000L) != 0L)
- return jjStopAtPos(2, 18);
- break;
- case 105:
- if ((active0 & 0x100L) != 0L)
- return jjStopAtPos(2, 8);
- break;
- case 108:
- if ((active0 & 0x20000L) != 0L)
- return jjStopAtPos(2, 17);
- break;
- case 110:
- if ((active0 & 0x10L) != 0L)
- return jjStopAtPos(2, 4);
- else if ((active0 & 0x400L) != 0L)
- return jjStopAtPos(2, 10);
- else if ((active0 & 0x800L) != 0L)
- return jjStopAtPos(2, 11);
- else if ((active0 & 0x10000L) != 0L)
- return jjStopAtPos(2, 16);
- break;
- case 112:
- if ((active0 & 0x80000L) != 0L)
- return jjStopAtPos(2, 19);
- break;
- case 114:
- if ((active0 & 0x2000L) != 0L)
- return jjStopAtPos(2, 13);
- else if ((active0 & 0x4000L) != 0L)
- return jjStopAtPos(2, 14);
- break;
- case 116:
- if ((active0 & 0x200L) != 0L)
- return jjStopAtPos(2, 9);
- else if ((active0 & 0x100000L) != 0L)
- return jjStopAtPos(2, 20);
- break;
- case 117:
- if ((active0 & 0x80L) != 0L)
- return jjStopAtPos(2, 7);
- break;
- case 118:
- if ((active0 & 0x200000L) != 0L)
- return jjStopAtPos(2, 21);
- break;
- case 121:
- if ((active0 & 0x8000L) != 0L)
- return jjStopAtPos(2, 15);
- break;
- default :
- break;
- }
- return jjStartNfa_0(1, active0);
-}
-private final void jjCheckNAdd(int state)
-{
- if (jjrounds[state] != jjround)
- {
- jjstateSet[jjnewStateCnt++] = state;
- jjrounds[state] = jjround;
- }
-}
-private final void jjAddStates(int start, int end)
-{
- do {
- jjstateSet[jjnewStateCnt++] = jjnextStates[start];
- } while (start++ != end);
-}
-private final void jjCheckNAddTwoStates(int state1, int state2)
-{
- jjCheckNAdd(state1);
- jjCheckNAdd(state2);
-}
-private final void jjCheckNAddStates(int start, int end)
-{
- do {
- jjCheckNAdd(jjnextStates[start]);
- } while (start++ != end);
-}
-private final void jjCheckNAddStates(int start)
-{
- jjCheckNAdd(jjnextStates[start]);
- jjCheckNAdd(jjnextStates[start + 1]);
-}
-private final int jjMoveNfa_0(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 4;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((0x3ff000000000000L & l) != 0L)
- {
- if (kind > 46)
- kind = 46;
- jjCheckNAdd(3);
- }
- else if ((0x100000200L & l) != 0L)
- {
- if (kind > 36)
- kind = 36;
- jjCheckNAdd(2);
- }
- else if ((0x280000000000L & l) != 0L)
- {
- if (kind > 24)
- kind = 24;
- }
- break;
- case 2:
- if ((0x100000200L & l) == 0L)
- break;
- kind = 36;
- jjCheckNAdd(2);
- break;
- case 3:
- if ((0x3ff000000000000L & l) == 0L)
- break;
- kind = 46;
- jjCheckNAdd(3);
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((0x7fffbfe07fffbfeL & l) != 0L)
- kind = 35;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 4 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_1(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_1(int pos, long active0)
-{
- return jjMoveNfa_1(jjStopStringLiteralDfa_1(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_1(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_1(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_1()
-{
- switch(curChar)
- {
- case 40:
- return jjStopAtPos(0, 40);
- case 41:
- return jjStopAtPos(0, 38);
- default :
- return jjMoveNfa_1(0, 0);
- }
-}
-static final long[] jjbitVec0 = {
- 0x0L, 0x0L, 0xffffffffffffffffL, 0xffffffffffffffffL
-};
-private final int jjMoveNfa_1(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 41)
- kind = 41;
- break;
- case 1:
- if (kind > 39)
- kind = 39;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 41)
- kind = 41;
- if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 39)
- kind = 39;
- break;
- case 2:
- if (kind > 41)
- kind = 41;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 41)
- kind = 41;
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 39)
- kind = 39;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-private final int jjStopStringLiteralDfa_2(int pos, long active0)
-{
- switch (pos)
- {
- default :
- return -1;
- }
-}
-private final int jjStartNfa_2(int pos, long active0)
-{
- return jjMoveNfa_2(jjStopStringLiteralDfa_2(pos, active0), pos + 1);
-}
-private final int jjStartNfaWithStates_2(int pos, int kind, int state)
-{
- jjmatchedKind = kind;
- jjmatchedPos = pos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return pos + 1; }
- return jjMoveNfa_2(state, pos + 1);
-}
-private final int jjMoveStringLiteralDfa0_2()
-{
- switch(curChar)
- {
- case 40:
- return jjStopAtPos(0, 43);
- case 41:
- return jjStopAtPos(0, 44);
- default :
- return jjMoveNfa_2(0, 0);
- }
-}
-private final int jjMoveNfa_2(int startState, int curPos)
-{
- int[] nextStates;
- int startsAt = 0;
- jjnewStateCnt = 3;
- int i = 1;
- jjstateSet[0] = startState;
- int j, kind = 0x7fffffff;
- for (;;)
- {
- if (++jjround == 0x7fffffff)
- ReInitRounds();
- if (curChar < 64)
- {
- long l = 1L << curChar;
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 45)
- kind = 45;
- break;
- case 1:
- if (kind > 42)
- kind = 42;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else if (curChar < 128)
- {
- long l = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if (kind > 45)
- kind = 45;
- if (curChar == 92)
- jjstateSet[jjnewStateCnt++] = 1;
- break;
- case 1:
- if (kind > 42)
- kind = 42;
- break;
- case 2:
- if (kind > 45)
- kind = 45;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- else
- {
- int i2 = (curChar & 0xff) >> 6;
- long l2 = 1L << (curChar & 077);
- MatchLoop: do
- {
- switch(jjstateSet[--i])
- {
- case 0:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 45)
- kind = 45;
- break;
- case 1:
- if ((jjbitVec0[i2] & l2) != 0L && kind > 42)
- kind = 42;
- break;
- default : break;
- }
- } while(i != startsAt);
- }
- if (kind != 0x7fffffff)
- {
- jjmatchedKind = kind;
- jjmatchedPos = curPos;
- kind = 0x7fffffff;
- }
- ++curPos;
- if ((i = jjnewStateCnt) == (startsAt = 3 - (jjnewStateCnt = startsAt)))
- return curPos;
- try { curChar = input_stream.readChar(); }
- catch(java.io.IOException e) { return curPos; }
- }
-}
-static final int[] jjnextStates = {
-};
-public static final String[] jjstrLiteralImages = {
-"", "\15", "\12", "\54", "\115\157\156", "\124\165\145", "\127\145\144",
-"\124\150\165", "\106\162\151", "\123\141\164", "\123\165\156", "\112\141\156",
-"\106\145\142", "\115\141\162", "\101\160\162", "\115\141\171", "\112\165\156",
-"\112\165\154", "\101\165\147", "\123\145\160", "\117\143\164", "\116\157\166",
-"\104\145\143", "\72", null, "\125\124", "\107\115\124", "\105\123\124", "\105\104\124",
-"\103\123\124", "\103\104\124", "\115\123\124", "\115\104\124", "\120\123\124",
-"\120\104\124", null, null, null, null, null, null, null, null, null, null, null, null, null,
-null, };
-public static final String[] lexStateNames = {
- "DEFAULT",
- "INCOMMENT",
- "NESTED_COMMENT",
-};
-public static final int[] jjnewLexState = {
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
- -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, 0, -1, 2, -1, -1, -1, -1, -1, -1, -1, -1,
-};
-static final long[] jjtoToken = {
- 0x400fffffffffL,
-};
-static final long[] jjtoSkip = {
- 0x5000000000L,
-};
-static final long[] jjtoSpecial = {
- 0x1000000000L,
-};
-static final long[] jjtoMore = {
- 0x3fa000000000L,
-};
-protected SimpleCharStream input_stream;
-private final int[] jjrounds = new int[4];
-private final int[] jjstateSet = new int[8];
-StringBuffer image;
-int jjimageLen;
-int lengthOfMatch;
-protected char curChar;
-public DateTimeParserTokenManager(SimpleCharStream stream){
- if (SimpleCharStream.staticFlag)
- throw new Error("ERROR: Cannot use a static CharStream class with a non-static lexical analyzer.");
- input_stream = stream;
-}
-public DateTimeParserTokenManager(SimpleCharStream stream, int lexState){
- this(stream);
- SwitchTo(lexState);
-}
-public void ReInit(SimpleCharStream stream)
-{
- jjmatchedPos = jjnewStateCnt = 0;
- curLexState = defaultLexState;
- input_stream = stream;
- ReInitRounds();
-}
-private final void ReInitRounds()
-{
- int i;
- jjround = 0x80000001;
- for (i = 4; i-- > 0;)
- jjrounds[i] = 0x80000000;
-}
-public void ReInit(SimpleCharStream stream, int lexState)
-{
- ReInit(stream);
- SwitchTo(lexState);
-}
-public void SwitchTo(int lexState)
-{
- if (lexState >= 3 || lexState < 0)
- throw new TokenMgrError("Error: Ignoring invalid lexical state : " + lexState + ". State unchanged.", TokenMgrError.INVALID_LEXICAL_STATE);
- else
- curLexState = lexState;
-}
-
-protected Token jjFillToken()
-{
- Token t = Token.newToken(jjmatchedKind);
- t.kind = jjmatchedKind;
- String im = jjstrLiteralImages[jjmatchedKind];
- t.image = (im == null) ? input_stream.GetImage() : im;
- t.beginLine = input_stream.getBeginLine();
- t.beginColumn = input_stream.getBeginColumn();
- t.endLine = input_stream.getEndLine();
- t.endColumn = input_stream.getEndColumn();
- return t;
-}
-
-int curLexState = 0;
-int defaultLexState = 0;
-int jjnewStateCnt;
-int jjround;
-int jjmatchedPos;
-int jjmatchedKind;
-
-public Token getNextToken()
-{
- int kind;
- Token specialToken = null;
- Token matchedToken;
- int curPos = 0;
-
- EOFLoop :
- for (;;)
- {
- try
- {
- curChar = input_stream.BeginToken();
- }
- catch(java.io.IOException e)
- {
- jjmatchedKind = 0;
- matchedToken = jjFillToken();
- matchedToken.specialToken = specialToken;
- return matchedToken;
- }
- image = null;
- jjimageLen = 0;
-
- for (;;)
- {
- switch(curLexState)
- {
- case 0:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_0();
- break;
- case 1:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_1();
- break;
- case 2:
- jjmatchedKind = 0x7fffffff;
- jjmatchedPos = 0;
- curPos = jjMoveStringLiteralDfa0_2();
- break;
- }
- if (jjmatchedKind != 0x7fffffff)
- {
- if (jjmatchedPos + 1 < curPos)
- input_stream.backup(curPos - jjmatchedPos - 1);
- if ((jjtoToken[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- matchedToken = jjFillToken();
- matchedToken.specialToken = specialToken;
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- return matchedToken;
- }
- else if ((jjtoSkip[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- if ((jjtoSpecial[jjmatchedKind >> 6] & (1L << (jjmatchedKind & 077))) != 0L)
- {
- matchedToken = jjFillToken();
- if (specialToken == null)
- specialToken = matchedToken;
- else
- {
- matchedToken.specialToken = specialToken;
- specialToken = (specialToken.next = matchedToken);
- }
- }
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- continue EOFLoop;
- }
- MoreLexicalActions();
- if (jjnewLexState[jjmatchedKind] != -1)
- curLexState = jjnewLexState[jjmatchedKind];
- curPos = 0;
- jjmatchedKind = 0x7fffffff;
- try {
- curChar = input_stream.readChar();
- continue;
- }
- catch (java.io.IOException e1) { }
- }
- int error_line = input_stream.getEndLine();
- int error_column = input_stream.getEndColumn();
- String error_after = null;
- boolean EOFSeen = false;
- try { input_stream.readChar(); input_stream.backup(1); }
- catch (java.io.IOException e1) {
- EOFSeen = true;
- error_after = curPos <= 1 ? "" : input_stream.GetImage();
- if (curChar == '\n' || curChar == '\r') {
- error_line++;
- error_column = 0;
- }
- else
- error_column++;
- }
- if (!EOFSeen) {
- input_stream.backup(1);
- error_after = curPos <= 1 ? "" : input_stream.GetImage();
- }
- throw new TokenMgrError(EOFSeen, curLexState, error_line, error_column, error_after, curChar, TokenMgrError.LEXICAL_ERROR);
- }
- }
-}
-
-void MoreLexicalActions()
-{
- jjimageLen += (lengthOfMatch = jjmatchedPos + 1);
- switch(jjmatchedKind)
- {
- case 39 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- case 40 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- commentNest = 1;
- break;
- case 42 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- image.deleteCharAt(image.length() - 2);
- break;
- case 43 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- ++commentNest;
- break;
- case 44 :
- if (image == null)
- image = new StringBuffer();
- image.append(input_stream.GetSuffix(jjimageLen));
- jjimageLen = 0;
- --commentNest; if (commentNest == 0) SwitchTo(INCOMMENT);
- break;
- default :
- break;
- }
-}
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/ParseException.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/ParseException.java
deleted file mode 100644
index 418699107..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/ParseException.java
+++ /dev/null
@@ -1,207 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.datetime.parser;
-
-/**
- * This exception is thrown when parse errors are encountered.
- * You can explicitly create objects of this exception type by
- * calling the method generateParseException in the generated
- * parser.
- *
- * You can modify this class to customize your error reporting
- * mechanisms so long as you retain the public fields.
- */
-public class ParseException extends Exception {
-
- /**
- * This constructor is used by the method "generateParseException"
- * in the generated parser. Calling this constructor generates
- * a new object of this type with the fields "currentToken",
- * "expectedTokenSequences", and "tokenImage" set. The boolean
- * flag "specialConstructor" is also set to true to indicate that
- * this constructor was used to create this object.
- * This constructor calls its super class with the empty string
- * to force the "toString" method of parent class "Throwable" to
- * print the error message in the form:
- * ParseException: <result of getMessage>
- */
- public ParseException(Token currentTokenVal,
- int[][] expectedTokenSequencesVal,
- String[] tokenImageVal
- )
- {
- super("");
- specialConstructor = true;
- currentToken = currentTokenVal;
- expectedTokenSequences = expectedTokenSequencesVal;
- tokenImage = tokenImageVal;
- }
-
- /**
- * The following constructors are for use by you for whatever
- * purpose you can think of. Constructing the exception in this
- * manner makes the exception behave in the normal way - i.e., as
- * documented in the class "Throwable". The fields "errorToken",
- * "expectedTokenSequences", and "tokenImage" do not contain
- * relevant information. The JavaCC generated code does not use
- * these constructors.
- */
-
- public ParseException() {
- super();
- specialConstructor = false;
- }
-
- public ParseException(String message) {
- super(message);
- specialConstructor = false;
- }
-
- /**
- * This variable determines which constructor was used to create
- * this object and thereby affects the semantics of the
- * "getMessage" method (see below).
- */
- protected boolean specialConstructor;
-
- /**
- * This is the last token that has been consumed successfully. If
- * this object has been created due to a parse error, the token
- * followng this token will (therefore) be the first error token.
- */
- public Token currentToken;
-
- /**
- * Each entry in this array is an array of integers. Each array
- * of integers represents a sequence of tokens (by their ordinal
- * values) that is expected at this point of the parse.
- */
- public int[][] expectedTokenSequences;
-
- /**
- * This is a reference to the "tokenImage" array of the generated
- * parser within which the parse error occurred. This array is
- * defined in the generated ...Constants interface.
- */
- public String[] tokenImage;
-
- /**
- * This method has the standard behavior when this object has been
- * created using the standard constructors. Otherwise, it uses
- * "currentToken" and "expectedTokenSequences" to generate a parse
- * error message and returns it. If this object has been created
- * due to a parse error, and you do not catch it (it gets thrown
- * from the parser), then this method is called during the printing
- * of the final stack trace, and hence the correct error message
- * gets displayed.
- */
- public String getMessage() {
- if (!specialConstructor) {
- return super.getMessage();
- }
- StringBuffer expected = new StringBuffer();
- int maxSize = 0;
- for (int i = 0; i < expectedTokenSequences.length; i++) {
- if (maxSize < expectedTokenSequences[i].length) {
- maxSize = expectedTokenSequences[i].length;
- }
- for (int j = 0; j < expectedTokenSequences[i].length; j++) {
- expected.append(tokenImage[expectedTokenSequences[i][j]]).append(" ");
- }
- if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
- expected.append("...");
- }
- expected.append(eol).append(" ");
- }
- String retval = "Encountered \"";
- Token tok = currentToken.next;
- for (int i = 0; i < maxSize; i++) {
- if (i != 0) retval += " ";
- if (tok.kind == 0) {
- retval += tokenImage[0];
- break;
- }
- retval += add_escapes(tok.image);
- tok = tok.next;
- }
- retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
- retval += "." + eol;
- if (expectedTokenSequences.length == 1) {
- retval += "Was expecting:" + eol + " ";
- } else {
- retval += "Was expecting one of:" + eol + " ";
- }
- retval += expected.toString();
- return retval;
- }
-
- /**
- * The end of line string for this machine.
- */
- protected String eol = System.getProperty("line.separator", "\n");
-
- /**
- * Used to convert raw characters to their escaped version
- * when these raw version cannot be used as part of an ASCII
- * string literal.
- */
- protected String add_escapes(String str) {
- StringBuffer retval = new StringBuffer();
- char ch;
- for (int i = 0; i < str.length(); i++) {
- switch (str.charAt(i))
- {
- case 0 :
- continue;
- case '\b':
- retval.append("\\b");
- continue;
- case '\t':
- retval.append("\\t");
- continue;
- case '\n':
- retval.append("\\n");
- continue;
- case '\f':
- retval.append("\\f");
- continue;
- case '\r':
- retval.append("\\r");
- continue;
- case '\"':
- retval.append("\\\"");
- continue;
- case '\'':
- retval.append("\\\'");
- continue;
- case '\\':
- retval.append("\\\\");
- continue;
- default:
- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
- String s = "0000" + Integer.toString(ch, 16);
- retval.append("\\u" + s.substring(s.length() - 4, s.length()));
- } else {
- retval.append(ch);
- }
- continue;
- }
- }
- return retval.toString();
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/SimpleCharStream.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/SimpleCharStream.java
deleted file mode 100644
index d44a9018b..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/SimpleCharStream.java
+++ /dev/null
@@ -1,454 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. SimpleCharStream.java Version 4.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.datetime.parser;
-
-/**
- * An implementation of interface CharStream, where the stream is assumed to
- * contain only ASCII characters (without unicode processing).
- */
-
-public class SimpleCharStream
-{
- public static final boolean staticFlag = false;
- int bufsize;
- int available;
- int tokenBegin;
- public int bufpos = -1;
- protected int bufline[];
- protected int bufcolumn[];
-
- protected int column = 0;
- protected int line = 1;
-
- protected boolean prevCharIsCR = false;
- protected boolean prevCharIsLF = false;
-
- protected java.io.Reader inputStream;
-
- protected char[] buffer;
- protected int maxNextCharInd = 0;
- protected int inBuf = 0;
- protected int tabSize = 8;
-
- protected void setTabSize(int i) { tabSize = i; }
- protected int getTabSize(int i) { return tabSize; }
-
-
- protected void ExpandBuff(boolean wrapAround)
- {
- char[] newbuffer = new char[bufsize + 2048];
- int newbufline[] = new int[bufsize + 2048];
- int newbufcolumn[] = new int[bufsize + 2048];
-
- try
- {
- if (wrapAround)
- {
- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
- System.arraycopy(buffer, 0, newbuffer,
- bufsize - tokenBegin, bufpos);
- buffer = newbuffer;
-
- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
- System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos);
- bufline = newbufline;
-
- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
- System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos);
- bufcolumn = newbufcolumn;
-
- maxNextCharInd = (bufpos += (bufsize - tokenBegin));
- }
- else
- {
- System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin);
- buffer = newbuffer;
-
- System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin);
- bufline = newbufline;
-
- System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin);
- bufcolumn = newbufcolumn;
-
- maxNextCharInd = (bufpos -= tokenBegin);
- }
- }
- catch (Throwable t)
- {
- throw new Error(t.getMessage());
- }
-
-
- bufsize += 2048;
- available = bufsize;
- tokenBegin = 0;
- }
-
- protected void FillBuff() throws java.io.IOException
- {
- if (maxNextCharInd == available)
- {
- if (available == bufsize)
- {
- if (tokenBegin > 2048)
- {
- bufpos = maxNextCharInd = 0;
- available = tokenBegin;
- }
- else if (tokenBegin < 0)
- bufpos = maxNextCharInd = 0;
- else
- ExpandBuff(false);
- }
- else if (available > tokenBegin)
- available = bufsize;
- else if ((tokenBegin - available) < 2048)
- ExpandBuff(true);
- else
- available = tokenBegin;
- }
-
- int i;
- try {
- if ((i = inputStream.read(buffer, maxNextCharInd,
- available - maxNextCharInd)) == -1)
- {
- inputStream.close();
- throw new java.io.IOException();
- }
- else
- maxNextCharInd += i;
- return;
- }
- catch(java.io.IOException e) {
- --bufpos;
- backup(0);
- if (tokenBegin == -1)
- tokenBegin = bufpos;
- throw e;
- }
- }
-
- public char BeginToken() throws java.io.IOException
- {
- tokenBegin = -1;
- char c = readChar();
- tokenBegin = bufpos;
-
- return c;
- }
-
- protected void UpdateLineColumn(char c)
- {
- column++;
-
- if (prevCharIsLF)
- {
- prevCharIsLF = false;
- line += (column = 1);
- }
- else if (prevCharIsCR)
- {
- prevCharIsCR = false;
- if (c == '\n')
- {
- prevCharIsLF = true;
- }
- else
- line += (column = 1);
- }
-
- switch (c)
- {
- case '\r' :
- prevCharIsCR = true;
- break;
- case '\n' :
- prevCharIsLF = true;
- break;
- case '\t' :
- column--;
- column += (tabSize - (column % tabSize));
- break;
- default :
- break;
- }
-
- bufline[bufpos] = line;
- bufcolumn[bufpos] = column;
- }
-
- public char readChar() throws java.io.IOException
- {
- if (inBuf > 0)
- {
- --inBuf;
-
- if (++bufpos == bufsize)
- bufpos = 0;
-
- return buffer[bufpos];
- }
-
- if (++bufpos >= maxNextCharInd)
- FillBuff();
-
- char c = buffer[bufpos];
-
- UpdateLineColumn(c);
- return (c);
- }
-
- /**
- * @deprecated
- * @see #getEndColumn
- */
-
- public int getColumn() {
- return bufcolumn[bufpos];
- }
-
- /**
- * @deprecated
- * @see #getEndLine
- */
-
- public int getLine() {
- return bufline[bufpos];
- }
-
- public int getEndColumn() {
- return bufcolumn[bufpos];
- }
-
- public int getEndLine() {
- return bufline[bufpos];
- }
-
- public int getBeginColumn() {
- return bufcolumn[tokenBegin];
- }
-
- public int getBeginLine() {
- return bufline[tokenBegin];
- }
-
- public void backup(int amount) {
-
- inBuf += amount;
- if ((bufpos -= amount) < 0)
- bufpos += bufsize;
- }
-
- public SimpleCharStream(java.io.Reader dstream, int startline,
- int startcolumn, int buffersize)
- {
- inputStream = dstream;
- line = startline;
- column = startcolumn - 1;
-
- available = bufsize = buffersize;
- buffer = new char[buffersize];
- bufline = new int[buffersize];
- bufcolumn = new int[buffersize];
- }
-
- public SimpleCharStream(java.io.Reader dstream, int startline,
- int startcolumn)
- {
- this(dstream, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.Reader dstream)
- {
- this(dstream, 1, 1, 4096);
- }
- public void ReInit(java.io.Reader dstream, int startline,
- int startcolumn, int buffersize)
- {
- inputStream = dstream;
- line = startline;
- column = startcolumn - 1;
-
- if (buffer == null || buffersize != buffer.length)
- {
- available = bufsize = buffersize;
- buffer = new char[buffersize];
- bufline = new int[buffersize];
- bufcolumn = new int[buffersize];
- }
- prevCharIsLF = prevCharIsCR = false;
- tokenBegin = inBuf = maxNextCharInd = 0;
- bufpos = -1;
- }
-
- public void ReInit(java.io.Reader dstream, int startline,
- int startcolumn)
- {
- ReInit(dstream, startline, startcolumn, 4096);
- }
-
- public void ReInit(java.io.Reader dstream)
- {
- ReInit(dstream, 1, 1, 4096);
- }
- public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
- {
- this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, int startline,
- int startcolumn, int buffersize)
- {
- this(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn) throws java.io.UnsupportedEncodingException
- {
- this(dstream, encoding, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, int startline,
- int startcolumn)
- {
- this(dstream, startline, startcolumn, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
- {
- this(dstream, encoding, 1, 1, 4096);
- }
-
- public SimpleCharStream(java.io.InputStream dstream)
- {
- this(dstream, 1, 1, 4096);
- }
-
- public void ReInit(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException
- {
- ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize);
- }
-
- public void ReInit(java.io.InputStream dstream, int startline,
- int startcolumn, int buffersize)
- {
- ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize);
- }
-
- public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException
- {
- ReInit(dstream, encoding, 1, 1, 4096);
- }
-
- public void ReInit(java.io.InputStream dstream)
- {
- ReInit(dstream, 1, 1, 4096);
- }
- public void ReInit(java.io.InputStream dstream, String encoding, int startline,
- int startcolumn) throws java.io.UnsupportedEncodingException
- {
- ReInit(dstream, encoding, startline, startcolumn, 4096);
- }
- public void ReInit(java.io.InputStream dstream, int startline,
- int startcolumn)
- {
- ReInit(dstream, startline, startcolumn, 4096);
- }
- public String GetImage()
- {
- if (bufpos >= tokenBegin)
- return new String(buffer, tokenBegin, bufpos - tokenBegin + 1);
- else
- return new String(buffer, tokenBegin, bufsize - tokenBegin) +
- new String(buffer, 0, bufpos + 1);
- }
-
- public char[] GetSuffix(int len)
- {
- char[] ret = new char[len];
-
- if ((bufpos + 1) >= len)
- System.arraycopy(buffer, bufpos - len + 1, ret, 0, len);
- else
- {
- System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0,
- len - bufpos - 1);
- System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1);
- }
-
- return ret;
- }
-
- public void Done()
- {
- buffer = null;
- bufline = null;
- bufcolumn = null;
- }
-
- /**
- * Method to adjust line and column numbers for the start of a token.
- */
- public void adjustBeginLineColumn(int newLine, int newCol)
- {
- int start = tokenBegin;
- int len;
-
- if (bufpos >= tokenBegin)
- {
- len = bufpos - tokenBegin + inBuf + 1;
- }
- else
- {
- len = bufsize - tokenBegin + bufpos + 1 + inBuf;
- }
-
- int i = 0, j = 0, k = 0;
- int nextColDiff = 0, columnDiff = 0;
-
- while (i < len &&
- bufline[j = start % bufsize] == bufline[k = ++start % bufsize])
- {
- bufline[j] = newLine;
- nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j];
- bufcolumn[j] = newCol + columnDiff;
- columnDiff = nextColDiff;
- i++;
- }
-
- if (i < len)
- {
- bufline[j] = newLine++;
- bufcolumn[j] = newCol + columnDiff;
-
- while (i++ < len)
- {
- if (bufline[j = start % bufsize] != bufline[++start % bufsize])
- bufline[j] = newLine++;
- else
- bufline[j] = newLine;
- }
- }
-
- line = bufline[j];
- column = bufcolumn[j];
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/Token.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/Token.java
deleted file mode 100644
index 52d101ed0..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/Token.java
+++ /dev/null
@@ -1,96 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. Token.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.datetime.parser;
-
-/**
- * Describes the input token stream.
- */
-
-public class Token {
-
- /**
- * An integer that describes the kind of this token. This numbering
- * system is determined by JavaCCParser, and a table of these numbers is
- * stored in the file ...Constants.java.
- */
- public int kind;
-
- /**
- * beginLine and beginColumn describe the position of the first character
- * of this token; endLine and endColumn describe the position of the
- * last character of this token.
- */
- public int beginLine, beginColumn, endLine, endColumn;
-
- /**
- * The string image of the token.
- */
- public String image;
-
- /**
- * A reference to the next regular (non-special) token from the input
- * stream. If this is the last token from the input stream, or if the
- * token manager has not read tokens beyond this one, this field is
- * set to null. This is true only if this token is also a regular
- * token. Otherwise, see below for a description of the contents of
- * this field.
- */
- public Token next;
-
- /**
- * This field is used to access special tokens that occur prior to this
- * token, but after the immediately preceding regular (non-special) token.
- * If there are no such special tokens, this field is set to null.
- * When there are more than one such special token, this field refers
- * to the last of these special tokens, which in turn refers to the next
- * previous special token through its specialToken field, and so on
- * until the first special token (whose specialToken field is null).
- * The next fields of special tokens refer to other special tokens that
- * immediately follow it (without an intervening regular token). If there
- * is no such token, this field is null.
- */
- public Token specialToken;
-
- /**
- * Returns the image.
- */
- public String toString()
- {
- return image;
- }
-
- /**
- * Returns a new Token object, by default. However, if you want, you
- * can create and return subclass objects based on the value of ofKind.
- * Simply add the cases to the switch for all those special cases.
- * For example, if you have a subclass of Token called IDToken that
- * you want to create if ofKind is ID, simlpy add something like :
- *
- * case MyParserConstants.ID : return new IDToken();
- *
- * to the following switch statement. Then you can cast matchedToken
- * variable to the appropriate type and use it in your lexical actions.
- */
- public static final Token newToken(int ofKind)
- {
- switch(ofKind)
- {
- default : return new Token();
- }
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/TokenMgrError.java b/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/TokenMgrError.java
deleted file mode 100644
index 973255070..000000000
--- a/emailcommon/src/org/apache/james/mime4j/field/datetime/parser/TokenMgrError.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/* Generated By:JavaCC: Do not edit this line. TokenMgrError.java Version 3.0 */
-/*
- * Copyright 2004 the mime4j project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.james.mime4j.field.datetime.parser;
-
-public class TokenMgrError extends Error
-{
- /*
- * Ordinals for various reasons why an Error of this type can be thrown.
- */
-
- /**
- * Lexical error occured.
- */
- static final int LEXICAL_ERROR = 0;
-
- /**
- * An attempt wass made to create a second instance of a static token manager.
- */
- static final int STATIC_LEXER_ERROR = 1;
-
- /**
- * Tried to change to an invalid lexical state.
- */
- static final int INVALID_LEXICAL_STATE = 2;
-
- /**
- * Detected (and bailed out of) an infinite loop in the token manager.
- */
- static final int LOOP_DETECTED = 3;
-
- /**
- * Indicates the reason why the exception is thrown. It will have
- * one of the above 4 values.
- */
- int errorCode;
-
- /**
- * Replaces unprintable characters by their espaced (or unicode escaped)
- * equivalents in the given string
- */
- protected static final String addEscapes(String str) {
- StringBuffer retval = new StringBuffer();
- char ch;
- for (int i = 0; i < str.length(); i++) {
- switch (str.charAt(i))
- {
- case 0 :
- continue;
- case '\b':
- retval.append("\\b");
- continue;
- case '\t':
- retval.append("\\t");
- continue;
- case '\n':
- retval.append("\\n");
- continue;
- case '\f':
- retval.append("\\f");
- continue;
- case '\r':
- retval.append("\\r");
- continue;
- case '\"':
- retval.append("\\\"");
- continue;
- case '\'':
- retval.append("\\\'");
- continue;
- case '\\':
- retval.append("\\\\");
- continue;
- default:
- if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
- String s = "0000" + Integer.toString(ch, 16);
- retval.append("\\u" + s.substring(s.length() - 4, s.length()));
- } else {
- retval.append(ch);
- }
- continue;
- }
- }
- return retval.toString();
- }
-
- /**
- * Returns a detailed message for the Error when it is thrown by the
- * token manager to indicate a lexical error.
- * Parameters :
- * EOFSeen : indicates if EOF caused the lexicl error
- * curLexState : lexical state in which this error occured
- * errorLine : line number when the error occured
- * errorColumn : column number when the error occured
- * errorAfter : prefix that was seen before this error occured
- * curchar : the offending character
- * Note: You can customize the lexical error message by modifying this method.
- */
- protected static String LexicalError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar) {
- return("Lexical error at line " +
- errorLine + ", column " +
- errorColumn + ". Encountered: " +
- (EOFSeen ? "<EOF> " : ("\"" + addEscapes(String.valueOf(curChar)) + "\"") + " (" + (int)curChar + "), ") +
- "after : \"" + addEscapes(errorAfter) + "\"");
- }
-
- /**
- * You can also modify the body of this method to customize your error messages.
- * For example, cases like LOOP_DETECTED and INVALID_LEXICAL_STATE are not
- * of end-users concern, so you can return something like :
- *
- * "Internal Error : Please file a bug report .... "
- *
- * from this method for such cases in the release version of your parser.
- */
- public String getMessage() {
- return super.getMessage();
- }
-
- /*
- * Constructors of various flavors follow.
- */
-
- public TokenMgrError() {
- }
-
- public TokenMgrError(String message, int reason) {
- super(message);
- errorCode = reason;
- }
-
- public TokenMgrError(boolean EOFSeen, int lexState, int errorLine, int errorColumn, String errorAfter, char curChar, int reason) {
- this(LexicalError(EOFSeen, lexState, errorLine, errorColumn, errorAfter, curChar), reason);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/AbstractBody.java b/emailcommon/src/org/apache/james/mime4j/message/AbstractBody.java
deleted file mode 100644
index d2647ec77..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/AbstractBody.java
+++ /dev/null
@@ -1,47 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-
-/**
- * Abstract <code>Body</code> implementation providing the parent
- * functionality required by bodies.
- *
- *
- * @version $Id: AbstractBody.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
- */
-public abstract class AbstractBody implements Body {
- private Entity parent = null;
-
- /**
- * @see org.apache.james.mime4j.message.Body#getParent()
- */
- public Entity getParent() {
- return parent;
- }
-
- /**
- * @see org.apache.james.mime4j.message.Body#setParent(org.apache.james.mime4j.message.Entity)
- */
- public void setParent(Entity parent) {
- this.parent = parent;
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/BinaryBody.java b/emailcommon/src/org/apache/james/mime4j/message/BinaryBody.java
deleted file mode 100644
index bfc992a8f..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/BinaryBody.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.InputStream;
-
-
-/**
- * Interface implemented by bodies containing binary data.
- *
- *
- * @version $Id: BinaryBody.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public interface BinaryBody extends Body {
-
- /**
- * Gets a <code>InputStream</code> which reads the bytes of the
- * body.
- *
- * @return the stream.
- * @throws IOException on I/O errors.
- */
- InputStream getInputStream() throws IOException;
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/Body.java b/emailcommon/src/org/apache/james/mime4j/message/Body.java
deleted file mode 100644
index 54b8948db..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/Body.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-/**
- * Encapsulates the body of an entity (see RFC 2045).
- *
- *
- * @version $Id: Body.java,v 1.4 2004/10/04 15:36:43 ntherning Exp $
- */
-public interface Body {
-
- /**
- * Gets the parent of this body.
- *
- * @return the parent.
- */
- Entity getParent();
-
- /**
- * Sets the parent of this body.
- *
- * @param parent the parent.
- */
- void setParent(Entity parent);
-
- /**
- * Writes this body to the given stream in MIME message format.
- *
- * @param out the stream to write to.
- * @throws IOException on I/O errors.
- */
- void writeTo(OutputStream out) throws IOException;
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/BodyPart.java b/emailcommon/src/org/apache/james/mime4j/message/BodyPart.java
deleted file mode 100644
index 474030d7f..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/BodyPart.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-
-/**
- * Represents a MIME body part (see RFC 2045).
- *
- *
- * @version $Id: BodyPart.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public class BodyPart extends Entity {
-
- /**
- *
- * @see org.apache.james.mime4j.message.Entity#writeTo(java.io.OutputStream)
- */
- public void writeTo(OutputStream out) throws IOException {
- getHeader().writeTo(out);
- getBody().writeTo(out);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/Entity.java b/emailcommon/src/org/apache/james/mime4j/message/Entity.java
deleted file mode 100644
index 96f2a4875..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/Entity.java
+++ /dev/null
@@ -1,170 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.OutputStream;
-
-import org.apache.james.mime4j.field.ContentTransferEncodingField;
-import org.apache.james.mime4j.field.ContentTypeField;
-import org.apache.james.mime4j.field.Field;
-
-/**
- * MIME entity. An entity has a header and a body (see RFC 2045).
- *
- *
- * @version $Id: Entity.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public abstract class Entity {
- private Header header = null;
- private Body body = null;
- private Entity parent = null;
-
- /**
- * Gets the parent entity of this entity.
- * Returns <code>null</code> if this is the root entity.
- *
- * @return the parent or <code>null</code>.
- */
- public Entity getParent() {
- return parent;
- }
-
- /**
- * Sets the parent entity of this entity.
- *
- * @param parent the parent entity or <code>null</code> if
- * this will be the root entity.
- */
- public void setParent(Entity parent) {
- this.parent = parent;
- }
-
- /**
- * Gets the entity header.
- *
- * @return the header.
- */
- public Header getHeader() {
- return header;
- }
-
- /**
- * Sets the entity header.
- *
- * @param header the header.
- */
- public void setHeader(Header header) {
- this.header = header;
- }
-
- /**
- * Gets the body of this entity.
- *
- * @return the body,
- */
- public Body getBody() {
- return body;
- }
-
- /**
- * Sets the body of this entity.
- *
- * @param body the body.
- */
- public void setBody(Body body) {
- this.body = body;
- body.setParent(this);
- }
-
- /**
- * Determines the MIME type of this <code>Entity</code>. The MIME type
- * is derived by looking at the parent's Content-Type field if no
- * Content-Type field is set for this <code>Entity</code>.
- *
- * @return the MIME type.
- */
- public String getMimeType() {
- ContentTypeField child =
- (ContentTypeField) getHeader().getField(Field.CONTENT_TYPE);
- ContentTypeField parent = getParent() != null
- ? (ContentTypeField) getParent().getHeader().
- getField(Field.CONTENT_TYPE)
- : null;
-
- return ContentTypeField.getMimeType(child, parent);
- }
-
- /**
- * Determines the MIME character set encoding of this <code>Entity</code>.
- *
- * @return the MIME character set encoding.
- */
- public String getCharset() {
- return ContentTypeField.getCharset(
- (ContentTypeField) getHeader().getField(Field.CONTENT_TYPE));
- }
-
- /**
- * Determines the transfer encoding of this <code>Entity</code>.
- *
- * @return the transfer encoding.
- */
- public String getContentTransferEncoding() {
- ContentTransferEncodingField f = (ContentTransferEncodingField)
- getHeader().getField(Field.CONTENT_TRANSFER_ENCODING);
-
- return ContentTransferEncodingField.getEncoding(f);
- }
-
- /**
- * Determines if the MIME type of this <code>Entity</code> matches the
- * given one. MIME types are case-insensitive.
- *
- * @param type the MIME type to match against.
- * @return <code>true</code> on match, <code>false</code> otherwise.
- */
- public boolean isMimeType(String type) {
- return getMimeType().equalsIgnoreCase(type);
- }
-
- /**
- * Determines if the MIME type of this <code>Entity</code> is
- * <code>multipart/*</code>. Since multipart-entities must have
- * a boundary parameter in the <code>Content-Type</code> field this
- * method returns <code>false</code> if no boundary exists.
- *
- * @return <code>true</code> on match, <code>false</code> otherwise.
- */
- public boolean isMultipart() {
- ContentTypeField f =
- (ContentTypeField) getHeader().getField(Field.CONTENT_TYPE);
- return f != null && f.getBoundary() != null
- && getMimeType().startsWith(ContentTypeField.TYPE_MULTIPART_PREFIX);
- }
-
- /**
- * Write the content to the given outputstream
- *
- * @param out the outputstream to write to
- * @throws IOException
- */
- public abstract void writeTo(OutputStream out) throws IOException;
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/Header.java b/emailcommon/src/org/apache/james/mime4j/message/Header.java
deleted file mode 100644
index e9216a821..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/Header.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.apache.james.mime4j.AbstractContentHandler;
-import org.apache.james.mime4j.MimeStreamParser;
-import org.apache.james.mime4j.field.ContentTypeField;
-import org.apache.james.mime4j.field.Field;
-import org.apache.james.mime4j.util.CharsetUtil;
-
-
-/**
- * The header of an entity (see RFC 2045).
- *
- *
- * @version $Id: Header.java,v 1.3 2004/10/04 15:36:44 ntherning Exp $
- */
-public class Header {
- private List<Field> fields = new LinkedList<Field>();
- private HashMap<String, List<Field>> fieldMap = new HashMap<String, List<Field>>();
-
- /**
- * Creates a new empty <code>Header</code>.
- */
- public Header() {
- }
-
- /**
- * Creates a new <code>Header</code> from the specified stream.
- *
- * @param is the stream to read the header from.
- */
- public Header(InputStream is) throws IOException {
- final MimeStreamParser parser = new MimeStreamParser();
- parser.setContentHandler(new AbstractContentHandler() {
- @Override
- public void endHeader() {
- parser.stop();
- }
- @Override
- public void field(String fieldData) {
- addField(Field.parse(fieldData));
- }
- });
- parser.parse(is);
- }
-
- /**
- * Adds a field to the end of the list of fields.
- *
- * @param field the field to add.
- */
- public void addField(Field field) {
- List<Field> values = fieldMap.get(field.getName().toLowerCase());
- if (values == null) {
- values = new LinkedList<Field>();
- fieldMap.put(field.getName().toLowerCase(), values);
- }
- values.add(field);
- fields.add(field);
- }
-
- /**
- * Gets the fields of this header. The returned list will not be
- * modifiable.
- *
- * @return the list of <code>Field</code> objects.
- */
- public List<Field> getFields() {
- return Collections.unmodifiableList(fields);
- }
-
- /**
- * Gets a <code>Field</code> given a field name. If there are multiple
- * such fields defined in this header the first one will be returned.
- *
- * @param name the field name (e.g. From, Subject).
- * @return the field or <code>null</code> if none found.
- */
- public Field getField(String name) {
- List<Field> l = fieldMap.get(name.toLowerCase());
- if (l != null && !l.isEmpty()) {
- return l.get(0);
- }
- return null;
- }
-
- /**
- * Gets all <code>Field</code>s having the specified field name.
- *
- * @param name the field name (e.g. From, Subject).
- * @return the list of fields.
- */
- public List<Field> getFields(String name) {
- List<Field> l = fieldMap.get(name.toLowerCase());
- return Collections.unmodifiableList(l);
- }
-
- /**
- * Return Header Object as String representation. Each headerline is
- * seperated by "\r\n"
- *
- * @return headers
- */
- @Override
- public String toString() {
- StringBuffer str = new StringBuffer();
- for (Iterator<Field> it = fields.iterator(); it.hasNext();) {
- str.append(it.next().toString());
- str.append("\r\n");
- }
- return str.toString();
- }
-
-
- /**
- * Write the Header to the given OutputStream
- *
- * @param out the OutputStream to write to
- * @throws IOException
- */
- public void writeTo(OutputStream out) throws IOException {
- String charString = ((ContentTypeField) getField(Field.CONTENT_TYPE)).getCharset();
-
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, CharsetUtil.getCharset(charString)),8192);
- writer.write(toString()+ "\r\n");
- writer.flush();
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/MemoryBinaryBody.java b/emailcommon/src/org/apache/james/mime4j/message/MemoryBinaryBody.java
deleted file mode 100644
index a44db4db1..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/MemoryBinaryBody.java
+++ /dev/null
@@ -1,92 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import org.apache.commons.io.IOUtils;
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.util.TempPath;
-import org.apache.james.mime4j.util.TempStorage;
-
-
-/**
- * Binary body backed by a {@link org.apache.james.mime4j.util.TempFile}.
- *
- *
- * @version $Id: TempFileBinaryBody.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
- */
-class MemoryBinaryBody extends AbstractBody implements BinaryBody {
- private static Log log = LogFactory.getLog(MemoryBinaryBody.class);
-
- private Entity parent = null;
- private byte[] tempFile = null;
-
- /**
- * Use the given InputStream to build the TemporyFileBinaryBody
- *
- * @param is the InputStream to use as source
- * @throws IOException
- */
- public MemoryBinaryBody(InputStream is) throws IOException {
-
- TempPath tempPath = TempStorage.getInstance().getRootTempPath();
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- IOUtils.copy(is, out);
- out.close();
- tempFile = out.toByteArray();
- }
-
- /**
- * @see org.apache.james.mime4j.message.AbstractBody#getParent()
- */
- public Entity getParent() {
- return parent;
- }
-
- /**
- * @see org.apache.james.mime4j.message.AbstractBody#setParent(org.apache.james.mime4j.message.Entity)
- */
- public void setParent(Entity parent) {
- this.parent = parent;
- }
-
- /**
- * @see org.apache.james.mime4j.message.BinaryBody#getInputStream()
- */
- public InputStream getInputStream() throws IOException {
- return new ByteArrayInputStream(tempFile);
- }
-
- /**
- * @see org.apache.james.mime4j.message.Body#writeTo(java.io.OutputStream)
- */
- public void writeTo(OutputStream out) throws IOException {
- IOUtils.copy(getInputStream(),out);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/MemoryTextBody.java b/emailcommon/src/org/apache/james/mime4j/message/MemoryTextBody.java
deleted file mode 100644
index 71af6637c..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/MemoryTextBody.java
+++ /dev/null
@@ -1,118 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-
-import org.apache.commons.io.IOUtils;
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.util.CharsetUtil;
-import org.apache.james.mime4j.util.TempPath;
-import org.apache.james.mime4j.util.TempStorage;
-
-
-/**
- * Text body backed by a {@link org.apache.james.mime4j.util.TempFile}.
- *
- *
- * @version $Id: TempFileTextBody.java,v 1.3 2004/10/25 07:26:46 ntherning Exp $
- */
-class MemoryTextBody extends AbstractBody implements TextBody {
- private static Log log = LogFactory.getLog(MemoryTextBody.class);
-
- private String mimeCharset = null;
- private byte[] tempFile = null;
-
- public MemoryTextBody(InputStream is) throws IOException {
- this(is, null);
- }
-
- public MemoryTextBody(InputStream is, String mimeCharset)
- throws IOException {
-
- this.mimeCharset = mimeCharset;
-
- TempPath tempPath = TempStorage.getInstance().getRootTempPath();
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- IOUtils.copy(is, out);
- out.close();
- tempFile = out.toByteArray();
- }
-
- /**
- * @see org.apache.james.mime4j.message.TextBody#getReader()
- */
- public Reader getReader() throws UnsupportedEncodingException, IOException {
- String javaCharset = null;
- if (mimeCharset != null) {
- javaCharset = CharsetUtil.toJavaCharset(mimeCharset);
- }
-
- if (javaCharset == null) {
- javaCharset = "ISO-8859-1";
-
- if (log.isWarnEnabled()) {
- if (mimeCharset == null) {
- log.warn("No MIME charset specified. Using " + javaCharset
- + " instead.");
- } else {
- log.warn("MIME charset '" + mimeCharset + "' has no "
- + "corresponding Java charset. Using " + javaCharset
- + " instead.");
- }
- }
- }
- /*
- if (log.isWarnEnabled()) {
- if (mimeCharset == null) {
- log.warn("No MIME charset specified. Using the "
- + "platform's default charset.");
- } else {
- log.warn("MIME charset '" + mimeCharset + "' has no "
- + "corresponding Java charset. Using the "
- + "platform's default charset.");
- }
- }
-
- return new InputStreamReader(tempFile.getInputStream());
- }*/
-
- return new InputStreamReader(new ByteArrayInputStream(tempFile), javaCharset);
- }
-
-
- /**
- * @see org.apache.james.mime4j.message.Body#writeTo(java.io.OutputStream)
- */
- public void writeTo(OutputStream out) throws IOException {
- IOUtils.copy(new ByteArrayInputStream(tempFile), out);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/Message.java b/emailcommon/src/org/apache/james/mime4j/message/Message.java
deleted file mode 100644
index 514307185..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/Message.java
+++ /dev/null
@@ -1,257 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Stack;
-
-import org.apache.james.mime4j.BodyDescriptor;
-import org.apache.james.mime4j.ContentHandler;
-import org.apache.james.mime4j.MimeStreamParser;
-import org.apache.james.mime4j.decoder.Base64InputStream;
-import org.apache.james.mime4j.decoder.QuotedPrintableInputStream;
-import org.apache.james.mime4j.field.Field;
-import org.apache.james.mime4j.field.UnstructuredField;
-
-
-/**
- * Represents a MIME message. The following code parses a stream into a
- * <code>Message</code> object.
- *
- * <pre>
- * Message msg = new Message(new BufferedInputStream(
- * new FileInputStream("mime.msg")));
- * </pre>
- *
- *
- *
- * @version $Id: Message.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public class Message extends Entity implements Body {
-
- /**
- * Creates a new empty <code>Message</code>.
- */
- public Message() {
- }
-
- /**
- * Parses the specified MIME message stream into a <code>Message</code>
- * instance.
- *
- * @param is the stream to parse.
- * @throws IOException on I/O errors.
- */
- public Message(InputStream is) throws IOException {
- MimeStreamParser parser = new MimeStreamParser();
- parser.setContentHandler(new MessageBuilder());
- parser.parse(is);
- }
-
-
- /**
- * Gets the <code>Subject</code> field.
- *
- * @return the <code>Subject</code> field or <code>null</code> if it
- * doesn't exist.
- */
- public UnstructuredField getSubject() {
- return (UnstructuredField) getHeader().getField(Field.SUBJECT);
- }
-
- /**
- *
- * @see org.apache.james.mime4j.message.Entity#writeTo(java.io.OutputStream)
- */
- @Override
- public void writeTo(OutputStream out) throws IOException {
- getHeader().writeTo(out);
-
- Body body = getBody();
- if (body instanceof Multipart) {
- Multipart mp = (Multipart) body;
- mp.writeTo(out);
- } else {
- body.writeTo(out);
- }
- }
-
-
- private class MessageBuilder implements ContentHandler {
- private Stack<Object> stack = new Stack<Object>();
-
- public MessageBuilder() {
- }
-
- private void expect(Class c) {
- if (!c.isInstance(stack.peek())) {
- throw new IllegalStateException("Internal stack error: "
- + "Expected '" + c.getName() + "' found '"
- + stack.peek().getClass().getName() + "'");
- }
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startMessage()
- */
- public void startMessage() {
- if (stack.isEmpty()) {
- stack.push(Message.this);
- } else {
- expect(Entity.class);
- Message m = new Message();
- ((Entity) stack.peek()).setBody(m);
- stack.push(m);
- }
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endMessage()
- */
- public void endMessage() {
- expect(Message.class);
- stack.pop();
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startHeader()
- */
- public void startHeader() {
- stack.push(new Header());
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#field(java.lang.String)
- */
- public void field(String fieldData) {
- expect(Header.class);
- ((Header) stack.peek()).addField(Field.parse(fieldData));
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endHeader()
- */
- public void endHeader() {
- expect(Header.class);
- Header h = (Header) stack.pop();
- expect(Entity.class);
- ((Entity) stack.peek()).setHeader(h);
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startMultipart(org.apache.james.mime4j.BodyDescriptor)
- */
- public void startMultipart(BodyDescriptor bd) {
- expect(Entity.class);
-
- Entity e = (Entity) stack.peek();
- Multipart multiPart = new Multipart();
- e.setBody(multiPart);
- stack.push(multiPart);
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#body(org.apache.james.mime4j.BodyDescriptor, java.io.InputStream)
- */
- public void body(BodyDescriptor bd, InputStream is) throws IOException {
- expect(Entity.class);
-
- String enc = bd.getTransferEncoding();
- if ("base64".equals(enc)) {
- is = new Base64InputStream(is);
- } else if ("quoted-printable".equals(enc)) {
- is = new QuotedPrintableInputStream(is);
- }
-
- Body body = null;
- if (bd.getMimeType().startsWith("text/")) {
- body = new MemoryTextBody(is, bd.getCharset());
- } else {
- body = new MemoryBinaryBody(is);
- }
-
- ((Entity) stack.peek()).setBody(body);
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endMultipart()
- */
- public void endMultipart() {
- stack.pop();
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#startBodyPart()
- */
- public void startBodyPart() {
- expect(Multipart.class);
-
- BodyPart bodyPart = new BodyPart();
- ((Multipart) stack.peek()).addBodyPart(bodyPart);
- stack.push(bodyPart);
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#endBodyPart()
- */
- public void endBodyPart() {
- expect(BodyPart.class);
- stack.pop();
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#epilogue(java.io.InputStream)
- */
- public void epilogue(InputStream is) throws IOException {
- expect(Multipart.class);
- StringBuffer sb = new StringBuffer();
- int b;
- while ((b = is.read()) != -1) {
- sb.append((char) b);
- }
- ((Multipart) stack.peek()).setEpilogue(sb.toString());
- }
-
- /**
- * @see org.apache.james.mime4j.ContentHandler#preamble(java.io.InputStream)
- */
- public void preamble(InputStream is) throws IOException {
- expect(Multipart.class);
- StringBuffer sb = new StringBuffer();
- int b;
- while ((b = is.read()) != -1) {
- sb.append((char) b);
- }
- ((Multipart) stack.peek()).setPreamble(sb.toString());
- }
-
- /**
- * TODO: Implement me
- *
- * @see org.apache.james.mime4j.ContentHandler#raw(java.io.InputStream)
- */
- public void raw(InputStream is) throws IOException {
- throw new UnsupportedOperationException("Not supported");
- }
-
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/Multipart.java b/emailcommon/src/org/apache/james/mime4j/message/Multipart.java
deleted file mode 100644
index d83400097..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/Multipart.java
+++ /dev/null
@@ -1,203 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.BufferedWriter;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-
-import org.apache.james.mime4j.field.ContentTypeField;
-import org.apache.james.mime4j.field.Field;
-import org.apache.james.mime4j.util.CharsetUtil;
-
-/**
- * Represents a MIME multipart body (see RFC 2045).A multipart body has a
- * ordered list of body parts. The multipart body also has a preamble and
- * epilogue. The preamble consists of whatever characters appear before the
- * first body part while the epilogue consists of whatever characters come
- * after the last body part.
- *
- *
- * @version $Id: Multipart.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public class Multipart implements Body {
- private String preamble = "";
- private String epilogue = "";
- private List<BodyPart> bodyParts = new LinkedList<BodyPart>();
- private Entity parent = null;
- private String subType = "alternative";
-
- /**
- * Creates a new empty <code>Multipart</code> instance.
- */
- public Multipart() {
- }
-
- /**
- * Gets the multipart sub-type. E.g. <code>alternative</code> (the default)
- * or <code>parallel</code>. See RFC 2045 for common sub-types and their
- * meaning.
- *
- * @return the multipart sub-type.
- */
- public String getSubType() {
- return subType;
- }
-
- /**
- * Sets the multipart sub-type. E.g. <code>alternative</code>
- * or <code>parallel</code>. See RFC 2045 for common sub-types and their
- * meaning.
- *
- * @param subType the sub-type.
- */
- public void setSubType(String subType) {
- this.subType = subType;
- }
-
- /**
- * @see org.apache.james.mime4j.message.Body#getParent()
- */
- public Entity getParent() {
- return parent;
- }
-
- /**
- * @see org.apache.james.mime4j.message.Body#setParent(org.apache.james.mime4j.message.Entity)
- */
- public void setParent(Entity parent) {
- this.parent = parent;
- for (Iterator<BodyPart> it = bodyParts.iterator(); it.hasNext();) {
- it.next().setParent(parent);
- }
- }
-
- /**
- * Gets the epilogue.
- *
- * @return the epilogue.
- */
- public String getEpilogue() {
- return epilogue;
- }
-
- /**
- * Sets the epilogue.
- *
- * @param epilogue the epilogue.
- */
- public void setEpilogue(String epilogue) {
- this.epilogue = epilogue;
- }
-
- /**
- * Gets the list of body parts. The list is immutable.
- *
- * @return the list of <code>BodyPart</code> objects.
- */
- public List<BodyPart> getBodyParts() {
- return Collections.unmodifiableList(bodyParts);
- }
-
- /**
- * Sets the list of body parts.
- *
- * @param bodyParts the new list of <code>BodyPart</code> objects.
- */
- public void setBodyParts(List<BodyPart> bodyParts) {
- this.bodyParts = bodyParts;
- for (Iterator<BodyPart> it = bodyParts.iterator(); it.hasNext();) {
- it.next().setParent(parent);
- }
- }
-
- /**
- * Adds a body part to the end of the list of body parts.
- *
- * @param bodyPart the body part.
- */
- public void addBodyPart(BodyPart bodyPart) {
- bodyParts.add(bodyPart);
- bodyPart.setParent(parent);
- }
-
- /**
- * Gets the preamble.
- *
- * @return the preamble.
- */
- public String getPreamble() {
- return preamble;
- }
-
- /**
- * Sets the preamble.
- *
- * @param preamble the preamble.
- */
- public void setPreamble(String preamble) {
- this.preamble = preamble;
- }
-
- /**
- *
- * @see org.apache.james.mime4j.message.Body#writeTo(java.io.OutputStream)
- */
- public void writeTo(OutputStream out) throws IOException {
- String boundary = getBoundary();
- List<BodyPart> bodyParts = getBodyParts();
-
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, CharsetUtil.getCharset(getCharset())),8192);
-
- writer.write(getPreamble() + "\r\n");
-
- for (int i = 0; i < bodyParts.size(); i++) {
- writer.write(boundary + "\r\n");
- bodyParts.get(i).writeTo(out);
- }
-
- writer.write(getEpilogue() + "\r\n");
- writer.write(boundary + "--" + "\r\n");
-
- }
-
- /**
- * Return the boundory of the parent Entity
- *
- * @return boundery
- */
- private String getBoundary() {
- Entity e = getParent();
- ContentTypeField cField = (ContentTypeField) e.getHeader().getField(
- Field.CONTENT_TYPE);
- return cField.getBoundary();
- }
-
- private String getCharset() {
- Entity e = getParent();
- String charString = ((ContentTypeField) e.getHeader().getField(Field.CONTENT_TYPE)).getCharset();
- return charString;
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/TempFileBinaryBody.java b/emailcommon/src/org/apache/james/mime4j/message/TempFileBinaryBody.java
deleted file mode 100644
index 9db1482f4..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/TempFileBinaryBody.java
+++ /dev/null
@@ -1,91 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-import org.apache.commons.io.IOUtils;
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.util.TempFile;
-import org.apache.james.mime4j.util.TempPath;
-import org.apache.james.mime4j.util.TempStorage;
-
-
-/**
- * Binary body backed by a {@link org.apache.james.mime4j.util.TempFile}.
- *
- *
- * @version $Id: TempFileBinaryBody.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
- */
-class TempFileBinaryBody extends AbstractBody implements BinaryBody {
- private static Log log = LogFactory.getLog(TempFileBinaryBody.class);
-
- private Entity parent = null;
- private TempFile tempFile = null;
-
- /**
- * Use the given InputStream to build the TemporyFileBinaryBody
- *
- * @param is the InputStream to use as source
- * @throws IOException
- */
- public TempFileBinaryBody(InputStream is) throws IOException {
-
- TempPath tempPath = TempStorage.getInstance().getRootTempPath();
- tempFile = tempPath.createTempFile("attachment", ".bin");
-
- OutputStream out = tempFile.getOutputStream();
- IOUtils.copy(is, out);
- out.close();
- }
-
- /**
- * @see org.apache.james.mime4j.message.AbstractBody#getParent()
- */
- public Entity getParent() {
- return parent;
- }
-
- /**
- * @see org.apache.james.mime4j.message.AbstractBody#setParent(org.apache.james.mime4j.message.Entity)
- */
- public void setParent(Entity parent) {
- this.parent = parent;
- }
-
- /**
- * @see org.apache.james.mime4j.message.BinaryBody#getInputStream()
- */
- public InputStream getInputStream() throws IOException {
- return tempFile.getInputStream();
- }
-
- /**
- * @see org.apache.james.mime4j.message.Body#writeTo(java.io.OutputStream)
- */
- public void writeTo(OutputStream out) throws IOException {
- IOUtils.copy(getInputStream(),out);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/TempFileTextBody.java b/emailcommon/src/org/apache/james/mime4j/message/TempFileTextBody.java
deleted file mode 100644
index b74e15d24..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/TempFileTextBody.java
+++ /dev/null
@@ -1,117 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.io.UnsupportedEncodingException;
-
-import org.apache.commons.io.IOUtils;
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-import org.apache.james.mime4j.util.CharsetUtil;
-import org.apache.james.mime4j.util.TempFile;
-import org.apache.james.mime4j.util.TempPath;
-import org.apache.james.mime4j.util.TempStorage;
-
-
-/**
- * Text body backed by a {@link org.apache.james.mime4j.util.TempFile}.
- *
- *
- * @version $Id: TempFileTextBody.java,v 1.3 2004/10/25 07:26:46 ntherning Exp $
- */
-class TempFileTextBody extends AbstractBody implements TextBody {
- private static Log log = LogFactory.getLog(TempFileTextBody.class);
-
- private String mimeCharset = null;
- private TempFile tempFile = null;
-
- public TempFileTextBody(InputStream is) throws IOException {
- this(is, null);
- }
-
- public TempFileTextBody(InputStream is, String mimeCharset)
- throws IOException {
-
- this.mimeCharset = mimeCharset;
-
- TempPath tempPath = TempStorage.getInstance().getRootTempPath();
- tempFile = tempPath.createTempFile("attachment", ".txt");
-
- OutputStream out = tempFile.getOutputStream();
- IOUtils.copy(is, out);
- out.close();
- }
-
- /**
- * @see org.apache.james.mime4j.message.TextBody#getReader()
- */
- public Reader getReader() throws UnsupportedEncodingException, IOException {
- String javaCharset = null;
- if (mimeCharset != null) {
- javaCharset = CharsetUtil.toJavaCharset(mimeCharset);
- }
-
- if (javaCharset == null) {
- javaCharset = "ISO-8859-1";
-
- if (log.isWarnEnabled()) {
- if (mimeCharset == null) {
- log.warn("No MIME charset specified. Using " + javaCharset
- + " instead.");
- } else {
- log.warn("MIME charset '" + mimeCharset + "' has no "
- + "corresponding Java charset. Using " + javaCharset
- + " instead.");
- }
- }
- }
- /*
- if (log.isWarnEnabled()) {
- if (mimeCharset == null) {
- log.warn("No MIME charset specified. Using the "
- + "platform's default charset.");
- } else {
- log.warn("MIME charset '" + mimeCharset + "' has no "
- + "corresponding Java charset. Using the "
- + "platform's default charset.");
- }
- }
-
- return new InputStreamReader(tempFile.getInputStream());
- }*/
-
- return new InputStreamReader(tempFile.getInputStream(), javaCharset);
- }
-
-
- /**
- * @see org.apache.james.mime4j.message.Body#writeTo(java.io.OutputStream)
- */
- public void writeTo(OutputStream out) throws IOException {
- IOUtils.copy(tempFile.getInputStream(), out);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/message/TextBody.java b/emailcommon/src/org/apache/james/mime4j/message/TextBody.java
deleted file mode 100644
index 4fe714466..000000000
--- a/emailcommon/src/org/apache/james/mime4j/message/TextBody.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.message;
-
-import java.io.IOException;
-import java.io.Reader;
-
-
-/**
- * Encapsulates the contents of a <code>text/*</code> entity body.
- *
- *
- * @version $Id: TextBody.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public interface TextBody extends Body {
-
- /**
- * Gets a <code>Reader</code> which may be used to read out the contents
- * of this body.
- *
- * @return the <code>Reader</code>.
- * @throws IOException on I/O errors.
- */
- Reader getReader() throws IOException;
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/util/CharsetUtil.java b/emailcommon/src/org/apache/james/mime4j/util/CharsetUtil.java
deleted file mode 100644
index 0fc267d3e..000000000
--- a/emailcommon/src/org/apache/james/mime4j/util/CharsetUtil.java
+++ /dev/null
@@ -1,1246 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.util;
-
-import java.io.UnsupportedEncodingException;
-import java.nio.charset.IllegalCharsetNameException;
-import java.nio.charset.UnsupportedCharsetException;
-import java.util.HashMap;
-import java.util.TreeSet;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-
-/**
- * Utility class for working with character sets. It is somewhat similar to
- * the Java 1.4 <code>java.nio.charset.Charset</code> class but knows many
- * more aliases and is compatible with Java 1.3. It will use a simple detection
- * mechanism to detect what character sets the current VM supports. This will
- * be a sub-set of the character sets listed in the
- * <a href="http://java.sun.com/j2se/1.5.0/docs/guide/intl/encoding.doc.html">
- * Java 1.5 (J2SE5.0) Supported Encodings</a> document.
- * <p>
- * The <a href="http://www.iana.org/assignments/character-sets">
- * IANA Character Sets</a> document has been used to determine the preferred
- * MIME character set names and to get a list of known aliases.
- * <p>
- * This is a complete list of the character sets known to this class:
- * <table>
- * <tr>
- * <td>Canonical (Java) name</td>
- * <td>MIME preferred</td>
- * <td>Aliases</td>
- * </tr>
- * <tr>
- * <td>ASCII</td>
- * <td>US-ASCII</td>
- * <td>ANSI_X3.4-1968 iso-ir-6 ANSI_X3.4-1986 ISO_646.irv:1991 ISO646-US us IBM367 cp367 csASCII ascii7 646 iso_646.irv:1983 </td>
- * </tr>
- * <tr>
- * <td>Big5</td>
- * <td>Big5</td>
- * <td>csBig5 CN-Big5 BIG-FIVE BIGFIVE </td>
- * </tr>
- * <tr>
- * <td>Big5_HKSCS</td>
- * <td>Big5-HKSCS</td>
- * <td>big5hkscs </td>
- * </tr>
- * <tr>
- * <td>Big5_Solaris</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp037</td>
- * <td>IBM037</td>
- * <td>ebcdic-cp-us ebcdic-cp-ca ebcdic-cp-wt ebcdic-cp-nl csIBM037 </td>
- * </tr>
- * <tr>
- * <td>Cp1006</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1025</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1026</td>
- * <td>IBM1026</td>
- * <td>csIBM1026 </td>
- * </tr>
- * <tr>
- * <td>Cp1046</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1047</td>
- * <td>IBM1047</td>
- * <td>IBM-1047 </td>
- * </tr>
- * <tr>
- * <td>Cp1097</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1098</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1112</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1122</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1123</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1124</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1140</td>
- * <td>IBM01140</td>
- * <td>CCSID01140 CP01140 ebcdic-us-37+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1141</td>
- * <td>IBM01141</td>
- * <td>CCSID01141 CP01141 ebcdic-de-273+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1142</td>
- * <td>IBM01142</td>
- * <td>CCSID01142 CP01142 ebcdic-dk-277+euro ebcdic-no-277+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1143</td>
- * <td>IBM01143</td>
- * <td>CCSID01143 CP01143 ebcdic-fi-278+euro ebcdic-se-278+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1144</td>
- * <td>IBM01144</td>
- * <td>CCSID01144 CP01144 ebcdic-it-280+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1145</td>
- * <td>IBM01145</td>
- * <td>CCSID01145 CP01145 ebcdic-es-284+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1146</td>
- * <td>IBM01146</td>
- * <td>CCSID01146 CP01146 ebcdic-gb-285+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1147</td>
- * <td>IBM01147</td>
- * <td>CCSID01147 CP01147 ebcdic-fr-297+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1148</td>
- * <td>IBM01148</td>
- * <td>CCSID01148 CP01148 ebcdic-international-500+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1149</td>
- * <td>IBM01149</td>
- * <td>CCSID01149 CP01149 ebcdic-is-871+euro </td>
- * </tr>
- * <tr>
- * <td>Cp1250</td>
- * <td>windows-1250</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1251</td>
- * <td>windows-1251</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1252</td>
- * <td>windows-1252</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1253</td>
- * <td>windows-1253</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1254</td>
- * <td>windows-1254</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1255</td>
- * <td>windows-1255</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1256</td>
- * <td>windows-1256</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1257</td>
- * <td>windows-1257</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1258</td>
- * <td>windows-1258</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1381</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp1383</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp273</td>
- * <td>IBM273</td>
- * <td>csIBM273 </td>
- * </tr>
- * <tr>
- * <td>Cp277</td>
- * <td>IBM277</td>
- * <td>EBCDIC-CP-DK EBCDIC-CP-NO csIBM277 </td>
- * </tr>
- * <tr>
- * <td>Cp278</td>
- * <td>IBM278</td>
- * <td>CP278 ebcdic-cp-fi ebcdic-cp-se csIBM278 </td>
- * </tr>
- * <tr>
- * <td>Cp280</td>
- * <td>IBM280</td>
- * <td>ebcdic-cp-it csIBM280 </td>
- * </tr>
- * <tr>
- * <td>Cp284</td>
- * <td>IBM284</td>
- * <td>ebcdic-cp-es csIBM284 </td>
- * </tr>
- * <tr>
- * <td>Cp285</td>
- * <td>IBM285</td>
- * <td>ebcdic-cp-gb csIBM285 </td>
- * </tr>
- * <tr>
- * <td>Cp297</td>
- * <td>IBM297</td>
- * <td>ebcdic-cp-fr csIBM297 </td>
- * </tr>
- * <tr>
- * <td>Cp33722</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp420</td>
- * <td>IBM420</td>
- * <td>ebcdic-cp-ar1 csIBM420 </td>
- * </tr>
- * <tr>
- * <td>Cp424</td>
- * <td>IBM424</td>
- * <td>ebcdic-cp-he csIBM424 </td>
- * </tr>
- * <tr>
- * <td>Cp437</td>
- * <td>IBM437</td>
- * <td>437 csPC8CodePage437 </td>
- * </tr>
- * <tr>
- * <td>Cp500</td>
- * <td>IBM500</td>
- * <td>ebcdic-cp-be ebcdic-cp-ch csIBM500 </td>
- * </tr>
- * <tr>
- * <td>Cp737</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp775</td>
- * <td>IBM775</td>
- * <td>csPC775Baltic </td>
- * </tr>
- * <tr>
- * <td>Cp838</td>
- * <td>IBM-Thai</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp850</td>
- * <td>IBM850</td>
- * <td>850 csPC850Multilingual </td>
- * </tr>
- * <tr>
- * <td>Cp852</td>
- * <td>IBM852</td>
- * <td>852 csPCp852 </td>
- * </tr>
- * <tr>
- * <td>Cp855</td>
- * <td>IBM855</td>
- * <td>855 csIBM855 </td>
- * </tr>
- * <tr>
- * <td>Cp856</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp857</td>
- * <td>IBM857</td>
- * <td>857 csIBM857 </td>
- * </tr>
- * <tr>
- * <td>Cp858</td>
- * <td>IBM00858</td>
- * <td>CCSID00858 CP00858 PC-Multilingual-850+euro </td>
- * </tr>
- * <tr>
- * <td>Cp860</td>
- * <td>IBM860</td>
- * <td>860 csIBM860 </td>
- * </tr>
- * <tr>
- * <td>Cp861</td>
- * <td>IBM861</td>
- * <td>861 cp-is csIBM861 </td>
- * </tr>
- * <tr>
- * <td>Cp862</td>
- * <td>IBM862</td>
- * <td>862 csPC862LatinHebrew </td>
- * </tr>
- * <tr>
- * <td>Cp863</td>
- * <td>IBM863</td>
- * <td>863 csIBM863 </td>
- * </tr>
- * <tr>
- * <td>Cp864</td>
- * <td>IBM864</td>
- * <td>cp864 csIBM864 </td>
- * </tr>
- * <tr>
- * <td>Cp865</td>
- * <td>IBM865</td>
- * <td>865 csIBM865 </td>
- * </tr>
- * <tr>
- * <td>Cp866</td>
- * <td>IBM866</td>
- * <td>866 csIBM866 </td>
- * </tr>
- * <tr>
- * <td>Cp868</td>
- * <td>IBM868</td>
- * <td>cp-ar csIBM868 </td>
- * </tr>
- * <tr>
- * <td>Cp869</td>
- * <td>IBM869</td>
- * <td>cp-gr csIBM869 </td>
- * </tr>
- * <tr>
- * <td>Cp870</td>
- * <td>IBM870</td>
- * <td>ebcdic-cp-roece ebcdic-cp-yu csIBM870 </td>
- * </tr>
- * <tr>
- * <td>Cp871</td>
- * <td>IBM871</td>
- * <td>ebcdic-cp-is csIBM871 </td>
- * </tr>
- * <tr>
- * <td>Cp875</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp918</td>
- * <td>IBM918</td>
- * <td>ebcdic-cp-ar2 csIBM918 </td>
- * </tr>
- * <tr>
- * <td>Cp921</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp922</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp930</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp933</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp935</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp937</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp939</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp942</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp942C</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp943</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp943C</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp948</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp949</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp949C</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp950</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp964</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>Cp970</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>EUC_CN</td>
- * <td>GB2312</td>
- * <td>x-EUC-CN csGB2312 euccn euc-cn gb2312-80 gb2312-1980 CN-GB CN-GB-ISOIR165 </td>
- * </tr>
- * <tr>
- * <td>EUC_JP</td>
- * <td>EUC-JP</td>
- * <td>csEUCPkdFmtJapanese Extended_UNIX_Code_Packed_Format_for_Japanese eucjis x-eucjp eucjp x-euc-jp </td>
- * </tr>
- * <tr>
- * <td>EUC_JP_LINUX</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>EUC_JP_Solaris</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>EUC_KR</td>
- * <td>EUC-KR</td>
- * <td>csEUCKR ksc5601 5601 ksc5601_1987 ksc_5601 ksc5601-1987 ks_c_5601-1987 euckr </td>
- * </tr>
- * <tr>
- * <td>EUC_TW</td>
- * <td>EUC-TW</td>
- * <td>x-EUC-TW cns11643 euctw </td>
- * </tr>
- * <tr>
- * <td>GB18030</td>
- * <td>GB18030</td>
- * <td>gb18030-2000 </td>
- * </tr>
- * <tr>
- * <td>GBK</td>
- * <td>windows-936</td>
- * <td>CP936 MS936 ms_936 x-mswin-936 </td>
- * </tr>
- * <tr>
- * <td>ISCII91</td>
- * <td>?</td>
- * <td>x-ISCII91 iscii </td>
- * </tr>
- * <tr>
- * <td>ISO2022CN</td>
- * <td>ISO-2022-CN</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>ISO2022JP</td>
- * <td>ISO-2022-JP</td>
- * <td>csISO2022JP JIS jis_encoding csjisencoding </td>
- * </tr>
- * <tr>
- * <td>ISO2022KR</td>
- * <td>ISO-2022-KR</td>
- * <td>csISO2022KR </td>
- * </tr>
- * <tr>
- * <td>ISO2022_CN_CNS</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>ISO2022_CN_GB</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>ISO8859_1</td>
- * <td>ISO-8859-1</td>
- * <td>ISO_8859-1:1987 iso-ir-100 ISO_8859-1 latin1 l1 IBM819 CP819 csISOLatin1 8859_1 819 IBM-819 ISO8859-1 ISO_8859_1 </td>
- * </tr>
- * <tr>
- * <td>ISO8859_13</td>
- * <td>ISO-8859-13</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>ISO8859_15</td>
- * <td>ISO-8859-15</td>
- * <td>ISO_8859-15 Latin-9 8859_15 csISOlatin9 IBM923 cp923 923 L9 IBM-923 ISO8859-15 LATIN9 LATIN0 csISOlatin0 ISO8859_15_FDIS </td>
- * </tr>
- * <tr>
- * <td>ISO8859_2</td>
- * <td>ISO-8859-2</td>
- * <td>ISO_8859-2:1987 iso-ir-101 ISO_8859-2 latin2 l2 csISOLatin2 8859_2 iso8859_2 </td>
- * </tr>
- * <tr>
- * <td>ISO8859_3</td>
- * <td>ISO-8859-3</td>
- * <td>ISO_8859-3:1988 iso-ir-109 ISO_8859-3 latin3 l3 csISOLatin3 8859_3 </td>
- * </tr>
- * <tr>
- * <td>ISO8859_4</td>
- * <td>ISO-8859-4</td>
- * <td>ISO_8859-4:1988 iso-ir-110 ISO_8859-4 latin4 l4 csISOLatin4 8859_4 </td>
- * </tr>
- * <tr>
- * <td>ISO8859_5</td>
- * <td>ISO-8859-5</td>
- * <td>ISO_8859-5:1988 iso-ir-144 ISO_8859-5 cyrillic csISOLatinCyrillic 8859_5 </td>
- * </tr>
- * <tr>
- * <td>ISO8859_6</td>
- * <td>ISO-8859-6</td>
- * <td>ISO_8859-6:1987 iso-ir-127 ISO_8859-6 ECMA-114 ASMO-708 arabic csISOLatinArabic 8859_6 </td>
- * </tr>
- * <tr>
- * <td>ISO8859_7</td>
- * <td>ISO-8859-7</td>
- * <td>ISO_8859-7:1987 iso-ir-126 ISO_8859-7 ELOT_928 ECMA-118 greek greek8 csISOLatinGreek 8859_7 sun_eu_greek </td>
- * </tr>
- * <tr>
- * <td>ISO8859_8</td>
- * <td>ISO-8859-8</td>
- * <td>ISO_8859-8:1988 iso-ir-138 ISO_8859-8 hebrew csISOLatinHebrew 8859_8 </td>
- * </tr>
- * <tr>
- * <td>ISO8859_9</td>
- * <td>ISO-8859-9</td>
- * <td>ISO_8859-9:1989 iso-ir-148 ISO_8859-9 latin5 l5 csISOLatin5 8859_9 </td>
- * </tr>
- * <tr>
- * <td>JISAutoDetect</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>JIS_C6626-1983</td>
- * <td>JIS_C6626-1983</td>
- * <td>x-JIS0208 JIS0208 csISO87JISX0208 x0208 JIS_X0208-1983 iso-ir-87 </td>
- * </tr>
- * <tr>
- * <td>JIS_X0201</td>
- * <td>JIS_X0201</td>
- * <td>X0201 JIS0201 csHalfWidthKatakana </td>
- * </tr>
- * <tr>
- * <td>JIS_X0212-1990</td>
- * <td>JIS_X0212-1990</td>
- * <td>iso-ir-159 x0212 JIS0212 csISO159JISX02121990 </td>
- * </tr>
- * <tr>
- * <td>KOI8_R</td>
- * <td>KOI8-R</td>
- * <td>csKOI8R koi8 </td>
- * </tr>
- * <tr>
- * <td>MS874</td>
- * <td>windows-874</td>
- * <td>cp874 </td>
- * </tr>
- * <tr>
- * <td>MS932</td>
- * <td>Windows-31J</td>
- * <td>windows-932 csWindows31J x-ms-cp932 </td>
- * </tr>
- * <tr>
- * <td>MS949</td>
- * <td>windows-949</td>
- * <td>windows949 ms_949 x-windows-949 </td>
- * </tr>
- * <tr>
- * <td>MS950</td>
- * <td>windows-950</td>
- * <td>x-windows-950 </td>
- * </tr>
- * <tr>
- * <td>MS950_HKSCS</td>
- * <td></td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacArabic</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacCentralEurope</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacCroatian</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacCyrillic</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacDingbat</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacGreek</td>
- * <td>MacGreek</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacHebrew</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacIceland</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacRoman</td>
- * <td>MacRoman</td>
- * <td>Macintosh MAC csMacintosh </td>
- * </tr>
- * <tr>
- * <td>MacRomania</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacSymbol</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacThai</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacTurkish</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>MacUkraine</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>SJIS</td>
- * <td>Shift_JIS</td>
- * <td>MS_Kanji csShiftJIS shift-jis x-sjis pck </td>
- * </tr>
- * <tr>
- * <td>TIS620</td>
- * <td>TIS-620</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>UTF-16</td>
- * <td>UTF-16</td>
- * <td>UTF_16 </td>
- * </tr>
- * <tr>
- * <td>UTF8</td>
- * <td>UTF-8</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>UnicodeBig</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>UnicodeBigUnmarked</td>
- * <td>UTF-16BE</td>
- * <td>X-UTF-16BE UTF_16BE ISO-10646-UCS-2 </td>
- * </tr>
- * <tr>
- * <td>UnicodeLittle</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * <tr>
- * <td>UnicodeLittleUnmarked</td>
- * <td>UTF-16LE</td>
- * <td>UTF_16LE X-UTF-16LE </td>
- * </tr>
- * <tr>
- * <td>x-Johab</td>
- * <td>johab</td>
- * <td>johab cp1361 ms1361 ksc5601-1992 ksc5601_1992 </td>
- * </tr>
- * <tr>
- * <td>x-iso-8859-11</td>
- * <td>?</td>
- * <td></td>
- * </tr>
- * </table>
- *
- *
- * @version $Id: CharsetUtil.java,v 1.1 2004/10/25 07:26:46 ntherning Exp $
- */
-public class CharsetUtil {
- private static Log log = LogFactory.getLog(CharsetUtil.class);
-
- private static class Charset implements Comparable<Charset> {
- private String canonical = null;
- private String mime = null;
- private String[] aliases = null;
-
- private Charset(String canonical, String mime, String[] aliases) {
- this.canonical = canonical;
- this.mime = mime;
- this.aliases = aliases;
- }
-
- public int compareTo(Charset c) {
- return this.canonical.compareTo(c.canonical);
- }
- }
-
- private static Charset[] JAVA_CHARSETS = {
- new Charset("ISO8859_1", "ISO-8859-1",
- new String[] {"ISO_8859-1:1987", "iso-ir-100", "ISO_8859-1",
- "latin1", "l1", "IBM819", "CP819",
- "csISOLatin1", "8859_1", "819", "IBM-819",
- "ISO8859-1", "ISO_8859_1"}),
- new Charset("ISO8859_2", "ISO-8859-2",
- new String[] {"ISO_8859-2:1987", "iso-ir-101", "ISO_8859-2",
- "latin2", "l2", "csISOLatin2", "8859_2",
- "iso8859_2"}),
- new Charset("ISO8859_3", "ISO-8859-3", new String[] {"ISO_8859-3:1988", "iso-ir-109", "ISO_8859-3", "latin3", "l3", "csISOLatin3", "8859_3"}),
- new Charset("ISO8859_4", "ISO-8859-4",
- new String[] {"ISO_8859-4:1988", "iso-ir-110", "ISO_8859-4",
- "latin4", "l4", "csISOLatin4", "8859_4"}),
- new Charset("ISO8859_5", "ISO-8859-5",
- new String[] {"ISO_8859-5:1988", "iso-ir-144", "ISO_8859-5",
- "cyrillic", "csISOLatinCyrillic", "8859_5"}),
- new Charset("ISO8859_6", "ISO-8859-6", new String[] {"ISO_8859-6:1987", "iso-ir-127", "ISO_8859-6", "ECMA-114", "ASMO-708", "arabic", "csISOLatinArabic", "8859_6"}),
- new Charset("ISO8859_7", "ISO-8859-7",
- new String[] {"ISO_8859-7:1987", "iso-ir-126", "ISO_8859-7",
- "ELOT_928", "ECMA-118", "greek", "greek8",
- "csISOLatinGreek", "8859_7", "sun_eu_greek"}),
- new Charset("ISO8859_8", "ISO-8859-8", new String[] {"ISO_8859-8:1988", "iso-ir-138", "ISO_8859-8", "hebrew", "csISOLatinHebrew", "8859_8"}),
- new Charset("ISO8859_9", "ISO-8859-9",
- new String[] {"ISO_8859-9:1989", "iso-ir-148", "ISO_8859-9",
- "latin5", "l5", "csISOLatin5", "8859_9"}),
-
- new Charset("ISO8859_13", "ISO-8859-13", new String[] {}),
- new Charset("ISO8859_15", "ISO-8859-15",
- new String[] {"ISO_8859-15", "Latin-9", "8859_15",
- "csISOlatin9", "IBM923", "cp923", "923", "L9",
- "IBM-923", "ISO8859-15", "LATIN9", "LATIN0",
- "csISOlatin0", "ISO8859_15_FDIS"}),
- new Charset("KOI8_R", "KOI8-R", new String[] {"csKOI8R", "koi8"}),
- new Charset("ASCII", "US-ASCII",
- new String[] {"ANSI_X3.4-1968", "iso-ir-6",
- "ANSI_X3.4-1986", "ISO_646.irv:1991",
- "ISO646-US", "us", "IBM367", "cp367",
- "csASCII", "ascii7", "646", "iso_646.irv:1983"}),
- new Charset("UTF8", "UTF-8", new String[] {}),
- new Charset("UTF-16", "UTF-16", new String[] {"UTF_16"}),
- new Charset("UnicodeBigUnmarked", "UTF-16BE", new String[] {"X-UTF-16BE", "UTF_16BE", "ISO-10646-UCS-2"}),
- new Charset("UnicodeLittleUnmarked", "UTF-16LE", new String[] {"UTF_16LE", "X-UTF-16LE"}),
- new Charset("Big5", "Big5", new String[] {"csBig5", "CN-Big5", "BIG-FIVE", "BIGFIVE"}),
- new Charset("Big5_HKSCS", "Big5-HKSCS", new String[] {"big5hkscs"}),
- new Charset("EUC_JP", "EUC-JP",
- new String[] {"csEUCPkdFmtJapanese",
- "Extended_UNIX_Code_Packed_Format_for_Japanese",
- "eucjis", "x-eucjp", "eucjp", "x-euc-jp"}),
- new Charset("EUC_KR", "EUC-KR",
- new String[] {"csEUCKR", "ksc5601", "5601", "ksc5601_1987",
- "ksc_5601", "ksc5601-1987", "ks_c_5601-1987",
- "euckr"}),
- new Charset("GB18030", "GB18030", new String[] {"gb18030-2000"}),
- new Charset("EUC_CN", "GB2312", new String[] {"x-EUC-CN", "csGB2312", "euccn", "euc-cn", "gb2312-80", "gb2312-1980", "CN-GB", "CN-GB-ISOIR165"}),
- new Charset("GBK", "windows-936", new String[] {"CP936", "MS936", "ms_936", "x-mswin-936"}),
-
- new Charset("Cp037", "IBM037", new String[] {"ebcdic-cp-us", "ebcdic-cp-ca", "ebcdic-cp-wt", "ebcdic-cp-nl", "csIBM037"}),
- new Charset("Cp273", "IBM273", new String[] {"csIBM273"}),
- new Charset("Cp277", "IBM277", new String[] {"EBCDIC-CP-DK", "EBCDIC-CP-NO", "csIBM277"}),
- new Charset("Cp278", "IBM278", new String[] {"CP278", "ebcdic-cp-fi", "ebcdic-cp-se", "csIBM278"}),
- new Charset("Cp280", "IBM280", new String[] {"ebcdic-cp-it", "csIBM280"}),
- new Charset("Cp284", "IBM284", new String[] {"ebcdic-cp-es", "csIBM284"}),
- new Charset("Cp285", "IBM285", new String[] {"ebcdic-cp-gb", "csIBM285"}),
- new Charset("Cp297", "IBM297", new String[] {"ebcdic-cp-fr", "csIBM297"}),
- new Charset("Cp420", "IBM420", new String[] {"ebcdic-cp-ar1", "csIBM420"}),
- new Charset("Cp424", "IBM424", new String[] {"ebcdic-cp-he", "csIBM424"}),
- new Charset("Cp437", "IBM437", new String[] {"437", "csPC8CodePage437"}),
- new Charset("Cp500", "IBM500", new String[] {"ebcdic-cp-be", "ebcdic-cp-ch", "csIBM500"}),
- new Charset("Cp775", "IBM775", new String[] {"csPC775Baltic"}),
- new Charset("Cp838", "IBM-Thai", new String[] {}),
- new Charset("Cp850", "IBM850", new String[] {"850", "csPC850Multilingual"}),
- new Charset("Cp852", "IBM852", new String[] {"852", "csPCp852"}),
- new Charset("Cp855", "IBM855", new String[] {"855", "csIBM855"}),
- new Charset("Cp857", "IBM857", new String[] {"857", "csIBM857"}),
- new Charset("Cp858", "IBM00858",
- new String[] {"CCSID00858", "CP00858",
- "PC-Multilingual-850+euro"}),
- new Charset("Cp860", "IBM860", new String[] {"860", "csIBM860"}),
- new Charset("Cp861", "IBM861", new String[] {"861", "cp-is", "csIBM861"}),
- new Charset("Cp862", "IBM862", new String[] {"862", "csPC862LatinHebrew"}),
- new Charset("Cp863", "IBM863", new String[] {"863", "csIBM863"}),
- new Charset("Cp864", "IBM864", new String[] {"cp864", "csIBM864"}),
- new Charset("Cp865", "IBM865", new String[] {"865", "csIBM865"}),
- new Charset("Cp866", "IBM866", new String[] {"866", "csIBM866"}),
- new Charset("Cp868", "IBM868", new String[] {"cp-ar", "csIBM868"}),
- new Charset("Cp869", "IBM869", new String[] {"cp-gr", "csIBM869"}),
- new Charset("Cp870", "IBM870", new String[] {"ebcdic-cp-roece", "ebcdic-cp-yu", "csIBM870"}),
- new Charset("Cp871", "IBM871", new String[] {"ebcdic-cp-is", "csIBM871"}),
- new Charset("Cp918", "IBM918", new String[] {"ebcdic-cp-ar2", "csIBM918"}),
- new Charset("Cp1026", "IBM1026", new String[] {"csIBM1026"}),
- new Charset("Cp1047", "IBM1047", new String[] {"IBM-1047"}),
- new Charset("Cp1140", "IBM01140",
- new String[] {"CCSID01140", "CP01140",
- "ebcdic-us-37+euro"}),
- new Charset("Cp1141", "IBM01141",
- new String[] {"CCSID01141", "CP01141",
- "ebcdic-de-273+euro"}),
- new Charset("Cp1142", "IBM01142", new String[] {"CCSID01142", "CP01142", "ebcdic-dk-277+euro", "ebcdic-no-277+euro"}),
- new Charset("Cp1143", "IBM01143", new String[] {"CCSID01143", "CP01143", "ebcdic-fi-278+euro", "ebcdic-se-278+euro"}),
- new Charset("Cp1144", "IBM01144", new String[] {"CCSID01144", "CP01144", "ebcdic-it-280+euro"}),
- new Charset("Cp1145", "IBM01145", new String[] {"CCSID01145", "CP01145", "ebcdic-es-284+euro"}),
- new Charset("Cp1146", "IBM01146", new String[] {"CCSID01146", "CP01146", "ebcdic-gb-285+euro"}),
- new Charset("Cp1147", "IBM01147", new String[] {"CCSID01147", "CP01147", "ebcdic-fr-297+euro"}),
- new Charset("Cp1148", "IBM01148", new String[] {"CCSID01148", "CP01148", "ebcdic-international-500+euro"}),
- new Charset("Cp1149", "IBM01149", new String[] {"CCSID01149", "CP01149", "ebcdic-is-871+euro"}),
- new Charset("Cp1250", "windows-1250", new String[] {}),
- new Charset("Cp1251", "windows-1251", new String[] {}),
- new Charset("Cp1252", "windows-1252", new String[] {}),
- new Charset("Cp1253", "windows-1253", new String[] {}),
- new Charset("Cp1254", "windows-1254", new String[] {}),
- new Charset("Cp1255", "windows-1255", new String[] {}),
- new Charset("Cp1256", "windows-1256", new String[] {}),
- new Charset("Cp1257", "windows-1257", new String[] {}),
- new Charset("Cp1258", "windows-1258", new String[] {}),
- new Charset("ISO2022CN", "ISO-2022-CN", new String[] {}),
- new Charset("ISO2022JP", "ISO-2022-JP", new String[] {"csISO2022JP", "JIS", "jis_encoding", "csjisencoding"}),
- new Charset("ISO2022KR", "ISO-2022-KR", new String[] {"csISO2022KR"}),
- new Charset("JIS_X0201", "JIS_X0201", new String[] {"X0201", "JIS0201", "csHalfWidthKatakana"}),
- new Charset("JIS_X0212-1990", "JIS_X0212-1990", new String[] {"iso-ir-159", "x0212", "JIS0212", "csISO159JISX02121990"}),
- new Charset("JIS_C6626-1983", "JIS_C6626-1983", new String[] {"x-JIS0208", "JIS0208", "csISO87JISX0208", "x0208", "JIS_X0208-1983", "iso-ir-87"}),
- new Charset("SJIS", "Shift_JIS", new String[] {"MS_Kanji", "csShiftJIS", "shift-jis", "x-sjis", "pck"}),
- new Charset("TIS620", "TIS-620", new String[] {}),
- new Charset("MS932", "Windows-31J", new String[] {"windows-932", "csWindows31J", "x-ms-cp932"}),
- new Charset("EUC_TW", "EUC-TW", new String[] {"x-EUC-TW", "cns11643", "euctw"}),
- new Charset("x-Johab", "johab", new String[] {"johab", "cp1361", "ms1361", "ksc5601-1992", "ksc5601_1992"}),
- new Charset("MS950_HKSCS", "", new String[] {}),
- new Charset("MS874", "windows-874", new String[] {"cp874"}),
- new Charset("MS949", "windows-949", new String[] {"windows949", "ms_949", "x-windows-949"}),
- new Charset("MS950", "windows-950", new String[] {"x-windows-950"}),
-
- new Charset("Cp737", null, new String[] {}),
- new Charset("Cp856", null, new String[] {}),
- new Charset("Cp875", null, new String[] {}),
- new Charset("Cp921", null, new String[] {}),
- new Charset("Cp922", null, new String[] {}),
- new Charset("Cp930", null, new String[] {}),
- new Charset("Cp933", null, new String[] {}),
- new Charset("Cp935", null, new String[] {}),
- new Charset("Cp937", null, new String[] {}),
- new Charset("Cp939", null, new String[] {}),
- new Charset("Cp942", null, new String[] {}),
- new Charset("Cp942C", null, new String[] {}),
- new Charset("Cp943", null, new String[] {}),
- new Charset("Cp943C", null, new String[] {}),
- new Charset("Cp948", null, new String[] {}),
- new Charset("Cp949", null, new String[] {}),
- new Charset("Cp949C", null, new String[] {}),
- new Charset("Cp950", null, new String[] {}),
- new Charset("Cp964", null, new String[] {}),
- new Charset("Cp970", null, new String[] {}),
- new Charset("Cp1006", null, new String[] {}),
- new Charset("Cp1025", null, new String[] {}),
- new Charset("Cp1046", null, new String[] {}),
- new Charset("Cp1097", null, new String[] {}),
- new Charset("Cp1098", null, new String[] {}),
- new Charset("Cp1112", null, new String[] {}),
- new Charset("Cp1122", null, new String[] {}),
- new Charset("Cp1123", null, new String[] {}),
- new Charset("Cp1124", null, new String[] {}),
- new Charset("Cp1381", null, new String[] {}),
- new Charset("Cp1383", null, new String[] {}),
- new Charset("Cp33722", null, new String[] {}),
- new Charset("Big5_Solaris", null, new String[] {}),
- new Charset("EUC_JP_LINUX", null, new String[] {}),
- new Charset("EUC_JP_Solaris", null, new String[] {}),
- new Charset("ISCII91", null, new String[] {"x-ISCII91", "iscii"}),
- new Charset("ISO2022_CN_CNS", null, new String[] {}),
- new Charset("ISO2022_CN_GB", null, new String[] {}),
- new Charset("x-iso-8859-11", null, new String[] {}),
- new Charset("JISAutoDetect", null, new String[] {}),
- new Charset("MacArabic", null, new String[] {}),
- new Charset("MacCentralEurope", null, new String[] {}),
- new Charset("MacCroatian", null, new String[] {}),
- new Charset("MacCyrillic", null, new String[] {}),
- new Charset("MacDingbat", null, new String[] {}),
- new Charset("MacGreek", "MacGreek", new String[] {}),
- new Charset("MacHebrew", null, new String[] {}),
- new Charset("MacIceland", null, new String[] {}),
- new Charset("MacRoman", "MacRoman", new String[] {"Macintosh", "MAC", "csMacintosh"}),
- new Charset("MacRomania", null, new String[] {}),
- new Charset("MacSymbol", null, new String[] {}),
- new Charset("MacThai", null, new String[] {}),
- new Charset("MacTurkish", null, new String[] {}),
- new Charset("MacUkraine", null, new String[] {}),
- new Charset("UnicodeBig", null, new String[] {}),
- new Charset("UnicodeLittle", null, new String[] {})
- };
-
- /**
- * Contains the canonical names of character sets which can be used to
- * decode bytes into Java chars.
- */
- private static TreeSet<String> decodingSupported = null;
-
- /**
- * Contains the canonical names of character sets which can be used to
- * encode Java chars into bytes.
- */
- private static TreeSet<String> encodingSupported = null;
-
- /**
- * Maps character set names to Charset objects. All possible names of
- * a charset will be mapped to the Charset.
- */
- private static HashMap<String, Charset> charsetMap = null;
-
- static {
- decodingSupported = new TreeSet<String>();
- encodingSupported = new TreeSet<String>();
- byte[] dummy = new byte[] {'d', 'u', 'm', 'm', 'y'};
- for (int i = 0; i < JAVA_CHARSETS.length; i++) {
- try {
- String s = new String(dummy, JAVA_CHARSETS[i].canonical);
- decodingSupported.add(JAVA_CHARSETS[i].canonical.toLowerCase());
- } catch (UnsupportedOperationException e) {
- } catch (UnsupportedEncodingException e) {
- }
- try {
- "dummy".getBytes(JAVA_CHARSETS[i].canonical);
- encodingSupported.add(JAVA_CHARSETS[i].canonical.toLowerCase());
- } catch (UnsupportedOperationException e) {
- } catch (UnsupportedEncodingException e) {
- }
- }
-
- charsetMap = new HashMap<String, Charset>();
- for (int i = 0; i < JAVA_CHARSETS.length; i++) {
- Charset c = JAVA_CHARSETS[i];
- charsetMap.put(c.canonical.toLowerCase(), c);
- if (c.mime != null) {
- charsetMap.put(c.mime.toLowerCase(), c);
- }
- if (c.aliases != null) {
- for (int j = 0; j < c.aliases.length; j++) {
- charsetMap.put(c.aliases[j].toLowerCase(), c);
- }
- }
- }
-
- if (log.isDebugEnabled()) {
- log.debug("Character sets which support decoding: "
- + decodingSupported);
- log.debug("Character sets which support encoding: "
- + encodingSupported);
- }
- }
-
- /**
- * ANDROID: THE FOLLOWING SET OF STATIC STRINGS ARE COPIED FROM A NEWER VERSION OF MIME4J
- */
-
- /** carriage return - line feed sequence */
- public static final String CRLF = "\r\n";
-
- /** US-ASCII CR, carriage return (13) */
- public static final int CR = '\r';
-
- /** US-ASCII LF, line feed (10) */
- public static final int LF = '\n';
-
- /** US-ASCII SP, space (32) */
- public static final int SP = ' ';
-
- /** US-ASCII HT, horizontal-tab (9)*/
- public static final int HT = '\t';
-
- public static final java.nio.charset.Charset US_ASCII = java.nio.charset.Charset
- .forName("US-ASCII");
-
- public static final java.nio.charset.Charset ISO_8859_1 = java.nio.charset.Charset
- .forName("ISO-8859-1");
-
- public static final java.nio.charset.Charset UTF_8 = java.nio.charset.Charset
- .forName("UTF-8");
-
- /**
- * Returns <code>true</code> if the specified character is a whitespace
- * character (CR, LF, SP or HT).
- *
- * ANDROID: COPIED FROM A NEWER VERSION OF MIME4J
- *
- * @param ch
- * character to test.
- * @return <code>true</code> if the specified character is a whitespace
- * character, <code>false</code> otherwise.
- */
- public static boolean isWhitespace(char ch) {
- return ch == SP || ch == HT || ch == CR || ch == LF;
- }
-
- /**
- * Returns <code>true</code> if the specified string consists entirely of
- * whitespace characters.
- *
- * ANDROID: COPIED FROM A NEWER VERSION OF MIME4J
- *
- * @param s
- * string to test.
- * @return <code>true</code> if the specified string consists entirely of
- * whitespace characters, <code>false</code> otherwise.
- */
- public static boolean isWhitespace(final String s) {
- if (s == null) {
- throw new IllegalArgumentException("String may not be null");
- }
- final int len = s.length();
- for (int i = 0; i < len; i++) {
- if (!isWhitespace(s.charAt(i))) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Determines if the VM supports encoding (chars to bytes) the
- * specified character set. NOTE: the given character set name may
- * not be known to the VM even if this method returns <code>true</code>.
- * Use {@link #toJavaCharset(String)} to get the canonical Java character
- * set name.
- *
- * @param charsetName the characters set name.
- * @return <code>true</code> if encoding is supported, <code>false</code>
- * otherwise.
- */
- public static boolean isEncodingSupported(String charsetName) {
- return encodingSupported.contains(charsetName.toLowerCase());
- }
-
- /**
- * Determines if the VM supports decoding (bytes to chars) the
- * specified character set. NOTE: the given character set name may
- * not be known to the VM even if this method returns <code>true</code>.
- * Use {@link #toJavaCharset(String)} to get the canonical Java character
- * set name.
- *
- * @param charsetName the characters set name.
- * @return <code>true</code> if decoding is supported, <code>false</code>
- * otherwise.
- */
- public static boolean isDecodingSupported(String charsetName) {
- return decodingSupported.contains(charsetName.toLowerCase());
- }
-
- /**
- * Gets the preferred MIME character set name for the specified
- * character set or <code>null</code> if not known.
- *
- * @param charsetName the character set name to look for.
- * @return the MIME preferred name or <code>null</code> if not known.
- */
- public static String toMimeCharset(String charsetName) {
- Charset c = charsetMap.get(charsetName.toLowerCase());
- if (c != null) {
- return c.mime;
- }
- return null;
- }
-
- /**
- * Gets the canonical Java character set name for the specified
- * character set or <code>null</code> if not known. This should be
- * called before doing any conversions using the Java API. NOTE:
- * you must use {@link #isEncodingSupported(String)} or
- * {@link #isDecodingSupported(String)} to make sure the returned
- * Java character set is supported by the current VM.
- *
- * @param charsetName the character set name to look for.
- * @return the canonical Java name or <code>null</code> if not known.
- */
- public static String toJavaCharset(String charsetName) {
- Charset c = charsetMap.get(charsetName.toLowerCase());
- if (c != null) {
- return c.canonical;
- }
- return null;
- }
-
- public static java.nio.charset.Charset getCharset(String charsetName) {
- String defaultCharset = "ISO-8859-1";
-
- // Use the default chareset if given charset is null
- if(charsetName == null) charsetName = defaultCharset;
-
- try {
- return java.nio.charset.Charset.forName(charsetName);
- } catch (IllegalCharsetNameException e) {
- log.info("Illegal charset " + charsetName + ", fallback to " + defaultCharset + ": " + e);
- // Use default charset on exception
- return java.nio.charset.Charset.forName(defaultCharset);
- } catch (UnsupportedCharsetException ex) {
- log.info("Unsupported charset " + charsetName + ", fallback to " + defaultCharset + ": " + ex);
- // Use default charset on exception
- return java.nio.charset.Charset.forName(defaultCharset);
- }
-
- }
- /*
- * Uncomment the code below and run the main method to regenerate the
- * Javadoc table above when the known charsets change.
- */
-
- /*
- private static String dumpHtmlTable() {
- LinkedList l = new LinkedList(Arrays.asList(JAVA_CHARSETS));
- Collections.sort(l);
- StringBuffer sb = new StringBuffer();
- sb.append(" * <table>\n");
- sb.append(" * <tr>\n");
- sb.append(" * <td>Canonical (Java) name</td>\n");
- sb.append(" * <td>MIME preferred</td>\n");
- sb.append(" * <td>Aliases</td>\n");
- sb.append(" * </tr>\n");
-
- for (Iterator it = l.iterator(); it.hasNext();) {
- Charset c = (Charset) it.next();
- sb.append(" * <tr>\n");
- sb.append(" * <td>" + c.canonical + "</td>\n");
- sb.append(" * <td>" + (c.mime == null ? "?" : c.mime)+ "</td>\n");
- sb.append(" * <td>");
- for (int i = 0; c.aliases != null && i < c.aliases.length; i++) {
- sb.append(c.aliases[i] + " ");
- }
- sb.append("</td>\n");
- sb.append(" * </tr>\n");
- }
- sb.append(" * </table>\n");
- return sb.toString();
- }
-
- public static void main(String[] args) {
- System.out.println(dumpHtmlTable());
- }*/
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/util/PartialInputStream.java b/emailcommon/src/org/apache/james/mime4j/util/PartialInputStream.java
deleted file mode 100644
index a5ac0596d..000000000
--- a/emailcommon/src/org/apache/james/mime4j/util/PartialInputStream.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-
-package org.apache.james.mime4j.util;
-
-import java.io.InputStream;
-import java.io.IOException;
-
-public class PartialInputStream extends PositionInputStream {
- private final long limit;
-
- public PartialInputStream(InputStream inputStream, long offset, long length) throws IOException {
- super(inputStream);
- inputStream.skip(offset);
- this.limit = offset + length;
- }
-
- public int available() throws IOException {
- return Math.min(super.available(), getBytesLeft());
- }
-
- public int read() throws IOException {
- if (limit > position)
- return super.read();
- else
- return -1;
- }
-
- public int read(byte b[]) throws IOException {
- return read(b, 0, b.length);
- }
-
- public int read(byte b[], int off, int len) throws IOException {
- len = Math.min(len, getBytesLeft());
- return super.read(b, off, len); //To change body of overridden methods use File | Settings | File Templates.
- }
-
- public long skip(long n) throws IOException {
- n = Math.min(n, getBytesLeft());
- return super.skip(n); //To change body of overridden methods use File | Settings | File Templates.
- }
-
- private int getBytesLeft() {
- return (int)Math.min(Integer.MAX_VALUE, limit - position);
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/util/PositionInputStream.java b/emailcommon/src/org/apache/james/mime4j/util/PositionInputStream.java
deleted file mode 100644
index 9fcd21d0c..000000000
--- a/emailcommon/src/org/apache/james/mime4j/util/PositionInputStream.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-
-package org.apache.james.mime4j.util;
-
-import java.io.InputStream;
-import java.io.IOException;
-
-public class PositionInputStream extends InputStream {
-
- private final InputStream inputStream;
- protected long position = 0;
- private long markedPosition = 0;
-
- public PositionInputStream(InputStream inputStream) {
- this.inputStream = inputStream;
- }
-
- public long getPosition() {
- return position;
- }
-
- public int available() throws IOException {
- return inputStream.available();
- }
-
- public int read() throws IOException {
- int b = inputStream.read();
- if (b != -1)
- position++;
- return b;
- }
-
- public void close() throws IOException {
- inputStream.close();
- }
-
- public void reset() throws IOException {
- inputStream.reset();
- position = markedPosition;
- }
-
- public boolean markSupported() {
- return inputStream.markSupported();
- }
-
- public void mark(int readlimit) {
- inputStream.mark(readlimit);
- markedPosition = position;
- }
-
- public long skip(long n) throws IOException {
- final long c = inputStream.skip(n);
- position += c;
- return c;
- }
-
- public int read(byte b[]) throws IOException {
- final int c = inputStream.read(b);
- position += c;
- return c;
- }
-
- public int read(byte b[], int off, int len) throws IOException {
- final int c = inputStream.read(b, off, len);
- position += c;
- return c;
- }
-
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/util/SimpleTempStorage.java b/emailcommon/src/org/apache/james/mime4j/util/SimpleTempStorage.java
deleted file mode 100644
index 930e4db02..000000000
--- a/emailcommon/src/org/apache/james/mime4j/util/SimpleTempStorage.java
+++ /dev/null
@@ -1,238 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.util;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.util.Random;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-
-/**
- *
- * @version $Id: SimpleTempStorage.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
- */
-public class SimpleTempStorage extends TempStorage {
- private static Log log = LogFactory.getLog(SimpleTempStorage.class);
-
- private TempPath rootPath = null;
- private Random random = new Random();
-
- /**
- * Creates a new <code>SimpleTempStorageManager</code> instance.
- */
- public SimpleTempStorage() {
- rootPath = new SimpleTempPath(System.getProperty("java.io.tmpdir"));
- }
-
- private TempPath createTempPath(TempPath parent, String prefix)
- throws IOException {
-
- if (prefix == null) {
- prefix = "";
- }
-
- File p = null;
- int count = 1000;
- do {
- long n = Math.abs(random.nextLong());
- p = new File(parent.getAbsolutePath(), prefix + n);
- count--;
- } while (p.exists() && count > 0);
-
- if (p.exists() || !p.mkdirs()) {
- log.error("Unable to mkdirs on " + p.getAbsolutePath());
- throw new IOException("Creating dir '"
- + p.getAbsolutePath() + "' failed.");
- }
-
- return new SimpleTempPath(p);
- }
-
- private TempFile createTempFile(TempPath parent, String prefix,
- String suffix) throws IOException {
-
- if (prefix == null) {
- prefix = "";
- }
- if (suffix == null) {
- suffix = ".tmp";
- }
-
- File f = null;
-
- int count = 1000;
- synchronized (this) {
- do {
- long n = Math.abs(random.nextLong());
- f = new File(parent.getAbsolutePath(), prefix + n + suffix);
- count--;
- } while (f.exists() && count > 0);
-
- if (f.exists()) {
- throw new IOException("Creating temp file failed: "
- + "Unable to find unique file name");
- }
-
- try {
- f.createNewFile();
- } catch (IOException e) {
- throw new IOException("Creating dir '"
- + f.getAbsolutePath() + "' failed.");
- }
- }
-
- return new SimpleTempFile(f);
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempStorage#getRootTempPath()
- */
- public TempPath getRootTempPath() {
- return rootPath;
- }
-
- private class SimpleTempPath implements TempPath {
- private File path = null;
-
- private SimpleTempPath(String path) {
- this.path = new File(path);
- }
-
- private SimpleTempPath(File path) {
- this.path = path;
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempPath#createTempFile()
- */
- public TempFile createTempFile() throws IOException {
- return SimpleTempStorage.this.createTempFile(this, null, null);
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempPath#createTempFile(java.lang.String, java.lang.String)
- */
- public TempFile createTempFile(String prefix, String suffix)
- throws IOException {
-
- return SimpleTempStorage.this.createTempFile(this, prefix, suffix);
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempPath#createTempFile(java.lang.String, java.lang.String, boolean)
- */
- public TempFile createTempFile(String prefix, String suffix,
- boolean allowInMemory)
- throws IOException {
-
- return SimpleTempStorage.this.createTempFile(this, prefix, suffix);
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempPath#getAbsolutePath()
- */
- public String getAbsolutePath() {
- return path.getAbsolutePath();
- }
-
- /**
- * Do nothing
- */
- public void delete() {
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempPath#createTempPath()
- */
- public TempPath createTempPath() throws IOException {
- return SimpleTempStorage.this.createTempPath(this, null);
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempPath#createTempPath(java.lang.String)
- */
- public TempPath createTempPath(String prefix) throws IOException {
- return SimpleTempStorage.this.createTempPath(this, prefix);
- }
-
- }
-
- private class SimpleTempFile implements TempFile {
- private File file = null;
-
- private SimpleTempFile(File file) {
- this.file = file;
- this.file.deleteOnExit();
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempFile#getInputStream()
- */
- public InputStream getInputStream() throws IOException {
- return new BufferedInputStream(new FileInputStream(file));
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempFile#getOutputStream()
- */
- public OutputStream getOutputStream() throws IOException {
- return new BufferedOutputStream(new FileOutputStream(file));
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempFile#getAbsolutePath()
- */
- public String getAbsolutePath() {
- return file.getAbsolutePath();
- }
-
- /**
- * Do nothing
- */
- public void delete() {
- // Not implementated
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempFile#isInMemory()
- */
- public boolean isInMemory() {
- return false;
- }
-
- /**
- * @see org.apache.james.mime4j.util.TempFile#length()
- */
- public long length() {
- return file.length();
- }
-
- }
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/util/TempFile.java b/emailcommon/src/org/apache/james/mime4j/util/TempFile.java
deleted file mode 100644
index f67e1e93e..000000000
--- a/emailcommon/src/org/apache/james/mime4j/util/TempFile.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.util;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-
-/**
- * @version $Id: TempFile.java,v 1.3 2004/10/02 12:41:11 ntherning Exp $
- */
-public interface TempFile {
- /**
- * Gets an <code>InputStream</code> to read bytes from this temporary file.
- * NOTE: The stream should NOT be wrapped in
- * <code>BufferedInputStream</code> by the caller. If the implementing
- * <code>TempFile</code> creates a <code>FileInputStream</code> or any
- * other stream which would benefit from being buffered it's the
- * <code>TempFile</code>'s responsibility to wrap it.
- *
- * @return the stream.
- * @throws IOException
- */
- InputStream getInputStream() throws IOException;
-
- /**
- * Gets an <code>OutputStream</code> to write bytes to this temporary file.
- * NOTE: The stream should NOT be wrapped in
- * <code>BufferedOutputStream</code> by the caller. If the implementing
- * <code>TempFile</code> creates a <code>FileOutputStream</code> or any
- * other stream which would benefit from being buffered it's the
- * <code>TempFile</code>'s responsibility to wrap it.
- *
- * @return the stream.
- * @throws IOException
- */
- OutputStream getOutputStream() throws IOException;
-
- /**
- * Returns the absolute path including file name of this
- * <code>TempFile</code>. The path may be <code>null</code> if this is
- * an in-memory file.
- *
- * @return the absolute path.
- */
- String getAbsolutePath();
-
- /**
- * Deletes this file as soon as possible.
- */
- void delete();
-
- /**
- * Determines if this is an in-memory file.
- *
- * @return <code>true</code> if this file is currently in memory,
- * <code>false</code> otherwise.
- */
- boolean isInMemory();
-
- /**
- * Gets the length of this temporary file.
- *
- * @return the length.
- */
- long length();
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/util/TempPath.java b/emailcommon/src/org/apache/james/mime4j/util/TempPath.java
deleted file mode 100644
index 3b55aa6db..000000000
--- a/emailcommon/src/org/apache/james/mime4j/util/TempPath.java
+++ /dev/null
@@ -1,73 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.util;
-
-import java.io.IOException;
-
-/**
- *
- * @version $Id: TempPath.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
- */
-public interface TempPath {
- TempPath createTempPath() throws IOException;
- TempPath createTempPath(String prefix) throws IOException;
-
- /**
- * Creates a new temporary file. Wheter it will be be created in memory
- * or on disk is up to to the implementation.
- * The prefix will be empty and the suffix will be
- * <code>.tmp</code> if created on disk.
- *
- * @return the temporary file.
- */
- TempFile createTempFile() throws IOException;
-
- /**
- * Creates a new temporary file. Wheter it will be be created in memory
- * or on disk is up to to the implementation.
- * The prefix and suffix can be set by the user.
- *
- * @param prefix the prefix to use. <code>null</code> gives no prefix.
- * @param suffix the suffix to use. <code>null</code> gives
- * <code>.tmp</code>.
- * @return the temporary file.
- */
- TempFile createTempFile(String prefix, String suffix) throws IOException;
-
- /**
- * Creates a new temporary file. Wheter it will be be created in memory
- * or on disk can be specified using the <code>allowInMemory</code>
- * parameter. If the implementation doesn't support in-memory files
- * the new file will be created on disk.
- * The prefix and suffix can be set by the user.
- *
- * @param prefix the prefix to use. <code>null</code> gives no prefix.
- * @param suffix the suffix to use. <code>null</code> gives
- * <code>.tmp</code>.
- * @param allowInMemory if <code>true</code> the file MIGHT be created in
- * memory if supported by the implentation. If <code>false</code> the
- * file MUST be created on disk.
- * @return the temporary file.
- */
- TempFile createTempFile(String prefix, String suffix,
- boolean allowInMemory) throws IOException;
- String getAbsolutePath();
- void delete();
-}
diff --git a/emailcommon/src/org/apache/james/mime4j/util/TempStorage.java b/emailcommon/src/org/apache/james/mime4j/util/TempStorage.java
deleted file mode 100644
index 4d3be4746..000000000
--- a/emailcommon/src/org/apache/james/mime4j/util/TempStorage.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/****************************************************************
- * Licensed to the Apache Software Foundation (ASF) under one *
- * or more contributor license agreements. See the NOTICE file *
- * distributed with this work for additional information *
- * regarding copyright ownership. The ASF licenses this file *
- * to you under the Apache License, Version 2.0 (the *
- * "License"); you may not use this file except in compliance *
- * with the License. You may obtain a copy of the License at *
- * *
- * http://www.apache.org/licenses/LICENSE-2.0 *
- * *
- * Unless required by applicable law or agreed to in writing, *
- * software distributed under the License is distributed on an *
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY *
- * KIND, either express or implied. See the License for the *
- * specific language governing permissions and limitations *
- * under the License. *
- ****************************************************************/
-
-package org.apache.james.mime4j.util;
-
-//BEGIN android-changed: Stubbing out logging
-import org.apache.james.mime4j.Log;
-import org.apache.james.mime4j.LogFactory;
-//END android-changed
-
-/**
- *
- * @version $Id: TempStorage.java,v 1.2 2004/10/02 12:41:11 ntherning Exp $
- */
-public abstract class TempStorage {
- private static Log log = LogFactory.getLog(TempStorage.class);
- private static TempStorage inst = null;
-
- static {
-
- String clazz = System.getProperty("org.apache.james.mime4j.tempStorage");
- try {
-
- if (inst != null) {
- inst = (TempStorage) Class.forName(clazz).newInstance();
- }
-
- } catch (Throwable t) {
- log.warn("Unable to create or instantiate TempStorage class '"
- + clazz + "' using SimpleTempStorage instead", t);
- }
-
- if (inst == null) {
- inst = new SimpleTempStorage();
- }
- }
-
- /**
- * Gets the root temporary path which should be used to
- * create new temporary paths or files.
- *
- * @return the root temporary path.
- */
- public abstract TempPath getRootTempPath();
-
- public static TempStorage getInstance() {
- return inst;
- }
-
- public static void setInstance(TempStorage inst) {
- if (inst == null) {
- throw new NullPointerException("inst");
- }
- TempStorage.inst = inst;
- }
-}